_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 |
|---|---|---|---|---|---|---|---|---|
8c7a58fdf4f684795496e776da4d6e5d515c5213b16d710275859093e0bc52c6 | aaronc/ClojureClrEx | impl.clj | Copyright ( c ) . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns ^{:author "Alex Taggart"
:doc "Protocols used to allow access to logging implementations.
This namespace only need be used by those providing logging
implementations to be consumed by the core api."}
clojure.tools.logging.impl
(:refer-clojure :exclude [name]))
(defprotocol Logger
"The protocol through which the core api will interact with an underlying logging
implementation. Implementations should at least support the six standard
logging levels if they wish to work from the level-specific macros."
(enabled? [logger level]
"Check if a particular level is enabled for the given Logger.")
(write! [logger level throwable message]
"Writes a log message to the given Logger."))
(defprotocol LoggerFactory
"The protocol through which the core api will obtain an instance satisfying Logger
as well as providing information about the particular implementation being used.
Implementations should be bound to *logger-factory* in order to be picked up by
this library."
(name [factory]
"Returns some text identifying the underlying implementation.")
(get-logger [factory logger-ns]
"Returns an implementation-specific Logger by namespace."))
(defn common-logging-factory
"Returns a Commons Logging-based implementation of the LoggerFactory protocol, or
nil if not available."
[]
(try
(when (Type/GetType "Common.Logging.LogManager, Common.Logging")
(eval
`(do
(extend Common.Logging.ILog
Logger
{:enabled?
(fn [^Common.Logging.ILog logger# level#]
(condp = level#
:trace (.IsTraceEnabled logger#)
:debug (.IsDebugEnabled logger#)
:info (.IsInfoEnabled logger#)
:warn (.IsWarnEnabled logger#)
:error (.IsErrorEnabled logger#)
:fatal (.IsFatalEnabled logger#)
(throw (ArgumentException. (str level#)))))
:write!
(fn [^Common.Logging.ILog logger# level# ^Exception e# msg#]
(let [^String msg# (str msg#)]
(if e#
(condp = level#
:trace (.Trace logger# msg# e#)
:debug (.Debug logger# msg# e#)
:info (.Info logger# msg# e#)
:warn (.Warn logger# msg# e#)
:error (.Error logger# msg# e#)
:fatal (.Fatal logger# msg# e#)
(throw (ArgumentException. (str level#))))
(condp = level#
:trace (.Trace logger# msg#)
:debug (.Debug logger# msg#)
:info (.Info logger# msg#)
:warn (.Warn logger# msg#)
:error (.Error logger# msg#)
:fatal (.Fatal logger# msg#)
(throw (ArgumentException. (str level#)))))))})
(reify LoggerFactory
(name [_#]
"Common.Logging")
(get-logger [_# logger-ns#]
(Common.Logging.LogManager/GetLogger ^String (str logger-ns#)))))))
(catch Exception e nil)))
(defn find-factory
"Returns the first non-nil value from common-logging-factory."
[]
(or
(common-logging-factory)
(comment
(throw
(Exception.
"Valid logging implementation could not be found.")))))
| null | https://raw.githubusercontent.com/aaronc/ClojureClrEx/465e05b5872816056544c89b47c1997f6067ae89/src/clojure/tools/logging/impl.clj | clojure | Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution. By using this software in any fashion, you are
agreeing to be bound by the terms of this license. You must not
remove this notice, or any other, from this software.
| Copyright ( c ) . All rights reserved . The use
and distribution terms for this software are covered by the Eclipse
(ns ^{:author "Alex Taggart"
:doc "Protocols used to allow access to logging implementations.
This namespace only need be used by those providing logging
implementations to be consumed by the core api."}
clojure.tools.logging.impl
(:refer-clojure :exclude [name]))
(defprotocol Logger
"The protocol through which the core api will interact with an underlying logging
implementation. Implementations should at least support the six standard
logging levels if they wish to work from the level-specific macros."
(enabled? [logger level]
"Check if a particular level is enabled for the given Logger.")
(write! [logger level throwable message]
"Writes a log message to the given Logger."))
(defprotocol LoggerFactory
"The protocol through which the core api will obtain an instance satisfying Logger
as well as providing information about the particular implementation being used.
Implementations should be bound to *logger-factory* in order to be picked up by
this library."
(name [factory]
"Returns some text identifying the underlying implementation.")
(get-logger [factory logger-ns]
"Returns an implementation-specific Logger by namespace."))
(defn common-logging-factory
"Returns a Commons Logging-based implementation of the LoggerFactory protocol, or
nil if not available."
[]
(try
(when (Type/GetType "Common.Logging.LogManager, Common.Logging")
(eval
`(do
(extend Common.Logging.ILog
Logger
{:enabled?
(fn [^Common.Logging.ILog logger# level#]
(condp = level#
:trace (.IsTraceEnabled logger#)
:debug (.IsDebugEnabled logger#)
:info (.IsInfoEnabled logger#)
:warn (.IsWarnEnabled logger#)
:error (.IsErrorEnabled logger#)
:fatal (.IsFatalEnabled logger#)
(throw (ArgumentException. (str level#)))))
:write!
(fn [^Common.Logging.ILog logger# level# ^Exception e# msg#]
(let [^String msg# (str msg#)]
(if e#
(condp = level#
:trace (.Trace logger# msg# e#)
:debug (.Debug logger# msg# e#)
:info (.Info logger# msg# e#)
:warn (.Warn logger# msg# e#)
:error (.Error logger# msg# e#)
:fatal (.Fatal logger# msg# e#)
(throw (ArgumentException. (str level#))))
(condp = level#
:trace (.Trace logger# msg#)
:debug (.Debug logger# msg#)
:info (.Info logger# msg#)
:warn (.Warn logger# msg#)
:error (.Error logger# msg#)
:fatal (.Fatal logger# msg#)
(throw (ArgumentException. (str level#)))))))})
(reify LoggerFactory
(name [_#]
"Common.Logging")
(get-logger [_# logger-ns#]
(Common.Logging.LogManager/GetLogger ^String (str logger-ns#)))))))
(catch Exception e nil)))
(defn find-factory
"Returns the first non-nil value from common-logging-factory."
[]
(or
(common-logging-factory)
(comment
(throw
(Exception.
"Valid logging implementation could not be found.")))))
|
70e79b0beda9645a51d7449ea14151702263c68c87fffc114e5b263555da620f | sebastiaanvisser/clay | Clay.hs | module Clay
(
-- * Rendering stylesheets to CSS.
render
, renderWith
, putCss
, pretty
, compact
, renderSelector
* The @Css@ monad for collecting style rules .
, Css
, (?)
, (<?)
, (&)
, root
, pop
, (-:)
-- ** Comments
-- $comments
, commenting
-- * The selector language.
, Selector
, Refinement
-- ** Elements selectors.
, star
, element
, (**)
, (|>)
, (#)
, (|+)
, (|~)
-- ** Refining selectors.
, byId
, byClass
, pseudo
, func
-- ** Attribute based refining.
, attr
, (@=)
, (^=)
, ($=)
, (*=)
, (~=)
, (|=)
-- * Apply media queries.
-- $media
, query
, queryNot
, queryOnly
-- * Apply key-frame animation.
, keyframes
, keyframesFromTo
-- * Define font-faces.
, fontFace
-- * !important
, important
-- * Import other CSS files
, importUrl
-- * Pseudo elements and classes.
, module Clay.Pseudo
-- * HTML5 attribute and element names.
, module Clay.Attributes
, module Clay.Elements
-- * Commonly used value types.
, module Clay.Size
, module Clay.Color
, module Clay.Time
-- * Values shared between multiple properties.
, module Clay.Common
-- * Embedded style properties.
, module Clay.Background
, module Clay.Border
, module Clay.Box
, module Clay.Display
, module Clay.Dynamic
, module Clay.Flexbox
, module Clay.Font
, module Clay.FontFace
, module Clay.Geometry
, module Clay.Gradient
, module Clay.Grid
, module Clay.List
, module Clay.Text
, module Clay.Transform
, module Clay.Transition
, module Clay.Animation
, module Clay.Mask
, module Clay.Filter
-- * Writing your own properties.
, module Clay.Property
)
where
import Prelude ()
import Clay.Render
import Clay.Stylesheet
import Clay.Selector
import Clay.Property
import Clay.Pseudo hiding (default_, required, root, lang)
import Clay.Elements hiding (link, em)
import Clay.Attributes hiding
( content, class_, target, checked, disabled
, value, width, height, size, translate
, hidden, start
)
import Clay.Background
import Clay.Border
import Clay.Box
import Clay.Color
import Clay.Time
import Clay.Comments (commenting)
import Clay.Common
import Clay.Display hiding (table)
import Clay.Dynamic
import Clay.Flexbox hiding (flex, nowrap, wrap)
import Clay.Font hiding (menu, caption, small, icon)
import Clay.FontFace
import Clay.Geometry
import Clay.Gradient
import Clay.Grid
import Clay.List
import Clay.Size
import Clay.Text hiding (pre)
import Clay.Transform
import Clay.Transition
import Clay.Animation
import Clay.Mask hiding (clear)
import Clay.Filter hiding (url, opacity)
-- $media
--
Because a large part of the names export by " . Media " clash with names
-- export by other modules we don't re-export it here and recommend you to
-- import the module qualified.
-- $comments
--
-- It is occasionally useful to output comments in the generated css.
-- 'commenting' appends comments (surrounded by '@ /* @' and '@ */@') to the
values of the supplied ' ' as
--
-- > key: value /* comment */;
--
-- Placing the comments before the semicolon ensures they are obviously
-- grouped with the preceding value when rendered compactly.
--
-- Note that /every/ generated line in the generated content will feature the
-- comment.
--
-- An empty comment generates '@/* */@'.
| null | https://raw.githubusercontent.com/sebastiaanvisser/clay/16f55a5c6ab7fd98e39cedf852bd3400a02ac45f/src/Clay.hs | haskell | * Rendering stylesheets to CSS.
** Comments
$comments
* The selector language.
** Elements selectors.
** Refining selectors.
** Attribute based refining.
* Apply media queries.
$media
* Apply key-frame animation.
* Define font-faces.
* !important
* Import other CSS files
* Pseudo elements and classes.
* HTML5 attribute and element names.
* Commonly used value types.
* Values shared between multiple properties.
* Embedded style properties.
* Writing your own properties.
$media
export by other modules we don't re-export it here and recommend you to
import the module qualified.
$comments
It is occasionally useful to output comments in the generated css.
'commenting' appends comments (surrounded by '@ /* @' and '@ */@') to the
> key: value /* comment */;
Placing the comments before the semicolon ensures they are obviously
grouped with the preceding value when rendered compactly.
Note that /every/ generated line in the generated content will feature the
comment.
An empty comment generates '@/* */@'. | module Clay
(
render
, renderWith
, putCss
, pretty
, compact
, renderSelector
* The @Css@ monad for collecting style rules .
, Css
, (?)
, (<?)
, (&)
, root
, pop
, (-:)
, commenting
, Selector
, Refinement
, star
, element
, (**)
, (|>)
, (#)
, (|+)
, (|~)
, byId
, byClass
, pseudo
, func
, attr
, (@=)
, (^=)
, ($=)
, (*=)
, (~=)
, (|=)
, query
, queryNot
, queryOnly
, keyframes
, keyframesFromTo
, fontFace
, important
, importUrl
, module Clay.Pseudo
, module Clay.Attributes
, module Clay.Elements
, module Clay.Size
, module Clay.Color
, module Clay.Time
, module Clay.Common
, module Clay.Background
, module Clay.Border
, module Clay.Box
, module Clay.Display
, module Clay.Dynamic
, module Clay.Flexbox
, module Clay.Font
, module Clay.FontFace
, module Clay.Geometry
, module Clay.Gradient
, module Clay.Grid
, module Clay.List
, module Clay.Text
, module Clay.Transform
, module Clay.Transition
, module Clay.Animation
, module Clay.Mask
, module Clay.Filter
, module Clay.Property
)
where
import Prelude ()
import Clay.Render
import Clay.Stylesheet
import Clay.Selector
import Clay.Property
import Clay.Pseudo hiding (default_, required, root, lang)
import Clay.Elements hiding (link, em)
import Clay.Attributes hiding
( content, class_, target, checked, disabled
, value, width, height, size, translate
, hidden, start
)
import Clay.Background
import Clay.Border
import Clay.Box
import Clay.Color
import Clay.Time
import Clay.Comments (commenting)
import Clay.Common
import Clay.Display hiding (table)
import Clay.Dynamic
import Clay.Flexbox hiding (flex, nowrap, wrap)
import Clay.Font hiding (menu, caption, small, icon)
import Clay.FontFace
import Clay.Geometry
import Clay.Gradient
import Clay.Grid
import Clay.List
import Clay.Size
import Clay.Text hiding (pre)
import Clay.Transform
import Clay.Transition
import Clay.Animation
import Clay.Mask hiding (clear)
import Clay.Filter hiding (url, opacity)
Because a large part of the names export by " . Media " clash with names
values of the supplied ' ' as
|
e54439d2d044754db72384da15827e3c9ece62835d8a8d170b53089215cf1bec | rabbitmq/rabbitmq-federation | Elixir.RabbitMQ.CLI.Ctl.Commands.FederationStatusCommand.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('Elixir.RabbitMQ.CLI.Ctl.Commands.FederationStatusCommand').
-include("rabbit_federation.hrl").
-behaviour('Elixir.RabbitMQ.CLI.CommandBehaviour').
-export([
usage/0,
usage_additional/0,
usage_doc_guides/0,
flags/0,
validate/2,
merge_defaults/2,
banner/2,
run/2,
switches/0,
aliases/0,
output/2,
scopes/0,
formatter/0,
help_section/0,
description/0
]).
%%----------------------------------------------------------------------------
%% Callbacks
%%----------------------------------------------------------------------------
usage() ->
<<"federation_status [--only-down]">>.
usage_additional() ->
[
{<<"--only-down">>, <<"only display links that failed or are not currently connected">>}
].
usage_doc_guides() ->
[?FEDERATION_GUIDE_URL].
help_section() ->
{plugin, federation}.
description() ->
<<"Displays federation link status">>.
flags() ->
[].
validate(_,_) ->
ok.
formatter() ->
'Elixir.RabbitMQ.CLI.Formatters.Erlang'.
merge_defaults(A, Opts) ->
{A, maps:merge(#{only_down => false}, Opts)}.
banner(_, #{node := Node, only_down := true}) ->
erlang:iolist_to_binary([<<"Listing federation links which are down on node ">>,
atom_to_binary(Node, utf8), <<"...">>]);
banner(_, #{node := Node, only_down := false}) ->
erlang:iolist_to_binary([<<"Listing federation links on node ">>,
atom_to_binary(Node, utf8), <<"...">>]).
run(_Args, #{node := Node, only_down := OnlyDown}) ->
case rabbit_misc:rpc_call(Node, rabbit_federation_status, status, []) of
{badrpc, _} = Error ->
Error;
Status ->
{stream, filter(Status, OnlyDown)}
end.
switches() ->
[{only_down, boolean}].
aliases() ->
[].
output({stream, FederationStatus}, _) ->
Formatted = [begin
Timestamp = proplists:get_value(timestamp, St),
Map0 = maps:remove(timestamp, maps:from_list(St)),
Map1 = maps:merge(#{queue => <<>>,
exchange => <<>>,
upstream_queue => <<>>,
upstream_exchange => <<>>,
local_connection => <<>>,
error => <<>>}, Map0),
Map1#{last_changed => fmt_ts(Timestamp)}
end || St <- FederationStatus],
{stream, Formatted};
output(E, _Opts) ->
'Elixir.RabbitMQ.CLI.DefaultOutput':output(E).
scopes() ->
['ctl', 'diagnostics'].
%%----------------------------------------------------------------------------
%% Formatting
%%----------------------------------------------------------------------------
fmt_ts({{YY, MM, DD}, {Hour, Min, Sec}}) ->
erlang:list_to_binary(
io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",
[YY, MM, DD, Hour, Min, Sec])).
filter(Status, _OnlyDown = false) ->
Status;
filter(Status, _OnlyDown = true) ->
[St || St <- Status,
not lists:member(proplists:get_value(status, St), [running, starting])].
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-federation/960b8214487ae2495cd39afbbd3a2c4d9ea37985/src/Elixir.RabbitMQ.CLI.Ctl.Commands.FederationStatusCommand.erl | erlang |
----------------------------------------------------------------------------
Callbacks
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Formatting
---------------------------------------------------------------------------- | 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('Elixir.RabbitMQ.CLI.Ctl.Commands.FederationStatusCommand').
-include("rabbit_federation.hrl").
-behaviour('Elixir.RabbitMQ.CLI.CommandBehaviour').
-export([
usage/0,
usage_additional/0,
usage_doc_guides/0,
flags/0,
validate/2,
merge_defaults/2,
banner/2,
run/2,
switches/0,
aliases/0,
output/2,
scopes/0,
formatter/0,
help_section/0,
description/0
]).
usage() ->
<<"federation_status [--only-down]">>.
usage_additional() ->
[
{<<"--only-down">>, <<"only display links that failed or are not currently connected">>}
].
usage_doc_guides() ->
[?FEDERATION_GUIDE_URL].
help_section() ->
{plugin, federation}.
description() ->
<<"Displays federation link status">>.
flags() ->
[].
validate(_,_) ->
ok.
formatter() ->
'Elixir.RabbitMQ.CLI.Formatters.Erlang'.
merge_defaults(A, Opts) ->
{A, maps:merge(#{only_down => false}, Opts)}.
banner(_, #{node := Node, only_down := true}) ->
erlang:iolist_to_binary([<<"Listing federation links which are down on node ">>,
atom_to_binary(Node, utf8), <<"...">>]);
banner(_, #{node := Node, only_down := false}) ->
erlang:iolist_to_binary([<<"Listing federation links on node ">>,
atom_to_binary(Node, utf8), <<"...">>]).
run(_Args, #{node := Node, only_down := OnlyDown}) ->
case rabbit_misc:rpc_call(Node, rabbit_federation_status, status, []) of
{badrpc, _} = Error ->
Error;
Status ->
{stream, filter(Status, OnlyDown)}
end.
switches() ->
[{only_down, boolean}].
aliases() ->
[].
output({stream, FederationStatus}, _) ->
Formatted = [begin
Timestamp = proplists:get_value(timestamp, St),
Map0 = maps:remove(timestamp, maps:from_list(St)),
Map1 = maps:merge(#{queue => <<>>,
exchange => <<>>,
upstream_queue => <<>>,
upstream_exchange => <<>>,
local_connection => <<>>,
error => <<>>}, Map0),
Map1#{last_changed => fmt_ts(Timestamp)}
end || St <- FederationStatus],
{stream, Formatted};
output(E, _Opts) ->
'Elixir.RabbitMQ.CLI.DefaultOutput':output(E).
scopes() ->
['ctl', 'diagnostics'].
fmt_ts({{YY, MM, DD}, {Hour, Min, Sec}}) ->
erlang:list_to_binary(
io_lib:format("~4..0w-~2..0w-~2..0w ~2..0w:~2..0w:~2..0w",
[YY, MM, DD, Hour, Min, Sec])).
filter(Status, _OnlyDown = false) ->
Status;
filter(Status, _OnlyDown = true) ->
[St || St <- Status,
not lists:member(proplists:get_value(status, St), [running, starting])].
|
effb03839c24f43eff5d91200490dfb90c57381dc29afd5558475aa44ba717dd | audreyt/openafp | DXD.hs |
module OpenAFP.Records.AFP.DXD where
import OpenAFP.Types
import OpenAFP.Internals
data DXD = DXD {
dxd_Type :: !N3
,dxd_ :: !N3
,dxd :: !NStr
} deriving (Show, Typeable)
| null | https://raw.githubusercontent.com/audreyt/openafp/178e0dd427479ac7b8b461e05c263e52dd614b73/src/OpenAFP/Records/AFP/DXD.hs | haskell |
module OpenAFP.Records.AFP.DXD where
import OpenAFP.Types
import OpenAFP.Internals
data DXD = DXD {
dxd_Type :: !N3
,dxd_ :: !N3
,dxd :: !NStr
} deriving (Show, Typeable)
| |
fccfe9ebb97d233a2b01dcd0d68a06b5baa86574dec3466ec35b73c539abc8c6 | input-output-hk/marlowe-cardano | Sign.hs |
module Language.Marlowe.Runtime.App.Sign
( sign
) where
import Language.Marlowe.Runtime.Cardano.Api (fromCardanoTxId)
import Language.Marlowe.Runtime.ChainSync.Api (TxId)
import qualified Cardano.Api as C
( IsShelleyBasedEra
, PaymentExtendedKey
, PaymentKey
, ShelleyWitnessSigningKey(WitnessPaymentExtendedKey, WitnessPaymentKey)
, SigningKey
, Tx
, TxBody
, getTxId
, signShelleyTransaction
)
sign :: C.IsShelleyBasedEra era
=> C.TxBody era
-> [C.SigningKey C.PaymentKey]
-> [C.SigningKey C.PaymentExtendedKey]
-> (TxId, C.Tx era)
sign body paymentKeys paymentExtendedKeys =
let
tx =
C.signShelleyTransaction body
$ fmap C.WitnessPaymentKey paymentKeys
<> fmap C.WitnessPaymentExtendedKey paymentExtendedKeys
in
(fromCardanoTxId $ C.getTxId body, tx)
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/3c65414ea55ac58d12ea974fa40c4f0deb4cc0a6/marlowe-apps/src/Language/Marlowe/Runtime/App/Sign.hs | haskell |
module Language.Marlowe.Runtime.App.Sign
( sign
) where
import Language.Marlowe.Runtime.Cardano.Api (fromCardanoTxId)
import Language.Marlowe.Runtime.ChainSync.Api (TxId)
import qualified Cardano.Api as C
( IsShelleyBasedEra
, PaymentExtendedKey
, PaymentKey
, ShelleyWitnessSigningKey(WitnessPaymentExtendedKey, WitnessPaymentKey)
, SigningKey
, Tx
, TxBody
, getTxId
, signShelleyTransaction
)
sign :: C.IsShelleyBasedEra era
=> C.TxBody era
-> [C.SigningKey C.PaymentKey]
-> [C.SigningKey C.PaymentExtendedKey]
-> (TxId, C.Tx era)
sign body paymentKeys paymentExtendedKeys =
let
tx =
C.signShelleyTransaction body
$ fmap C.WitnessPaymentKey paymentKeys
<> fmap C.WitnessPaymentExtendedKey paymentExtendedKeys
in
(fromCardanoTxId $ C.getTxId body, tx)
| |
b7e8a99b4bc07bf68da2ca050958b244a328a6acda7dc6fbca8c5f380cd48bb0 | ocamllabs/ocaml-modular-implicits | arrayLabels.mli | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
(** Array operations. *)
external length : 'a array -> int = "%array_length"
(** Return the length (number of elements) of the given array. *)
external get : 'a array -> int -> 'a = "%array_safe_get"
* [ Array.get a n ] returns the element number [ n ] of array [ a ] .
The first element has number 0 .
The last element has number [ Array.length a - 1 ] .
You can also write [ a.(n ) ] instead of [ Array.get a n ] .
Raise [ Invalid_argument " index out of bounds " ]
if [ n ] is outside the range 0 to [ ( Array.length a - 1 ) ] .
The first element has number 0.
The last element has number [Array.length a - 1].
You can also write [a.(n)] instead of [Array.get a n].
Raise [Invalid_argument "index out of bounds"]
if [n] is outside the range 0 to [(Array.length a - 1)]. *)
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
* [ Array.set a n x ] modifies array [ a ] in place , replacing
element number [ n ] with [ x ] .
You can also write [ a.(n ) < - x ] instead of [ Array.set a n x ] .
Raise [ Invalid_argument " index out of bounds " ]
if [ n ] is outside the range 0 to [ Array.length a - 1 ] .
element number [n] with [x].
You can also write [a.(n) <- x] instead of [Array.set a n x].
Raise [Invalid_argument "index out of bounds"]
if [n] is outside the range 0 to [Array.length a - 1]. *)
external make : int -> 'a -> 'a array = "caml_make_vect"
* [ Array.make n x ] returns a fresh array of length [ n ] ,
initialized with [ x ] .
All the elements of this new array are initially
physically equal to [ x ] ( in the sense of the [= =] predicate ) .
Consequently , if [ x ] is mutable , it is shared among all elements
of the array , and modifying [ x ] through one of the array entries
will modify all other entries at the same time .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the value of [ x ] is a floating - point number , then the maximum
size is only [ / 2 ] .
initialized with [x].
All the elements of this new array are initially
physically equal to [x] (in the sense of the [==] predicate).
Consequently, if [x] is mutable, it is shared among all elements
of the array, and modifying [x] through one of the array entries
will modify all other entries at the same time.
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the value of [x] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2].*)
external create : int -> 'a -> 'a array = "caml_make_vect"
[@@ocaml.deprecated]
* @deprecated [ ArrayLabels.create ] is an alias for { ! ArrayLabels.make } .
val init : int -> f:(int -> 'a) -> 'a array
* [ Array.init n f ] returns a fresh array of length [ n ] ,
with element number [ i ] initialized to the result of [ f i ] .
In other terms , [ Array.init n f ] tabulates the results of [ f ]
applied to the integers [ 0 ] to [ n-1 ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the return type of [ f ] is [ float ] , then the maximum
size is only [ / 2 ] .
with element number [i] initialized to the result of [f i].
In other terms, [Array.init n f] tabulates the results of [f]
applied to the integers [0] to [n-1].
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the return type of [f] is [float], then the maximum
size is only [Sys.max_array_length / 2].*)
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
* [ Array.make_matrix dimx e ] returns a two - dimensional array
( an array of arrays ) with first dimension [ dimx ] and
second dimension [ dimy ] . All the elements of this new matrix
are initially physically equal to [ e ] .
The element ( [ x , y ] ) of a matrix [ m ] is accessed
with the notation [ m.(x).(y ) ] .
Raise [ Invalid_argument ] if [ dimx ] or [ dimy ] is negative or
greater than [ ] .
If the value of [ e ] is a floating - point number , then the maximum
size is only [ / 2 ] .
(an array of arrays) with first dimension [dimx] and
second dimension [dimy]. All the elements of this new matrix
are initially physically equal to [e].
The element ([x,y]) of a matrix [m] is accessed
with the notation [m.(x).(y)].
Raise [Invalid_argument] if [dimx] or [dimy] is negative or
greater than [Sys.max_array_length].
If the value of [e] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2]. *)
val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
[@@ocaml.deprecated]
* @deprecated [ ArrayLabels.create_matrix ] is an alias for
{ ! ArrayLabels.make_matrix } .
{!ArrayLabels.make_matrix}. *)
val append : 'a array -> 'a array -> 'a array
(** [Array.append v1 v2] returns a fresh array containing the
concatenation of the arrays [v1] and [v2]. *)
val concat : 'a array list -> 'a array
(** Same as [Array.append], but concatenates a list of arrays. *)
val sub : 'a array -> pos:int -> len:int -> 'a array
* [ Array.sub a start len ] returns a fresh array of length [ len ] ,
containing the elements number [ start ] to [ start + len - 1 ]
of array [ a ] .
Raise [ Invalid_argument " Array.sub " ] if [ start ] and [ len ] do not
designate a valid subarray of [ a ] ; that is , if
[ start < 0 ] , or [ len < 0 ] , or [ start + len > Array.length a ] .
containing the elements number [start] to [start + len - 1]
of array [a].
Raise [Invalid_argument "Array.sub"] if [start] and [len] do not
designate a valid subarray of [a]; that is, if
[start < 0], or [len < 0], or [start + len > Array.length a]. *)
val copy : 'a array -> 'a array
(** [Array.copy a] returns a copy of [a], that is, a fresh array
containing the same elements as [a]. *)
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
* [ Array.fill ] modifies the array [ a ] in place ,
storing [ x ] in elements number [ ofs ] to ] .
Raise [ Invalid_argument " Array.fill " ] if [ ofs ] and [ len ] do not
designate a valid subarray of [ a ] .
storing [x] in elements number [ofs] to [ofs + len - 1].
Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not
designate a valid subarray of [a]. *)
val blit :
src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int ->
unit
* [ Array.blit v1 o1 v2 o2 len ] copies [ len ] elements
from array [ v1 ] , starting at element number [ o1 ] , to array [ v2 ] ,
starting at element number [ o2 ] . It works correctly even if
[ v1 ] and [ v2 ] are the same array , and the source and
destination chunks overlap .
Raise [ Invalid_argument " Array.blit " ] if [ o1 ] and [ len ] do not
designate a valid subarray of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subarray of [ v2 ] .
from array [v1], starting at element number [o1], to array [v2],
starting at element number [o2]. It works correctly even if
[v1] and [v2] are the same array, and the source and
destination chunks overlap.
Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not
designate a valid subarray of [v1], or if [o2] and [len] do not
designate a valid subarray of [v2]. *)
val to_list : 'a array -> 'a list
(** [Array.to_list a] returns the list of all the elements of [a]. *)
val of_list : 'a list -> 'a array
(** [Array.of_list l] returns a fresh array containing the elements
of [l]. *)
val iter : f:('a -> unit) -> 'a array -> unit
* [ Array.iter f a ] applies function [ f ] in turn to all
the elements of [ a ] . It is equivalent to
[ f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) ; ( ) ] .
the elements of [a]. It is equivalent to
[f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *)
val map : f:('a -> 'b) -> 'a array -> 'b array
* [ Array.map f a ] applies function [ f ] to all the elements of [ a ] ,
and builds an array with the results returned by [ f ] :
[ [ | f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) | ] ] .
and builds an array with the results returned by [f]:
[[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *)
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
* Same as { ! ArrayLabels.iter } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
* Same as { ! ArrayLabels.map } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
* [ Array.fold_left f x a ] computes
[ f ( ... ( f ( f x ) ) a.(1 ) ) ... ) a.(n-1 ) ] ,
where [ n ] is the length of the array [ a ] .
[f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
where [n] is the length of the array [a]. *)
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
* [ Array.fold_right f a x ] computes
[ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) x ) ... ) ) ] ,
where [ n ] is the length of the array [ a ] .
[f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
where [n] is the length of the array [a]. *)
* { 6 Sorting }
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
* Sort an array in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see below for a
complete specification ) . For example , { ! Pervasives.compare } is
a suitable comparison function , provided there are no floating - point
NaN values in the data . After calling [ Array.sort ] , the
array is sorted in place in increasing order .
[ Array.sort ] is guaranteed to run in constant heap space
and ( at most ) logarithmic stack space .
The current implementation uses Heap Sort . It runs in constant
stack space .
Specification of the comparison function :
Let [ a ] be the array and [ cmp ] the comparison function . The following
must be true for all x , y , z in a :
- [ cmp x y ] > 0 if and only if [ cmp y x ] < 0
- if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0
When [ Array.sort ] returns , [ a ] contains the same elements as before ,
reordered in such a way that for all i and j valid indices of [ a ] :
- [ cmp a.(i ) ) ] > = 0 if and only if i > = j
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see below for a
complete specification). For example, {!Pervasives.compare} is
a suitable comparison function, provided there are no floating-point
NaN values in the data. After calling [Array.sort], the
array is sorted in place in increasing order.
[Array.sort] is guaranteed to run in constant heap space
and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant
stack space.
Specification of the comparison function:
Let [a] be the array and [cmp] the comparison function. The following
must be true for all x, y, z in a :
- [cmp x y] > 0 if and only if [cmp y x] < 0
- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
When [Array.sort] returns, [a] contains the same elements as before,
reordered in such a way that for all i and j valid indices of [a] :
- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
*)
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
* Same as { ! ArrayLabels.sort } , but the sorting algorithm is stable ( i.e.
elements that compare equal are kept in their original order ) and
not guaranteed to run in constant heap space .
The current implementation uses Merge Sort . It uses [ ]
words of heap space , where [ n ] is the length of the array .
It is usually faster than the current implementation of { ! ArrayLabels.sort } .
elements that compare equal are kept in their original order) and
not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses [n/2]
words of heap space, where [n] is the length of the array.
It is usually faster than the current implementation of {!ArrayLabels.sort}.
*)
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
(** Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster
on typical input.
*)
(**/**)
* { 6 Undocumented functions }
(* The following is for system use only. Do not call directly. *)
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/stdlib/arrayLabels.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* Array operations.
* Return the length (number of elements) of the given array.
* [Array.append v1 v2] returns a fresh array containing the
concatenation of the arrays [v1] and [v2].
* Same as [Array.append], but concatenates a list of arrays.
* [Array.copy a] returns a copy of [a], that is, a fresh array
containing the same elements as [a].
* [Array.to_list a] returns the list of all the elements of [a].
* [Array.of_list l] returns a fresh array containing the elements
of [l].
* Same as {!Array.sort} or {!Array.stable_sort}, whichever is faster
on typical input.
*/*
The following is for system use only. Do not call directly. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
external length : 'a array -> int = "%array_length"
external get : 'a array -> int -> 'a = "%array_safe_get"
* [ Array.get a n ] returns the element number [ n ] of array [ a ] .
The first element has number 0 .
The last element has number [ Array.length a - 1 ] .
You can also write [ a.(n ) ] instead of [ Array.get a n ] .
Raise [ Invalid_argument " index out of bounds " ]
if [ n ] is outside the range 0 to [ ( Array.length a - 1 ) ] .
The first element has number 0.
The last element has number [Array.length a - 1].
You can also write [a.(n)] instead of [Array.get a n].
Raise [Invalid_argument "index out of bounds"]
if [n] is outside the range 0 to [(Array.length a - 1)]. *)
external set : 'a array -> int -> 'a -> unit = "%array_safe_set"
* [ Array.set a n x ] modifies array [ a ] in place , replacing
element number [ n ] with [ x ] .
You can also write [ a.(n ) < - x ] instead of [ Array.set a n x ] .
Raise [ Invalid_argument " index out of bounds " ]
if [ n ] is outside the range 0 to [ Array.length a - 1 ] .
element number [n] with [x].
You can also write [a.(n) <- x] instead of [Array.set a n x].
Raise [Invalid_argument "index out of bounds"]
if [n] is outside the range 0 to [Array.length a - 1]. *)
external make : int -> 'a -> 'a array = "caml_make_vect"
* [ Array.make n x ] returns a fresh array of length [ n ] ,
initialized with [ x ] .
All the elements of this new array are initially
physically equal to [ x ] ( in the sense of the [= =] predicate ) .
Consequently , if [ x ] is mutable , it is shared among all elements
of the array , and modifying [ x ] through one of the array entries
will modify all other entries at the same time .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the value of [ x ] is a floating - point number , then the maximum
size is only [ / 2 ] .
initialized with [x].
All the elements of this new array are initially
physically equal to [x] (in the sense of the [==] predicate).
Consequently, if [x] is mutable, it is shared among all elements
of the array, and modifying [x] through one of the array entries
will modify all other entries at the same time.
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the value of [x] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2].*)
external create : int -> 'a -> 'a array = "caml_make_vect"
[@@ocaml.deprecated]
* @deprecated [ ArrayLabels.create ] is an alias for { ! ArrayLabels.make } .
val init : int -> f:(int -> 'a) -> 'a array
* [ Array.init n f ] returns a fresh array of length [ n ] ,
with element number [ i ] initialized to the result of [ f i ] .
In other terms , [ Array.init n f ] tabulates the results of [ f ]
applied to the integers [ 0 ] to [ n-1 ] .
Raise [ Invalid_argument ] if [ n < 0 ] or [ n > Sys.max_array_length ] .
If the return type of [ f ] is [ float ] , then the maximum
size is only [ / 2 ] .
with element number [i] initialized to the result of [f i].
In other terms, [Array.init n f] tabulates the results of [f]
applied to the integers [0] to [n-1].
Raise [Invalid_argument] if [n < 0] or [n > Sys.max_array_length].
If the return type of [f] is [float], then the maximum
size is only [Sys.max_array_length / 2].*)
val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
* [ Array.make_matrix dimx e ] returns a two - dimensional array
( an array of arrays ) with first dimension [ dimx ] and
second dimension [ dimy ] . All the elements of this new matrix
are initially physically equal to [ e ] .
The element ( [ x , y ] ) of a matrix [ m ] is accessed
with the notation [ m.(x).(y ) ] .
Raise [ Invalid_argument ] if [ dimx ] or [ dimy ] is negative or
greater than [ ] .
If the value of [ e ] is a floating - point number , then the maximum
size is only [ / 2 ] .
(an array of arrays) with first dimension [dimx] and
second dimension [dimy]. All the elements of this new matrix
are initially physically equal to [e].
The element ([x,y]) of a matrix [m] is accessed
with the notation [m.(x).(y)].
Raise [Invalid_argument] if [dimx] or [dimy] is negative or
greater than [Sys.max_array_length].
If the value of [e] is a floating-point number, then the maximum
size is only [Sys.max_array_length / 2]. *)
val create_matrix : dimx:int -> dimy:int -> 'a -> 'a array array
[@@ocaml.deprecated]
* @deprecated [ ArrayLabels.create_matrix ] is an alias for
{ ! ArrayLabels.make_matrix } .
{!ArrayLabels.make_matrix}. *)
val append : 'a array -> 'a array -> 'a array
val concat : 'a array list -> 'a array
val sub : 'a array -> pos:int -> len:int -> 'a array
* [ Array.sub a start len ] returns a fresh array of length [ len ] ,
containing the elements number [ start ] to [ start + len - 1 ]
of array [ a ] .
Raise [ Invalid_argument " Array.sub " ] if [ start ] and [ len ] do not
designate a valid subarray of [ a ] ; that is , if
[ start < 0 ] , or [ len < 0 ] , or [ start + len > Array.length a ] .
containing the elements number [start] to [start + len - 1]
of array [a].
Raise [Invalid_argument "Array.sub"] if [start] and [len] do not
designate a valid subarray of [a]; that is, if
[start < 0], or [len < 0], or [start + len > Array.length a]. *)
val copy : 'a array -> 'a array
val fill : 'a array -> pos:int -> len:int -> 'a -> unit
* [ Array.fill ] modifies the array [ a ] in place ,
storing [ x ] in elements number [ ofs ] to ] .
Raise [ Invalid_argument " Array.fill " ] if [ ofs ] and [ len ] do not
designate a valid subarray of [ a ] .
storing [x] in elements number [ofs] to [ofs + len - 1].
Raise [Invalid_argument "Array.fill"] if [ofs] and [len] do not
designate a valid subarray of [a]. *)
val blit :
src:'a array -> src_pos:int -> dst:'a array -> dst_pos:int -> len:int ->
unit
* [ Array.blit v1 o1 v2 o2 len ] copies [ len ] elements
from array [ v1 ] , starting at element number [ o1 ] , to array [ v2 ] ,
starting at element number [ o2 ] . It works correctly even if
[ v1 ] and [ v2 ] are the same array , and the source and
destination chunks overlap .
Raise [ Invalid_argument " Array.blit " ] if [ o1 ] and [ len ] do not
designate a valid subarray of [ v1 ] , or if [ o2 ] and [ len ] do not
designate a valid subarray of [ v2 ] .
from array [v1], starting at element number [o1], to array [v2],
starting at element number [o2]. It works correctly even if
[v1] and [v2] are the same array, and the source and
destination chunks overlap.
Raise [Invalid_argument "Array.blit"] if [o1] and [len] do not
designate a valid subarray of [v1], or if [o2] and [len] do not
designate a valid subarray of [v2]. *)
val to_list : 'a array -> 'a list
val of_list : 'a list -> 'a array
val iter : f:('a -> unit) -> 'a array -> unit
* [ Array.iter f a ] applies function [ f ] in turn to all
the elements of [ a ] . It is equivalent to
[ f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) ; ( ) ] .
the elements of [a]. It is equivalent to
[f a.(0); f a.(1); ...; f a.(Array.length a - 1); ()]. *)
val map : f:('a -> 'b) -> 'a array -> 'b array
* [ Array.map f a ] applies function [ f ] to all the elements of [ a ] ,
and builds an array with the results returned by [ f ] :
[ [ | f ) ; f a.(1 ) ; ... ; f a.(Array.length a - 1 ) | ] ] .
and builds an array with the results returned by [f]:
[[| f a.(0); f a.(1); ...; f a.(Array.length a - 1) |]]. *)
val iteri : f:(int -> 'a -> unit) -> 'a array -> unit
* Same as { ! ArrayLabels.iter } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array
* Same as { ! ArrayLabels.map } , but the
function is applied to the index of the element as first argument ,
and the element itself as second argument .
function is applied to the index of the element as first argument,
and the element itself as second argument. *)
val fold_left : f:('a -> 'b -> 'a) -> init:'a -> 'b array -> 'a
* [ Array.fold_left f x a ] computes
[ f ( ... ( f ( f x ) ) a.(1 ) ) ... ) a.(n-1 ) ] ,
where [ n ] is the length of the array [ a ] .
[f (... (f (f x a.(0)) a.(1)) ...) a.(n-1)],
where [n] is the length of the array [a]. *)
val fold_right : f:('b -> 'a -> 'a) -> 'b array -> init:'a -> 'a
* [ Array.fold_right f a x ] computes
[ f ) ( f a.(1 ) ( ... ( f a.(n-1 ) x ) ... ) ) ] ,
where [ n ] is the length of the array [ a ] .
[f a.(0) (f a.(1) ( ... (f a.(n-1) x) ...))],
where [n] is the length of the array [a]. *)
* { 6 Sorting }
val sort : cmp:('a -> 'a -> int) -> 'a array -> unit
* Sort an array in increasing order according to a comparison
function . The comparison function must return 0 if its arguments
compare as equal , a positive integer if the first is greater ,
and a negative integer if the first is smaller ( see below for a
complete specification ) . For example , { ! Pervasives.compare } is
a suitable comparison function , provided there are no floating - point
NaN values in the data . After calling [ Array.sort ] , the
array is sorted in place in increasing order .
[ Array.sort ] is guaranteed to run in constant heap space
and ( at most ) logarithmic stack space .
The current implementation uses Heap Sort . It runs in constant
stack space .
Specification of the comparison function :
Let [ a ] be the array and [ cmp ] the comparison function . The following
must be true for all x , y , z in a :
- [ cmp x y ] > 0 if and only if [ cmp y x ] < 0
- if [ cmp x y ] > = 0 and [ cmp y z ] > = 0 then [ cmp x z ] > = 0
When [ Array.sort ] returns , [ a ] contains the same elements as before ,
reordered in such a way that for all i and j valid indices of [ a ] :
- [ cmp a.(i ) ) ] > = 0 if and only if i > = j
function. The comparison function must return 0 if its arguments
compare as equal, a positive integer if the first is greater,
and a negative integer if the first is smaller (see below for a
complete specification). For example, {!Pervasives.compare} is
a suitable comparison function, provided there are no floating-point
NaN values in the data. After calling [Array.sort], the
array is sorted in place in increasing order.
[Array.sort] is guaranteed to run in constant heap space
and (at most) logarithmic stack space.
The current implementation uses Heap Sort. It runs in constant
stack space.
Specification of the comparison function:
Let [a] be the array and [cmp] the comparison function. The following
must be true for all x, y, z in a :
- [cmp x y] > 0 if and only if [cmp y x] < 0
- if [cmp x y] >= 0 and [cmp y z] >= 0 then [cmp x z] >= 0
When [Array.sort] returns, [a] contains the same elements as before,
reordered in such a way that for all i and j valid indices of [a] :
- [cmp a.(i) a.(j)] >= 0 if and only if i >= j
*)
val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
* Same as { ! ArrayLabels.sort } , but the sorting algorithm is stable ( i.e.
elements that compare equal are kept in their original order ) and
not guaranteed to run in constant heap space .
The current implementation uses Merge Sort . It uses [ ]
words of heap space , where [ n ] is the length of the array .
It is usually faster than the current implementation of { ! ArrayLabels.sort } .
elements that compare equal are kept in their original order) and
not guaranteed to run in constant heap space.
The current implementation uses Merge Sort. It uses [n/2]
words of heap space, where [n] is the length of the array.
It is usually faster than the current implementation of {!ArrayLabels.sort}.
*)
val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit
* { 6 Undocumented functions }
external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get"
external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
|
4d75caa17b63b4ef6ff0395fc6606542fdbb77eb990b861f09e0b4f15c0b2a69 | petro-rudenko/cdr-analysis | topology.clj | (ns com.cybervisiontech.cdr.realtime.topology
(:require [backtype.storm [clojure
:refer [topology spout-spec bolt-spec]]])
(:require [com.cybervisiontech.cdr.realtime [spouts :refer :all] [bolts :refer :all]] :verbose)
(:gen-class))
(defn mk-topology []
(topology
{"1" (spout-spec cdr-generator :p 4)}
{"2" (bolt-spec {"1" ["calling-party"]} ;;This bolt would make aggregation on calling party
dummy-hdfs-passer :p 10)}))
| null | https://raw.githubusercontent.com/petro-rudenko/cdr-analysis/5e583b0cca30c4faf474507998bd7a9a0380f569/src/com/cybervisiontech/cdr/realtime/topology.clj | clojure | This bolt would make aggregation on calling party | (ns com.cybervisiontech.cdr.realtime.topology
(:require [backtype.storm [clojure
:refer [topology spout-spec bolt-spec]]])
(:require [com.cybervisiontech.cdr.realtime [spouts :refer :all] [bolts :refer :all]] :verbose)
(:gen-class))
(defn mk-topology []
(topology
{"1" (spout-spec cdr-generator :p 4)}
dummy-hdfs-passer :p 10)}))
|
99c265a94e2e13877afb194e708f3fc798a7f6bc73742e332d40662e1fc502a8 | mindreframer/clojure-stuff | project.clj | (defproject korma "0.4.1-SNAPSHOT"
:description "Tasty SQL for Clojure"
:url ""
:mailing-list {:name "Korma Google Group"
:subscribe ""}
:codox {:exclude [korma.sql.engine
korma.sql.fns
korma.sql.utils]
:src-dir-uri ""
:src-linenum-anchor-prefix "L"}
:dependencies [[org.clojure/clojure "1.6.0"]
[c3p0/c3p0 "0.9.1.2"]
[org.clojure/java.jdbc "0.3.5"]]
:min-lein-version "2.0.0"
:profiles {:dev {:dependencies [[gui-diff "0.4.0"]
[postgresql "9.0-801.jdbc4"]
[slamhound "1.3.1"]
[criterium "0.3.1"]]
:plugins [[codox "0.6.4"]
[jonase/eastwood "0.0.2"]
[lein-localrepo "0.4.1"]]}
:test {:dependencies [[mysql/mysql-connector-java "5.1.22"]
[com.h2database/h2 "1.3.164"]
[criterium "0.3.1"]]}
:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]}
:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]}
:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}}
:aliases {"run-tests" ["with-profile" "1.3:1.4:1.5:1.6" "test"]
"slamhound" ["run" "-m" "slam.hound"]}
:jvm-opts ["-Dline.separator=\n"])
| null | https://raw.githubusercontent.com/mindreframer/clojure-stuff/1e761b2dacbbfbeec6f20530f136767e788e0fe3/github.com/korma/Korma/project.clj | clojure | (defproject korma "0.4.1-SNAPSHOT"
:description "Tasty SQL for Clojure"
:url ""
:mailing-list {:name "Korma Google Group"
:subscribe ""}
:codox {:exclude [korma.sql.engine
korma.sql.fns
korma.sql.utils]
:src-dir-uri ""
:src-linenum-anchor-prefix "L"}
:dependencies [[org.clojure/clojure "1.6.0"]
[c3p0/c3p0 "0.9.1.2"]
[org.clojure/java.jdbc "0.3.5"]]
:min-lein-version "2.0.0"
:profiles {:dev {:dependencies [[gui-diff "0.4.0"]
[postgresql "9.0-801.jdbc4"]
[slamhound "1.3.1"]
[criterium "0.3.1"]]
:plugins [[codox "0.6.4"]
[jonase/eastwood "0.0.2"]
[lein-localrepo "0.4.1"]]}
:test {:dependencies [[mysql/mysql-connector-java "5.1.22"]
[com.h2database/h2 "1.3.164"]
[criterium "0.3.1"]]}
:1.3 {:dependencies [[org.clojure/clojure "1.3.0"]]}
:1.4 {:dependencies [[org.clojure/clojure "1.4.0"]]}
:1.5 {:dependencies [[org.clojure/clojure "1.5.1"]]}
:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]}}
:aliases {"run-tests" ["with-profile" "1.3:1.4:1.5:1.6" "test"]
"slamhound" ["run" "-m" "slam.hound"]}
:jvm-opts ["-Dline.separator=\n"])
| |
1052ff271ee7810011d645fd43a9b95b9e923223bb4ab52ffb713473adb93414 | google/lisp-koans | asserts.lisp | Copyright 2013 Google Inc.
;;;
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.
╭ ╮ ╭ ╮ ///////
╭ ┳ ┳ ╮ ╭ ┳ ┳ ┳ ╮ ╭ ╮
╭ ╮ ╰ ╯ ┫ ╭ ╮ ╭ ╮ ╭ ╮ ┫ ━ ━ ┫
╰ ┫ ┣ ╰ ╯ ┃ ┃ ╭ ╮ ┫ ╰ ╭ ╮ ┃ ┃
;;; ╰━┻┻━━┫╭━╯/╰╯╰┻━━┻╯╰┻╯╰┻━━╯
//////
;;; ╰╯//////
;;; Welcome to the Lisp Koans.
May the code stored here influence your enlightenment as a programmer .
;;; In order to progress, fill in the blanks, denoted via ____ in source code.
;;; Sometimes, you will be asked to provide values that are equal to something.
(define-test fill-in-the-blanks
(assert-equal ____ 2)
(assert-equal ____ 3.14)
(assert-equal ____ "Hello World"))
;;; Sometimes, you will be asked to say whether something is true or false,
In , the canonical values for truth and falsehood are T and NIL .
(define-test assert-true
(assert-true ____))
(define-test assert-false
(assert-false ____))
(define-test true-or-false
(true-or-false? ____ (= 34 34))
(true-or-false? ____ (= 19 78)))
;;; Since T and NIL are symbols, you can type them in lowercase or uppercase;
by default , Common Lisp will automatically upcase them upon reading .
(define-test upcase-downcase
;; Try inserting a lowercase t here.
(assert-equal ____ T)
;; Try inserting an uppercase NIL here.
(assert-equal ____ nil))
;;; Sometimes, you will be asked to provide a part of an expression that must be
;;; either true or false.
(define-test a-true-assertion
(assert-true (= ____ (+ 2 2))))
(define-test a-false-assertion
(assert-false (= ____ (+ 2 2))))
| null | https://raw.githubusercontent.com/google/lisp-koans/df5e58dc88429ef0ff202d0b45c21ce572144ba8/koans/asserts.lisp | lisp |
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.
╰━┻┻━━┫╭━╯/╰╯╰┻━━┻╯╰┻╯╰┻━━╯
╰╯//////
Welcome to the Lisp Koans.
In order to progress, fill in the blanks, denoted via ____ in source code.
Sometimes, you will be asked to provide values that are equal to something.
Sometimes, you will be asked to say whether something is true or false,
Since T and NIL are symbols, you can type them in lowercase or uppercase;
Try inserting a lowercase t here.
Try inserting an uppercase NIL here.
Sometimes, you will be asked to provide a part of an expression that must be
either true or false. | Copyright 2013 Google Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
╭ ╮ ╭ ╮ ///////
╭ ┳ ┳ ╮ ╭ ┳ ┳ ┳ ╮ ╭ ╮
╭ ╮ ╰ ╯ ┫ ╭ ╮ ╭ ╮ ╭ ╮ ┫ ━ ━ ┫
╰ ┫ ┣ ╰ ╯ ┃ ┃ ╭ ╮ ┫ ╰ ╭ ╮ ┃ ┃
//////
May the code stored here influence your enlightenment as a programmer .
(define-test fill-in-the-blanks
(assert-equal ____ 2)
(assert-equal ____ 3.14)
(assert-equal ____ "Hello World"))
In , the canonical values for truth and falsehood are T and NIL .
(define-test assert-true
(assert-true ____))
(define-test assert-false
(assert-false ____))
(define-test true-or-false
(true-or-false? ____ (= 34 34))
(true-or-false? ____ (= 19 78)))
by default , Common Lisp will automatically upcase them upon reading .
(define-test upcase-downcase
(assert-equal ____ T)
(assert-equal ____ nil))
(define-test a-true-assertion
(assert-true (= ____ (+ 2 2))))
(define-test a-false-assertion
(assert-false (= ____ (+ 2 2))))
|
f8cb18c9f82febccbacc4a8588807217385337c60bedd46ee7dd2a838e2a40a6 | mirage/ocaml-openflow | ofcontroller.ml |
* Copyright ( c ) 2005 - 2011 < >
*
* Permission to use , copy , modify , and 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 .
* Copyright (c) 2005-2011 Charalampos Rotsos <>
*
* Permission to use, copy, modify, and 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.
*)
open Lwt
open Net
open Ofsocket
let sp = Printf.sprintf
let cp = OS.Console.log
module OP = Ofpacket
module Event = struct
type t =
| DATAPATH_JOIN | DATAPATH_LEAVE | PACKET_IN | FLOW_REMOVED
| FLOW_STATS_REPLY | AGGR_FLOW_STATS_REPLY | DESC_STATS_REPLY
| PORT_STATS_REPLY | TABLE_STATS_REPLY | PORT_STATUS_CHANGE
type e =
| Datapath_join of OP.datapath_id * OP.Port.phy list
| Datapath_leave of OP.datapath_id
| Packet_in of OP.Port.t * OP.Packet_in.reason *
int32 * Cstruct.t * OP.datapath_id
| Flow_removed of
OP.Match.t * OP.Flow_removed.reason * int32 * int32 * int64 * int64
* OP.datapath_id
| Flow_stats_reply of int32 * bool * OP.Flow.stats list * OP.datapath_id
| Aggr_flow_stats_reply of int32 * int64 * int64 * int32 * OP.datapath_id
| Port_stats_reply of int32 * bool * OP.Port.stats list * OP.datapath_id
| Table_stats_reply of int32 * bool * OP.Stats.table list * OP.datapath_id
| Desc_stats_reply of
string * string * string * string * string
* OP.datapath_id
| Port_status of OP.Port.reason * OP.Port.phy * OP.datapath_id
let string_of_event = function
| Datapath_join (dpid, _) -> sp "Datapath_join: dpid:0x%012Lx" dpid
| Datapath_leave dpid -> sp "Datapath_leave: dpid:0x%012Lx" dpid
| Packet_in (port, r, buffer_id, bs, dpid) ->
(sp "Packet_in: port:%s reason:%s dpid:0x%012Lx buffer_id:%ld"
(OP.Port.string_of_port port)
(OP.Packet_in.string_of_reason r)
dpid buffer_id )
| Flow_removed (flow, reason, duration_sec, duration_usec,
packet_count, byte_count, dpid)
-> (sp "Flow_removed: flow: %s reason:%s duration:%ld.%ld packets:%s \
bytes:%s dpid:0x%012Lx"
(OP.Match.match_to_string flow)
(OP.Flow_removed.string_of_reason reason)
duration_sec duration_usec
(Int64.to_string packet_count) (Int64.to_string byte_count) dpid)
| Flow_stats_reply(xid, more, flows, dpid)
-> (sp "Flow stats reply: dpid:%012Lx more:%s flows:%d xid:%ld"
dpid (string_of_bool more) (List.length flows) xid)
| Aggr_flow_stats_reply(xid, packet_count, byte_count, flow_count, dpid)
-> (sp "aggr flow stats reply: dpid:%012Lx packets:%Ld bytes:%Ld \
flows:%ld xid:%ld"
dpid packet_count byte_count flow_count xid)
| Port_stats_reply (xid, _, ports, dpid)
-> (sp "port stats reply: dpid:%012Lx ports:%d xid%ld"
dpid (List.length ports) xid)
| Table_stats_reply (xid, _, tables, dpid)
-> (sp "table stats reply: dpid:%012Lx tables:%d xid%ld"
dpid (List.length tables) xid)
| Desc_stats_reply (mfr_desc, hw_desc, sw_desc, serial_num, dp_desc, dpid)
-> (sp "table stats reply: dpid:%012Lx mfr_desc:%s hw_desc:%s \
sw_desc:%s serial_num:%s dp_desc:%s"
dpid mfr_desc hw_desc sw_desc serial_num dp_desc)
| Port_status (r, ph, dpid)
-> (sp "post stats: port:%s status:%s dpid:%012Lx" ph.OP.Port.name
(OP.Port.reason_to_string r) dpid)
end
type t = {
mutable dp_db: (OP.datapath_id, conn_state) Hashtbl.t;
mutable datapath_join_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable datapath_leave_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable packet_in_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable flow_removed_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable flow_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable aggr_flow_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable desc_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable port_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable table_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable port_status_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
verbose : bool;
}
let register_cb controller e cb =
Event.(
match e with
| DATAPATH_JOIN
-> controller.datapath_join_cb <- controller.datapath_join_cb @ [cb]
| DATAPATH_LEAVE
-> controller.datapath_leave_cb <- controller.datapath_leave_cb @ [cb]
| PACKET_IN
-> controller.packet_in_cb <- controller.packet_in_cb @ [cb]
| FLOW_REMOVED
-> controller.flow_removed_cb <- controller.flow_removed_cb @ [cb]
| FLOW_STATS_REPLY
-> (controller.flow_stats_reply_cb
<- controller.flow_stats_reply_cb @ [cb]
)
| AGGR_FLOW_STATS_REPLY
-> (controller.aggr_flow_stats_reply_cb
<- controller.aggr_flow_stats_reply_cb @ [cb]
)
| DESC_STATS_REPLY
-> (controller.desc_stats_reply_cb
<- controller.desc_stats_reply_cb @ [cb]
)
| PORT_STATS_REPLY
-> (controller.port_stats_reply_cb
<- controller.port_stats_reply_cb @ [cb]
)
| TABLE_STATS_REPLY
-> (controller.table_stats_reply_cb
<- controller.table_stats_reply_cb @ [cb])
| PORT_STATUS_CHANGE
-> controller.port_status_cb <- controller.port_status_cb @ [cb]
)
let process_of_packet state conn ofp =
let _ = if state.verbose then cp (sp "[controller] rcv: %s\n%!" (OP.to_string ofp)) in
OP.(
match ofp with
| Hello (h) -> (* Reply to HELLO with a HELLO and a feature request *)
lwt _ = send_packet conn (OP.Hello (h)) in
let h = OP.Header.create OP.Header.FEATURES_REQ OP.Header.get_len in
send_packet conn (OP.Features_req (h) )
| Echo_req h -> (* Reply to ECHO requests *)
send_packet conn (OP.Echo_resp OP.Header.(create ~xid:h.xid ECHO_RESP get_len))
| Echo_resp h -> return () (* At the moment ignore echo responses *)
| Features_resp (h, sfs) -> begin (* Generate a datapath join event *)
let open OP.Switch in
let _ = conn.dpid <- sfs.datapath_id in
let evt = Event.Datapath_join (sfs.datapath_id, sfs.ports) in
let _ =
if (Hashtbl.mem state.dp_db sfs.datapath_id) then
cp (sp "[controller] Deleting old state for %Lx\n%!" conn.dpid)
in
let _ = Hashtbl.replace state.dp_db sfs.datapath_id conn in
Lwt_list.iter_p (fun cb -> cb state sfs.datapath_id evt)
state.datapath_join_cb
end
| OP.Packet_in (h, p) -> begin (* Generate a packet_in event *)
let open OP.Packet_in in
let evt =
Event.Packet_in (p.in_port, p.reason, p.buffer_id, p.data, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.packet_in_cb
end
| OP.Flow_removed (h, p) ->
let open OP.Flow_removed in
let evt = Event.Flow_removed (
p.of_match, p.reason, p.duration_sec, p.duration_nsec,
p.packet_count, p.byte_count, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.flow_removed_cb
| Stats_resp(h, resp) -> begin
match resp with
| OP.Stats.Flow_resp(resp_h, flows) -> begin
let evt = Event.Flow_stats_reply(
h.Header.xid, resp_h.OP.Stats.more, flows, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.flow_stats_reply_cb
end
| OP.Stats.Aggregate_resp(resp_h, aggr) -> begin
let evt = Event.Aggr_flow_stats_reply(
h.Header.xid, aggr.OP.Stats.packet_count,
aggr.OP.Stats.byte_count, aggr.OP.Stats.flow_count, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.aggr_flow_stats_reply_cb
end
| OP.Stats.Desc_resp (resp_h, aggr) -> begin
let evt = Event.Desc_stats_reply(
aggr.OP.Stats.imfr_desc, aggr.OP.Stats.hw_desc,
aggr.OP.Stats.sw_desc, aggr.OP.Stats.serial_num,
aggr.OP.Stats.dp_desc, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.desc_stats_reply_cb
end
| OP.Stats.Port_resp (resp_h, ports) -> begin
let evt =
Event.Port_stats_reply(h.Header.xid, resp_h.OP.Stats.more,
ports, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.port_stats_reply_cb
end
| OP.Stats.Table_resp (resp_h, tables) -> begin
let evt =
Event.Table_stats_reply(h.Header.xid, resp_h.OP.Stats.more,
tables, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.table_stats_reply_cb
end
| _ -> return (cp "[controller] unsupported stats response ")
end
| Port_status(h, st) -> begin
let evt = Event.Port_status (st.OP.Port.reason, st.OP.Port.desc, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.port_status_cb
end
| ofp -> return (cp (sp "[controller] Unsupported %s" (OP.to_string ofp)))
)
let send_of_data controller dpid bits =
Ofsocket.send_data_raw (Hashtbl.find controller.dp_db dpid ) bits
let send_data controller dpid ofp =
Ofsocket.send_packet (Hashtbl.find controller.dp_db dpid ) ofp
let controller_run st conn =
lwt _ =
try_lwt
while_lwt true do
read_packet conn >>= process_of_packet st conn
done
with
| Nettypes.Closed -> return (cp "[controller] switch disconnected\n%!")
| OP.Unparsed(m, bs)
| OP.Unparsable(m, bs) ->
let _ = cp (sp "# unparsed! m=%s" m) in
return (Cstruct.hexdump bs)
| exn -> return (cp (sp "[controller] ERROR:%s\n%!" (Printexc.to_string exn)))
in
if (conn.dpid > 0L) then
let evt = Event.Datapath_leave (conn.dpid) in
lwt _ = Lwt_list.iter_p (fun cb -> cb st conn.dpid evt)
st.datapath_leave_cb in
let _ = Hashtbl.remove st.dp_db conn.dpid in
return ()
else
return ()
let socket_controller st (remote_addr, remote_port) t =
let rs = Ipaddr.V4.to_string remote_addr in
let _ = cp (sp "[controller]+ Controller %s:%d\n%!" rs remote_port) in
let conn = init_socket_conn_state t in
controller_run st conn
let init_controller ?(verbose=false) init =
let t = { verbose;
dp_db = Hashtbl.create 0;
datapath_join_cb = [];
datapath_leave_cb = [];
packet_in_cb = [];
flow_removed_cb = [];
flow_stats_reply_cb = [];
aggr_flow_stats_reply_cb = [];
desc_stats_reply_cb = [];
port_stats_reply_cb = [];
table_stats_reply_cb = [];
port_status_cb = []; } in
let _ = init t in
t
let listen mgr ?(verbose=false) loc init =
let st = init_controller ~verbose init in
(Channel.listen mgr (`TCPv4 (loc, (socket_controller st) )))
let connect mgr ?(verbose=false) loc init =
let st = init_controller ~verbose init in
Net.Channel.connect mgr (`TCPv4 (None, loc,
(socket_controller st loc) ))
let local_connect st conn = controller_run st conn
| null | https://raw.githubusercontent.com/mirage/ocaml-openflow/dcda113745e8edc61b5508eb8ac2d1e864e1a2df/lib/ofcontroller.ml | ocaml | Reply to HELLO with a HELLO and a feature request
Reply to ECHO requests
At the moment ignore echo responses
Generate a datapath join event
Generate a packet_in event |
* Copyright ( c ) 2005 - 2011 < >
*
* Permission to use , copy , modify , and 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 .
* Copyright (c) 2005-2011 Charalampos Rotsos <>
*
* Permission to use, copy, modify, and 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.
*)
open Lwt
open Net
open Ofsocket
let sp = Printf.sprintf
let cp = OS.Console.log
module OP = Ofpacket
module Event = struct
type t =
| DATAPATH_JOIN | DATAPATH_LEAVE | PACKET_IN | FLOW_REMOVED
| FLOW_STATS_REPLY | AGGR_FLOW_STATS_REPLY | DESC_STATS_REPLY
| PORT_STATS_REPLY | TABLE_STATS_REPLY | PORT_STATUS_CHANGE
type e =
| Datapath_join of OP.datapath_id * OP.Port.phy list
| Datapath_leave of OP.datapath_id
| Packet_in of OP.Port.t * OP.Packet_in.reason *
int32 * Cstruct.t * OP.datapath_id
| Flow_removed of
OP.Match.t * OP.Flow_removed.reason * int32 * int32 * int64 * int64
* OP.datapath_id
| Flow_stats_reply of int32 * bool * OP.Flow.stats list * OP.datapath_id
| Aggr_flow_stats_reply of int32 * int64 * int64 * int32 * OP.datapath_id
| Port_stats_reply of int32 * bool * OP.Port.stats list * OP.datapath_id
| Table_stats_reply of int32 * bool * OP.Stats.table list * OP.datapath_id
| Desc_stats_reply of
string * string * string * string * string
* OP.datapath_id
| Port_status of OP.Port.reason * OP.Port.phy * OP.datapath_id
let string_of_event = function
| Datapath_join (dpid, _) -> sp "Datapath_join: dpid:0x%012Lx" dpid
| Datapath_leave dpid -> sp "Datapath_leave: dpid:0x%012Lx" dpid
| Packet_in (port, r, buffer_id, bs, dpid) ->
(sp "Packet_in: port:%s reason:%s dpid:0x%012Lx buffer_id:%ld"
(OP.Port.string_of_port port)
(OP.Packet_in.string_of_reason r)
dpid buffer_id )
| Flow_removed (flow, reason, duration_sec, duration_usec,
packet_count, byte_count, dpid)
-> (sp "Flow_removed: flow: %s reason:%s duration:%ld.%ld packets:%s \
bytes:%s dpid:0x%012Lx"
(OP.Match.match_to_string flow)
(OP.Flow_removed.string_of_reason reason)
duration_sec duration_usec
(Int64.to_string packet_count) (Int64.to_string byte_count) dpid)
| Flow_stats_reply(xid, more, flows, dpid)
-> (sp "Flow stats reply: dpid:%012Lx more:%s flows:%d xid:%ld"
dpid (string_of_bool more) (List.length flows) xid)
| Aggr_flow_stats_reply(xid, packet_count, byte_count, flow_count, dpid)
-> (sp "aggr flow stats reply: dpid:%012Lx packets:%Ld bytes:%Ld \
flows:%ld xid:%ld"
dpid packet_count byte_count flow_count xid)
| Port_stats_reply (xid, _, ports, dpid)
-> (sp "port stats reply: dpid:%012Lx ports:%d xid%ld"
dpid (List.length ports) xid)
| Table_stats_reply (xid, _, tables, dpid)
-> (sp "table stats reply: dpid:%012Lx tables:%d xid%ld"
dpid (List.length tables) xid)
| Desc_stats_reply (mfr_desc, hw_desc, sw_desc, serial_num, dp_desc, dpid)
-> (sp "table stats reply: dpid:%012Lx mfr_desc:%s hw_desc:%s \
sw_desc:%s serial_num:%s dp_desc:%s"
dpid mfr_desc hw_desc sw_desc serial_num dp_desc)
| Port_status (r, ph, dpid)
-> (sp "post stats: port:%s status:%s dpid:%012Lx" ph.OP.Port.name
(OP.Port.reason_to_string r) dpid)
end
type t = {
mutable dp_db: (OP.datapath_id, conn_state) Hashtbl.t;
mutable datapath_join_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable datapath_leave_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable packet_in_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable flow_removed_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable flow_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable aggr_flow_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable desc_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable port_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable table_stats_reply_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
mutable port_status_cb:
(t -> OP.datapath_id -> Event.e -> unit Lwt.t) list;
verbose : bool;
}
let register_cb controller e cb =
Event.(
match e with
| DATAPATH_JOIN
-> controller.datapath_join_cb <- controller.datapath_join_cb @ [cb]
| DATAPATH_LEAVE
-> controller.datapath_leave_cb <- controller.datapath_leave_cb @ [cb]
| PACKET_IN
-> controller.packet_in_cb <- controller.packet_in_cb @ [cb]
| FLOW_REMOVED
-> controller.flow_removed_cb <- controller.flow_removed_cb @ [cb]
| FLOW_STATS_REPLY
-> (controller.flow_stats_reply_cb
<- controller.flow_stats_reply_cb @ [cb]
)
| AGGR_FLOW_STATS_REPLY
-> (controller.aggr_flow_stats_reply_cb
<- controller.aggr_flow_stats_reply_cb @ [cb]
)
| DESC_STATS_REPLY
-> (controller.desc_stats_reply_cb
<- controller.desc_stats_reply_cb @ [cb]
)
| PORT_STATS_REPLY
-> (controller.port_stats_reply_cb
<- controller.port_stats_reply_cb @ [cb]
)
| TABLE_STATS_REPLY
-> (controller.table_stats_reply_cb
<- controller.table_stats_reply_cb @ [cb])
| PORT_STATUS_CHANGE
-> controller.port_status_cb <- controller.port_status_cb @ [cb]
)
let process_of_packet state conn ofp =
let _ = if state.verbose then cp (sp "[controller] rcv: %s\n%!" (OP.to_string ofp)) in
OP.(
match ofp with
lwt _ = send_packet conn (OP.Hello (h)) in
let h = OP.Header.create OP.Header.FEATURES_REQ OP.Header.get_len in
send_packet conn (OP.Features_req (h) )
send_packet conn (OP.Echo_resp OP.Header.(create ~xid:h.xid ECHO_RESP get_len))
let open OP.Switch in
let _ = conn.dpid <- sfs.datapath_id in
let evt = Event.Datapath_join (sfs.datapath_id, sfs.ports) in
let _ =
if (Hashtbl.mem state.dp_db sfs.datapath_id) then
cp (sp "[controller] Deleting old state for %Lx\n%!" conn.dpid)
in
let _ = Hashtbl.replace state.dp_db sfs.datapath_id conn in
Lwt_list.iter_p (fun cb -> cb state sfs.datapath_id evt)
state.datapath_join_cb
end
let open OP.Packet_in in
let evt =
Event.Packet_in (p.in_port, p.reason, p.buffer_id, p.data, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.packet_in_cb
end
| OP.Flow_removed (h, p) ->
let open OP.Flow_removed in
let evt = Event.Flow_removed (
p.of_match, p.reason, p.duration_sec, p.duration_nsec,
p.packet_count, p.byte_count, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.flow_removed_cb
| Stats_resp(h, resp) -> begin
match resp with
| OP.Stats.Flow_resp(resp_h, flows) -> begin
let evt = Event.Flow_stats_reply(
h.Header.xid, resp_h.OP.Stats.more, flows, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.flow_stats_reply_cb
end
| OP.Stats.Aggregate_resp(resp_h, aggr) -> begin
let evt = Event.Aggr_flow_stats_reply(
h.Header.xid, aggr.OP.Stats.packet_count,
aggr.OP.Stats.byte_count, aggr.OP.Stats.flow_count, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.aggr_flow_stats_reply_cb
end
| OP.Stats.Desc_resp (resp_h, aggr) -> begin
let evt = Event.Desc_stats_reply(
aggr.OP.Stats.imfr_desc, aggr.OP.Stats.hw_desc,
aggr.OP.Stats.sw_desc, aggr.OP.Stats.serial_num,
aggr.OP.Stats.dp_desc, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.desc_stats_reply_cb
end
| OP.Stats.Port_resp (resp_h, ports) -> begin
let evt =
Event.Port_stats_reply(h.Header.xid, resp_h.OP.Stats.more,
ports, conn.dpid)
in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.port_stats_reply_cb
end
| OP.Stats.Table_resp (resp_h, tables) -> begin
let evt =
Event.Table_stats_reply(h.Header.xid, resp_h.OP.Stats.more,
tables, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt)
state.table_stats_reply_cb
end
| _ -> return (cp "[controller] unsupported stats response ")
end
| Port_status(h, st) -> begin
let evt = Event.Port_status (st.OP.Port.reason, st.OP.Port.desc, conn.dpid) in
Lwt_list.iter_p (fun cb -> cb state conn.dpid evt) state.port_status_cb
end
| ofp -> return (cp (sp "[controller] Unsupported %s" (OP.to_string ofp)))
)
let send_of_data controller dpid bits =
Ofsocket.send_data_raw (Hashtbl.find controller.dp_db dpid ) bits
let send_data controller dpid ofp =
Ofsocket.send_packet (Hashtbl.find controller.dp_db dpid ) ofp
let controller_run st conn =
lwt _ =
try_lwt
while_lwt true do
read_packet conn >>= process_of_packet st conn
done
with
| Nettypes.Closed -> return (cp "[controller] switch disconnected\n%!")
| OP.Unparsed(m, bs)
| OP.Unparsable(m, bs) ->
let _ = cp (sp "# unparsed! m=%s" m) in
return (Cstruct.hexdump bs)
| exn -> return (cp (sp "[controller] ERROR:%s\n%!" (Printexc.to_string exn)))
in
if (conn.dpid > 0L) then
let evt = Event.Datapath_leave (conn.dpid) in
lwt _ = Lwt_list.iter_p (fun cb -> cb st conn.dpid evt)
st.datapath_leave_cb in
let _ = Hashtbl.remove st.dp_db conn.dpid in
return ()
else
return ()
let socket_controller st (remote_addr, remote_port) t =
let rs = Ipaddr.V4.to_string remote_addr in
let _ = cp (sp "[controller]+ Controller %s:%d\n%!" rs remote_port) in
let conn = init_socket_conn_state t in
controller_run st conn
let init_controller ?(verbose=false) init =
let t = { verbose;
dp_db = Hashtbl.create 0;
datapath_join_cb = [];
datapath_leave_cb = [];
packet_in_cb = [];
flow_removed_cb = [];
flow_stats_reply_cb = [];
aggr_flow_stats_reply_cb = [];
desc_stats_reply_cb = [];
port_stats_reply_cb = [];
table_stats_reply_cb = [];
port_status_cb = []; } in
let _ = init t in
t
let listen mgr ?(verbose=false) loc init =
let st = init_controller ~verbose init in
(Channel.listen mgr (`TCPv4 (loc, (socket_controller st) )))
let connect mgr ?(verbose=false) loc init =
let st = init_controller ~verbose init in
Net.Channel.connect mgr (`TCPv4 (None, loc,
(socket_controller st loc) ))
let local_connect st conn = controller_run st conn
|
ab9f1e108c07e1d5ae8532e9dcb95e00b4e9909a9cb0a6fa2fb5be2af53f4851 | comby-tools/comby | ripgrep.ml | open Core
open Lwt
let debug = Sys.getenv "DEBUG_COMBY" |> Option.is_some
let run ~pattern ~args =
let options = [ "--files-with-matches"; "--multiline" ] in
let pattern = Format.sprintf {|'%s'|} pattern in
let command = ("rg" :: options) @ args @ [ pattern ] |> String.concat ~sep:" " in
if debug then Format.printf "Executing: %s@." command;
let lwt_command = Lwt_process.shell command in
let recv proc =
let ic = proc#stdout in
Lwt.finalize (fun () -> Lwt_io.read ic) (fun () -> Lwt_io.close ic)
in
let f () =
Lwt_process.with_process_in lwt_command (fun proc ->
recv proc
>>= fun result ->
proc#status
>>= function
| WEXITED v when v = 1 -> return (Ok None) (* no matches *)
| WEXITED v when v <> 0 -> return @@ Or_error.errorf "Error executing rg, exit status %d." v
| _ -> return (Ok (Some (String.split ~on:'\n' result |> List.filter ~f:(String.( <> ) "")))))
in
try Lwt_main.run (f ()) with
| Sys.Break -> exit 0
| null | https://raw.githubusercontent.com/comby-tools/comby/a36c63fb1e686adaff3e90aed00e88404f8cda78/lib/app/configuration/ripgrep.ml | ocaml | no matches | open Core
open Lwt
let debug = Sys.getenv "DEBUG_COMBY" |> Option.is_some
let run ~pattern ~args =
let options = [ "--files-with-matches"; "--multiline" ] in
let pattern = Format.sprintf {|'%s'|} pattern in
let command = ("rg" :: options) @ args @ [ pattern ] |> String.concat ~sep:" " in
if debug then Format.printf "Executing: %s@." command;
let lwt_command = Lwt_process.shell command in
let recv proc =
let ic = proc#stdout in
Lwt.finalize (fun () -> Lwt_io.read ic) (fun () -> Lwt_io.close ic)
in
let f () =
Lwt_process.with_process_in lwt_command (fun proc ->
recv proc
>>= fun result ->
proc#status
>>= function
| WEXITED v when v <> 0 -> return @@ Or_error.errorf "Error executing rg, exit status %d." v
| _ -> return (Ok (Some (String.split ~on:'\n' result |> List.filter ~f:(String.( <> ) "")))))
in
try Lwt_main.run (f ()) with
| Sys.Break -> exit 0
|
5cde4993be719117e817917a7050f7b86e2666255cf6fb90b0d246f721af8081 | yogthos/reagent-example | services.clj | (ns reagent-example.routes.services
(:use compojure.core)
(:require [reagent-example.layout :as layout]
[noir.response :refer [edn]]
[clojure.pprint :refer [pprint]]))
(defn save-document [doc]
(pprint doc)
{:status "ok"})
(defroutes service-routes
(POST "/save" {:keys [body-params]}
(edn (save-document body-params))))
| null | https://raw.githubusercontent.com/yogthos/reagent-example/2512a61dfd8c00169af05fce253920567182095e/src/reagent_example/routes/services.clj | clojure | (ns reagent-example.routes.services
(:use compojure.core)
(:require [reagent-example.layout :as layout]
[noir.response :refer [edn]]
[clojure.pprint :refer [pprint]]))
(defn save-document [doc]
(pprint doc)
{:status "ok"})
(defroutes service-routes
(POST "/save" {:keys [body-params]}
(edn (save-document body-params))))
| |
7cdc4d540742818601465abc1613081ff01c8f69f461c05041b4a91121f36c1a | xray-tech/xorc-xray | run.clj | (ns re.handler.run
(:require [ataraxy.response :as response]
[cheshire.generate :as cheshire]
[integrant.core :as ig]
[qbits.alia.uuid :as uuid]
[re.boundary.programs :as programs]
[re.oam :as oam]
[re.pipeline :as pipeline]
[slingshot.slingshot :refer [try+]]))
(cheshire/add-encoder io.xorc.oam.Tuple
(fn [c jsonGenerator]
(cheshire/encode-seq (.getV c) jsonGenerator)))
(cheshire/add-encoder io.xorc.oam.ConstSignal
(fn [c jsonGenerator]
(.writeString jsonGenerator "signal")))
(defmethod ig/init-key :re.handler/run [_ {:keys [pipeline]}]
(fn [req]
(try+
(let [results (pipeline/execute {:core/now (System/currentTimeMillis)
:core/code (:body req)}
pipeline)]
[::response/ok {:values (mapcat :oam/values results)
:states (keep #(when (:oam/state %) (:core/state-id %)) results)}])
(catch [:type ::oam/compilation-failed] {:keys [exit message]}
[::response/bad-request {:exit exit :message message}]))))
| null | https://raw.githubusercontent.com/xray-tech/xorc-xray/ee1c841067207c5952473dc8fb1f0b7d237976cb/src/re/handler/run.clj | clojure | (ns re.handler.run
(:require [ataraxy.response :as response]
[cheshire.generate :as cheshire]
[integrant.core :as ig]
[qbits.alia.uuid :as uuid]
[re.boundary.programs :as programs]
[re.oam :as oam]
[re.pipeline :as pipeline]
[slingshot.slingshot :refer [try+]]))
(cheshire/add-encoder io.xorc.oam.Tuple
(fn [c jsonGenerator]
(cheshire/encode-seq (.getV c) jsonGenerator)))
(cheshire/add-encoder io.xorc.oam.ConstSignal
(fn [c jsonGenerator]
(.writeString jsonGenerator "signal")))
(defmethod ig/init-key :re.handler/run [_ {:keys [pipeline]}]
(fn [req]
(try+
(let [results (pipeline/execute {:core/now (System/currentTimeMillis)
:core/code (:body req)}
pipeline)]
[::response/ok {:values (mapcat :oam/values results)
:states (keep #(when (:oam/state %) (:core/state-id %)) results)}])
(catch [:type ::oam/compilation-failed] {:keys [exit message]}
[::response/bad-request {:exit exit :message message}]))))
| |
1687a466b3e0ceb63ac7e8725938c4186d0bcf538576c5e5253f9a88814273dd | divs1210/streamer | core.clj | (ns streamer.core
"Use transducers like normal collection functions!")
(defmacro =>
"Thread coll through xforms, returning value from terminal.
`coll` is a collection.
`xforms` are functions like (map first) and (filter even) that
return transducers.
`terminal` is the last form in the `=>` body. It takes %xform and %coll
as implicit parameters and can be used to generate the final value
once computation is complete.
Also see: `transduce!`, `sequence!`, and `into!`."
[coll & xforms-and-terminal]
(let [[xforms terminal] ((juxt butlast last) xforms-and-terminal)]
`((fn [~'%xform ~'%coll]
~terminal) ~(cons `comp xforms) ~coll)))
;; Terminal Forms
;; ==============
(defmacro transduce!
"Dispatches to `transduce`.
Use inside `=>` as a terminal."
([f]
`(transduce ~'%xform ~f ~'%coll))
([f init]
`(transduce ~'%xform ~f ~init ~'%coll)))
(defmacro sequence!
"Dispatches to `sequence`.
Use inside `=>` as a terminal."
[]
`(sequence ~'%xform ~'%coll))
(defmacro into!
"Dispatches to `into`.
Use inside `=>` as a terminal."
[to]
`(into ~to ~'%xform ~'%coll))
| null | https://raw.githubusercontent.com/divs1210/streamer/5e6976c5025007c7f6afa55251bc6081b43a78f4/src/streamer/core.clj | clojure | Terminal Forms
============== | (ns streamer.core
"Use transducers like normal collection functions!")
(defmacro =>
"Thread coll through xforms, returning value from terminal.
`coll` is a collection.
`xforms` are functions like (map first) and (filter even) that
return transducers.
`terminal` is the last form in the `=>` body. It takes %xform and %coll
as implicit parameters and can be used to generate the final value
once computation is complete.
Also see: `transduce!`, `sequence!`, and `into!`."
[coll & xforms-and-terminal]
(let [[xforms terminal] ((juxt butlast last) xforms-and-terminal)]
`((fn [~'%xform ~'%coll]
~terminal) ~(cons `comp xforms) ~coll)))
(defmacro transduce!
"Dispatches to `transduce`.
Use inside `=>` as a terminal."
([f]
`(transduce ~'%xform ~f ~'%coll))
([f init]
`(transduce ~'%xform ~f ~init ~'%coll)))
(defmacro sequence!
"Dispatches to `sequence`.
Use inside `=>` as a terminal."
[]
`(sequence ~'%xform ~'%coll))
(defmacro into!
"Dispatches to `into`.
Use inside `=>` as a terminal."
[to]
`(into ~to ~'%xform ~'%coll))
|
a376055a3510b4a487c903bc149c71f408cd81b816576a790ff944d3c03c2f12 | jumarko/clojure-experiments | 146_trees_into_tables.clj | (ns four-clojure.146-trees-into-tables
".
for is great to traversing in a nested fashion")
(defn my-flatten [map-of-maps]
(into {}
(for [[parent-key m] map-of-maps
[child-key v] m]
[[parent-key child-key] v])))
;; this is the version submitted
#_#(into {}
(for [[parent-key m] %
[child-key v] m]
[[parent-key child-key] v]))
(= (my-flatten
'{a {p 1, q 2}
b {m 3, n 4}})
'{[a p] 1, [a q] 2
[b m] 3, [b n] 4})
(= (my-flatten
'{[1] {a b c d}
[2] {q r s t u v w x}})
'{[[1] a] b, [[1] c] d,
[[2] q] r, [[2] s] t,
[[2] u] v, [[2] w] x})
(= (my-flatten
'{m {1 [a b c] 3 nil}})
'{[m 1] [a b c], [m 3] nil})
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/four_clojure/146_trees_into_tables.clj | clojure | this is the version submitted | (ns four-clojure.146-trees-into-tables
".
for is great to traversing in a nested fashion")
(defn my-flatten [map-of-maps]
(into {}
(for [[parent-key m] map-of-maps
[child-key v] m]
[[parent-key child-key] v])))
#_#(into {}
(for [[parent-key m] %
[child-key v] m]
[[parent-key child-key] v]))
(= (my-flatten
'{a {p 1, q 2}
b {m 3, n 4}})
'{[a p] 1, [a q] 2
[b m] 3, [b n] 4})
(= (my-flatten
'{[1] {a b c d}
[2] {q r s t u v w x}})
'{[[1] a] b, [[1] c] d,
[[2] q] r, [[2] s] t,
[[2] u] v, [[2] w] x})
(= (my-flatten
'{m {1 [a b c] 3 nil}})
'{[m 1] [a b c], [m 3] nil})
|
bb38c1f2094eb21ea090664c15a6e3f5699fbcbe8cad9edf84e136007fcd2527 | faylang/fay | B.hs | module ImportList1.B where
import Prelude
import FFI
x :: Double
x = 2
y :: Double
y = 2
data R = S { s1 :: Double, s2 :: Double }
r :: R
r = S 3 4
data X = Y Int
(<<>>) :: Double -> Double -> Double
(<<>>) = (+)
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/ImportList1/B.hs | haskell | module ImportList1.B where
import Prelude
import FFI
x :: Double
x = 2
y :: Double
y = 2
data R = S { s1 :: Double, s2 :: Double }
r :: R
r = S 3 4
data X = Y Int
(<<>>) :: Double -> Double -> Double
(<<>>) = (+)
| |
880d8088a263d05cc77e76a7c6169a6308a8ebc5a05cc8ae75a4f5c09e8a4367 | fulcrologic/semantic-ui-wrapper | ui_segment_inline.cljc | (ns com.fulcrologic.semantic-ui.elements.segment.ui-segment-inline
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$SegmentInline" :as SegmentInline])))
(def ui-segment-inline
"A placeholder segment can be inline.
Props:
- as (elementType): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content."
#?(:cljs (h/factory-apply SegmentInline)))
| null | https://raw.githubusercontent.com/fulcrologic/semantic-ui-wrapper/7bd53f445bc4ca7e052c69596dc089282671df6c/src/main/com/fulcrologic/semantic_ui/elements/segment/ui_segment_inline.cljc | clojure | (ns com.fulcrologic.semantic-ui.elements.segment.ui-segment-inline
(:require
[com.fulcrologic.semantic-ui.factory-helpers :as h]
#?(:cljs ["semantic-ui-react$SegmentInline" :as SegmentInline])))
(def ui-segment-inline
"A placeholder segment can be inline.
Props:
- as (elementType): An element type to render as (string or function).
- children (node): Primary content.
- className (string): Additional classes.
- content (custom): Shorthand for primary content."
#?(:cljs (h/factory-apply SegmentInline)))
| |
b56bc2103d92bc2eec127c668059e757f129e016d2fa969e0df0945e1c16503d | ZeusWPI/contests | pipes.hs | import Control.Applicative ((<$>))
import Control.Monad (replicateM, replicateM_)
import Data.Bits (setBit, testBit)
import Data.Char (chr, ord)
import Data.List (delete, nub)
import Data.Map (Map)
import qualified Data.Map as M
data Tile
= Tile {tileU :: Bool, tileR :: Bool, tileD :: Bool, tileL :: Bool}
| Unknown
deriving (Eq, Show)
parseTile :: Char -> Tile
parseTile '?' = Unknown
parseTile c = Tile (testBit i 0) (testBit i 1) (testBit i 2) (testBit i 3)
where
i = ord c - ord 'A' + 1
unparseTile :: Tile -> Char
unparseTile Unknown = '?'
unparseTile (Tile u r b l) =
let i = sb u 0 $ sb r 1 $ sb b 2 $ sb l 3 $ 0
in chr $ i + ord 'A' - 1
where
sb s i x = if s then setBit x i else x
type Field = Map (Int, Int) Tile
parseField :: [String] -> Field
parseField rows = M.fromList
[ ((r, c), parseTile x)
| (r, row) <- zip [0 ..] rows
, (c, x) <- zip [0 ..] row
]
unparseField :: Int -> Field -> [String]
unparseField size field = do
r <- [0 .. size - 1]
let tiles = [field M.! (r, c) | c <- [0 .. size - 1]]
return $ map unparseTile tiles
unknowns :: Field -> [(Int, Int)]
unknowns = map fst . filter ((== Unknown) . snd) . M.toList
matches :: (Int, Int) -> Tile -> Field -> Bool
matches _ Unknown _ = True
matches (r, c) (Tile up right down left) field =
match up (r - 1, c) tileD &&
match right (r, c + 1) tileL &&
match down (r + 1, c) tileU &&
match left (r, c - 1) tileR
where
match x p f = case M.lookup p field of
Nothing -> not x -- Outside of grid
Just Unknown -> True
Just t -> x == f t
solve :: Int -> Field -> [(Int, Int)] -> [Tile] -> [Field]
solve _ field [] _ = [field]
solve size field (p : ps) available =
[ solution
| tile <- nub available
, matches p tile field
, let field' = M.insert p tile field
, let available' = delete tile available
, solution <- solve size field' ps available'
]
main :: IO ()
main = do
n <- readLn
replicateM_ n $ do
size <- readLn
available <- map parseTile <$> getLine
field <- parseField <$> replicateM size getLine
case solve size field (unknowns field) available of
[x] -> putStr $ unlines $ unparseField size x
_ -> error "No single solution found"
| null | https://raw.githubusercontent.com/ZeusWPI/contests/d78aec91be3ce32a436d160cd7a13825d36bbf3a/2011-vpw/pipes.hs | haskell | Outside of grid | import Control.Applicative ((<$>))
import Control.Monad (replicateM, replicateM_)
import Data.Bits (setBit, testBit)
import Data.Char (chr, ord)
import Data.List (delete, nub)
import Data.Map (Map)
import qualified Data.Map as M
data Tile
= Tile {tileU :: Bool, tileR :: Bool, tileD :: Bool, tileL :: Bool}
| Unknown
deriving (Eq, Show)
parseTile :: Char -> Tile
parseTile '?' = Unknown
parseTile c = Tile (testBit i 0) (testBit i 1) (testBit i 2) (testBit i 3)
where
i = ord c - ord 'A' + 1
unparseTile :: Tile -> Char
unparseTile Unknown = '?'
unparseTile (Tile u r b l) =
let i = sb u 0 $ sb r 1 $ sb b 2 $ sb l 3 $ 0
in chr $ i + ord 'A' - 1
where
sb s i x = if s then setBit x i else x
type Field = Map (Int, Int) Tile
parseField :: [String] -> Field
parseField rows = M.fromList
[ ((r, c), parseTile x)
| (r, row) <- zip [0 ..] rows
, (c, x) <- zip [0 ..] row
]
unparseField :: Int -> Field -> [String]
unparseField size field = do
r <- [0 .. size - 1]
let tiles = [field M.! (r, c) | c <- [0 .. size - 1]]
return $ map unparseTile tiles
unknowns :: Field -> [(Int, Int)]
unknowns = map fst . filter ((== Unknown) . snd) . M.toList
matches :: (Int, Int) -> Tile -> Field -> Bool
matches _ Unknown _ = True
matches (r, c) (Tile up right down left) field =
match up (r - 1, c) tileD &&
match right (r, c + 1) tileL &&
match down (r + 1, c) tileU &&
match left (r, c - 1) tileR
where
match x p f = case M.lookup p field of
Just Unknown -> True
Just t -> x == f t
solve :: Int -> Field -> [(Int, Int)] -> [Tile] -> [Field]
solve _ field [] _ = [field]
solve size field (p : ps) available =
[ solution
| tile <- nub available
, matches p tile field
, let field' = M.insert p tile field
, let available' = delete tile available
, solution <- solve size field' ps available'
]
main :: IO ()
main = do
n <- readLn
replicateM_ n $ do
size <- readLn
available <- map parseTile <$> getLine
field <- parseField <$> replicateM size getLine
case solve size field (unknowns field) available of
[x] -> putStr $ unlines $ unparseField size x
_ -> error "No single solution found"
|
65f2855fd4424c09dc92d8bfdd662f25a0e782ed5316ed9664711b325ec67301 | exercism/babashka | check_exercises.clj | (ns check-exercises
(:require [clojure.string :as str]
[clojure.test :refer [deftest is successful? run-tests]]
[cheshire.core :as json]))
(defn- ->snake_case [s] (str/replace s \- \_))
(deftest check-exercises
(doseq [exercise (((json/parse-string (slurp "config.json")) "exercises") "practice")
:let [slug (exercise "slug")
path-to-exercise (partial str "exercises/practice/" slug "/")
exercise-tests (symbol (str slug "-test"))]]
(load-file (path-to-exercise "src/example.clj"))
(load-file (path-to-exercise "test/" (->snake_case slug) "_test.clj"))
(is (successful? (run-tests exercise-tests)))))
(let [report (run-tests)]
(System/exit (+ (:fail report)
(:error report))))
| null | https://raw.githubusercontent.com/exercism/babashka/12844558d5671b9bef8f6d83c97b75a7973b22e7/_test/check_exercises.clj | clojure | (ns check-exercises
(:require [clojure.string :as str]
[clojure.test :refer [deftest is successful? run-tests]]
[cheshire.core :as json]))
(defn- ->snake_case [s] (str/replace s \- \_))
(deftest check-exercises
(doseq [exercise (((json/parse-string (slurp "config.json")) "exercises") "practice")
:let [slug (exercise "slug")
path-to-exercise (partial str "exercises/practice/" slug "/")
exercise-tests (symbol (str slug "-test"))]]
(load-file (path-to-exercise "src/example.clj"))
(load-file (path-to-exercise "test/" (->snake_case slug) "_test.clj"))
(is (successful? (run-tests exercise-tests)))))
(let [report (run-tests)]
(System/exit (+ (:fail report)
(:error report))))
| |
025acd47df01f0826bfad12b48f509993cc59192285ada3716a14e8220ff0187 | mbutterick/aoc-racket | test2.rkt | #lang reader "main.rkt" ★★
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10 | null | https://raw.githubusercontent.com/mbutterick/aoc-racket/2c6cb2f3ad876a91a82f33ce12844f7758b969d6/2017/d08/test2.rkt | racket | #lang reader "main.rkt" ★★
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10 | |
04d7fbc488fd1059b68fd9087285d9eb54b799acb6f1395c21bf027a0772267b | metosin/fnhouse-swagger | makkara.clj | (ns fnhouse.makkara
(:require [plumbing.core :refer [defnk]]
[schema.core :as s]))
(s/defschema Makkara {:id Long, :name s/Str, :size (s/enum :S :M :L)})
(s/defschema NewMakkara (dissoc Makkara :id))
(defnk $:makkara-id$GET
"Gets a Makkara"
{:responses {200 Makkara}}
[[:request [:uri-args makkara-id :- Long]]]
{:body {:id 1 :name "Musta" :size :L}})
(defnk $POST
"Adds a Makkara"
{:responses {200 Makkara}}
[[:request body :- NewMakkara]]
{:body (assoc Makkara :id 1)})
| null | https://raw.githubusercontent.com/metosin/fnhouse-swagger/69cdd92a5bb6466dce0c35e369147d7a2b598533/test/fnhouse/makkara.clj | clojure | (ns fnhouse.makkara
(:require [plumbing.core :refer [defnk]]
[schema.core :as s]))
(s/defschema Makkara {:id Long, :name s/Str, :size (s/enum :S :M :L)})
(s/defschema NewMakkara (dissoc Makkara :id))
(defnk $:makkara-id$GET
"Gets a Makkara"
{:responses {200 Makkara}}
[[:request [:uri-args makkara-id :- Long]]]
{:body {:id 1 :name "Musta" :size :L}})
(defnk $POST
"Adds a Makkara"
{:responses {200 Makkara}}
[[:request body :- NewMakkara]]
{:body (assoc Makkara :id 1)})
| |
a5abe4c468e9fc4b4a6d262aca09a6b9938517660f492035ba851bff22a7abc7 | janestreet/core_profiler | disabled.ml | open! Core
module Profiler = struct
let is_enabled = false
let safe_to_delay () = ()
let dump_stats () = ()
let configure
?don't_require_core_profiler_env:_
?offline_profiler_data_file:_
?online_print_time_interval_secs:_
?online_print_by_default:_
() = ()
end
module Timer = struct
type t = unit
type probe = t
let create ~name:_ = ()
let record _id = ()
module Group = struct
type t = unit
let create ~name:_ = ()
let add_probe _group ?sources:_ ~name:_ () = ()
let reset _group = ()
end
end
module Probe = struct
type t = unit
type probe = t
let create ~name:_ ~units:_ = ()
let record _id _value = ()
module Group = struct
type t = unit
let create ~name:_ ~units:_ = ()
let add_probe _group ?sources:_ ~name:_ () = ()
let reset _group = ()
end
end
module Delta_timer = struct
type state = unit
type t = unit
let create ~name:_ = ()
let stateless_start _t = ()
let stateless_stop _t _state = ()
let start _t = ()
let stop _t = ()
let pause _t = ()
let record _t = ()
let wrap_sync _t f x = f x
let wrap_sync2 _t f x y = f x y
let wrap_sync3 _t f x y z = f x y z
let wrap_sync4 _t f x y z w = f x y z w
(* let wrap_async _t f x = f x *)
end
module Delta_probe = struct
type state = unit
type t = unit
let create ~name:_ ~units:_ = ()
let stateless_start _t _value = ()
let stateless_stop _t _state _value = ()
let start _t _value = ()
let stop _t _value = ()
let pause _t _value = ()
let record _t = ()
end
| null | https://raw.githubusercontent.com/janestreet/core_profiler/3d1c0e61df848f5f25f78d64beea92b619b6d5d9/disabled_lib/disabled.ml | ocaml | let wrap_async _t f x = f x | open! Core
module Profiler = struct
let is_enabled = false
let safe_to_delay () = ()
let dump_stats () = ()
let configure
?don't_require_core_profiler_env:_
?offline_profiler_data_file:_
?online_print_time_interval_secs:_
?online_print_by_default:_
() = ()
end
module Timer = struct
type t = unit
type probe = t
let create ~name:_ = ()
let record _id = ()
module Group = struct
type t = unit
let create ~name:_ = ()
let add_probe _group ?sources:_ ~name:_ () = ()
let reset _group = ()
end
end
module Probe = struct
type t = unit
type probe = t
let create ~name:_ ~units:_ = ()
let record _id _value = ()
module Group = struct
type t = unit
let create ~name:_ ~units:_ = ()
let add_probe _group ?sources:_ ~name:_ () = ()
let reset _group = ()
end
end
module Delta_timer = struct
type state = unit
type t = unit
let create ~name:_ = ()
let stateless_start _t = ()
let stateless_stop _t _state = ()
let start _t = ()
let stop _t = ()
let pause _t = ()
let record _t = ()
let wrap_sync _t f x = f x
let wrap_sync2 _t f x y = f x y
let wrap_sync3 _t f x y z = f x y z
let wrap_sync4 _t f x y z w = f x y z w
end
module Delta_probe = struct
type state = unit
type t = unit
let create ~name:_ ~units:_ = ()
let stateless_start _t _value = ()
let stateless_stop _t _state _value = ()
let start _t _value = ()
let stop _t _value = ()
let pause _t _value = ()
let record _t = ()
end
|
2639312762b534a996d55ef3062f93b609c11d49ed9eb31498fca6ae8b495e17 | crategus/cl-cffi-gtk | rtest-gtk-settings.lisp | (def-suite gtk-settings :in gtk-suite)
(in-suite gtk-settings)
;;; --- Types and Values ------------------------------------------------------
GtkSettingsValue deprecated
;;; GtkIMPreeditStyle
(test gtk-im-preedit-style
;; Check the type
(is (g-type-is-enum "GtkIMPreeditStyle"))
;; Check the type initializer
(is (eq (gtype "GtkIMPreeditStyle")
(gtype (foreign-funcall "gtk_im_preedit_style_get_type" g-size))))
;; Check the registered name
(is (eq 'gtk-im-preedit-style
(registered-enum-type "GtkIMPreeditStyle")))
;; Check the names
(is (equal '("GTK_IM_PREEDIT_NOTHING" "GTK_IM_PREEDIT_CALLBACK"
"GTK_IM_PREEDIT_NONE")
(mapcar #'enum-item-name
(get-enum-items "GtkIMPreeditStyle"))))
;; Check the values
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GtkIMPreeditStyle"))))
Check the nick names
(is (equal '("nothing" "callback" "none")
(mapcar #'enum-item-nick
(get-enum-items "GtkIMPreeditStyle"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GtkIMPreeditStyle" GTK-I-M-PREEDIT-STYLE
(:EXPORT T)
(:NOTHING 0)
(:CALLBACK 1)
(:NONE 2))
(get-g-type-definition "GtkIMPreeditStyle"))))
;;; GtkIMStatusStyle
(test gtk-im-status-style
;; Check the type
(is (g-type-is-enum "GtkIMStatusStyle"))
;; Check the type initializer
(is (eq (gtype "GtkIMStatusStyle")
(gtype (foreign-funcall "gtk_im_status_style_get_type" g-size))))
;; Check the registered name
(is (eq 'gtk-im-status-style
(registered-enum-type "GtkIMStatusStyle")))
;; Check the names
(is (equal '("GTK_IM_STATUS_NOTHING" "GTK_IM_STATUS_CALLBACK"
"GTK_IM_STATUS_NONE")
(mapcar #'enum-item-name
(get-enum-items "GtkIMStatusStyle"))))
;; Check the values
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GtkIMStatusStyle"))))
Check the nick names
(is (equal '("nothing" "callback" "none")
(mapcar #'enum-item-nick
(get-enum-items "GtkIMStatusStyle"))))
;; Check the enum definition
(is (equal '(DEFINE-G-ENUM "GtkIMStatusStyle" GTK-I-M-STATUS-STYLE
(:EXPORT T)
(:NOTHING 0)
(:CALLBACK 1)
(:NONE 2))
(get-g-type-definition "GtkIMStatusStyle"))))
GtkSettings
(test gtk-settings-class
;; Type check
(is (g-type-is-object "GtkSettings"))
;; Check the registered name
(is (eq 'gtk-settings
(registered-object-type-by-name "GtkSettings")))
;; Check the type initializer
(is (eq (gtype "GtkSettings")
(gtype (foreign-funcall "gtk_settings_get_type" g-size))))
;; Check the parent
(is (eq (gtype "GObject") (g-type-parent "GtkSettings")))
;; Check the children
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkSettings"))))
;; Check the interfaces
(is (equal '("GtkStyleProvider" "GtkStyleProviderPrivate")
(mapcar #'g-type-name (g-type-interfaces "GtkSettings"))))
;; Check the class properties
(is (equal '("color-hash" "gtk-alternative-button-order"
"gtk-alternative-sort-arrows" "gtk-application-prefer-dark-theme"
"gtk-auto-mnemonics" "gtk-button-images" "gtk-can-change-accels"
"gtk-color-palette" "gtk-color-scheme" "gtk-cursor-aspect-ratio"
"gtk-cursor-blink" "gtk-cursor-blink-time"
"gtk-cursor-blink-timeout" "gtk-cursor-theme-name"
"gtk-cursor-theme-size" "gtk-decoration-layout"
"gtk-dialogs-use-header" "gtk-dnd-drag-threshold"
"gtk-double-click-distance" "gtk-double-click-time"
"gtk-enable-accels" "gtk-enable-animations"
"gtk-enable-event-sounds" "gtk-enable-input-feedback-sounds"
"gtk-enable-mnemonics" "gtk-enable-primary-paste"
"gtk-enable-tooltips" "gtk-entry-password-hint-timeout"
"gtk-entry-select-on-focus" "gtk-error-bell"
"gtk-fallback-icon-theme" "gtk-file-chooser-backend"
"gtk-font-name" "gtk-fontconfig-timestamp" "gtk-icon-sizes"
"gtk-icon-theme-name" "gtk-im-module" "gtk-im-preedit-style"
"gtk-im-status-style" "gtk-key-theme-name"
"gtk-keynav-cursor-only" "gtk-keynav-use-caret"
"gtk-keynav-wrap-around" "gtk-label-select-on-focus"
"gtk-long-press-time" "gtk-menu-bar-accel"
"gtk-menu-bar-popup-delay" "gtk-menu-images"
"gtk-menu-popdown-delay" "gtk-menu-popup-delay" "gtk-modules"
"gtk-overlay-scrolling" "gtk-primary-button-warps-slider"
"gtk-print-backends" "gtk-print-preview-command"
"gtk-recent-files-enabled" "gtk-recent-files-limit"
"gtk-recent-files-max-age" "gtk-scrolled-window-placement"
"gtk-shell-shows-app-menu" "gtk-shell-shows-desktop"
"gtk-shell-shows-menubar" "gtk-show-input-method-menu"
"gtk-show-unicode-menu" "gtk-sound-theme-name" "gtk-split-cursor"
"gtk-theme-name" "gtk-timeout-expand" "gtk-timeout-initial"
"gtk-timeout-repeat" "gtk-titlebar-double-click"
"gtk-titlebar-middle-click" "gtk-titlebar-right-click"
"gtk-toolbar-icon-size" "gtk-toolbar-style"
"gtk-tooltip-browse-mode-timeout" "gtk-tooltip-browse-timeout"
"gtk-tooltip-timeout" "gtk-touchscreen-mode" "gtk-visible-focus"
"gtk-xft-antialias" "gtk-xft-dpi" "gtk-xft-hinting"
"gtk-xft-hintstyle" "gtk-xft-rgba")
(stable-sort (mapcar #'g-param-spec-name
(g-object-class-list-properties "GtkSettings"))
#'string-lessp)))
;; Check the class definition
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkSettings" GTK-SETTINGS
(:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES
("GtkStyleProvider" "GtkStyleProviderPrivate")
:TYPE-INITIALIZER "gtk_settings_get_type")
((COLOR-HASH GTK-SETTINGS-COLOR-HASH "color-hash"
"GHashTable" T NIL)
(GTK-ALTERNATIVE-BUTTON-ORDER
GTK-SETTINGS-GTK-ALTERNATIVE-BUTTON-ORDER
"gtk-alternative-button-order" "gboolean" T T)
(GTK-ALTERNATIVE-SORT-ARROWS
GTK-SETTINGS-GTK-ALTERNATIVE-SORT-ARROWS
"gtk-alternative-sort-arrows" "gboolean" T T)
(GTK-APPLICATION-PREFER-DARK-THEME
GTK-SETTINGS-GTK-APPLICATION-PREFER-DARK-THEME
"gtk-application-prefer-dark-theme" "gboolean" T T)
(GTK-AUTO-MNEMONICS GTK-SETTINGS-GTK-AUTO-MNEMONICS
"gtk-auto-mnemonics" "gboolean" T T)
(GTK-BUTTON-IMAGES GTK-SETTINGS-GTK-BUTTON-IMAGES
"gtk-button-images" "gboolean" T T)
(GTK-CAN-CHANGE-ACCELS
GTK-SETTINGS-GTK-CAN-CHANGE-ACCELS
"gtk-can-change-accels" "gboolean" T T)
(GTK-COLOR-PALETTE GTK-SETTINGS-GTK-COLOR-PALETTE
"gtk-color-palette" "gchararray" T T)
(GTK-COLOR-SCHEME GTK-SETTINGS-GTK-COLOR-SCHEME
"gtk-color-scheme" "gchararray" T T)
(GTK-CURSOR-ASPECT-RATIO
GTK-SETTINGS-GTK-CURSOR-ASPECT-RATIO
"gtk-cursor-aspect-ratio" "gfloat" T T)
(GTK-CURSOR-BLINK GTK-SETTINGS-GTK-CURSOR-BLINK
"gtk-cursor-blink" "gboolean" T T)
(GTK-CURSOR-BLINK-TIME
GTK-SETTINGS-GTK-CURSOR-BLINK-TIME
"gtk-cursor-blink-time" "gint" T T)
(GTK-CURSOR-BLINK-TIMEOUT
GTK-SETTINGS-GTK-CURSOR-BLINK-TIMEOUT
"gtk-cursor-blink-timeout" "gint" T T)
(GTK-CURSOR-THEME-NAME
GTK-SETTINGS-GTK-CURSOR-THEME-NAME
"gtk-cursor-theme-name" "gchararray" T T)
(GTK-CURSOR-THEME-SIZE
GTK-SETTINGS-GTK-CURSOR-THEME-SIZE
"gtk-cursor-theme-size" "gint" T T)
(GTK-DECORATION-LAYOUT
GTK-SETTINGS-GTK-DECORATION-LAYOUT
"gtk-decoration-layout" "gchararray" T T)
(GTK-DIALOGS-USE-HEADER
GTK-SETTINGS-GTK-DIALOGS-USE-HEADER
"gtk-dialogs-use-header" "gboolean" T T)
(GTK-DND-DRAG-THRESHOLD
GTK-SETTINGS-GTK-DND-DRAG-THRESHOLD
"gtk-dnd-drag-threshold" "gint" T T)
(GTK-DOUBLE-CLICK-DISTANCE
GTK-SETTINGS-GTK-DOUBLE-CLICK-DISTANCE
"gtk-double-click-distance" "gint" T T)
(GTK-DOUBLE-CLICK-TIME
GTK-SETTINGS-GTK-DOUBLE-CLICK-TIME
"gtk-double-click-time" "gint" T T)
(GTK-ENABLE-ACCELS GTK-SETTINGS-GTK-ENABLE-ACCELS
"gtk-enable-accels" "gboolean" T T)
(GTK-ENABLE-ANIMATIONS
GTK-SETTINGS-GTK-ENABLE-ANIMATIONS
"gtk-enable-animations" "gboolean" T T)
(GTK-ENABLE-EVENT-SOUNDS
GTK-SETTINGS-GTK-ENABLE-EVENT-SOUNDS
"gtk-enable-event-sounds" "gboolean" T T)
(GTK-ENABLE-INPUT-FEEDBACK-SOUNDS
GTK-SETTINGS-GTK-ENABLE-INPUT-FEEDBACK-SOUNDS
"gtk-enable-input-feedback-sounds" "gboolean" T T)
(GTK-ENABLE-MNEMONICS GTK-SETTINGS-GTK-ENABLE-MNEMONICS
"gtk-enable-mnemonics" "gboolean" T T)
(GTK-ENABLE-PRIMARY-PASTE
GTK-SETTINGS-GTK-ENABLE-PRIMARY-PASTE
"gtk-enable-primary-paste" "gboolean" T T)
(GTK-ENABLE-TOOLTIPS GTK-SETTINGS-GTK-ENABLE-TOOLTIPS
"gtk-enable-tooltips" "gboolean" T T)
(GTK-ENTRY-PASSWORD-HINT-TIMEOUT
GTK-SETTINGS-GTK-ENTRY-PASSWORD-HINT-TIMEOUT
"gtk-entry-password-hint-timeout" "guint" T T)
(GTK-ENTRY-SELECT-ON-FOCUS
GTK-SETTINGS-GTK-ENTRY-SELECT-ON-FOCUS
"gtk-entry-select-on-focus" "gboolean" T T)
(GTK-ERROR-BELL GTK-SETTINGS-GTK-ERROR-BELL
"gtk-error-bell" "gboolean" T T)
(GTK-FALLBACK-ICON-THEME
GTK-SETTINGS-GTK-FALLBACK-ICON-THEME
"gtk-fallback-icon-theme" "gchararray" T T)
(GTK-FILE-CHOOSER-BACKEND
GTK-SETTINGS-GTK-FILE-CHOOSER-BACKEND
"gtk-file-chooser-backend" "gchararray" T T)
(GTK-FONT-NAME GTK-SETTINGS-GTK-FONT-NAME
"gtk-font-name" "gchararray" T T)
(GTK-FONTCONFIG-TIMESTAMP
GTK-SETTINGS-GTK-FONTCONFIG-TIMESTAMP
"gtk-fontconfig-timestamp" "guint" T T)
(GTK-ICON-SIZES GTK-SETTINGS-GTK-ICON-SIZES
"gtk-icon-sizes" "gchararray" T T)
(GTK-ICON-THEME-NAME GTK-SETTINGS-GTK-ICON-THEME-NAME
"gtk-icon-theme-name" "gchararray" T T)
(GTK-IM-MODULE GTK-SETTINGS-GTK-IM-MODULE
"gtk-im-module" "gchararray" T T)
(GTK-IM-PREEDIT-STYLE GTK-SETTINGS-GTK-IM-PREEDIT-STYLE
"gtk-im-preedit-style" "GtkIMPreeditStyle" T T)
(GTK-IM-STATUS-STYLE GTK-SETTINGS-GTK-IM-STATUS-STYLE
"gtk-im-status-style" "GtkIMStatusStyle" T T)
(GTK-KEY-THEME-NAME GTK-SETTINGS-GTK-KEY-THEME-NAME
"gtk-key-theme-name" "gchararray" T T)
(GTK-KEYNAV-CURSOR-ONLY
GTK-SETTINGS-GTK-KEYNAV-CURSOR-ONLY
"gtk-keynav-cursor-only" "gboolean" T T)
(GTK-KEYNAV-USE-CARET GTK-SETTINGS-GTK-KEYNAV-USE-CARET
"gtk-keynav-use-caret" "gboolean" T T)
(GTK-KEYNAV-WRAP-AROUND
GTK-SETTINGS-GTK-KEYNAV-WRAP-AROUND
"gtk-keynav-wrap-around" "gboolean" T T)
(GTK-LABEL-SELECT-ON-FOCUS
GTK-SETTINGS-GTK-LABEL-SELECT-ON-FOCUS
"gtk-label-select-on-focus" "gboolean" T T)
(GTK-LONG-PRESS-TIME GTK-SETTINGS-GTK-LONG-PRESS-TIME
"gtk-long-press-time" "guint" T T)
(GTK-MENU-BAR-ACCEL GTK-SETTINGS-GTK-MENU-BAR-ACCEL
"gtk-menu-bar-accel" "gchararray" T T)
(GTK-MENU-BAR-POPUP-DELAY
GTK-SETTINGS-GTK-MENU-BAR-POPUP-DELAY
"gtk-menu-bar-popup-delay" "gint" T T)
(GTK-MENU-IMAGES GTK-SETTINGS-GTK-MENU-IMAGES
"gtk-menu-images" "gboolean" T T)
(GTK-MENU-POPDOWN-DELAY
GTK-SETTINGS-GTK-MENU-POPDOWN-DELAY
"gtk-menu-popdown-delay" "gint" T T)
(GTK-MENU-POPUP-DELAY GTK-SETTINGS-GTK-MENU-POPUP-DELAY
"gtk-menu-popup-delay" "gint" T T)
(GTK-MODULES GTK-SETTINGS-GTK-MODULES "gtk-modules"
"gchararray" T T)
(GTK-OVERLAY-SCROLLING
GTK-SETTINGS-GTK-OVERLAY-SCROLLING
"gtk-overlay-scrolling" "gboolean" T T)
(GTK-PRIMARY-BUTTON-WARPS-SLIDER
GTK-SETTINGS-GTK-PRIMARY-BUTTON-WARPS-SLIDER
"gtk-primary-button-warps-slider" "gboolean" T T)
(GTK-PRINT-BACKENDS GTK-SETTINGS-GTK-PRINT-BACKENDS
"gtk-print-backends" "gchararray" T T)
(GTK-PRINT-PREVIEW-COMMAND
GTK-SETTINGS-GTK-PRINT-PREVIEW-COMMAND
"gtk-print-preview-command" "gchararray" T T)
(GTK-RECENT-FILES-ENABLED
GTK-SETTINGS-GTK-RECENT-FILES-ENABLED
"gtk-recent-files-enabled" "gboolean" T T)
(GTK-RECENT-FILES-LIMIT
GTK-SETTINGS-GTK-RECENT-FILES-LIMIT
"gtk-recent-files-limit" "gint" T T)
(GTK-RECENT-FILES-MAX-AGE
GTK-SETTINGS-GTK-RECENT-FILES-MAX-AGE
"gtk-recent-files-max-age" "gint" T T)
(GTK-SCROLLED-WINDOW-PLACEMENT
GTK-SETTINGS-GTK-SCROLLED-WINDOW-PLACEMENT
"gtk-scrolled-window-placement" "GtkCornerType" T T)
(GTK-SHELL-SHOWS-APP-MENU
GTK-SETTINGS-GTK-SHELL-SHOWS-APP-MENU
"gtk-shell-shows-app-menu" "gboolean" T T)
(GTK-SHELL-SHOWS-DESKTOP
GTK-SETTINGS-GTK-SHELL-SHOWS-DESKTOP
"gtk-shell-shows-desktop" "gboolean" T T)
(GTK-SHELL-SHOWS-MENUBAR
GTK-SETTINGS-GTK-SHELL-SHOWS-MENUBAR
"gtk-shell-shows-menubar" "gboolean" T T)
(GTK-SHOW-INPUT-METHOD-MENU
GTK-SETTINGS-GTK-SHOW-INPUT-METHOD-MENU
"gtk-show-input-method-menu" "gboolean" T T)
(GTK-SHOW-UNICODE-MENU
GTK-SETTINGS-GTK-SHOW-UNICODE-MENU
"gtk-show-unicode-menu" "gboolean" T T)
(GTK-SOUND-THEME-NAME GTK-SETTINGS-GTK-SOUND-THEME-NAME
"gtk-sound-theme-name" "gchararray" T T)
(GTK-SPLIT-CURSOR GTK-SETTINGS-GTK-SPLIT-CURSOR
"gtk-split-cursor" "gboolean" T T)
(GTK-THEME-NAME GTK-SETTINGS-GTK-THEME-NAME
"gtk-theme-name" "gchararray" T T)
(GTK-TIMEOUT-EXPAND GTK-SETTINGS-GTK-TIMEOUT-EXPAND
"gtk-timeout-expand" "gint" T T)
(GTK-TIMEOUT-INITIAL GTK-SETTINGS-GTK-TIMEOUT-INITIAL
"gtk-timeout-initial" "gint" T T)
(GTK-TIMEOUT-REPEAT GTK-SETTINGS-GTK-TIMEOUT-REPEAT
"gtk-timeout-repeat" "gint" T T)
(GTK-TITLEBAR-DOUBLE-CLICK
GTK-SETTINGS-GTK-TITLEBAR-DOUBLE-CLICK
"gtk-titlebar-double-click" "gchararray" T T)
(GTK-TITLEBAR-MIDDLE-CLICK
GTK-SETTINGS-GTK-TITLEBAR-MIDDLE-CLICK
"gtk-titlebar-middle-click" "gchararray" T T)
(GTK-TITLEBAR-RIGHT-CLICK
GTK-SETTINGS-GTK-TITLEBAR-RIGHT-CLICK
"gtk-titlebar-right-click" "gchararray" T T)
(GTK-TOOLBAR-ICON-SIZE
GTK-SETTINGS-GTK-TOOLBAR-ICON-SIZE
"gtk-toolbar-icon-size" "GtkIconSize" T T)
(GTK-TOOLBAR-STYLE GTK-SETTINGS-GTK-TOOLBAR-STYLE
"gtk-toolbar-style" "GtkToolbarStyle" T T)
(GTK-TOOLTIP-BROWSE-MODE-TIMEOUT
GTK-SETTINGS-GTK-TOOLTIP-BROWSE-MODE-TIMEOUT
"gtk-tooltip-browse-mode-timeout" "gint" T T)
(GTK-TOOLTIP-BROWSE-TIMEOUT
GTK-SETTINGS-GTK-TOOLTIP-BROWSE-TIMEOUT
"gtk-tooltip-browse-timeout" "gint" T T)
(GTK-TOOLTIP-TIMEOUT GTK-SETTINGS-GTK-TOOLTIP-TIMEOUT
"gtk-tooltip-timeout" "gint" T T)
(GTK-TOUCHSCREEN-MODE GTK-SETTINGS-GTK-TOUCHSCREEN-MODE
"gtk-touchscreen-mode" "gboolean" T T)
(GTK-VISIBLE-FOCUS GTK-SETTINGS-GTK-VISIBLE-FOCUS
"gtk-visible-focus" "GtkPolicyType" T T)
(GTK-XFT-ANTIALIAS GTK-SETTINGS-GTK-XFT-ANTIALIAS
"gtk-xft-antialias" "gint" T T)
(GTK-XFT-DPI GTK-SETTINGS-GTK-XFT-DPI "gtk-xft-dpi"
"gint" T T)
(GTK-XFT-HINTING GTK-SETTINGS-GTK-XFT-HINTING
"gtk-xft-hinting" "gint" T T)
(GTK-XFT-HINTSTYLE GTK-SETTINGS-GTK-XFT-HINTSTYLE
"gtk-xft-hintstyle" "gchararray" T T)
(GTK-XFT-RGBA GTK-SETTINGS-GTK-XFT-RGBA "gtk-xft-rgba"
"gchararray" T T)))
(get-g-type-definition "GtkSettings"))))
;;; --- Properties -------------------------------------------------------------
(test gtk-settings-properties
(let ((settings (gtk-settings-default)))
;; FIXME: GHashTable is not implemented
(signals (error) (gtk-settings-color-hash settings))
#-windows
(is-false (gtk-settings-gtk-alternative-button-order settings))
#-windows
(is-false (gtk-settings-gtk-alternative-sort-arrows settings))
(is-false (gtk-settings-gtk-application-prefer-dark-theme settings))
(is-true (gtk-settings-gtk-auto-mnemonics settings))
(is-false (gtk-settings-gtk-button-images settings))
(is-false (gtk-settings-gtk-can-change-accels settings))
(is (stringp (gtk-settings-gtk-color-palette settings)))
(is (stringp (gtk-settings-gtk-color-scheme settings)))
(is-true (gtk-settings-gtk-cursor-blink settings))
(is (integerp (gtk-settings-gtk-cursor-blink-time settings)))
(is (integerp (gtk-settings-gtk-cursor-blink-timeout settings)))
#-windows
(is (stringp (gtk-settings-gtk-cursor-theme-name settings)))
(is (integerp (gtk-settings-gtk-cursor-theme-size settings)))
(is-true (gtk-settings-gtk-decoration-layout settings))
#-windows
(is-true (gtk-settings-gtk-dialogs-use-header settings))
(is (integerp (gtk-settings-gtk-dnd-drag-threshold settings)))
(is (integerp (gtk-settings-gtk-double-click-distance settings)))
(is (integerp (gtk-settings-gtk-double-click-time settings)))
(is-true (gtk-settings-gtk-enable-accels settings))
(is-true (gtk-settings-gtk-enable-animations settings))
(is-true (gtk-settings-gtk-enable-event-sounds settings))
(is-true (gtk-settings-gtk-enable-input-feedback-sounds settings))
(is-true (gtk-settings-gtk-enable-mnemonics settings))
(is-true (gtk-settings-gtk-enable-primary-paste settings))
(is-true (gtk-settings-gtk-enable-tooltips settings))
(is-true (gtk-settings-gtk-entry-password-hint-timeout settings))
(is-true (gtk-settings-gtk-entry-select-on-focus settings))
(is-true (gtk-settings-gtk-error-bell settings))
(is-false (gtk-settings-gtk-fallback-icon-theme settings))
(is-false (gtk-settings-gtk-file-chooser-backend settings))
(is (stringp (gtk-settings-gtk-font-name settings)))
(is (integerp (gtk-settings-gtk-fontconfig-timestamp settings)))
#-windows
(is (stringp (gtk-settings-gtk-icon-sizes settings)))
(is (stringp (gtk-settings-gtk-icon-theme-name settings)))
(is (stringp (gtk-settings-gtk-im-module settings)))
(is (eq :callback (gtk-settings-gtk-im-preedit-style settings)))
(is (eq :callback (gtk-settings-gtk-im-status-style settings)))
#-windows
(is (stringp (gtk-settings-gtk-key-theme-name settings)))
(is-false (gtk-settings-gtk-keynav-cursor-only settings))
(is-false (gtk-settings-gtk-keynav-use-caret settings))
(is-true (gtk-settings-gtk-keynav-wrap-around settings))
(is-true (gtk-settings-gtk-label-select-on-focus settings))
(is (integerp (gtk-settings-gtk-long-press-time settings)))
(is (stringp (gtk-settings-gtk-menu-bar-accel settings)))
(is (integerp (gtk-settings-gtk-menu-bar-popup-delay settings)))
(is-false (gtk-settings-gtk-menu-images settings))
(is (integerp (gtk-settings-gtk-menu-popdown-delay settings)))
(is (integerp (gtk-settings-gtk-menu-popup-delay settings)))
#-windows
(is (stringp (gtk-settings-gtk-modules settings)))
(is-true (gtk-settings-gtk-primary-button-warps-slider settings))
(is (stringp (gtk-settings-gtk-print-backends settings)))
(is (stringp (gtk-settings-gtk-print-preview-command settings)))
;; TODO: Is this a bug?
(signals (error) (gtk-settings-gtk-recent-files-enabled settings))
(is (integerp (gtk-settings-gtk-recent-files-limit settings)))
(is (integerp (gtk-settings-gtk-recent-files-max-age settings)))
(is-true (gtk-settings-gtk-scrolled-window-placement settings))
(is-false (gtk-settings-gtk-shell-shows-app-menu settings))
(is-true (gtk-settings-gtk-shell-shows-desktop settings))
(is-false (gtk-settings-gtk-shell-shows-menubar settings))
(is-false (gtk-settings-gtk-show-input-method-menu settings))
(is-false (gtk-settings-gtk-show-unicode-menu settings))
(is (stringp (gtk-settings-gtk-sound-theme-name settings)))
#-windows
(is-true (gtk-settings-gtk-split-cursor settings))
(is (stringp (gtk-settings-gtk-theme-name settings)))
(is (integerp (gtk-settings-gtk-timeout-expand settings)))
(is (integerp (gtk-settings-gtk-timeout-initial settings)))
(is (integerp (gtk-settings-gtk-timeout-repeat settings)))
(is (stringp (gtk-settings-gtk-titlebar-double-click settings)))
(is (stringp (gtk-settings-gtk-titlebar-middle-click settings)))
(is (stringp (gtk-settings-gtk-titlebar-right-click settings)))
(is (eq :large-toolbar (gtk-settings-gtk-toolbar-icon-size settings)))
(is (eq :both-horiz (gtk-settings-gtk-toolbar-style settings)))
(is (integerp (gtk-settings-gtk-tooltip-browse-mode-timeout settings)))
(is (integerp (gtk-settings-gtk-tooltip-browse-timeout settings)))
(is (integerp (gtk-settings-gtk-tooltip-timeout settings)))
(is-false (gtk-settings-gtk-touchscreen-mode settings))
(is (eq :automatic (gtk-settings-gtk-visible-focus settings)))
(is (integerp (gtk-settings-gtk-xft-antialias settings)))
(is (integerp (gtk-settings-gtk-xft-dpi settings)))
(is (integerp (gtk-settings-gtk-xft-hinting settings)))
(is (stringp (gtk-settings-gtk-xft-hintstyle settings)))
(is (stringp (gtk-settings-gtk-xft-rgba settings)))))
;;; --- Functions --------------------------------------------------------------
;;; gtk_settings_get_default
;;; gtk_settings_get_for_screen
gtk_settings_install_property deprecated
;;; gtk_settings_install_property_parser deprecated
;;; gtk_rc_property_parse_color
;;; gtk_rc_property_parse_flags
;;; gtk_rc_property_parse_requisition
;;; gtk_rc_property_parse_border
deprecated
;;; gtk_settings_set_string_property deprecated
;;; gtk_settings_set_long_property deprecated
;;; gtk_settings_set_double_property deprecated
;;; gtk_settings_reset_property ()
2021 - 10 - 14
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/7f5a09f78d8004a71efa82794265f2587fff98ab/test/rtest-gtk-settings.lisp | lisp | --- Types and Values ------------------------------------------------------
GtkIMPreeditStyle
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
GtkIMStatusStyle
Check the type
Check the type initializer
Check the registered name
Check the names
Check the values
Check the enum definition
Type check
Check the registered name
Check the type initializer
Check the parent
Check the children
Check the interfaces
Check the class properties
Check the class definition
--- Properties -------------------------------------------------------------
FIXME: GHashTable is not implemented
TODO: Is this a bug?
--- Functions --------------------------------------------------------------
gtk_settings_get_default
gtk_settings_get_for_screen
gtk_settings_install_property_parser deprecated
gtk_rc_property_parse_color
gtk_rc_property_parse_flags
gtk_rc_property_parse_requisition
gtk_rc_property_parse_border
gtk_settings_set_string_property deprecated
gtk_settings_set_long_property deprecated
gtk_settings_set_double_property deprecated
gtk_settings_reset_property () | (def-suite gtk-settings :in gtk-suite)
(in-suite gtk-settings)
GtkSettingsValue deprecated
(test gtk-im-preedit-style
(is (g-type-is-enum "GtkIMPreeditStyle"))
(is (eq (gtype "GtkIMPreeditStyle")
(gtype (foreign-funcall "gtk_im_preedit_style_get_type" g-size))))
(is (eq 'gtk-im-preedit-style
(registered-enum-type "GtkIMPreeditStyle")))
(is (equal '("GTK_IM_PREEDIT_NOTHING" "GTK_IM_PREEDIT_CALLBACK"
"GTK_IM_PREEDIT_NONE")
(mapcar #'enum-item-name
(get-enum-items "GtkIMPreeditStyle"))))
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GtkIMPreeditStyle"))))
Check the nick names
(is (equal '("nothing" "callback" "none")
(mapcar #'enum-item-nick
(get-enum-items "GtkIMPreeditStyle"))))
(is (equal '(DEFINE-G-ENUM "GtkIMPreeditStyle" GTK-I-M-PREEDIT-STYLE
(:EXPORT T)
(:NOTHING 0)
(:CALLBACK 1)
(:NONE 2))
(get-g-type-definition "GtkIMPreeditStyle"))))
(test gtk-im-status-style
(is (g-type-is-enum "GtkIMStatusStyle"))
(is (eq (gtype "GtkIMStatusStyle")
(gtype (foreign-funcall "gtk_im_status_style_get_type" g-size))))
(is (eq 'gtk-im-status-style
(registered-enum-type "GtkIMStatusStyle")))
(is (equal '("GTK_IM_STATUS_NOTHING" "GTK_IM_STATUS_CALLBACK"
"GTK_IM_STATUS_NONE")
(mapcar #'enum-item-name
(get-enum-items "GtkIMStatusStyle"))))
(is (equal '(0 1 2)
(mapcar #'enum-item-value
(get-enum-items "GtkIMStatusStyle"))))
Check the nick names
(is (equal '("nothing" "callback" "none")
(mapcar #'enum-item-nick
(get-enum-items "GtkIMStatusStyle"))))
(is (equal '(DEFINE-G-ENUM "GtkIMStatusStyle" GTK-I-M-STATUS-STYLE
(:EXPORT T)
(:NOTHING 0)
(:CALLBACK 1)
(:NONE 2))
(get-g-type-definition "GtkIMStatusStyle"))))
GtkSettings
(test gtk-settings-class
(is (g-type-is-object "GtkSettings"))
(is (eq 'gtk-settings
(registered-object-type-by-name "GtkSettings")))
(is (eq (gtype "GtkSettings")
(gtype (foreign-funcall "gtk_settings_get_type" g-size))))
(is (eq (gtype "GObject") (g-type-parent "GtkSettings")))
(is (equal '()
(mapcar #'g-type-name (g-type-children "GtkSettings"))))
(is (equal '("GtkStyleProvider" "GtkStyleProviderPrivate")
(mapcar #'g-type-name (g-type-interfaces "GtkSettings"))))
(is (equal '("color-hash" "gtk-alternative-button-order"
"gtk-alternative-sort-arrows" "gtk-application-prefer-dark-theme"
"gtk-auto-mnemonics" "gtk-button-images" "gtk-can-change-accels"
"gtk-color-palette" "gtk-color-scheme" "gtk-cursor-aspect-ratio"
"gtk-cursor-blink" "gtk-cursor-blink-time"
"gtk-cursor-blink-timeout" "gtk-cursor-theme-name"
"gtk-cursor-theme-size" "gtk-decoration-layout"
"gtk-dialogs-use-header" "gtk-dnd-drag-threshold"
"gtk-double-click-distance" "gtk-double-click-time"
"gtk-enable-accels" "gtk-enable-animations"
"gtk-enable-event-sounds" "gtk-enable-input-feedback-sounds"
"gtk-enable-mnemonics" "gtk-enable-primary-paste"
"gtk-enable-tooltips" "gtk-entry-password-hint-timeout"
"gtk-entry-select-on-focus" "gtk-error-bell"
"gtk-fallback-icon-theme" "gtk-file-chooser-backend"
"gtk-font-name" "gtk-fontconfig-timestamp" "gtk-icon-sizes"
"gtk-icon-theme-name" "gtk-im-module" "gtk-im-preedit-style"
"gtk-im-status-style" "gtk-key-theme-name"
"gtk-keynav-cursor-only" "gtk-keynav-use-caret"
"gtk-keynav-wrap-around" "gtk-label-select-on-focus"
"gtk-long-press-time" "gtk-menu-bar-accel"
"gtk-menu-bar-popup-delay" "gtk-menu-images"
"gtk-menu-popdown-delay" "gtk-menu-popup-delay" "gtk-modules"
"gtk-overlay-scrolling" "gtk-primary-button-warps-slider"
"gtk-print-backends" "gtk-print-preview-command"
"gtk-recent-files-enabled" "gtk-recent-files-limit"
"gtk-recent-files-max-age" "gtk-scrolled-window-placement"
"gtk-shell-shows-app-menu" "gtk-shell-shows-desktop"
"gtk-shell-shows-menubar" "gtk-show-input-method-menu"
"gtk-show-unicode-menu" "gtk-sound-theme-name" "gtk-split-cursor"
"gtk-theme-name" "gtk-timeout-expand" "gtk-timeout-initial"
"gtk-timeout-repeat" "gtk-titlebar-double-click"
"gtk-titlebar-middle-click" "gtk-titlebar-right-click"
"gtk-toolbar-icon-size" "gtk-toolbar-style"
"gtk-tooltip-browse-mode-timeout" "gtk-tooltip-browse-timeout"
"gtk-tooltip-timeout" "gtk-touchscreen-mode" "gtk-visible-focus"
"gtk-xft-antialias" "gtk-xft-dpi" "gtk-xft-hinting"
"gtk-xft-hintstyle" "gtk-xft-rgba")
(stable-sort (mapcar #'g-param-spec-name
(g-object-class-list-properties "GtkSettings"))
#'string-lessp)))
(is (equal '(DEFINE-G-OBJECT-CLASS "GtkSettings" GTK-SETTINGS
(:SUPERCLASS G-OBJECT :EXPORT T :INTERFACES
("GtkStyleProvider" "GtkStyleProviderPrivate")
:TYPE-INITIALIZER "gtk_settings_get_type")
((COLOR-HASH GTK-SETTINGS-COLOR-HASH "color-hash"
"GHashTable" T NIL)
(GTK-ALTERNATIVE-BUTTON-ORDER
GTK-SETTINGS-GTK-ALTERNATIVE-BUTTON-ORDER
"gtk-alternative-button-order" "gboolean" T T)
(GTK-ALTERNATIVE-SORT-ARROWS
GTK-SETTINGS-GTK-ALTERNATIVE-SORT-ARROWS
"gtk-alternative-sort-arrows" "gboolean" T T)
(GTK-APPLICATION-PREFER-DARK-THEME
GTK-SETTINGS-GTK-APPLICATION-PREFER-DARK-THEME
"gtk-application-prefer-dark-theme" "gboolean" T T)
(GTK-AUTO-MNEMONICS GTK-SETTINGS-GTK-AUTO-MNEMONICS
"gtk-auto-mnemonics" "gboolean" T T)
(GTK-BUTTON-IMAGES GTK-SETTINGS-GTK-BUTTON-IMAGES
"gtk-button-images" "gboolean" T T)
(GTK-CAN-CHANGE-ACCELS
GTK-SETTINGS-GTK-CAN-CHANGE-ACCELS
"gtk-can-change-accels" "gboolean" T T)
(GTK-COLOR-PALETTE GTK-SETTINGS-GTK-COLOR-PALETTE
"gtk-color-palette" "gchararray" T T)
(GTK-COLOR-SCHEME GTK-SETTINGS-GTK-COLOR-SCHEME
"gtk-color-scheme" "gchararray" T T)
(GTK-CURSOR-ASPECT-RATIO
GTK-SETTINGS-GTK-CURSOR-ASPECT-RATIO
"gtk-cursor-aspect-ratio" "gfloat" T T)
(GTK-CURSOR-BLINK GTK-SETTINGS-GTK-CURSOR-BLINK
"gtk-cursor-blink" "gboolean" T T)
(GTK-CURSOR-BLINK-TIME
GTK-SETTINGS-GTK-CURSOR-BLINK-TIME
"gtk-cursor-blink-time" "gint" T T)
(GTK-CURSOR-BLINK-TIMEOUT
GTK-SETTINGS-GTK-CURSOR-BLINK-TIMEOUT
"gtk-cursor-blink-timeout" "gint" T T)
(GTK-CURSOR-THEME-NAME
GTK-SETTINGS-GTK-CURSOR-THEME-NAME
"gtk-cursor-theme-name" "gchararray" T T)
(GTK-CURSOR-THEME-SIZE
GTK-SETTINGS-GTK-CURSOR-THEME-SIZE
"gtk-cursor-theme-size" "gint" T T)
(GTK-DECORATION-LAYOUT
GTK-SETTINGS-GTK-DECORATION-LAYOUT
"gtk-decoration-layout" "gchararray" T T)
(GTK-DIALOGS-USE-HEADER
GTK-SETTINGS-GTK-DIALOGS-USE-HEADER
"gtk-dialogs-use-header" "gboolean" T T)
(GTK-DND-DRAG-THRESHOLD
GTK-SETTINGS-GTK-DND-DRAG-THRESHOLD
"gtk-dnd-drag-threshold" "gint" T T)
(GTK-DOUBLE-CLICK-DISTANCE
GTK-SETTINGS-GTK-DOUBLE-CLICK-DISTANCE
"gtk-double-click-distance" "gint" T T)
(GTK-DOUBLE-CLICK-TIME
GTK-SETTINGS-GTK-DOUBLE-CLICK-TIME
"gtk-double-click-time" "gint" T T)
(GTK-ENABLE-ACCELS GTK-SETTINGS-GTK-ENABLE-ACCELS
"gtk-enable-accels" "gboolean" T T)
(GTK-ENABLE-ANIMATIONS
GTK-SETTINGS-GTK-ENABLE-ANIMATIONS
"gtk-enable-animations" "gboolean" T T)
(GTK-ENABLE-EVENT-SOUNDS
GTK-SETTINGS-GTK-ENABLE-EVENT-SOUNDS
"gtk-enable-event-sounds" "gboolean" T T)
(GTK-ENABLE-INPUT-FEEDBACK-SOUNDS
GTK-SETTINGS-GTK-ENABLE-INPUT-FEEDBACK-SOUNDS
"gtk-enable-input-feedback-sounds" "gboolean" T T)
(GTK-ENABLE-MNEMONICS GTK-SETTINGS-GTK-ENABLE-MNEMONICS
"gtk-enable-mnemonics" "gboolean" T T)
(GTK-ENABLE-PRIMARY-PASTE
GTK-SETTINGS-GTK-ENABLE-PRIMARY-PASTE
"gtk-enable-primary-paste" "gboolean" T T)
(GTK-ENABLE-TOOLTIPS GTK-SETTINGS-GTK-ENABLE-TOOLTIPS
"gtk-enable-tooltips" "gboolean" T T)
(GTK-ENTRY-PASSWORD-HINT-TIMEOUT
GTK-SETTINGS-GTK-ENTRY-PASSWORD-HINT-TIMEOUT
"gtk-entry-password-hint-timeout" "guint" T T)
(GTK-ENTRY-SELECT-ON-FOCUS
GTK-SETTINGS-GTK-ENTRY-SELECT-ON-FOCUS
"gtk-entry-select-on-focus" "gboolean" T T)
(GTK-ERROR-BELL GTK-SETTINGS-GTK-ERROR-BELL
"gtk-error-bell" "gboolean" T T)
(GTK-FALLBACK-ICON-THEME
GTK-SETTINGS-GTK-FALLBACK-ICON-THEME
"gtk-fallback-icon-theme" "gchararray" T T)
(GTK-FILE-CHOOSER-BACKEND
GTK-SETTINGS-GTK-FILE-CHOOSER-BACKEND
"gtk-file-chooser-backend" "gchararray" T T)
(GTK-FONT-NAME GTK-SETTINGS-GTK-FONT-NAME
"gtk-font-name" "gchararray" T T)
(GTK-FONTCONFIG-TIMESTAMP
GTK-SETTINGS-GTK-FONTCONFIG-TIMESTAMP
"gtk-fontconfig-timestamp" "guint" T T)
(GTK-ICON-SIZES GTK-SETTINGS-GTK-ICON-SIZES
"gtk-icon-sizes" "gchararray" T T)
(GTK-ICON-THEME-NAME GTK-SETTINGS-GTK-ICON-THEME-NAME
"gtk-icon-theme-name" "gchararray" T T)
(GTK-IM-MODULE GTK-SETTINGS-GTK-IM-MODULE
"gtk-im-module" "gchararray" T T)
(GTK-IM-PREEDIT-STYLE GTK-SETTINGS-GTK-IM-PREEDIT-STYLE
"gtk-im-preedit-style" "GtkIMPreeditStyle" T T)
(GTK-IM-STATUS-STYLE GTK-SETTINGS-GTK-IM-STATUS-STYLE
"gtk-im-status-style" "GtkIMStatusStyle" T T)
(GTK-KEY-THEME-NAME GTK-SETTINGS-GTK-KEY-THEME-NAME
"gtk-key-theme-name" "gchararray" T T)
(GTK-KEYNAV-CURSOR-ONLY
GTK-SETTINGS-GTK-KEYNAV-CURSOR-ONLY
"gtk-keynav-cursor-only" "gboolean" T T)
(GTK-KEYNAV-USE-CARET GTK-SETTINGS-GTK-KEYNAV-USE-CARET
"gtk-keynav-use-caret" "gboolean" T T)
(GTK-KEYNAV-WRAP-AROUND
GTK-SETTINGS-GTK-KEYNAV-WRAP-AROUND
"gtk-keynav-wrap-around" "gboolean" T T)
(GTK-LABEL-SELECT-ON-FOCUS
GTK-SETTINGS-GTK-LABEL-SELECT-ON-FOCUS
"gtk-label-select-on-focus" "gboolean" T T)
(GTK-LONG-PRESS-TIME GTK-SETTINGS-GTK-LONG-PRESS-TIME
"gtk-long-press-time" "guint" T T)
(GTK-MENU-BAR-ACCEL GTK-SETTINGS-GTK-MENU-BAR-ACCEL
"gtk-menu-bar-accel" "gchararray" T T)
(GTK-MENU-BAR-POPUP-DELAY
GTK-SETTINGS-GTK-MENU-BAR-POPUP-DELAY
"gtk-menu-bar-popup-delay" "gint" T T)
(GTK-MENU-IMAGES GTK-SETTINGS-GTK-MENU-IMAGES
"gtk-menu-images" "gboolean" T T)
(GTK-MENU-POPDOWN-DELAY
GTK-SETTINGS-GTK-MENU-POPDOWN-DELAY
"gtk-menu-popdown-delay" "gint" T T)
(GTK-MENU-POPUP-DELAY GTK-SETTINGS-GTK-MENU-POPUP-DELAY
"gtk-menu-popup-delay" "gint" T T)
(GTK-MODULES GTK-SETTINGS-GTK-MODULES "gtk-modules"
"gchararray" T T)
(GTK-OVERLAY-SCROLLING
GTK-SETTINGS-GTK-OVERLAY-SCROLLING
"gtk-overlay-scrolling" "gboolean" T T)
(GTK-PRIMARY-BUTTON-WARPS-SLIDER
GTK-SETTINGS-GTK-PRIMARY-BUTTON-WARPS-SLIDER
"gtk-primary-button-warps-slider" "gboolean" T T)
(GTK-PRINT-BACKENDS GTK-SETTINGS-GTK-PRINT-BACKENDS
"gtk-print-backends" "gchararray" T T)
(GTK-PRINT-PREVIEW-COMMAND
GTK-SETTINGS-GTK-PRINT-PREVIEW-COMMAND
"gtk-print-preview-command" "gchararray" T T)
(GTK-RECENT-FILES-ENABLED
GTK-SETTINGS-GTK-RECENT-FILES-ENABLED
"gtk-recent-files-enabled" "gboolean" T T)
(GTK-RECENT-FILES-LIMIT
GTK-SETTINGS-GTK-RECENT-FILES-LIMIT
"gtk-recent-files-limit" "gint" T T)
(GTK-RECENT-FILES-MAX-AGE
GTK-SETTINGS-GTK-RECENT-FILES-MAX-AGE
"gtk-recent-files-max-age" "gint" T T)
(GTK-SCROLLED-WINDOW-PLACEMENT
GTK-SETTINGS-GTK-SCROLLED-WINDOW-PLACEMENT
"gtk-scrolled-window-placement" "GtkCornerType" T T)
(GTK-SHELL-SHOWS-APP-MENU
GTK-SETTINGS-GTK-SHELL-SHOWS-APP-MENU
"gtk-shell-shows-app-menu" "gboolean" T T)
(GTK-SHELL-SHOWS-DESKTOP
GTK-SETTINGS-GTK-SHELL-SHOWS-DESKTOP
"gtk-shell-shows-desktop" "gboolean" T T)
(GTK-SHELL-SHOWS-MENUBAR
GTK-SETTINGS-GTK-SHELL-SHOWS-MENUBAR
"gtk-shell-shows-menubar" "gboolean" T T)
(GTK-SHOW-INPUT-METHOD-MENU
GTK-SETTINGS-GTK-SHOW-INPUT-METHOD-MENU
"gtk-show-input-method-menu" "gboolean" T T)
(GTK-SHOW-UNICODE-MENU
GTK-SETTINGS-GTK-SHOW-UNICODE-MENU
"gtk-show-unicode-menu" "gboolean" T T)
(GTK-SOUND-THEME-NAME GTK-SETTINGS-GTK-SOUND-THEME-NAME
"gtk-sound-theme-name" "gchararray" T T)
(GTK-SPLIT-CURSOR GTK-SETTINGS-GTK-SPLIT-CURSOR
"gtk-split-cursor" "gboolean" T T)
(GTK-THEME-NAME GTK-SETTINGS-GTK-THEME-NAME
"gtk-theme-name" "gchararray" T T)
(GTK-TIMEOUT-EXPAND GTK-SETTINGS-GTK-TIMEOUT-EXPAND
"gtk-timeout-expand" "gint" T T)
(GTK-TIMEOUT-INITIAL GTK-SETTINGS-GTK-TIMEOUT-INITIAL
"gtk-timeout-initial" "gint" T T)
(GTK-TIMEOUT-REPEAT GTK-SETTINGS-GTK-TIMEOUT-REPEAT
"gtk-timeout-repeat" "gint" T T)
(GTK-TITLEBAR-DOUBLE-CLICK
GTK-SETTINGS-GTK-TITLEBAR-DOUBLE-CLICK
"gtk-titlebar-double-click" "gchararray" T T)
(GTK-TITLEBAR-MIDDLE-CLICK
GTK-SETTINGS-GTK-TITLEBAR-MIDDLE-CLICK
"gtk-titlebar-middle-click" "gchararray" T T)
(GTK-TITLEBAR-RIGHT-CLICK
GTK-SETTINGS-GTK-TITLEBAR-RIGHT-CLICK
"gtk-titlebar-right-click" "gchararray" T T)
(GTK-TOOLBAR-ICON-SIZE
GTK-SETTINGS-GTK-TOOLBAR-ICON-SIZE
"gtk-toolbar-icon-size" "GtkIconSize" T T)
(GTK-TOOLBAR-STYLE GTK-SETTINGS-GTK-TOOLBAR-STYLE
"gtk-toolbar-style" "GtkToolbarStyle" T T)
(GTK-TOOLTIP-BROWSE-MODE-TIMEOUT
GTK-SETTINGS-GTK-TOOLTIP-BROWSE-MODE-TIMEOUT
"gtk-tooltip-browse-mode-timeout" "gint" T T)
(GTK-TOOLTIP-BROWSE-TIMEOUT
GTK-SETTINGS-GTK-TOOLTIP-BROWSE-TIMEOUT
"gtk-tooltip-browse-timeout" "gint" T T)
(GTK-TOOLTIP-TIMEOUT GTK-SETTINGS-GTK-TOOLTIP-TIMEOUT
"gtk-tooltip-timeout" "gint" T T)
(GTK-TOUCHSCREEN-MODE GTK-SETTINGS-GTK-TOUCHSCREEN-MODE
"gtk-touchscreen-mode" "gboolean" T T)
(GTK-VISIBLE-FOCUS GTK-SETTINGS-GTK-VISIBLE-FOCUS
"gtk-visible-focus" "GtkPolicyType" T T)
(GTK-XFT-ANTIALIAS GTK-SETTINGS-GTK-XFT-ANTIALIAS
"gtk-xft-antialias" "gint" T T)
(GTK-XFT-DPI GTK-SETTINGS-GTK-XFT-DPI "gtk-xft-dpi"
"gint" T T)
(GTK-XFT-HINTING GTK-SETTINGS-GTK-XFT-HINTING
"gtk-xft-hinting" "gint" T T)
(GTK-XFT-HINTSTYLE GTK-SETTINGS-GTK-XFT-HINTSTYLE
"gtk-xft-hintstyle" "gchararray" T T)
(GTK-XFT-RGBA GTK-SETTINGS-GTK-XFT-RGBA "gtk-xft-rgba"
"gchararray" T T)))
(get-g-type-definition "GtkSettings"))))
(test gtk-settings-properties
(let ((settings (gtk-settings-default)))
(signals (error) (gtk-settings-color-hash settings))
#-windows
(is-false (gtk-settings-gtk-alternative-button-order settings))
#-windows
(is-false (gtk-settings-gtk-alternative-sort-arrows settings))
(is-false (gtk-settings-gtk-application-prefer-dark-theme settings))
(is-true (gtk-settings-gtk-auto-mnemonics settings))
(is-false (gtk-settings-gtk-button-images settings))
(is-false (gtk-settings-gtk-can-change-accels settings))
(is (stringp (gtk-settings-gtk-color-palette settings)))
(is (stringp (gtk-settings-gtk-color-scheme settings)))
(is-true (gtk-settings-gtk-cursor-blink settings))
(is (integerp (gtk-settings-gtk-cursor-blink-time settings)))
(is (integerp (gtk-settings-gtk-cursor-blink-timeout settings)))
#-windows
(is (stringp (gtk-settings-gtk-cursor-theme-name settings)))
(is (integerp (gtk-settings-gtk-cursor-theme-size settings)))
(is-true (gtk-settings-gtk-decoration-layout settings))
#-windows
(is-true (gtk-settings-gtk-dialogs-use-header settings))
(is (integerp (gtk-settings-gtk-dnd-drag-threshold settings)))
(is (integerp (gtk-settings-gtk-double-click-distance settings)))
(is (integerp (gtk-settings-gtk-double-click-time settings)))
(is-true (gtk-settings-gtk-enable-accels settings))
(is-true (gtk-settings-gtk-enable-animations settings))
(is-true (gtk-settings-gtk-enable-event-sounds settings))
(is-true (gtk-settings-gtk-enable-input-feedback-sounds settings))
(is-true (gtk-settings-gtk-enable-mnemonics settings))
(is-true (gtk-settings-gtk-enable-primary-paste settings))
(is-true (gtk-settings-gtk-enable-tooltips settings))
(is-true (gtk-settings-gtk-entry-password-hint-timeout settings))
(is-true (gtk-settings-gtk-entry-select-on-focus settings))
(is-true (gtk-settings-gtk-error-bell settings))
(is-false (gtk-settings-gtk-fallback-icon-theme settings))
(is-false (gtk-settings-gtk-file-chooser-backend settings))
(is (stringp (gtk-settings-gtk-font-name settings)))
(is (integerp (gtk-settings-gtk-fontconfig-timestamp settings)))
#-windows
(is (stringp (gtk-settings-gtk-icon-sizes settings)))
(is (stringp (gtk-settings-gtk-icon-theme-name settings)))
(is (stringp (gtk-settings-gtk-im-module settings)))
(is (eq :callback (gtk-settings-gtk-im-preedit-style settings)))
(is (eq :callback (gtk-settings-gtk-im-status-style settings)))
#-windows
(is (stringp (gtk-settings-gtk-key-theme-name settings)))
(is-false (gtk-settings-gtk-keynav-cursor-only settings))
(is-false (gtk-settings-gtk-keynav-use-caret settings))
(is-true (gtk-settings-gtk-keynav-wrap-around settings))
(is-true (gtk-settings-gtk-label-select-on-focus settings))
(is (integerp (gtk-settings-gtk-long-press-time settings)))
(is (stringp (gtk-settings-gtk-menu-bar-accel settings)))
(is (integerp (gtk-settings-gtk-menu-bar-popup-delay settings)))
(is-false (gtk-settings-gtk-menu-images settings))
(is (integerp (gtk-settings-gtk-menu-popdown-delay settings)))
(is (integerp (gtk-settings-gtk-menu-popup-delay settings)))
#-windows
(is (stringp (gtk-settings-gtk-modules settings)))
(is-true (gtk-settings-gtk-primary-button-warps-slider settings))
(is (stringp (gtk-settings-gtk-print-backends settings)))
(is (stringp (gtk-settings-gtk-print-preview-command settings)))
(signals (error) (gtk-settings-gtk-recent-files-enabled settings))
(is (integerp (gtk-settings-gtk-recent-files-limit settings)))
(is (integerp (gtk-settings-gtk-recent-files-max-age settings)))
(is-true (gtk-settings-gtk-scrolled-window-placement settings))
(is-false (gtk-settings-gtk-shell-shows-app-menu settings))
(is-true (gtk-settings-gtk-shell-shows-desktop settings))
(is-false (gtk-settings-gtk-shell-shows-menubar settings))
(is-false (gtk-settings-gtk-show-input-method-menu settings))
(is-false (gtk-settings-gtk-show-unicode-menu settings))
(is (stringp (gtk-settings-gtk-sound-theme-name settings)))
#-windows
(is-true (gtk-settings-gtk-split-cursor settings))
(is (stringp (gtk-settings-gtk-theme-name settings)))
(is (integerp (gtk-settings-gtk-timeout-expand settings)))
(is (integerp (gtk-settings-gtk-timeout-initial settings)))
(is (integerp (gtk-settings-gtk-timeout-repeat settings)))
(is (stringp (gtk-settings-gtk-titlebar-double-click settings)))
(is (stringp (gtk-settings-gtk-titlebar-middle-click settings)))
(is (stringp (gtk-settings-gtk-titlebar-right-click settings)))
(is (eq :large-toolbar (gtk-settings-gtk-toolbar-icon-size settings)))
(is (eq :both-horiz (gtk-settings-gtk-toolbar-style settings)))
(is (integerp (gtk-settings-gtk-tooltip-browse-mode-timeout settings)))
(is (integerp (gtk-settings-gtk-tooltip-browse-timeout settings)))
(is (integerp (gtk-settings-gtk-tooltip-timeout settings)))
(is-false (gtk-settings-gtk-touchscreen-mode settings))
(is (eq :automatic (gtk-settings-gtk-visible-focus settings)))
(is (integerp (gtk-settings-gtk-xft-antialias settings)))
(is (integerp (gtk-settings-gtk-xft-dpi settings)))
(is (integerp (gtk-settings-gtk-xft-hinting settings)))
(is (stringp (gtk-settings-gtk-xft-hintstyle settings)))
(is (stringp (gtk-settings-gtk-xft-rgba settings)))))
gtk_settings_install_property deprecated
deprecated
2021 - 10 - 14
|
6039b96207eac77f08c5cf6ddfebbb14f65c96c26fb10e75bc06737d93947b19 | mdsebald/link_blox_app | lblx_timer_min_on.erl |
%%% @doc
BLOCKTYPE
%%% Minimum On Time
%%% DESCRIPTION
%%% Block output will follow block binary input value but
%%% will remain true (on) for the minimum specified amount of time
%%% LINKS
%%% @end
-module(lblx_timer_min_on).
-author("Mark Sebald").
-include("../block_state.hrl").
%% ====================================================================
%% API functions
%% ====================================================================
-export([groups/0, version/0]).
-export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]).
-export([handle_info/2]).
groups() -> [timing].
version() -> "0.1.0".
%% Merge the block type specific, Config, Input, and Output attributes
%% with the common Config, Input, and Output attributes, that all block types have
-spec default_configs(BlockName :: block_name(),
Description :: string()) -> config_attribs().
default_configs(BlockName, Description) ->
attrib_utils:merge_attribute_lists(
block_common:configs(BlockName, ?MODULE, version(), Description),
[
]).
-spec default_inputs() -> input_attribs().
default_inputs() ->
attrib_utils:merge_attribute_lists(
block_common:inputs(),
[
{min_on_time, {1000, {1000}}}, %| int | 1000 | 1..max int |
{input, {empty, {empty}}} %| bool | empty | true, false |
]).
-spec default_outputs() -> output_attribs().
default_outputs() ->
attrib_utils:merge_attribute_lists(
block_common:outputs(),
[
]).
%%
%% Create a set of block attributes for this block type.
Init attributes are used to override the default attribute values
%% and to add attributes to the lists of default attributes
%%
-spec create(BlockName :: block_name(),
Description :: string()) -> block_defn().
create(BlockName, Description) ->
create(BlockName, Description, [], [], []).
-spec create(BlockName :: block_name(),
Description :: string(),
InitConfig :: config_attribs(),
InitInputs :: input_attribs()) -> block_defn().
create(BlockName, Description, InitConfig, InitInputs) ->
create(BlockName, Description, InitConfig, InitInputs, []).
-spec create(BlockName :: block_name(),
Description :: string(),
InitConfig :: config_attribs(),
InitInputs :: input_attribs(),
InitOutputs :: output_attribs()) -> block_defn().
create(BlockName, Description, InitConfig, InitInputs, InitOutputs) ->
% Update Default Config, Input, Output, and Private attribute values
% with the initial values passed into this function.
%
% If any of the intial attributes do not already exist in the
% default attribute lists, merge_attribute_lists() will create them.
Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig),
Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs),
Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs),
% This is the block definition,
{Config, Inputs, Outputs}.
%%
%% Upgrade block attribute values, when block code and block data versions are different
%%
-spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}.
upgrade({Config, Inputs, Outputs}) ->
ModuleVer = version(),
{BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config),
BlockType = type_utils:type_name(BlockModule),
case attrib_utils:set_value(Config, version, version()) of
{ok, UpdConfig} ->
m_logger:info(block_type_upgraded_from_ver_to,
[BlockName, BlockType, ConfigVer, ModuleVer]),
{ok, {UpdConfig, Inputs, Outputs}};
{error, Reason} ->
m_logger:error(err_upgrading_block_type_from_ver_to,
[Reason, BlockName, BlockType, ConfigVer, ModuleVer]),
{error, Reason}
end.
%%
Initialize block values
%% Perform any setup here as needed before starting execution
%%
-spec initialize(BlockState :: block_state()) -> block_state().
initialize({Config, Inputs, Outputs, Private}) ->
Private1 = attrib_utils:add_attribute(Private, {min_on_timer_ref, {empty}}),
% No config values to check
Outputs1 = output_utils:set_value_status(Outputs, null, initialed),
% This is the block state
{Config, Inputs, Outputs1, Private1}.
%%
%% Execute the block specific functionality
%%
-spec execute(BlockState :: block_state(),
ExecMethod :: exec_method()) -> block_state().
execute({Config, Inputs, Outputs, Private}, disable) ->
Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled),
{Config, Inputs, Outputs1, Private};
execute({Config, Inputs, Outputs, Private}, _ExecMethod) ->
Timer reference shows block is in min time on mode )
{ok, MinOnTimerRef} = attrib_utils:get_value(Private, min_on_timer_ref),
{ok, CurrValue} = attrib_utils:get_value(Outputs, value),
case input_utils:get_integer_greater_than(Inputs, min_on_time, -1) of
{ok, MinOnTime} ->
case input_utils:get_boolean(Inputs, input) of
% If input is true, start min on time timer if not started already
% Set output to true if input is true
{ok, true} ->
Value = true, Status = normal,
case MinOnTimerRef of
empty ->
BlockName = config_utils:name(Config),
if (is_integer(MinOnTime) andalso (MinOnTime > 0)) ->
NewTimerRef = set_min_on_timer(BlockName, MinOnTime),
{ok, Private1} = attrib_utils:set_value(Private, min_on_timer_ref, NewTimerRef);
true ->
Private1 = Private
end;
_Pid ->
Private1 = Private
end;
% Input is null or false, if min-on timer has expired, set output to null or false
% Otherwise leave output unchanged
{ok, NullFalse} ->
case MinOnTimerRef of
empty ->
Value = NullFalse, Status = normal;
_Pid ->
Value = CurrValue, Status = normal
end,
Private1 = Private;
{error, Reason} ->
input_utils:log_error(Config, input, Reason),
Value = null, Status = input_err,
Private1 = Private
end;
{error, Reason} ->
input_utils:log_error(Config, min_on_time, Reason),
Value = null, Status = input_err,
Private1 = Private
end,
Outputs1 = output_utils:set_value_status(Outputs, Value, Status),
% Return updated block state
{Config, Inputs, Outputs1, Private1}.
%%
%% Delete the block
%%
-spec delete(BlockState :: block_state()) -> block_defn().
delete({Config, Inputs, Outputs, Private}) ->
% Cancel min on timer if it exists
case attrib_utils:get_value(Private, min_on_timer_ref) of
{ok, empty} -> ok;
{ok, TimerRef} -> erlang:cancel_timer(TimerRef);
{error, _Reason} -> ok % Don't care if timer_ref doesn't exist
end,
{Config, Inputs, Outputs}.
%%
%% Info message, from min on timer expiring
%%
-spec handle_info(Info :: term(),
BlockState :: block_state()) -> {noreply, block_state()}.
handle_info(min_on_timer, {Config, Inputs, Outputs, Private}) ->
% Indicate min on timer has expired by clearing timer reference
{ok, Private1} = attrib_utils:set_value(Private, min_on_timer_ref, empty),
% Execute the block
NewBlockState = block_common:execute({Config, Inputs, Outputs, Private1}, timer),
{noreply, NewBlockState};
handle_info(Info, BlockState) ->
{BlockName, BlockModule} = config_utils:name_module(BlockState),
m_logger:warning(block_type_name_unknown_info_msg, [BlockModule, BlockName, Info]),
{noreply, BlockState}.
%% ====================================================================
Internal functions
%% ====================================================================
%%
%% Set minimum on time, timer
%%
-spec set_min_on_timer(BlockName :: block_name(),
MinOnTime :: pos_integer()) -> reference().
set_min_on_timer(BlockName, MinOnTime) ->
erlang:send_after(MinOnTime, BlockName, min_on_timer).
%% ====================================================================
%% Tests
%% ====================================================================
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include("block_io_test_gen.hrl").
test_sets() ->
[
{[{status, normal}]}
].
-endif.
| null | https://raw.githubusercontent.com/mdsebald/link_blox_app/64034fa5854759ad16625b93e3dde65a9c65f615/src/block_types/lblx_timer_min_on.erl | erlang | @doc
Minimum On Time
DESCRIPTION
Block output will follow block binary input value but
will remain true (on) for the minimum specified amount of time
LINKS
@end
====================================================================
API functions
====================================================================
Merge the block type specific, Config, Input, and Output attributes
with the common Config, Input, and Output attributes, that all block types have
| int | 1000 | 1..max int |
| bool | empty | true, false |
Create a set of block attributes for this block type.
and to add attributes to the lists of default attributes
Update Default Config, Input, Output, and Private attribute values
with the initial values passed into this function.
If any of the intial attributes do not already exist in the
default attribute lists, merge_attribute_lists() will create them.
This is the block definition,
Upgrade block attribute values, when block code and block data versions are different
Perform any setup here as needed before starting execution
No config values to check
This is the block state
Execute the block specific functionality
If input is true, start min on time timer if not started already
Set output to true if input is true
Input is null or false, if min-on timer has expired, set output to null or false
Otherwise leave output unchanged
Return updated block state
Delete the block
Cancel min on timer if it exists
Don't care if timer_ref doesn't exist
Info message, from min on timer expiring
Indicate min on timer has expired by clearing timer reference
Execute the block
====================================================================
====================================================================
Set minimum on time, timer
====================================================================
Tests
==================================================================== |
BLOCKTYPE
-module(lblx_timer_min_on).
-author("Mark Sebald").
-include("../block_state.hrl").
-export([groups/0, version/0]).
-export([create/2, create/4, create/5, upgrade/1, initialize/1, execute/2, delete/1]).
-export([handle_info/2]).
groups() -> [timing].
version() -> "0.1.0".
-spec default_configs(BlockName :: block_name(),
Description :: string()) -> config_attribs().
default_configs(BlockName, Description) ->
attrib_utils:merge_attribute_lists(
block_common:configs(BlockName, ?MODULE, version(), Description),
[
]).
-spec default_inputs() -> input_attribs().
default_inputs() ->
attrib_utils:merge_attribute_lists(
block_common:inputs(),
[
]).
-spec default_outputs() -> output_attribs().
default_outputs() ->
attrib_utils:merge_attribute_lists(
block_common:outputs(),
[
]).
Init attributes are used to override the default attribute values
-spec create(BlockName :: block_name(),
Description :: string()) -> block_defn().
create(BlockName, Description) ->
create(BlockName, Description, [], [], []).
-spec create(BlockName :: block_name(),
Description :: string(),
InitConfig :: config_attribs(),
InitInputs :: input_attribs()) -> block_defn().
create(BlockName, Description, InitConfig, InitInputs) ->
create(BlockName, Description, InitConfig, InitInputs, []).
-spec create(BlockName :: block_name(),
Description :: string(),
InitConfig :: config_attribs(),
InitInputs :: input_attribs(),
InitOutputs :: output_attribs()) -> block_defn().
create(BlockName, Description, InitConfig, InitInputs, InitOutputs) ->
Config = attrib_utils:merge_attribute_lists(default_configs(BlockName, Description), InitConfig),
Inputs = attrib_utils:merge_attribute_lists(default_inputs(), InitInputs),
Outputs = attrib_utils:merge_attribute_lists(default_outputs(), InitOutputs),
{Config, Inputs, Outputs}.
-spec upgrade(BlockDefn :: block_defn()) -> {ok, block_defn()} | {error, atom()}.
upgrade({Config, Inputs, Outputs}) ->
ModuleVer = version(),
{BlockName, BlockModule, ConfigVer} = config_utils:name_module_version(Config),
BlockType = type_utils:type_name(BlockModule),
case attrib_utils:set_value(Config, version, version()) of
{ok, UpdConfig} ->
m_logger:info(block_type_upgraded_from_ver_to,
[BlockName, BlockType, ConfigVer, ModuleVer]),
{ok, {UpdConfig, Inputs, Outputs}};
{error, Reason} ->
m_logger:error(err_upgrading_block_type_from_ver_to,
[Reason, BlockName, BlockType, ConfigVer, ModuleVer]),
{error, Reason}
end.
Initialize block values
-spec initialize(BlockState :: block_state()) -> block_state().
initialize({Config, Inputs, Outputs, Private}) ->
Private1 = attrib_utils:add_attribute(Private, {min_on_timer_ref, {empty}}),
Outputs1 = output_utils:set_value_status(Outputs, null, initialed),
{Config, Inputs, Outputs1, Private1}.
-spec execute(BlockState :: block_state(),
ExecMethod :: exec_method()) -> block_state().
execute({Config, Inputs, Outputs, Private}, disable) ->
Outputs1 = output_utils:update_all_outputs(Outputs, null, disabled),
{Config, Inputs, Outputs1, Private};
execute({Config, Inputs, Outputs, Private}, _ExecMethod) ->
Timer reference shows block is in min time on mode )
{ok, MinOnTimerRef} = attrib_utils:get_value(Private, min_on_timer_ref),
{ok, CurrValue} = attrib_utils:get_value(Outputs, value),
case input_utils:get_integer_greater_than(Inputs, min_on_time, -1) of
{ok, MinOnTime} ->
case input_utils:get_boolean(Inputs, input) of
{ok, true} ->
Value = true, Status = normal,
case MinOnTimerRef of
empty ->
BlockName = config_utils:name(Config),
if (is_integer(MinOnTime) andalso (MinOnTime > 0)) ->
NewTimerRef = set_min_on_timer(BlockName, MinOnTime),
{ok, Private1} = attrib_utils:set_value(Private, min_on_timer_ref, NewTimerRef);
true ->
Private1 = Private
end;
_Pid ->
Private1 = Private
end;
{ok, NullFalse} ->
case MinOnTimerRef of
empty ->
Value = NullFalse, Status = normal;
_Pid ->
Value = CurrValue, Status = normal
end,
Private1 = Private;
{error, Reason} ->
input_utils:log_error(Config, input, Reason),
Value = null, Status = input_err,
Private1 = Private
end;
{error, Reason} ->
input_utils:log_error(Config, min_on_time, Reason),
Value = null, Status = input_err,
Private1 = Private
end,
Outputs1 = output_utils:set_value_status(Outputs, Value, Status),
{Config, Inputs, Outputs1, Private1}.
-spec delete(BlockState :: block_state()) -> block_defn().
delete({Config, Inputs, Outputs, Private}) ->
case attrib_utils:get_value(Private, min_on_timer_ref) of
{ok, empty} -> ok;
{ok, TimerRef} -> erlang:cancel_timer(TimerRef);
end,
{Config, Inputs, Outputs}.
-spec handle_info(Info :: term(),
BlockState :: block_state()) -> {noreply, block_state()}.
handle_info(min_on_timer, {Config, Inputs, Outputs, Private}) ->
{ok, Private1} = attrib_utils:set_value(Private, min_on_timer_ref, empty),
NewBlockState = block_common:execute({Config, Inputs, Outputs, Private1}, timer),
{noreply, NewBlockState};
handle_info(Info, BlockState) ->
{BlockName, BlockModule} = config_utils:name_module(BlockState),
m_logger:warning(block_type_name_unknown_info_msg, [BlockModule, BlockName, Info]),
{noreply, BlockState}.
Internal functions
-spec set_min_on_timer(BlockName :: block_name(),
MinOnTime :: pos_integer()) -> reference().
set_min_on_timer(BlockName, MinOnTime) ->
erlang:send_after(MinOnTime, BlockName, min_on_timer).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include("block_io_test_gen.hrl").
test_sets() ->
[
{[{status, normal}]}
].
-endif.
|
138270952e4d2bc79e8d2e56d72ebb37a015833a4e0993250368ac860f11f2c1 | oakes/odoyle-rum-todo | start.clj | (ns odoyle-rum-todo.start
(:require [ring.adapter.jetty :refer [run-jetty]]
[ring.middleware.resource :refer [wrap-resource]]
[ring.middleware.session :refer [wrap-session]]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.gzip :refer [wrap-gzip]]
[ring.util.request :refer [body-string]]
[ring.util.response :refer [not-found]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.edn :as edn]
[clojure.data.codec.base64 :as base64]
[rum.core :as rum]
[odoyle.rum :as orum]
[odoyle-rum-todo.core :as c])
(:gen-class))
(def port 3000)
(defn page [initial-state]
(binding [;; this binding causes the new matches triggered by `insert-all-todos`
;; to be stored locally, so they don't affect other users
;; that happen to be requesting this route at the same time
orum/*matches* (volatile! {})]
;; if there are any todos in the user's ring session,
;; insert them into the o'doyle session.
;; we are only doing this for side-effects.
(c/insert-all-todos c/initial-session (:all-todos initial-state))
;; render the html
(-> "template.html" io/resource slurp
(str/replace "{{content}}" (rum/render-html (c/app-root nil)))
;; save the todos in a hidden div that the client can read when it loads
;; we are using base64 to prevent breakage (i.e. if a todo contains angle brackets)
(str/replace "{{initial-state}}" (-> (pr-str initial-state)
(.getBytes "UTF-8")
base64/encode
(String. "UTF-8"))))))
(defmulti handler (juxt :request-method :uri))
(defmethod handler [:get "/"]
[request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (page (:session request))})
(defmethod handler [:post "/all-todos"]
[request]
{:status 200
:session (assoc (:session request) :all-todos
(edn/read-string (body-string request)))})
(defmethod handler :default
[request]
(not-found "Page not found"))
(defn run-server [handler-fn]
(run-jetty (-> handler-fn
(wrap-resource "public")
wrap-session
wrap-content-type
wrap-gzip)
{:port port :join? false})
(println (str "Started server on :" port)))
(defn -main [& args]
(run-server handler))
| null | https://raw.githubusercontent.com/oakes/odoyle-rum-todo/15d6dca44ec5ffdb06952937a4a5f8e1de74ca1b/src/odoyle_rum_todo/start.clj | clojure | this binding causes the new matches triggered by `insert-all-todos`
to be stored locally, so they don't affect other users
that happen to be requesting this route at the same time
if there are any todos in the user's ring session,
insert them into the o'doyle session.
we are only doing this for side-effects.
render the html
save the todos in a hidden div that the client can read when it loads
we are using base64 to prevent breakage (i.e. if a todo contains angle brackets) | (ns odoyle-rum-todo.start
(:require [ring.adapter.jetty :refer [run-jetty]]
[ring.middleware.resource :refer [wrap-resource]]
[ring.middleware.session :refer [wrap-session]]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.gzip :refer [wrap-gzip]]
[ring.util.request :refer [body-string]]
[ring.util.response :refer [not-found]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.edn :as edn]
[clojure.data.codec.base64 :as base64]
[rum.core :as rum]
[odoyle.rum :as orum]
[odoyle-rum-todo.core :as c])
(:gen-class))
(def port 3000)
(defn page [initial-state]
orum/*matches* (volatile! {})]
(c/insert-all-todos c/initial-session (:all-todos initial-state))
(-> "template.html" io/resource slurp
(str/replace "{{content}}" (rum/render-html (c/app-root nil)))
(str/replace "{{initial-state}}" (-> (pr-str initial-state)
(.getBytes "UTF-8")
base64/encode
(String. "UTF-8"))))))
(defmulti handler (juxt :request-method :uri))
(defmethod handler [:get "/"]
[request]
{:status 200
:headers {"Content-Type" "text/html"}
:body (page (:session request))})
(defmethod handler [:post "/all-todos"]
[request]
{:status 200
:session (assoc (:session request) :all-todos
(edn/read-string (body-string request)))})
(defmethod handler :default
[request]
(not-found "Page not found"))
(defn run-server [handler-fn]
(run-jetty (-> handler-fn
(wrap-resource "public")
wrap-session
wrap-content-type
wrap-gzip)
{:port port :join? false})
(println (str "Started server on :" port)))
(defn -main [& args]
(run-server handler))
|
dddfe838e67d6e6d297f37971bacfa03fb8fc31d514fcd41b034e3e57fa92b0f | mishadoff/project-euler | problem028.clj | (ns project-euler)
Elapsed time : 3.276816 msecs
(defn euler-028 []
(inc (reduce +
(loop [incr 2 times 0 number 1 lst [] depth 0]
(if (= (/ (dec 1001) 2) depth) lst
(if (= times 4)
(recur (+ 2 incr) 0 number lst (inc depth))
(recur incr (inc times) (+ number incr)
(conj lst (+ number incr)) depth))))))) | null | https://raw.githubusercontent.com/mishadoff/project-euler/45642adf29626d3752227c5a342886b33c70b337/src/project_euler/problem028.clj | clojure | (ns project-euler)
Elapsed time : 3.276816 msecs
(defn euler-028 []
(inc (reduce +
(loop [incr 2 times 0 number 1 lst [] depth 0]
(if (= (/ (dec 1001) 2) depth) lst
(if (= times 4)
(recur (+ 2 incr) 0 number lst (inc depth))
(recur incr (inc times) (+ number incr)
(conj lst (+ number incr)) depth))))))) | |
f90c245f08cf55340684b63a7ce530c6661c84b61dc07afc69bc4a777d08d01b | ejgallego/coq-serapi | sertop_bin.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * INRIA , CNRS and contributors - Copyright 1999 - 2018
(* <O___,, * (see CREDITS file for the list of authors) *)
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(************************************************************************)
(* Coq serialization API/Plugin *)
Copyright 2016 - 2018 MINES ParisTech
Written by :
(************************************************************************)
(* Status: Very Experimental *)
(************************************************************************)
open Cmdliner
let sertop_version = Sertop.Ser_version.ser_git_version
let sertop printer print0 debug set_impredicative_set disallow_sprop indices_matter lheader coq_path ml_path no_init topfile no_prelude lp1 lp2 _std_impl async deep_edits async_workers error_recovery omit_loc omit_att omit_env exn_on_opaque =
let open Sertop.Sertop_init in
let open! Sertop.Sertop_sexp in
let options = Serlib.Serlib_init.{ omit_loc; omit_att; exn_on_opaque; omit_env } in
Serlib.Serlib_init.init ~options;
let dft_ml_path, vo_path =
Serapi.Serapi_paths.coq_loadpath_default ~implicit:true ~coq_path in
let ml_path = dft_ml_path @ ml_path in
let vo_path = vo_path @ lp1 @ lp2 in
let allow_sprop = not disallow_sprop in
ser_loop
{ in_chan = stdin
; out_chan = stdout
; debug
; set_impredicative_set
; allow_sprop
; indices_matter
; printer
; print0
; lheader
; no_init
; no_prelude
; topfile
; ml_path
; vo_path
; async =
{ enable_async = async
; deep_edits
; async_workers
; error_recovery
}
}
let sertop_cmd =
let open Sertop.Sertop_arg in
let doc = "SerAPI Coq Toplevel" in
let man = [
`S "DESCRIPTION";
`P "Experimental Coq Toplevel with Serialization Support";
`S "USAGE";
`P "To build a Coq document, use the `Add` command:";
`Pre "(Add () \"Lemma addn0 n : n + 0. Proof. now induction n. Qed.\")";
`P "SerAPI will parse and split the document into \"logical\" sentences.";
`P "Then, you can ask Coq to check the proof with `Exec`:";
`Pre "(Exec 5)";
`P "Other queries are also possible; some examples:";
`Pre "(Query ((sid 4)) Ast)";
`P "Will print the AST at sentence 4.";
`Pre "(Query ((sid 3)) Goals)";
`P "Will print the goals at sentence 3.";
`P "See the documentation on the project's webpage for more information"
]
in
let term =
Term.(const sertop
$ printer $ print0 $ debug $ set_impredicative_set $ disallow_sprop $ indices_matter $ length $ prelude $ ml_include_path $ no_init $topfile $ no_prelude $ load_path $ rload_path $ implicit_stdlib
$ async $ deep_edits $ async_workers $ error_recovery $ omit_loc $ omit_att $ omit_env $ exn_on_opaque ) in
let info = Cmd.info "sertop" ~version:sertop_version ~doc ~man in
Cmd.v info term
let main () = exit (Cmd.eval sertop_cmd)
let _ = main ()
| null | https://raw.githubusercontent.com/ejgallego/coq-serapi/dd9e3fbf7faaf3bf365fa3eff134641055151a9b/sertop/sertop_bin.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
<O___,, * (see CREDITS file for the list of authors)
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
**********************************************************************
Coq serialization API/Plugin
**********************************************************************
Status: Very Experimental
********************************************************************** | v * INRIA , CNRS and contributors - Copyright 1999 - 2018
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
Copyright 2016 - 2018 MINES ParisTech
Written by :
open Cmdliner
let sertop_version = Sertop.Ser_version.ser_git_version
let sertop printer print0 debug set_impredicative_set disallow_sprop indices_matter lheader coq_path ml_path no_init topfile no_prelude lp1 lp2 _std_impl async deep_edits async_workers error_recovery omit_loc omit_att omit_env exn_on_opaque =
let open Sertop.Sertop_init in
let open! Sertop.Sertop_sexp in
let options = Serlib.Serlib_init.{ omit_loc; omit_att; exn_on_opaque; omit_env } in
Serlib.Serlib_init.init ~options;
let dft_ml_path, vo_path =
Serapi.Serapi_paths.coq_loadpath_default ~implicit:true ~coq_path in
let ml_path = dft_ml_path @ ml_path in
let vo_path = vo_path @ lp1 @ lp2 in
let allow_sprop = not disallow_sprop in
ser_loop
{ in_chan = stdin
; out_chan = stdout
; debug
; set_impredicative_set
; allow_sprop
; indices_matter
; printer
; print0
; lheader
; no_init
; no_prelude
; topfile
; ml_path
; vo_path
; async =
{ enable_async = async
; deep_edits
; async_workers
; error_recovery
}
}
let sertop_cmd =
let open Sertop.Sertop_arg in
let doc = "SerAPI Coq Toplevel" in
let man = [
`S "DESCRIPTION";
`P "Experimental Coq Toplevel with Serialization Support";
`S "USAGE";
`P "To build a Coq document, use the `Add` command:";
`Pre "(Add () \"Lemma addn0 n : n + 0. Proof. now induction n. Qed.\")";
`P "SerAPI will parse and split the document into \"logical\" sentences.";
`P "Then, you can ask Coq to check the proof with `Exec`:";
`Pre "(Exec 5)";
`P "Other queries are also possible; some examples:";
`Pre "(Query ((sid 4)) Ast)";
`P "Will print the AST at sentence 4.";
`Pre "(Query ((sid 3)) Goals)";
`P "Will print the goals at sentence 3.";
`P "See the documentation on the project's webpage for more information"
]
in
let term =
Term.(const sertop
$ printer $ print0 $ debug $ set_impredicative_set $ disallow_sprop $ indices_matter $ length $ prelude $ ml_include_path $ no_init $topfile $ no_prelude $ load_path $ rload_path $ implicit_stdlib
$ async $ deep_edits $ async_workers $ error_recovery $ omit_loc $ omit_att $ omit_env $ exn_on_opaque ) in
let info = Cmd.info "sertop" ~version:sertop_version ~doc ~man in
Cmd.v info term
let main () = exit (Cmd.eval sertop_cmd)
let _ = main ()
|
f6ba89a5f816cbceacf00eacde66ad2ab4cebaadbab6cf6d151f59eee720c4ba | Gbury/archsat | rewrite.mli | This file is free software , part of Archsat . See file " LICENSE " for more details .
* rules
This module sdefines types and manipulation functions on rerite rules .
This module sdefines types and manipulation functions on rerite rules.
*)
* { 2 Rewrite rule guards }
module Guard : sig
type t =
| Pred_true of Expr.term
| Pred_false of Expr.term
| Eq of Expr.term * Expr.term
| Neq of Expr.term * Expr.term
val print :
?term:(Format.formatter -> Expr.term -> unit) ->
Format.formatter -> t -> unit
(** Printer function for guards. *)
val map : (Expr.term -> Expr.term) -> t -> t
(** Map a function on the terms in a guard. *)
val to_list : t -> Expr.term list
(** Returns the list of all top-level terms appearing in a guard. *)
val check : t -> bool
(** Check wether a guard is verified. *)
end
* { 2 Rewrite rules }
module Rule : sig
type 'a witness =
| Term : Expr.term witness
| Formula : Expr.formula witness
type 'a rewrite = {
trigger : 'a;
result : 'a;
}
type contents = C : 'a witness * 'a rewrite -> contents
type t = {
id : int;
manual : bool;
formula : Expr.formula;
guards : Guard.t list;
contents : contents;
}
(** A rewrite rule *)
val hash : t -> int
val equal : t -> t -> bool
val compare : t -> t -> int
(** Usual functions *)
val print :
?term:Expr.term CCFormat.printer ->
?formula:Expr.formula CCFormat.printer ->
t CCFormat.printer
(** A modular printer. *)
val print_id : t CCFormat.printer
(** Print only the rule id (shorter). *)
val mk_term : ?guards:Guard.t list -> bool -> Expr.term -> Expr.term -> t
val mk_formula : ?guards:Guard.t list -> bool -> Expr.formula -> Expr.formula -> t
(** [mk ?guards is_manual trigger result] creates a new rewrite rule, with
the formula field set to the constant [true] formula. *)
val add_guards : Guard.t list -> t -> t
(** Add the guards to the rule, in no specified order. *)
val set_formula : Expr.formula -> t -> t
(** Set the top-level formula of the rewrite rule. *)
val is_manual : t -> bool
(** Returns wether the rule is a manual one. *)
end
* { 2 Rewrite substitution }
module Subst : sig
type t
(** The type of a rewrite substitution. *)
val print : Format.formatter -> t -> unit
(** print a substitution *)
val rule : t -> Rule.t
(** Returns the rewrite rule used for the substitution *)
val inst : t -> Mapping.t
(** Returns the mappping used to instantiate the rule for the substitution *)
val formula : t -> Expr.formula
(** hortcut to directly extract the formula from the rewrite rule of the subst *)
val info : t -> Rule.contents
(** Returns the exact contents that have been substituted. *)
end
* { 2 Term normalization }
module Normalize : sig
val normalize_term :
Rule.t list -> Subst.t list -> Expr.term -> Expr.term * Subst.t list
val normalize_atomic :
Rule.t list -> Subst.t list -> Expr.formula -> Expr.formula * Subst.t list
end
* { 2 Narrowing }
module Narrow : sig
val term : Expr.term -> Rule.t list -> (Rule.t * Mapping.t * Mapping.t) list
val formula : Expr.formula -> Rule.t list -> (Rule.t * Mapping.t * Mapping.t) list
* Tries and narrow the given term / formula , and returns a list of triples
( rule , rule_inst , meta_inst ) that allows to unify with the term .
Instances of simple rewrite rule ( which require no meta instanciation ) , are
stripped away from the list of returned results . , each mapping
may refer to some fresh variables .
(rule, rule_inst, meta_inst) that allows to unify with the term.
Instances of simple rewrite rule (which require no meta instanciation), are
stripped away from the list of returned results. Addtionally, each mapping
may refer to some fresh variables. *)
end
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/algos/rewrite.mli | ocaml | * Printer function for guards.
* Map a function on the terms in a guard.
* Returns the list of all top-level terms appearing in a guard.
* Check wether a guard is verified.
* A rewrite rule
* Usual functions
* A modular printer.
* Print only the rule id (shorter).
* [mk ?guards is_manual trigger result] creates a new rewrite rule, with
the formula field set to the constant [true] formula.
* Add the guards to the rule, in no specified order.
* Set the top-level formula of the rewrite rule.
* Returns wether the rule is a manual one.
* The type of a rewrite substitution.
* print a substitution
* Returns the rewrite rule used for the substitution
* Returns the mappping used to instantiate the rule for the substitution
* hortcut to directly extract the formula from the rewrite rule of the subst
* Returns the exact contents that have been substituted. | This file is free software , part of Archsat . See file " LICENSE " for more details .
* rules
This module sdefines types and manipulation functions on rerite rules .
This module sdefines types and manipulation functions on rerite rules.
*)
* { 2 Rewrite rule guards }
module Guard : sig
type t =
| Pred_true of Expr.term
| Pred_false of Expr.term
| Eq of Expr.term * Expr.term
| Neq of Expr.term * Expr.term
val print :
?term:(Format.formatter -> Expr.term -> unit) ->
Format.formatter -> t -> unit
val map : (Expr.term -> Expr.term) -> t -> t
val to_list : t -> Expr.term list
val check : t -> bool
end
* { 2 Rewrite rules }
module Rule : sig
type 'a witness =
| Term : Expr.term witness
| Formula : Expr.formula witness
type 'a rewrite = {
trigger : 'a;
result : 'a;
}
type contents = C : 'a witness * 'a rewrite -> contents
type t = {
id : int;
manual : bool;
formula : Expr.formula;
guards : Guard.t list;
contents : contents;
}
val hash : t -> int
val equal : t -> t -> bool
val compare : t -> t -> int
val print :
?term:Expr.term CCFormat.printer ->
?formula:Expr.formula CCFormat.printer ->
t CCFormat.printer
val print_id : t CCFormat.printer
val mk_term : ?guards:Guard.t list -> bool -> Expr.term -> Expr.term -> t
val mk_formula : ?guards:Guard.t list -> bool -> Expr.formula -> Expr.formula -> t
val add_guards : Guard.t list -> t -> t
val set_formula : Expr.formula -> t -> t
val is_manual : t -> bool
end
* { 2 Rewrite substitution }
module Subst : sig
type t
val print : Format.formatter -> t -> unit
val rule : t -> Rule.t
val inst : t -> Mapping.t
val formula : t -> Expr.formula
val info : t -> Rule.contents
end
* { 2 Term normalization }
module Normalize : sig
val normalize_term :
Rule.t list -> Subst.t list -> Expr.term -> Expr.term * Subst.t list
val normalize_atomic :
Rule.t list -> Subst.t list -> Expr.formula -> Expr.formula * Subst.t list
end
* { 2 Narrowing }
module Narrow : sig
val term : Expr.term -> Rule.t list -> (Rule.t * Mapping.t * Mapping.t) list
val formula : Expr.formula -> Rule.t list -> (Rule.t * Mapping.t * Mapping.t) list
* Tries and narrow the given term / formula , and returns a list of triples
( rule , rule_inst , meta_inst ) that allows to unify with the term .
Instances of simple rewrite rule ( which require no meta instanciation ) , are
stripped away from the list of returned results . , each mapping
may refer to some fresh variables .
(rule, rule_inst, meta_inst) that allows to unify with the term.
Instances of simple rewrite rule (which require no meta instanciation), are
stripped away from the list of returned results. Addtionally, each mapping
may refer to some fresh variables. *)
end
|
35d8d9e2c6b731b4bdb2e84e4d1f6f288a3e5ab0f3d8e077463e3be41cafe7ea | TrustInSoft/tis-interpreter | export_altergo.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Logic
open Format
open Plib
open Engine
* Exportation Engine for Alt - Ergo .
Provides a full { { : Export . S.engine - c.html}engine }
from a { { : Export . S.linker - c.html}linker } .
Provides a full {{:Export.S.engine-c.html}engine}
from a {{:Export.S.linker-c.html}linker}. *)
module Make(T : Term) :
sig
open T
module Env : Engine.Env with type term := term
type trigger = (T.var,Fun.t) Engine.ftrigger
type typedef = (tau,Field.t,Fun.t) Engine.ftypedef
class virtual engine :
object
method set_quantify_let : bool -> unit
method typecheck : term -> tau (** or raise Not_found *)
method typeof_call : Fun.t -> tau (** or raise Not_found *)
method typeof_setfield : Field.t -> tau (** or raise Not_found *)
method typeof_getfield : Field.t -> tau (** or raise Not_found *)
method virtual get_typedef : ADT.t -> tau option
method virtual set_typedef : ADT.t -> tau -> unit
inherit [Z.t,ADT.t,Field.t,Fun.t,tau,var,term,Env.t] Engine.engine
method marks : Env.t * T.marks
method op_spaced : string -> bool
method op_record : string * string
method pp_forall : tau -> string list printer
method pp_intros : tau -> string list printer
method pp_exists : tau -> string list printer
method pp_param : (string * tau) printer
method pp_trigger : (var,Fun.t) ftrigger printer
method pp_declare_symbol : cmode -> Fun.t printer
method pp_declare_adt : formatter -> ADT.t -> int -> unit
method pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method pp_goal : formatter -> term -> unit
method declare_type : formatter -> ADT.t -> int -> typedef -> unit
method declare_prop : kind:string -> formatter -> string -> T.var list -> trigger list list -> term -> unit
method declare_axiom : formatter -> string -> var list -> trigger list list -> term -> unit
method declare_signature : formatter -> Fun.t -> tau list -> tau -> unit
method declare_definition : formatter -> Fun.t -> var list -> tau -> term -> unit
end
end
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/qed/src/export_altergo.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* or raise Not_found
* or raise Not_found
* or raise Not_found
* or raise Not_found | Modified by TrustInSoft
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Logic
open Format
open Plib
open Engine
* Exportation Engine for Alt - Ergo .
Provides a full { { : Export . S.engine - c.html}engine }
from a { { : Export . S.linker - c.html}linker } .
Provides a full {{:Export.S.engine-c.html}engine}
from a {{:Export.S.linker-c.html}linker}. *)
module Make(T : Term) :
sig
open T
module Env : Engine.Env with type term := term
type trigger = (T.var,Fun.t) Engine.ftrigger
type typedef = (tau,Field.t,Fun.t) Engine.ftypedef
class virtual engine :
object
method set_quantify_let : bool -> unit
method virtual get_typedef : ADT.t -> tau option
method virtual set_typedef : ADT.t -> tau -> unit
inherit [Z.t,ADT.t,Field.t,Fun.t,tau,var,term,Env.t] Engine.engine
method marks : Env.t * T.marks
method op_spaced : string -> bool
method op_record : string * string
method pp_forall : tau -> string list printer
method pp_intros : tau -> string list printer
method pp_exists : tau -> string list printer
method pp_param : (string * tau) printer
method pp_trigger : (var,Fun.t) ftrigger printer
method pp_declare_symbol : cmode -> Fun.t printer
method pp_declare_adt : formatter -> ADT.t -> int -> unit
method pp_declare_def : formatter -> ADT.t -> int -> tau -> unit
method pp_declare_sum : formatter -> ADT.t -> int -> (Fun.t * tau list) list -> unit
method pp_goal : formatter -> term -> unit
method declare_type : formatter -> ADT.t -> int -> typedef -> unit
method declare_prop : kind:string -> formatter -> string -> T.var list -> trigger list list -> term -> unit
method declare_axiom : formatter -> string -> var list -> trigger list list -> term -> unit
method declare_signature : formatter -> Fun.t -> tau list -> tau -> unit
method declare_definition : formatter -> Fun.t -> var list -> tau -> term -> unit
end
end
|
d8dcc417cac7ce25dccb36e8f92253bd8fc0426ad7d1df68a584e4185bfbef25 | Chimrod/i3_workspaces | actions.ml | type node = I3ipc.Reply.node
type actions =
| W: (unit -> (string * (unit -> unit Lwt.t)) Lwt.t) -> actions
| C: string -> actions
type t = actions list
type answer = I3ipc.Reply.command_outcome list
let create = []
(** Create a container which swallow the given class *)
let swallow class_name t = begin
let f () = begin
let%lwt (file, channel) = Lwt_io.open_temp_file ~prefix:"i3_workspaces" () in
let%lwt () = Lwt_io.fprintf channel {|{"swallows": [{"class": "%s"}]}|} class_name
in
let command = "append_layout " ^ file
and after () = Lwt_io.close channel
in Lwt.return (command, after)
end in
W f::t
end
(** Launch an application *)
let launch exec t command = begin
C (
begin match exec with
| `NoStartupId -> ("exec --no-startup-id \"" ^ command ^ "\"")
| _ -> ("exec \"" ^ command ^ "\"")
end
)::t
end
let _focus (container:I3ipc.Reply.node) = begin
"[con_id=" ^ (container.I3ipc.Reply.id) ^ "] "
end
let split (container:node) new_layout t = begin
let open I3ipc.Reply in
let con_id = _focus container in
C (
begin match new_layout with
| SplitV -> (con_id ^ "split vertical")
| SplitH -> (con_id ^ "split horizontal")
| _ -> "nop"
end
)::t
end
let layout (container:node) new_layout t = begin
let open I3ipc.Reply in
let con_id = _focus container in
C (
begin match new_layout with
| SplitV -> (con_id ^ "layout splitv")
| SplitH -> (con_id ^ "layout splith")
| _ -> "nop"
end
)::t
end
let exec ~focus message t =
let focus = _focus focus in
C (focus ^ message)::t
let empty = []
let apply conn t = begin
let b = Buffer.create 16 in
let add_elem b elem = begin
Buffer.add_string b elem;
Buffer.add_string b ";";
b
end in
let f (buffer, posts) = begin function
| C c -> Lwt.return (add_elem buffer c, posts)
| W f -> let%lwt c, p = f () in
Lwt.return (add_elem buffer c, p::posts)
end in
let%lwt command, posts = Lwt_list.fold_left_s f (b, []) t in
let command' = Buffer.contents command in
print_endline command';
let%lwt result = I3ipc.command conn command' in
let%lwt _posts = Lwt_list.iter_p (fun f -> f ()) posts in
Lwt.return result
end
| null | https://raw.githubusercontent.com/Chimrod/i3_workspaces/904209b58719f09cdf9f0238a6036d19c0129d4f/src/common/actions.ml | ocaml | * Create a container which swallow the given class
* Launch an application | type node = I3ipc.Reply.node
type actions =
| W: (unit -> (string * (unit -> unit Lwt.t)) Lwt.t) -> actions
| C: string -> actions
type t = actions list
type answer = I3ipc.Reply.command_outcome list
let create = []
let swallow class_name t = begin
let f () = begin
let%lwt (file, channel) = Lwt_io.open_temp_file ~prefix:"i3_workspaces" () in
let%lwt () = Lwt_io.fprintf channel {|{"swallows": [{"class": "%s"}]}|} class_name
in
let command = "append_layout " ^ file
and after () = Lwt_io.close channel
in Lwt.return (command, after)
end in
W f::t
end
let launch exec t command = begin
C (
begin match exec with
| `NoStartupId -> ("exec --no-startup-id \"" ^ command ^ "\"")
| _ -> ("exec \"" ^ command ^ "\"")
end
)::t
end
let _focus (container:I3ipc.Reply.node) = begin
"[con_id=" ^ (container.I3ipc.Reply.id) ^ "] "
end
let split (container:node) new_layout t = begin
let open I3ipc.Reply in
let con_id = _focus container in
C (
begin match new_layout with
| SplitV -> (con_id ^ "split vertical")
| SplitH -> (con_id ^ "split horizontal")
| _ -> "nop"
end
)::t
end
let layout (container:node) new_layout t = begin
let open I3ipc.Reply in
let con_id = _focus container in
C (
begin match new_layout with
| SplitV -> (con_id ^ "layout splitv")
| SplitH -> (con_id ^ "layout splith")
| _ -> "nop"
end
)::t
end
let exec ~focus message t =
let focus = _focus focus in
C (focus ^ message)::t
let empty = []
let apply conn t = begin
let b = Buffer.create 16 in
let add_elem b elem = begin
Buffer.add_string b elem;
Buffer.add_string b ";";
b
end in
let f (buffer, posts) = begin function
| C c -> Lwt.return (add_elem buffer c, posts)
| W f -> let%lwt c, p = f () in
Lwt.return (add_elem buffer c, p::posts)
end in
let%lwt command, posts = Lwt_list.fold_left_s f (b, []) t in
let command' = Buffer.contents command in
print_endline command';
let%lwt result = I3ipc.command conn command' in
let%lwt _posts = Lwt_list.iter_p (fun f -> f ()) posts in
Lwt.return result
end
|
3d00cedd18397dc24f0cb0cc69cdd2ea488bc84ff9b3d84f24ea69703609580f | clojure-interop/google-cloud-clients | core.clj | (ns com.google.cloud.vision.v1p1beta1.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorClient])
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorSettings$Builder])
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorSettings])
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.vision/src/com/google/cloud/vision/v1p1beta1/core.clj | clojure | (ns com.google.cloud.vision.v1p1beta1.core
(:refer-clojure :only [require comment defn ->])
(:import ))
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorClient])
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorSettings$Builder])
(require '[com.google.cloud.vision.v1p1beta1.ImageAnnotatorSettings])
| |
9bf25eefd4f9824c6bce274fc87d03d1eec473b244632d9777e37d5f8c2a394b | skanev/playground | tests.scm | (require rackunit rackunit/text-ui)
(load-relative "evaluator.scm")
(define ec-machine (make-explicit-control-machine))
(define (run exp)
(set-register-contents! ec-machine 'env (setup-environment))
(set-register-contents! ec-machine 'exp exp)
(start ec-machine)
(get-register-contents ec-machine 'val))
(define evaluator-tests
(test-suite
"Tests for the explicit control evaluator"
(test-suite "Self-evaluating expressions"
(check-equal? (run '1) 1)
(check-equal? (run '"something") "something"))
(test-suite "Quotation"
(check-equal? (run '(quote foo)) 'foo))
(test-suite "Begin"
(check-equal? (run '(begin 1 2)) 2))
(test-suite "Define"
(check-equal? (run '(define x 1)) 'ok)
(check-equal? (run '(begin (define x 1)
x))
1)
(check-equal? (run '(define (x) 1)) 'ok)
(check-equal? (run '(begin (define (x) 1)
(x)))
1))
(test-suite "Set!"
(check-equal? (run '(begin (define x 1)
(set! x 2)))
'ok)
(check-equal? (run '(begin (define x 1)
(set! x 2)
x))
2))
(test-suite "If"
(check-equal? (run '(if true 1 2)) 1)
(check-equal? (run '(if false 1 2)) 2)
(check-equal? (run '(if true 1)) 1)
(check-equal? (run '(if false 1)) false))
(test-suite "Lambda"
(check-equal? (run '((lambda () 1))) 1)
(check-equal? (run '((lambda (x) x) 1)) 1)
(check-equal? (run '((lambda (a b) (cons a b)) 1 2)) '(1 . 2))
(check-equal? (run '(begin (define a 1)
(define b 2)
((lambda (a) (cons a b)) 3)))
'(3 . 2)))
(test-suite "Procedure application"
(check-equal? (run '(begin (define (a) 1)
(a)))
1)
(check-equal? (run '(begin (define (pair a b) (cons a b))
(pair 1 2)))
'(1 . 2))
(check-equal? (run '(begin (define a 1)
(define (pair b) (cons a b))
(pair 2)))
'(1 . 2)))
(test-suite "Defining append"
(check-equal? (run '(begin (define (append x y)
(if (null? x)
y
(cons (car x)
(append (cdr x) y))))
(append '(a b c) '(d e f))))
'(a b c d e f)))
(test-suite "Factorial"
(check-equal? (run '(begin (define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
(factorial 5)))
120)
(check-equal? (run '(begin (define (factorial n)
(define (iter n result)
(if (= n 0)
result
(iter (- n 1) (* result n))))
(iter n 1))
(factorial 5)))
120))
))
(run-tests evaluator-tests)
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/05/showcase/explicit/tests.scm | scheme | (require rackunit rackunit/text-ui)
(load-relative "evaluator.scm")
(define ec-machine (make-explicit-control-machine))
(define (run exp)
(set-register-contents! ec-machine 'env (setup-environment))
(set-register-contents! ec-machine 'exp exp)
(start ec-machine)
(get-register-contents ec-machine 'val))
(define evaluator-tests
(test-suite
"Tests for the explicit control evaluator"
(test-suite "Self-evaluating expressions"
(check-equal? (run '1) 1)
(check-equal? (run '"something") "something"))
(test-suite "Quotation"
(check-equal? (run '(quote foo)) 'foo))
(test-suite "Begin"
(check-equal? (run '(begin 1 2)) 2))
(test-suite "Define"
(check-equal? (run '(define x 1)) 'ok)
(check-equal? (run '(begin (define x 1)
x))
1)
(check-equal? (run '(define (x) 1)) 'ok)
(check-equal? (run '(begin (define (x) 1)
(x)))
1))
(test-suite "Set!"
(check-equal? (run '(begin (define x 1)
(set! x 2)))
'ok)
(check-equal? (run '(begin (define x 1)
(set! x 2)
x))
2))
(test-suite "If"
(check-equal? (run '(if true 1 2)) 1)
(check-equal? (run '(if false 1 2)) 2)
(check-equal? (run '(if true 1)) 1)
(check-equal? (run '(if false 1)) false))
(test-suite "Lambda"
(check-equal? (run '((lambda () 1))) 1)
(check-equal? (run '((lambda (x) x) 1)) 1)
(check-equal? (run '((lambda (a b) (cons a b)) 1 2)) '(1 . 2))
(check-equal? (run '(begin (define a 1)
(define b 2)
((lambda (a) (cons a b)) 3)))
'(3 . 2)))
(test-suite "Procedure application"
(check-equal? (run '(begin (define (a) 1)
(a)))
1)
(check-equal? (run '(begin (define (pair a b) (cons a b))
(pair 1 2)))
'(1 . 2))
(check-equal? (run '(begin (define a 1)
(define (pair b) (cons a b))
(pair 2)))
'(1 . 2)))
(test-suite "Defining append"
(check-equal? (run '(begin (define (append x y)
(if (null? x)
y
(cons (car x)
(append (cdr x) y))))
(append '(a b c) '(d e f))))
'(a b c d e f)))
(test-suite "Factorial"
(check-equal? (run '(begin (define (factorial n)
(if (= n 1)
1
(* n (factorial (- n 1)))))
(factorial 5)))
120)
(check-equal? (run '(begin (define (factorial n)
(define (iter n result)
(if (= n 0)
result
(iter (- n 1) (* result n))))
(iter n 1))
(factorial 5)))
120))
))
(run-tests evaluator-tests)
| |
702dff63417b1abef6b491529c98169d764d1b0b008052ae2f2923a65a4564af | slindley/effect-handlers | AOPExtra.hs | Aspect - oriented programming using handlers .
Inspired by Oliveira , Shrijvers , and 's paper : Modular
reasoning about interference in incremental programming
Inspired by Oliveira, Shrijvers, and Cook's JFP paper: Modular
reasoning about interference in incremental programming -}
{- This version supports overriding the behaviour of a function on a
particular expression constructor by reflecting each expression
constructor as an effectful operation and defining functions on
expressions as handlers. -}
# LANGUAGE TypeFamilies ,
GADTs ,
NoMonomorphismRestriction ,
RankNTypes ,
MultiParamTypeClasses ,
QuasiQuotes ,
FlexibleInstances ,
FlexibleContexts ,
OverlappingInstances ,
UndecidableInstances ,
ConstraintKinds ,
DataKinds ,
PolyKinds ,
TypeOperators ,
ScopedTypeVariables #
GADTs,
NoMonomorphismRestriction,
RankNTypes,
MultiParamTypeClasses,
QuasiQuotes,
FlexibleInstances,
FlexibleContexts,
OverlappingInstances,
UndecidableInstances,
ConstraintKinds,
DataKinds,
PolyKinds,
TypeOperators,
ScopedTypeVariables #-}
module Examples.AOPExtra where
import Handlers
import TopLevel
import DesugarHandlers
import Control.Monad
import Data.Monoid
import Benchmarks.MRI_code.Interpreters (Expr(..), Env)
[operation|Get s :: s|]
[operation|Put s :: s -> ()|]
[operation|Ask s :: s|]
[operation|Tell s :: s -> ()|]
type SComp s a =
((h `Handles` Get) s, (h `Handles` Put) s) => Comp h a
[handler|
forward h.
RunState s a :: s -> (a, s)
handles {Get s, Put s} where
Return x s -> return (x, s)
Get k s -> k s s
Put s k _ -> k () s
|]
[handler|
forward h.
EvalState s a :: s -> a
handles {Get s, Put s} where
Return x _ -> return x
Get k s -> k s s
Put s k _ -> k () s
|]
[handler|
forward h.
RunReader s a :: s -> a
handles {Ask s} where
Return x s -> return x
Ask k s -> k s s
|]
[handler|
forward h.(Monoid s) =>
RunWriter s a :: s -> (a, s)
handles {Tell s} where
Return x s -> return (x, s)
Tell s' k s -> k () (s `mappend` s')
|]
runWriter' comp = runWriter mempty comp
[handler|
forward h.(Monoid s) =>
EvalWriter s a :: s -> a
handles {Tell s} where
Return x _ -> return x
Tell s' k s -> k () (s `mappend` s')
|]
evalWriter' comp = evalWriter mempty comp
[handler|
IoStringWriter a :: IO a
handles {Tell (String)} where
Return x -> return x
Tell s k -> do putStr s; k ()
|]
[handler|
forward h.(Monoid s) =>
ExecWriter s a :: s -> s
handles {Tell s} where
Return x s -> return s
Tell s' k s -> k () (s `mappend` s')
|]
execWriter' comp = execWriter mempty comp
[operation|forall a.ThrowError e :: e -> a|]
[handler|
forward h.
CatchError e a :: (e -> Comp h a) -> a
handles {ThrowError e} where
Return x _ -> return x
ThrowError e k f -> f e
|]
[handler|
forward h.
RunError e a :: Either e a
handles {ThrowError e} where
Return x -> return (Right x)
ThrowError e k -> return (Left e)
|]
data
-- = Lit Int
-- | Var String
| Plus
| Assign
-- | Sequence [Expr]
| While
-- deriving Show
-- type Env = [(String, Int)]
-- the representation of an expression as a computation
type ExprComp a =
([handles|h {CLit}|],
[handles|h {CVar}|],
[handles|h {CPlus}|],
[handles|h {CAssign}|],
[handles|h {CSequence}|],
[handles|h {CWhile}|]) => Comp h a
[operation|forall a.CLit :: Int -> a |]
[operation|forall a.CVar :: String -> a |]
[operation| CPlus :: Bool|]
[operation| CAssign :: String -> () |]
[operation| CSequence :: Int -> Int |]
[operation| CWhile :: Bool|]
-- effectful smart constructors
lit = cLit
var = cVar
plus e1 e2 = do b <- cPlus; if b then e1 else e2
assign x e = do cAssign x; e
sequence' es = do i <- cSequence (length es); es !! i
while e1 e2 = do b <- cWhile; if b then e1 else e2
[operation|Suspend h s a :: s -> Comp h a -> a|]
[handler|
forward h.
Force s a :: a
handles {Suspend (Force h s a) s a} where
Return x -> return x
Suspend e comp k -> do x <- force comp; k x
|]
[handler|
forward h handles {Tell (String), Suspend h s a}.(Show s, Show a) =>
Logger s a :: String -> a
handles {Suspend (Logger h s a) s a} where
Return x _ -> return x
Suspend e comp k name -> do tell ("Entering " ++ name ++ " with " ++ show e ++ "\n")
y <- suspend e (logger name comp)
tell ("Exiting " ++ name ++ " with " ++ show y ++ "\n")
k y name
|]
[handler|
forward h handles {Get s, Tell (String), Suspend h t a}.(Show s) =>
Dump s a :: a
handles {Suspend (Dump h s a) t a} where
Return x -> return x
Suspend e comp k -> do s <- get
tell (show s ++ "\n")
x <- suspend e (dump comp)
k x
|]
type ExprSuspendComp a =
([handles|h {CLit}|],
[handles|h {CVar}|],
[handles|h {CPlus}|],
[handles|h {CAssign}|],
[handles|h {CSequence}|],
[handles|h {CWhile}|],
[handles|h {Suspend h (Expr) a}|]) => Comp h a
-- we won't use this, but we can pretty print reflected expressions
-- using a handler
[handler|
forward h handles {Tell (String)}.
ShowExpr :: ()
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile} where
Return x -> tell (show x)
CLit x k -> tell (show x)
CVar s k -> tell s
CPlus k -> do tell "("
k True
tell ")+("
k False
tell ")"
CAssign s k -> do tell (s ++ ":=(")
k ()
tell ")"
CSequence n k -> do tell "["
loop n
tell "]"
where loop 0 = return ()
loop 1 = k 0
loop n = do k (n-1); tell ","
CWhile k -> do tell "while "
k True
tell " do "
k False
|]
showExpr' :: ([handles|h {Tell (String)}|], Show a) => ExprComp a -> Comp h ()
showExpr' comp = showExpr comp
-- similarly to pretty-printing, we can reify reflected expressions as
-- plain expressions
[handler|
forward h.
Reify :: Expr
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile} where
Return x -> return (Lit x)
CLit x k -> return (Lit x)
CVar s k -> return (Var s)
CPlus k -> do l <- k True; r <- k False; return (Plus l r)
CAssign s k -> do e <- k (); return (Assign s e)
CSequence n k -> do es <- loop n
return (Sequence es)
where loop 0 = return []
loop n = do e <- k (n-1); es <- loop (n-1); return (e:es)
CWhile k -> do c <- k True; b <- k False; return (While c b)
|]
-- reflect an expression
reflect :: Expr -> ExprComp a
reflect (Var s) = var s
reflect (Lit x) = lit x
reflect (Plus e1 e2) = plus (reflect e1) (reflect e2)
reflect (Assign x r) = assign x (reflect r)
reflect (Sequence es) = sequence' (map reflect es)
reflect (While c b) = while (reflect c) (reflect b)
-- reflect an expression by 'suspending' each constructor
-- this provides a hook to support aspect-oriented programming
reflectSuspend :: Expr -> ExprSuspendComp a
reflectSuspend (Var s) = suspend (Var s) (var s)
reflectSuspend (Lit x) = suspend (Lit x) (lit x)
reflectSuspend (Plus e1 e2) = suspend (Plus e1 e2) (plus (reflectSuspend e1) (reflectSuspend e2))
reflectSuspend (Assign x r) = suspend (Assign x r) (assign x (reflectSuspend r))
reflectSuspend (Sequence es) = suspend (Sequence es) (sequence' (map reflectSuspend es))
reflectSuspend (While c b) = suspend (While c b) (while (reflectSuspend c) (reflectSuspend b))
-- We could separate reflection from the introduction of suspended
-- computations, but filling in the annotations on each suspended node
-- would probably require us to reify computations, which might be
-- undesirable.
--
-- [handler|
forward h handles { Suspend h ( ) ( Int ) , CLit , CVar , CPlus , CAssign , CSequence , } .
-- Suspify :: Int
handles { CLit , CVar , CPlus , CAssign , CSequence , where
-- Return x -> return x
-- CLit x k -> suspend undefined (do y <- cLit x; k y)
CVar s k - > suspend undefined ( do y ; k y )
CPlus k - > suspend undefined ( do y < - cPlus ; k y )
-- CAssign s k -> suspend undefined (do y <- cAssign s; k y)
CSequence n k - > suspend undefined ( do y < - cSequence n ; k y )
suspend undefined ( do y < - cWhile ; k y )
-- |]
[handler|
forward h handles {Get (Env), Put (Env), Suspend h (Expr) (Int)}.
Beval :: Int
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile, Suspend (Beval h) (Expr) (Int)} where
Return x -> return x
CLit x k -> return x
CVar s k -> do e <- get
case lookup s e of
Just x -> return x
_ -> error "Variable not found!"
CPlus k -> do x <- k True
y <- k False
return (x + y)
CAssign x k -> do y <- k ()
e <- get
put ((x, y) : e)
return y
CSequence n k -> loop n
where
loop 0 = return 0
loop 1 = k 0
loop n = k (n-1) >> loop (n-1)
CWhile k -> loop
where
loop = do x <- k True
if x == 0 then return 0
else k False >> loop
Suspend e comp k -> do x <- suspend e (beval comp); k x
|]
[handler|
forward h handles {Get (Env), Put (Env), ThrowError (String, String, Env), Suspend h (Expr) (Int)}.
Eeval :: Int
handles {CVar, Suspend (Eeval h) (Expr) (Int)} where
Return x -> return x
CVar s k -> do e <- get
case lookup s e of
Just x -> return x
_ -> throwError ("Variable not found!", s, e)
Suspend e comp k -> do x <- suspend e (eeval comp); k x
|]
e1 = Plus (Lit 3) (Lit 4)
e2 = Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))
e3 = Plus (Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))) (Plus (Var "x") (Var "y"))
e4 = Plus (Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))) (Plus (Var "x") (Var "z"))
test1 e = ioStringWriter (evalState [] (force (logger "eval" (beval (reflectSuspend e)))))
test2 e = ioStringWriter (evalState [] (force (dump (beval (reflectSuspend e)))))
test3 e = ioStringWriter (evalState [] (force (dump (logger "eval" (beval (reflectSuspend e))))))
test4 e = ioStringWriter (runError (evalState [] (force (beval (eeval (logger "eval" (reflectSuspend e)))))))
test5 e = ioStringWriter (runError (evalState [] (force (beval (eeval (dump (logger "eval" (reflectSuspend e))))))))
| null | https://raw.githubusercontent.com/slindley/effect-handlers/39d0d09582d198dd6210177a0896db55d92529f4/Examples/AOPExtra.hs | haskell | This version supports overriding the behaviour of a function on a
particular expression constructor by reflecting each expression
constructor as an effectful operation and defining functions on
expressions as handlers.
= Lit Int
| Var String
| Sequence [Expr]
deriving Show
type Env = [(String, Int)]
the representation of an expression as a computation
effectful smart constructors
we won't use this, but we can pretty print reflected expressions
using a handler
similarly to pretty-printing, we can reify reflected expressions as
plain expressions
reflect an expression
reflect an expression by 'suspending' each constructor
this provides a hook to support aspect-oriented programming
We could separate reflection from the introduction of suspended
computations, but filling in the annotations on each suspended node
would probably require us to reify computations, which might be
undesirable.
[handler|
Suspify :: Int
Return x -> return x
CLit x k -> suspend undefined (do y <- cLit x; k y)
CAssign s k -> suspend undefined (do y <- cAssign s; k y)
|] | Aspect - oriented programming using handlers .
Inspired by Oliveira , Shrijvers , and 's paper : Modular
reasoning about interference in incremental programming
Inspired by Oliveira, Shrijvers, and Cook's JFP paper: Modular
reasoning about interference in incremental programming -}
# LANGUAGE TypeFamilies ,
GADTs ,
NoMonomorphismRestriction ,
RankNTypes ,
MultiParamTypeClasses ,
QuasiQuotes ,
FlexibleInstances ,
FlexibleContexts ,
OverlappingInstances ,
UndecidableInstances ,
ConstraintKinds ,
DataKinds ,
PolyKinds ,
TypeOperators ,
ScopedTypeVariables #
GADTs,
NoMonomorphismRestriction,
RankNTypes,
MultiParamTypeClasses,
QuasiQuotes,
FlexibleInstances,
FlexibleContexts,
OverlappingInstances,
UndecidableInstances,
ConstraintKinds,
DataKinds,
PolyKinds,
TypeOperators,
ScopedTypeVariables #-}
module Examples.AOPExtra where
import Handlers
import TopLevel
import DesugarHandlers
import Control.Monad
import Data.Monoid
import Benchmarks.MRI_code.Interpreters (Expr(..), Env)
[operation|Get s :: s|]
[operation|Put s :: s -> ()|]
[operation|Ask s :: s|]
[operation|Tell s :: s -> ()|]
type SComp s a =
((h `Handles` Get) s, (h `Handles` Put) s) => Comp h a
[handler|
forward h.
RunState s a :: s -> (a, s)
handles {Get s, Put s} where
Return x s -> return (x, s)
Get k s -> k s s
Put s k _ -> k () s
|]
[handler|
forward h.
EvalState s a :: s -> a
handles {Get s, Put s} where
Return x _ -> return x
Get k s -> k s s
Put s k _ -> k () s
|]
[handler|
forward h.
RunReader s a :: s -> a
handles {Ask s} where
Return x s -> return x
Ask k s -> k s s
|]
[handler|
forward h.(Monoid s) =>
RunWriter s a :: s -> (a, s)
handles {Tell s} where
Return x s -> return (x, s)
Tell s' k s -> k () (s `mappend` s')
|]
runWriter' comp = runWriter mempty comp
[handler|
forward h.(Monoid s) =>
EvalWriter s a :: s -> a
handles {Tell s} where
Return x _ -> return x
Tell s' k s -> k () (s `mappend` s')
|]
evalWriter' comp = evalWriter mempty comp
[handler|
IoStringWriter a :: IO a
handles {Tell (String)} where
Return x -> return x
Tell s k -> do putStr s; k ()
|]
[handler|
forward h.(Monoid s) =>
ExecWriter s a :: s -> s
handles {Tell s} where
Return x s -> return s
Tell s' k s -> k () (s `mappend` s')
|]
execWriter' comp = execWriter mempty comp
[operation|forall a.ThrowError e :: e -> a|]
[handler|
forward h.
CatchError e a :: (e -> Comp h a) -> a
handles {ThrowError e} where
Return x _ -> return x
ThrowError e k f -> f e
|]
[handler|
forward h.
RunError e a :: Either e a
handles {ThrowError e} where
Return x -> return (Right x)
ThrowError e k -> return (Left e)
|]
data
| Plus
| Assign
| While
type ExprComp a =
([handles|h {CLit}|],
[handles|h {CVar}|],
[handles|h {CPlus}|],
[handles|h {CAssign}|],
[handles|h {CSequence}|],
[handles|h {CWhile}|]) => Comp h a
[operation|forall a.CLit :: Int -> a |]
[operation|forall a.CVar :: String -> a |]
[operation| CPlus :: Bool|]
[operation| CAssign :: String -> () |]
[operation| CSequence :: Int -> Int |]
[operation| CWhile :: Bool|]
lit = cLit
var = cVar
plus e1 e2 = do b <- cPlus; if b then e1 else e2
assign x e = do cAssign x; e
sequence' es = do i <- cSequence (length es); es !! i
while e1 e2 = do b <- cWhile; if b then e1 else e2
[operation|Suspend h s a :: s -> Comp h a -> a|]
[handler|
forward h.
Force s a :: a
handles {Suspend (Force h s a) s a} where
Return x -> return x
Suspend e comp k -> do x <- force comp; k x
|]
[handler|
forward h handles {Tell (String), Suspend h s a}.(Show s, Show a) =>
Logger s a :: String -> a
handles {Suspend (Logger h s a) s a} where
Return x _ -> return x
Suspend e comp k name -> do tell ("Entering " ++ name ++ " with " ++ show e ++ "\n")
y <- suspend e (logger name comp)
tell ("Exiting " ++ name ++ " with " ++ show y ++ "\n")
k y name
|]
[handler|
forward h handles {Get s, Tell (String), Suspend h t a}.(Show s) =>
Dump s a :: a
handles {Suspend (Dump h s a) t a} where
Return x -> return x
Suspend e comp k -> do s <- get
tell (show s ++ "\n")
x <- suspend e (dump comp)
k x
|]
type ExprSuspendComp a =
([handles|h {CLit}|],
[handles|h {CVar}|],
[handles|h {CPlus}|],
[handles|h {CAssign}|],
[handles|h {CSequence}|],
[handles|h {CWhile}|],
[handles|h {Suspend h (Expr) a}|]) => Comp h a
[handler|
forward h handles {Tell (String)}.
ShowExpr :: ()
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile} where
Return x -> tell (show x)
CLit x k -> tell (show x)
CVar s k -> tell s
CPlus k -> do tell "("
k True
tell ")+("
k False
tell ")"
CAssign s k -> do tell (s ++ ":=(")
k ()
tell ")"
CSequence n k -> do tell "["
loop n
tell "]"
where loop 0 = return ()
loop 1 = k 0
loop n = do k (n-1); tell ","
CWhile k -> do tell "while "
k True
tell " do "
k False
|]
showExpr' :: ([handles|h {Tell (String)}|], Show a) => ExprComp a -> Comp h ()
showExpr' comp = showExpr comp
[handler|
forward h.
Reify :: Expr
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile} where
Return x -> return (Lit x)
CLit x k -> return (Lit x)
CVar s k -> return (Var s)
CPlus k -> do l <- k True; r <- k False; return (Plus l r)
CAssign s k -> do e <- k (); return (Assign s e)
CSequence n k -> do es <- loop n
return (Sequence es)
where loop 0 = return []
loop n = do e <- k (n-1); es <- loop (n-1); return (e:es)
CWhile k -> do c <- k True; b <- k False; return (While c b)
|]
reflect :: Expr -> ExprComp a
reflect (Var s) = var s
reflect (Lit x) = lit x
reflect (Plus e1 e2) = plus (reflect e1) (reflect e2)
reflect (Assign x r) = assign x (reflect r)
reflect (Sequence es) = sequence' (map reflect es)
reflect (While c b) = while (reflect c) (reflect b)
reflectSuspend :: Expr -> ExprSuspendComp a
reflectSuspend (Var s) = suspend (Var s) (var s)
reflectSuspend (Lit x) = suspend (Lit x) (lit x)
reflectSuspend (Plus e1 e2) = suspend (Plus e1 e2) (plus (reflectSuspend e1) (reflectSuspend e2))
reflectSuspend (Assign x r) = suspend (Assign x r) (assign x (reflectSuspend r))
reflectSuspend (Sequence es) = suspend (Sequence es) (sequence' (map reflectSuspend es))
reflectSuspend (While c b) = suspend (While c b) (while (reflectSuspend c) (reflectSuspend b))
forward h handles { Suspend h ( ) ( Int ) , CLit , CVar , CPlus , CAssign , CSequence , } .
handles { CLit , CVar , CPlus , CAssign , CSequence , where
CVar s k - > suspend undefined ( do y ; k y )
CPlus k - > suspend undefined ( do y < - cPlus ; k y )
CSequence n k - > suspend undefined ( do y < - cSequence n ; k y )
suspend undefined ( do y < - cWhile ; k y )
[handler|
forward h handles {Get (Env), Put (Env), Suspend h (Expr) (Int)}.
Beval :: Int
handles {CLit, CVar, CPlus, CAssign, CSequence, CWhile, Suspend (Beval h) (Expr) (Int)} where
Return x -> return x
CLit x k -> return x
CVar s k -> do e <- get
case lookup s e of
Just x -> return x
_ -> error "Variable not found!"
CPlus k -> do x <- k True
y <- k False
return (x + y)
CAssign x k -> do y <- k ()
e <- get
put ((x, y) : e)
return y
CSequence n k -> loop n
where
loop 0 = return 0
loop 1 = k 0
loop n = k (n-1) >> loop (n-1)
CWhile k -> loop
where
loop = do x <- k True
if x == 0 then return 0
else k False >> loop
Suspend e comp k -> do x <- suspend e (beval comp); k x
|]
[handler|
forward h handles {Get (Env), Put (Env), ThrowError (String, String, Env), Suspend h (Expr) (Int)}.
Eeval :: Int
handles {CVar, Suspend (Eeval h) (Expr) (Int)} where
Return x -> return x
CVar s k -> do e <- get
case lookup s e of
Just x -> return x
_ -> throwError ("Variable not found!", s, e)
Suspend e comp k -> do x <- suspend e (eeval comp); k x
|]
e1 = Plus (Lit 3) (Lit 4)
e2 = Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))
e3 = Plus (Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))) (Plus (Var "x") (Var "y"))
e4 = Plus (Plus (Assign "x" (Lit 3)) (Assign "y" (Lit 4))) (Plus (Var "x") (Var "z"))
test1 e = ioStringWriter (evalState [] (force (logger "eval" (beval (reflectSuspend e)))))
test2 e = ioStringWriter (evalState [] (force (dump (beval (reflectSuspend e)))))
test3 e = ioStringWriter (evalState [] (force (dump (logger "eval" (beval (reflectSuspend e))))))
test4 e = ioStringWriter (runError (evalState [] (force (beval (eeval (logger "eval" (reflectSuspend e)))))))
test5 e = ioStringWriter (runError (evalState [] (force (beval (eeval (dump (logger "eval" (reflectSuspend e))))))))
|
a56caa9445df0e556539072e8f914d649da239eb3ab8ceb3911a8dabf46a4f16 | issuu/sure-deploy | composefile.ml | open Core
module Service = Swarm_types.Service
module Image = Swarm_types.Image
type service_spec = {
name : Service.t;
image : Image.t;
}
let load_file : string -> Yaml.value Or_error.t =
fun filename ->
Or_error.try_with_join @@ fun () ->
In_channel.read_all filename
|> Yaml.of_string
|> Result.map_error ~f:(fun (`Msg s) -> Error.createf "%s" s)
let extract_service : string * Yaml.value -> service_spec Or_error.t =
fun (name, definition) ->
match definition with
| `O defs -> (
match List.Assoc.find defs ~equal:String.equal "image" with
| None -> Or_error.errorf "Definition of service '%s' has no 'image' field" name
| Some (`String image) ->
let name = Service.of_string name in
let image = Image.of_string image in
Or_error.return {name; image}
| Some _ ->
Or_error.errorf
"Definition of 'image' field in service '%s' has invalid type"
name)
| _ -> Or_error.errorf "Expected an object in definition of service '%s'" name
let extract_services : Yaml.value -> service_spec list Or_error.t = function
| `O service_list -> service_list |> List.map ~f:extract_service |> Or_error.all
| _ -> Or_error.errorf "'service' key did not map to an object"
let specs : Yaml.value -> service_spec list Or_error.t = function
| `O top_level -> (
match List.Assoc.find top_level ~equal:String.equal "services" with
| None -> Or_error.errorf "No 'services' defined"
| Some services -> extract_services services)
| _ -> Or_error.errorf "Top level object expected"
type context = string String.Map.t
let substitute_template : context -> service_spec -> service_spec Or_error.t =
fun context ({image; _} as spec) ->
let open Or_error.Let_syntax in
let%bind image = Variable.substitute context (Image.to_string image) in
let image = Image.of_string image in
return {spec with image}
let resolve_specs : context -> service_spec list -> service_spec list Or_error.t =
fun context specs -> specs |> List.map ~f:(substitute_template context) |> Or_error.all
let load : string -> context -> service_spec list Or_error.t =
fun filename context ->
let open Or_error.Let_syntax in
let%bind yaml_parsed = load_file filename in
let%bind extracted_specs = specs yaml_parsed in
resolve_specs context extracted_specs
| null | https://raw.githubusercontent.com/issuu/sure-deploy/3df4298fd698dbdf221a8929e0c2b309728481f9/src/lib/composefile.ml | ocaml | open Core
module Service = Swarm_types.Service
module Image = Swarm_types.Image
type service_spec = {
name : Service.t;
image : Image.t;
}
let load_file : string -> Yaml.value Or_error.t =
fun filename ->
Or_error.try_with_join @@ fun () ->
In_channel.read_all filename
|> Yaml.of_string
|> Result.map_error ~f:(fun (`Msg s) -> Error.createf "%s" s)
let extract_service : string * Yaml.value -> service_spec Or_error.t =
fun (name, definition) ->
match definition with
| `O defs -> (
match List.Assoc.find defs ~equal:String.equal "image" with
| None -> Or_error.errorf "Definition of service '%s' has no 'image' field" name
| Some (`String image) ->
let name = Service.of_string name in
let image = Image.of_string image in
Or_error.return {name; image}
| Some _ ->
Or_error.errorf
"Definition of 'image' field in service '%s' has invalid type"
name)
| _ -> Or_error.errorf "Expected an object in definition of service '%s'" name
let extract_services : Yaml.value -> service_spec list Or_error.t = function
| `O service_list -> service_list |> List.map ~f:extract_service |> Or_error.all
| _ -> Or_error.errorf "'service' key did not map to an object"
let specs : Yaml.value -> service_spec list Or_error.t = function
| `O top_level -> (
match List.Assoc.find top_level ~equal:String.equal "services" with
| None -> Or_error.errorf "No 'services' defined"
| Some services -> extract_services services)
| _ -> Or_error.errorf "Top level object expected"
type context = string String.Map.t
let substitute_template : context -> service_spec -> service_spec Or_error.t =
fun context ({image; _} as spec) ->
let open Or_error.Let_syntax in
let%bind image = Variable.substitute context (Image.to_string image) in
let image = Image.of_string image in
return {spec with image}
let resolve_specs : context -> service_spec list -> service_spec list Or_error.t =
fun context specs -> specs |> List.map ~f:(substitute_template context) |> Or_error.all
let load : string -> context -> service_spec list Or_error.t =
fun filename context ->
let open Or_error.Let_syntax in
let%bind yaml_parsed = load_file filename in
let%bind extracted_specs = specs yaml_parsed in
resolve_specs context extracted_specs
| |
08d8db6e4ed0e6941d943edd5874bf8c0ccfd0d948287e49cc4c9189e5b44b9c | spechub/Hets | Print.hs | |
Module : ./CSMOF / Print.hs
Description : pretty printing for CSMOF
Copyright : ( c ) Universidad de la Republica , Uruguay 2013
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
Module : ./CSMOF/Print.hs
Description : pretty printing for CSMOF
Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
-}
module CSMOF.Print where
import CSMOF.As
import Common.Doc
import Common.DocUtils
instance Pretty Metamodel where
pretty (Metamodel nam ele mode) =
text "metamodel" <+> text nam <+> lbrace
$++$ space <+> space <+> foldr (($++$) . pretty) empty ele
$+$ rbrace
$++$ foldr (($+$) . pretty) empty mode
instance Show Metamodel where
show m = show $ pretty m
instance Pretty NamedElement where
pretty (NamedElement _ _ nes) = pretty nes
instance Show NamedElement where
show m = show $ pretty m
instance Pretty TypeOrTypedElement where
pretty (TType typ) = pretty typ
pretty (TTypedElement _) = empty -- Do not show properties at top level but inside classes
instance Show TypeOrTypedElement where
show m = show $ pretty m
instance Pretty Type where
pretty (Type _ sub) = pretty sub
instance Show Type where
show m = show $ pretty m
instance Pretty DataTypeOrClass where
pretty (DDataType dat) = pretty dat
pretty (DClass cla) = pretty cla
instance Show DataTypeOrClass where
show m = show $ pretty m
instance Pretty Datatype where
pretty (Datatype sup) =
text "datatype" <+> text (namedElementName (typeSuper sup))
instance Show Datatype where
show m = show $ pretty m
instance Pretty Class where
pretty (Class sup isa supC own) =
text (if isa then "abstract class" else "class")
<+> text (namedElementName (typeSuper sup))
<+> (case supC of
[] -> lbrace
_ : _ -> text "extends"
<+> foldr ( (<+>) . text . namedElementName . typeSuper . classSuperType) empty supC
<+> lbrace)
$+$ space <+> space <+> foldr (($+$) . pretty) empty own
$+$ rbrace
instance Show Class where
show m = show $ pretty m
instance Pretty TypedElement where
pretty (TypedElement _ _ sub) = pretty sub
instance Show TypedElement where
show m = show $ pretty m
instance Pretty Property where
pretty (Property sup mul opp _) =
text "property" <+> text (namedElementName (typedElementSuper sup))
<> pretty mul
<+> colon <+> text (namedElementName (typeSuper (typedElementType sup)))
<+> (case opp of
Just n -> text "oppositeOf" <+> text (namedElementName (typedElementSuper (propertySuper n)))
Nothing -> empty)
instance Show Property where
show m = show $ pretty m
instance Pretty MultiplicityElement where
pretty (MultiplicityElement low upp _) =
lbrack <> pretty low <> comma
<> (if upp == -1
then text "*"
else pretty upp)
<> rbrack
instance Show MultiplicityElement where
show m = show $ pretty m
Model part of CSMOF
instance Pretty Model where
pretty (Model mon obj lin mode) =
text "model" <+> text mon
<+> text "conformsTo" <+> text (metamodelName mode) <+> lbrace
$++$ space <+> space <+> foldr (($+$) . pretty) empty obj
$++$ space <+> space <+> foldr (($+$) . pretty) empty lin
$+$ rbrace
instance Show Model where
show m = show $ pretty m
instance Pretty Object where
pretty (Object on ot _) =
text "object " <> text on
<+> colon <+> text (namedElementName (typeSuper ot))
instance Show Object where
show m = show $ pretty m
instance Pretty Link where
pretty (Link lt sou tar _) =
text "link" <+> text (namedElementName (typedElementSuper (propertySuper lt)))
<> lparen <> text (objectName sou) <> comma <> text (objectName tar) <> rparen $+$ empty
instance Show Link where
show m = show $ pretty m
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/CSMOF/Print.hs | haskell | Do not show properties at top level but inside classes | |
Module : ./CSMOF / Print.hs
Description : pretty printing for CSMOF
Copyright : ( c ) Universidad de la Republica , Uruguay 2013
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
Module : ./CSMOF/Print.hs
Description : pretty printing for CSMOF
Copyright : (c) Daniel Calegari Universidad de la Republica, Uruguay 2013
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
-}
module CSMOF.Print where
import CSMOF.As
import Common.Doc
import Common.DocUtils
instance Pretty Metamodel where
pretty (Metamodel nam ele mode) =
text "metamodel" <+> text nam <+> lbrace
$++$ space <+> space <+> foldr (($++$) . pretty) empty ele
$+$ rbrace
$++$ foldr (($+$) . pretty) empty mode
instance Show Metamodel where
show m = show $ pretty m
instance Pretty NamedElement where
pretty (NamedElement _ _ nes) = pretty nes
instance Show NamedElement where
show m = show $ pretty m
instance Pretty TypeOrTypedElement where
pretty (TType typ) = pretty typ
instance Show TypeOrTypedElement where
show m = show $ pretty m
instance Pretty Type where
pretty (Type _ sub) = pretty sub
instance Show Type where
show m = show $ pretty m
instance Pretty DataTypeOrClass where
pretty (DDataType dat) = pretty dat
pretty (DClass cla) = pretty cla
instance Show DataTypeOrClass where
show m = show $ pretty m
instance Pretty Datatype where
pretty (Datatype sup) =
text "datatype" <+> text (namedElementName (typeSuper sup))
instance Show Datatype where
show m = show $ pretty m
instance Pretty Class where
pretty (Class sup isa supC own) =
text (if isa then "abstract class" else "class")
<+> text (namedElementName (typeSuper sup))
<+> (case supC of
[] -> lbrace
_ : _ -> text "extends"
<+> foldr ( (<+>) . text . namedElementName . typeSuper . classSuperType) empty supC
<+> lbrace)
$+$ space <+> space <+> foldr (($+$) . pretty) empty own
$+$ rbrace
instance Show Class where
show m = show $ pretty m
instance Pretty TypedElement where
pretty (TypedElement _ _ sub) = pretty sub
instance Show TypedElement where
show m = show $ pretty m
instance Pretty Property where
pretty (Property sup mul opp _) =
text "property" <+> text (namedElementName (typedElementSuper sup))
<> pretty mul
<+> colon <+> text (namedElementName (typeSuper (typedElementType sup)))
<+> (case opp of
Just n -> text "oppositeOf" <+> text (namedElementName (typedElementSuper (propertySuper n)))
Nothing -> empty)
instance Show Property where
show m = show $ pretty m
instance Pretty MultiplicityElement where
pretty (MultiplicityElement low upp _) =
lbrack <> pretty low <> comma
<> (if upp == -1
then text "*"
else pretty upp)
<> rbrack
instance Show MultiplicityElement where
show m = show $ pretty m
Model part of CSMOF
instance Pretty Model where
pretty (Model mon obj lin mode) =
text "model" <+> text mon
<+> text "conformsTo" <+> text (metamodelName mode) <+> lbrace
$++$ space <+> space <+> foldr (($+$) . pretty) empty obj
$++$ space <+> space <+> foldr (($+$) . pretty) empty lin
$+$ rbrace
instance Show Model where
show m = show $ pretty m
instance Pretty Object where
pretty (Object on ot _) =
text "object " <> text on
<+> colon <+> text (namedElementName (typeSuper ot))
instance Show Object where
show m = show $ pretty m
instance Pretty Link where
pretty (Link lt sou tar _) =
text "link" <+> text (namedElementName (typedElementSuper (propertySuper lt)))
<> lparen <> text (objectName sou) <> comma <> text (objectName tar) <> rparen $+$ empty
instance Show Link where
show m = show $ pretty m
|
26fe55c258958d8a2561eda2a861c2493b3a94221d06d43b7a1b9d70e5e6f8da | panda-planner-dev/ipc2020-domains | d-07.lisp | (defdomain domain (
(:operator (!obtain_permit ?op_h)
;; preconditions
(
(type_Hazardous ?op_h)
(not (Have_Permit ?op_h))
)
;; delete effects
()
;; add effects
((Have_Permit ?op_h))
)
(:operator (!collect_fees ?cf_p)
;; preconditions
(
(type_Package ?cf_p)
(not (Fees_Collected ?cf_p))
)
;; delete effects
()
;; add effects
((Fees_Collected ?cf_p))
)
(:operator (!collect_insurance ?ci_v)
;; preconditions
(
(type_Valuable ?ci_v)
(not (Insured ?ci_v))
)
;; delete effects
()
;; add effects
((Insured ?ci_v))
)
(:operator (!go_through_tcenter_cc ?gttc_lo ?gttc_ld ?gttc_co ?gttc_cd ?gttc_tc)
;; preconditions
(
(type_Not_TCenter ?gttc_lo) (type_Not_TCenter ?gttc_ld) (type_City ?gttc_co) (type_City ?gttc_cd) (type_TCenter ?gttc_tc)
(In_City ?gttc_lo ?gttc_co) (In_City ?gttc_ld ?gttc_cd) (Serves ?gttc_tc ?gttc_co) (Serves ?gttc_tc ?gttc_cd) (Available ?gttc_tc)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_ottd ?gtttcc_lo ?gtttcc_ld ?gtttcc_co ?gtttcc_cd ?gtttcc_t1 ?gtttcc_t2)
;; preconditions
(
(type_Not_TCenter ?gtttcc_lo) (type_Not_TCenter ?gtttcc_ld) (type_City ?gtttcc_co) (type_City ?gtttcc_cd) (type_TCenter ?gtttcc_t1) (type_TCenter ?gtttcc_t2)
(In_City ?gtttcc_lo ?gtttcc_co) (In_City ?gtttcc_ld ?gtttcc_cd) (Serves ?gtttcc_t1 ?gtttcc_co) (Serves ?gtttcc_t2 ?gtttcc_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_otd ?gtttccotd_ld ?gtttccotd_co ?gtttccotd_cd ?gtttccotd_to ?gtttccotd_t1)
;; preconditions
(
(type_Not_TCenter ?gtttccotd_ld) (type_City ?gtttccotd_co) (type_City ?gtttccotd_cd) (type_TCenter ?gtttccotd_to) (type_TCenter ?gtttccotd_t1)
(In_City ?gtttccotd_to ?gtttccotd_co) (In_City ?gtttccotd_ld ?gtttccotd_cd) (Serves ?gtttccotd_t1 ?gtttccotd_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_cities_ott ?gtttccott_ld ?gtttccott_co ?gtttccott_cd ?gtttccott_to ?gtttccott_td)
;; preconditions
(
(type_City_Location ?gtttccott_ld) (type_City ?gtttccott_co) (type_City ?gtttccott_cd) (type_TCenter ?gtttccott_to) (type_TCenter ?gtttccott_td)
(In_City ?gtttccott_ld ?gtttccott_co) (In_City ?gtttccott_td ?gtttccott_cd) (Serves ?gtttccott_to ?gtttccott_co)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters ?gtttc_to ?gtttc_td)
;; preconditions
(
(type_TCenter ?gtttc_to) (type_TCenter ?gtttc_td)
(Available ?gtttc_to) (Available ?gtttc_td)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_tt ?gtttctt_to ?gtttctt_td ?gtttctt_co ?gtttctt_cd)
;; preconditions
(
(type_TCenter ?gtttctt_to) (type_TCenter ?gtttctt_td) (type_City ?gtttctt_co) (type_City ?gtttctt_cd)
(In_City ?gtttctt_to ?gtttctt_co) (In_City ?gtttctt_td ?gtttctt_cd)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_via_hub_hazardous ?gtttcvhh_to ?gtttcvhh_td ?gtttcvhh_h ?gtttcvhh_co ?gtttcvhh_ch ?gtttcvhh_cd ?gtttcvhh_ro ?gtttcvhh_rd)
;; preconditions
(
(type_TCenter ?gtttcvhh_to) (type_TCenter ?gtttcvhh_td) (type_Hub ?gtttcvhh_h) (type_City ?gtttcvhh_co) (type_City ?gtttcvhh_ch) (type_City ?gtttcvhh_cd) (type_Region ?gtttcvhh_ro) (type_Region ?gtttcvhh_rd)
(Available ?gtttcvhh_to) (Available ?gtttcvhh_td) (In_City ?gtttcvhh_h ?gtttcvhh_ch) (City_Hazardous_Compatible ?gtttcvhh_ch) (In_City ?gtttcvhh_to ?gtttcvhh_co) (In_City ?gtttcvhh_td ?gtttcvhh_cd) (In_Region ?gtttcvhh_co ?gtttcvhh_ro) (In_Region ?gtttcvhh_cd ?gtttcvhh_rd) (Serves ?gtttcvhh_h ?gtttcvhh_ro) (Serves ?gtttcvhh_h ?gtttcvhh_rd) (Available ?gtttcvhh_h)
)
;; delete effects
()
;; add effects
()
)
(:operator (!go_through_two_tcenters_via_hub_not_hazardous ?gtttcvhnh_to ?gtttcvhnh_td ?gtttcvhnh_co ?gtttcvhnh_cd ?gtttcvhnh_ro ?gtttcvhnh_rd ?gtttcvhnh_h)
;; preconditions
(
(type_TCenter ?gtttcvhnh_to) (type_TCenter ?gtttcvhnh_td) (type_City ?gtttcvhnh_co) (type_City ?gtttcvhnh_cd) (type_Region ?gtttcvhnh_ro) (type_Region ?gtttcvhnh_rd) (type_Hub ?gtttcvhnh_h)
(Available ?gtttcvhnh_to) (Available ?gtttcvhnh_td) (In_City ?gtttcvhnh_to ?gtttcvhnh_co) (In_City ?gtttcvhnh_td ?gtttcvhnh_cd) (In_Region ?gtttcvhnh_co ?gtttcvhnh_ro) (In_Region ?gtttcvhnh_cd ?gtttcvhnh_rd) (Serves ?gtttcvhnh_h ?gtttcvhnh_ro) (Serves ?gtttcvhnh_h ?gtttcvhnh_rd) (Available ?gtttcvhnh_h)
)
;; delete effects
()
;; add effects
()
)
(:operator (!deliver_p ?dp_p)
;; preconditions
(
(type_Package ?dp_p)
(Fees_Collected ?dp_p)
)
;; delete effects
((Fees_Collected ?dp_p))
;; add effects
((Delivered ?dp_p))
)
(:operator (!deliver_h ?dh_h)
;; preconditions
(
(type_Hazardous ?dh_h)
(Fees_Collected ?dh_h) (Have_Permit ?dh_h)
)
;; delete effects
((Have_Permit ?dh_h) (Fees_Collected ?dh_h))
;; add effects
((Delivered ?dh_h))
)
(:operator (!deliver_v ?dv_v)
;; preconditions
(
(type_Valuable ?dv_v)
(Fees_Collected ?dv_v) (Insured ?dv_v)
)
;; delete effects
((Fees_Collected ?dv_v) (Insured ?dv_v))
;; add effects
((Delivered ?dv_v))
)
(:operator (!post_guard_outside ?pco_a)
;; preconditions
(
(type_Armored ?pco_a)
)
;; delete effects
((Guard_Inside ?pco_a))
;; add effects
((Guard_Outside ?pco_a))
)
(:operator (!post_guard_inside ?pci_a)
;; preconditions
(
(type_Armored ?pci_a)
)
;; delete effects
((Guard_Outside ?pci_a))
;; add effects
((Guard_Inside ?pci_a))
)
(:operator (!remove_guard ?mc_a)
;; preconditions
(
(type_Armored ?mc_a)
)
;; delete effects
((Guard_Outside ?mc_a) (Guard_Inside ?mc_a))
;; add effects
()
)
(:operator (!decontaminate_interior ?di_v)
;; preconditions
(
(type_Vehicle ?di_v)
)
;; delete effects
()
;; add effects
((Decontaminated_Interior ?di_v))
)
(:operator (!affix_warning_signs ?fws_v)
;; preconditions
(
(type_Vehicle ?fws_v)
(not (Warning_Signs_Affixed ?fws_v))
)
;; delete effects
()
;; add effects
((Warning_Signs_Affixed ?fws_v))
)
(:operator (!remove_warning_signs ?mws_v)
;; preconditions
(
(type_Vehicle ?mws_v)
(Warning_Signs_Affixed ?mws_v)
)
;; delete effects
((Warning_Signs_Affixed ?mws_v))
;; add effects
()
)
(:operator (!attach_train_car ?atc_t ?atc_tc ?atc_l)
;; preconditions
(
(type_Train ?atc_t) (type_Traincar ?atc_tc) (type_Location ?atc_l)
(At_Vehicle ?atc_tc ?atc_l) (At_Vehicle ?atc_t ?atc_l) (not (Connected_To ?atc_tc ?atc_t))
)
;; delete effects
((At_Vehicle ?atc_tc ?atc_l))
;; add effects
((Connected_To ?atc_tc ?atc_t))
)
(:operator (!detach_train_car ?dtc_t ?dtc_tc ?dtc_l)
;; preconditions
(
(type_Train ?dtc_t) (type_Traincar ?dtc_tc) (type_Location ?dtc_l)
(At_Vehicle ?dtc_t ?dtc_l) (Connected_To ?dtc_tc ?dtc_t)
)
;; delete effects
((Connected_To ?dtc_tc ?dtc_t))
;; add effects
((At_Vehicle ?dtc_tc ?dtc_l))
)
(:operator (!connect_hose ?ch_tv ?ch_l)
;; preconditions
(
(type_Tanker_Vehicle ?ch_tv) (type_Liquid ?ch_l)
(not (Hose_Connected ?ch_tv ?ch_l))
)
;; delete effects
()
;; add effects
((Hose_Connected ?ch_tv ?ch_l))
)
(:operator (!disconnect_hose ?dch_tv ?dch_l)
;; preconditions
(
(type_Tanker_Vehicle ?dch_tv) (type_Liquid ?dch_l)
(Hose_Connected ?dch_tv ?dch_l)
)
;; delete effects
((Hose_Connected ?dch_tv ?dch_l))
;; add effects
()
)
(:operator (!open_valve ?ov_tv)
;; preconditions
(
(type_Tanker_Vehicle ?ov_tv)
(not (Valve_Open ?ov_tv))
)
;; delete effects
()
;; add effects
((Valve_Open ?ov_tv))
)
(:operator (!close_valve ?cv_tv)
;; preconditions
(
(type_Tanker_Vehicle ?cv_tv)
(Valve_Open ?cv_tv)
)
;; delete effects
((Valve_Open ?cv_tv))
;; add effects
()
)
(:operator (!fill_tank ?ft_tv ?ft_li ?ft_lo)
;; preconditions
(
(type_Tanker_Vehicle ?ft_tv) (type_Liquid ?ft_li) (type_Location ?ft_lo)
(Hose_Connected ?ft_tv ?ft_li) (Valve_Open ?ft_tv) (At_Package ?ft_li ?ft_lo) (At_Vehicle ?ft_tv ?ft_lo) (PV_Compatible ?ft_li ?ft_tv)
)
;; delete effects
((At_Package ?ft_li ?ft_lo))
;; add effects
((At_Package ?ft_li ?ft_tv))
)
(:operator (!empty_tank ?et_tv ?et_li ?et_lo)
;; preconditions
(
(type_Tanker_Vehicle ?et_tv) (type_Liquid ?et_li) (type_Location ?et_lo)
(Hose_Connected ?et_tv ?et_li) (Valve_Open ?et_tv) (At_Package ?et_li ?et_tv) (At_Vehicle ?et_tv ?et_lo)
)
;; delete effects
((At_Package ?et_li ?et_tv))
;; add effects
((At_Package ?et_li ?et_lo))
)
(:operator (!load_cars ?lc_c ?lc_v ?lc_l)
;; preconditions
(
(type_Cars ?lc_c) (type_Auto_Vehicle ?lc_v) (type_Location ?lc_l)
(At_Package ?lc_c ?lc_l) (At_Vehicle ?lc_v ?lc_l) (Ramp_Down ?lc_v) (PV_Compatible ?lc_c ?lc_v)
)
;; delete effects
((At_Package ?lc_c ?lc_l))
;; add effects
((At_Package ?lc_c ?lc_v))
)
(:operator (!unload_cars ?uc_c ?uc_v ?uc_l)
;; preconditions
(
(type_Cars ?uc_c) (type_Auto_Vehicle ?uc_v) (type_Location ?uc_l)
(At_Package ?uc_c ?uc_v) (At_Vehicle ?uc_v ?uc_l) (Ramp_Down ?uc_v)
)
;; delete effects
((At_Package ?uc_c ?uc_v))
;; add effects
((At_Package ?uc_c ?uc_l))
)
(:operator (!raise_ramp ?rr_v)
;; preconditions
(
(type_Vehicle ?rr_v)
(Ramp_Down ?rr_v)
)
;; delete effects
((Ramp_Down ?rr_v))
;; add effects
()
)
(:operator (!lower_ramp ?lr_v)
;; preconditions
(
(type_Vehicle ?lr_v)
(not (Ramp_Down ?lr_v))
)
;; delete effects
()
;; add effects
((Ramp_Down ?lr_v))
)
(:operator (!load_livestock ?ll_p ?ll_v ?ll_l)
;; preconditions
(
(type_Livestock_Package ?ll_p) (type_Livestock_Vehicle ?ll_v) (type_Location ?ll_l)
(At_Package ?ll_p ?ll_l) (At_Vehicle ?ll_v ?ll_l) (Ramp_Down ?ll_v) (PV_Compatible ?ll_p ?ll_v)
)
;; delete effects
((At_Package ?ll_p ?ll_l) (Clean_Interior ?ll_v))
;; add effects
((At_Package ?ll_p ?ll_v))
)
(:operator (!unload_livestock ?ull_p ?ull_v ?ull_l)
;; preconditions
(
(type_Livestock_Package ?ull_p) (type_Livestock_Vehicle ?ull_v) (type_Location ?ull_l)
(At_Package ?ull_p ?ull_v) (At_Vehicle ?ull_v ?ull_l) (Ramp_Down ?ull_v)
)
;; delete effects
((At_Package ?ull_p ?ull_v) (Trough_Full ?ull_v))
;; add effects
((At_Package ?ull_p ?ull_l))
)
(:operator (!fill_trough ?ftr_v)
;; preconditions
(
(type_Livestock_Vehicle ?ftr_v)
)
;; delete effects
()
;; add effects
((Trough_Full ?ftr_v))
)
(:operator (!do_clean_interior ?cli_v)
;; preconditions
(
(type_Vehicle ?cli_v)
)
;; delete effects
()
;; add effects
((Clean_Interior ?cli_v))
)
(:operator (!attach_conveyor_ramp ?acr_ap ?acr_pr ?acr_l)
;; preconditions
(
(type_Airplane ?acr_ap) (type_Plane_Ramp ?acr_pr) (type_Location ?acr_l)
(Available ?acr_pr) (At_Equipment ?acr_pr ?acr_l) (At_Vehicle ?acr_ap ?acr_l)
)
;; delete effects
((Available ?acr_pr))
;; add effects
((Ramp_Connected ?acr_pr ?acr_ap))
)
(:operator (!detach_conveyor_ramp ?dcr_ap ?dcr_pr ?dcr_l)
;; preconditions
(
(type_Airplane ?dcr_ap) (type_Plane_Ramp ?dcr_pr) (type_Location ?dcr_l)
(Ramp_Connected ?dcr_pr ?dcr_ap) (At_Equipment ?dcr_pr ?dcr_l) (At_Vehicle ?dcr_ap ?dcr_l)
)
;; delete effects
((Ramp_Connected ?dcr_pr ?dcr_ap))
;; add effects
((Available ?dcr_pr))
)
(:operator (!connect_chute ?cc_h)
;; preconditions
(
(type_Hopper_Vehicle ?cc_h)
(not (Chute_Connected ?cc_h))
)
;; delete effects
()
;; add effects
((Chute_Connected ?cc_h))
)
(:operator (!disconnect_chute ?dc_h)
;; preconditions
(
(type_Hopper_Vehicle ?dc_h)
(Chute_Connected ?dc_h)
)
;; delete effects
((Chute_Connected ?dc_h))
;; add effects
()
)
(:operator (!fill_hopper ?fh_p ?fh_hv ?fh_l)
;; preconditions
(
(type_Package ?fh_p) (type_Hopper_Vehicle ?fh_hv) (type_Location ?fh_l)
(Chute_Connected ?fh_hv) (At_Vehicle ?fh_hv ?fh_l) (At_Package ?fh_p ?fh_l) (PV_Compatible ?fh_p ?fh_hv)
)
;; delete effects
((At_Package ?fh_p ?fh_l))
;; add effects
((At_Package ?fh_p ?fh_hv))
)
(:operator (!empty_hopper ?eh_p ?eh_hv ?eh_l)
;; preconditions
(
(type_Package ?eh_p) (type_Hopper_Vehicle ?eh_hv) (type_Location ?eh_l)
(Chute_Connected ?eh_hv) (At_Vehicle ?eh_hv ?eh_l) (At_Package ?eh_p ?eh_hv)
)
;; delete effects
((At_Package ?eh_p ?eh_hv))
;; add effects
((At_Package ?eh_p ?eh_l))
)
(:operator (!pick_up_package_ground ?pupg_p ?pupg_c ?pupg_l)
;; preconditions
(
(type_Package ?pupg_p) (type_Crane ?pupg_c) (type_Location ?pupg_l)
(Empty ?pupg_c) (Available ?pupg_c) (At_Equipment ?pupg_c ?pupg_l) (At_Package ?pupg_p ?pupg_l)
)
;; delete effects
((Empty ?pupg_c) (At_Package ?pupg_p ?pupg_l))
;; add effects
((At_Package ?pupg_p ?pupg_c))
)
(:operator (!put_down_package_ground ?pdpg_p ?pdpg_c ?pdpg_l)
;; preconditions
(
(type_Package ?pdpg_p) (type_Crane ?pdpg_c) (type_Location ?pdpg_l)
(Available ?pdpg_c) (At_Equipment ?pdpg_c ?pdpg_l) (At_Package ?pdpg_p ?pdpg_c)
)
;; delete effects
((At_Package ?pdpg_p ?pdpg_c))
;; add effects
((At_Package ?pdpg_p ?pdpg_l) (Empty ?pdpg_c))
)
(:operator (!pick_up_package_vehicle ?pupv_p ?pupv_c ?pupv_fv ?pupv_l)
;; preconditions
(
(type_Package ?pupv_p) (type_Crane ?pupv_c) (type_Flatbed_Vehicle ?pupv_fv) (type_Location ?pupv_l)
(Empty ?pupv_c) (Available ?pupv_c) (At_Equipment ?pupv_c ?pupv_l) (At_Package ?pupv_p ?pupv_fv) (At_Vehicle ?pupv_fv ?pupv_l)
)
;; delete effects
((Empty ?pupv_c) (At_Package ?pupv_p ?pupv_fv))
;; add effects
((At_Package ?pupv_p ?pupv_c))
)
(:operator (!put_down_package_vehicle ?pdpv_p ?pdpv_c ?pdpv_fv ?pdpv_l)
;; preconditions
(
(type_Package ?pdpv_p) (type_Crane ?pdpv_c) (type_Flatbed_Vehicle ?pdpv_fv) (type_Location ?pdpv_l)
(Available ?pdpv_c) (At_Package ?pdpv_p ?pdpv_c) (At_Equipment ?pdpv_c ?pdpv_l) (At_Vehicle ?pdpv_fv ?pdpv_l) (PV_Compatible ?pdpv_p ?pdpv_fv)
)
;; delete effects
((At_Package ?pdpv_p ?pdpv_c))
;; add effects
((Empty ?pdpv_c) (At_Package ?pdpv_p ?pdpv_fv))
)
(:operator (!open_door ?od_rv)
;; preconditions
(
(type_Regular_Vehicle ?od_rv)
(not (Door_Open ?od_rv))
)
;; delete effects
()
;; add effects
((Door_Open ?od_rv))
)
(:operator (!close_door ?cd_rv)
;; preconditions
(
(type_Regular_Vehicle ?cd_rv)
(Door_Open ?cd_rv)
)
;; delete effects
((Door_Open ?cd_rv))
;; add effects
()
)
(:operator (!load_package ?lp_p ?lp_v ?lp_l)
;; preconditions
(
(type_Package ?lp_p) (type_Vehicle ?lp_v) (type_Location ?lp_l)
(At_Package ?lp_p ?lp_l) (At_Vehicle ?lp_v ?lp_l) (PV_Compatible ?lp_p ?lp_v)
)
;; delete effects
((At_Package ?lp_p ?lp_l))
;; add effects
((At_Package ?lp_p ?lp_v))
)
(:operator (!unload_package ?up_p ?up_v ?up_l)
;; preconditions
(
(type_Package ?up_p) (type_Vehicle ?up_v) (type_Location ?up_l)
(At_Package ?up_p ?up_v) (At_Vehicle ?up_v ?up_l)
)
;; delete effects
((At_Package ?up_p ?up_v))
;; add effects
((At_Package ?up_p ?up_l))
)
(:operator (!move_vehicle_no_traincar ?hmnt_v ?hmnt_o ?hmnt_r ?hmnt_d)
;; preconditions
(
(type_Vehicle ?hmnt_v) (type_Location ?hmnt_o) (type_Route ?hmnt_r) (type_Location ?hmnt_d)
(Connects ?hmnt_r ?hmnt_o ?hmnt_d) (Available ?hmnt_v) (Available ?hmnt_r) (RV_Compatible ?hmnt_r ?hmnt_v) (At_Vehicle ?hmnt_v ?hmnt_o)
)
;; delete effects
((At_Vehicle ?hmnt_v ?hmnt_o))
;; add effects
((At_Vehicle ?hmnt_v ?hmnt_d))
)
(:method (__top)
__top_method
(
(type_sort_for_Holz ?var_for_Holz_1) (type_sort_for_O27 ?var_for_O27_2) (type_sort_for_O28 ?var_for_O28_3)
)
((transport ?var_for_Holz_1 ?var_for_O27_2 ?var_for_O28_3))
)
(:method (carry ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld)
method_carry_cd
(
(type_Package ?mccd_cd_p) (type_Location ?mccd_cd_lo) (type_Location ?mccd_cd_ld)
(type_Location ?mccd_cd_ld) (type_Location ?mccd_cd_lo) (type_Package ?mccd_cd_p)
)
((carry_direct ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld))
)
(:method (carry ?mch_hctt_p ?mch_hctt_o ?mch_hctt_d)
method_carry_cvh
(
(type_Package ?mch_hctt_p) (type_Location ?mch_hctt_o) (type_Location ?mch_hctt_d)
(type_City ?mch_hctt_cd) (type_City ?mch_hctt_co) (type_TCenter ?mch_hctt_d) (type_TCenter ?mch_hctt_o) (type_Package ?mch_hctt_p)
)
((helper_carry_tt ?mch_hctt_p ?mch_hctt_o ?mch_hctt_co ?mch_hctt_d ?mch_hctt_cd))
)
(:method (carry ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_d)
method_carry_cd_cbtc
(
(type_Package ?mccct_hcott_p) (type_Location ?mccct_hcott_o) (type_Location ?mccct_hcott_d)
(type_City ?mccct_hcott_cd) (type_City ?mccct_hcott_co) (type_TCenter ?mccct_hcott_d) (type_City_Location ?mccct_hcott_o) (type_Package ?mccct_hcott_p) (type_TCenter ?mccct_hcott_t1)
)
((helper_carry_ott ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_co ?mccct_hcott_t1 ?mccct_hcott_d ?mccct_hcott_cd))
)
(:method (carry ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_d)
method_carry_cbtc_cd
(
(type_Package ?mcctc_hcotd_p) (type_Location ?mcctc_hcotd_o) (type_Location ?mcctc_hcotd_d)
(type_City ?mcctc_hcotd_cd) (type_City ?mcctc_hcotd_co) (type_Not_TCenter ?mcctc_hcotd_d) (type_TCenter ?mcctc_hcotd_o) (type_Package ?mcctc_hcotd_p) (type_TCenter ?mcctc_hcotd_t1)
)
((helper_carry_otd ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_co ?mcctc_hcotd_t1 ?mcctc_hcotd_d ?mcctc_hcotd_cd))
)
(:method (carry ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_d)
method_carry_cd_cbtc_cd
(
(type_Package ?mcccc_hcottd_p) (type_Location ?mcccc_hcottd_o) (type_Location ?mcccc_hcottd_d)
(type_City ?mcccc_hcottd_cd) (type_City ?mcccc_hcottd_co) (type_Not_TCenter ?mcccc_hcottd_d) (type_Not_TCenter ?mcccc_hcottd_o) (type_Package ?mcccc_hcottd_p) (type_TCenter ?mcccc_hcottd_t1) (type_TCenter ?mcccc_hcottd_t2)
)
((helper_carry_ottd ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_co ?mcccc_hcottd_t1 ?mcccc_hcottd_t2 ?mcccc_hcottd_d ?mcccc_hcottd_cd))
)
(:method (carry ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_d)
method_carry_cd_cd
(
(type_Package ?mccc_hccc_p) (type_Location ?mccc_hccc_o) (type_Location ?mccc_hccc_d)
(type_City ?mccc_hccc_cd) (type_City ?mccc_hccc_co) (type_Not_TCenter ?mccc_hccc_d) (type_Not_TCenter ?mccc_hccc_o) (type_Package ?mccc_hccc_p) (type_TCenter ?mccc_hccc_t)
)
((helper_carry_cc ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_co ?mccc_hccc_t ?mccc_hccc_d ?mccc_hccc_cd))
)
(:method (carry_between_tcenters ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td)
method_carry_between_tcenters_cd
(
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_to) (type_TCenter ?mcbtc_gtttc_td)
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_td) (type_TCenter ?mcbtc_gtttc_to)
)
(:unordered (!go_through_two_tcenters ?mcbtc_gtttc_to ?mcbtc_gtttc_td) (carry_direct ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td))
)
(:method (carry_between_tcenters ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd)
method_carry_between_tcenters_cvh
(
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tco) (type_TCenter ?mcbth_tch_tcd)
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tcd) (type_TCenter ?mcbth_tch_tco)
)
((carry_via_hub ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd))
)
(:method (carry_direct ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d)
method_carry_direct
(
(type_Package ?mcd_hmcd_p) (type_Location ?mcd_hmcd_o) (type_Location ?mcd_hmcd_d)
(type_Location ?mcd_hmcd_d) (type_Location ?mcd_hmcd_o) (type_Package ?mcd_hmcd_p) (type_Vehicle ?mcd_hmcd_v)
)
((helper_carry_direct ?mcd_hmcd_v ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d))
)
(:method (carry_via_hub ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_tcd)
method_carry_via_hub_not_hazardous
(
(type_Package ?mcvhn_hcvhn_p) (type_TCenter ?mcvhn_hcvhn_tco) (type_TCenter ?mcvhn_hcvhn_tcd)
(type_City ?mcvhn_hcvhn_ctcd) (type_City ?mcvhn_hcvhn_ctco) (type_Hub ?mcvhn_hcvhn_h) (type_Package ?mcvhn_hcvhn_p) (type_Region ?mcvhn_hcvhn_rctcd) (type_Region ?mcvhn_hcvhn_rctco) (type_TCenter ?mcvhn_hcvhn_tcd) (type_TCenter ?mcvhn_hcvhn_tco)
)
((helper_carry_via_hub_not_hazardous ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_ctco ?mcvhn_hcvhn_rctco ?mcvhn_hcvhn_h ?mcvhn_hcvhn_tcd ?mcvhn_hcvhn_ctcd ?mcvhn_hcvhn_rctcd))
)
(:method (carry_via_hub ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_tcd)
method_carry_via_hub_hazardous
(
(type_Package ?mcvhh_hcvhh_p) (type_TCenter ?mcvhh_hcvhh_tco) (type_TCenter ?mcvhh_hcvhh_tcd)
(type_City ?mcvhh_hcvhh_ch) (type_City ?mcvhh_hcvhh_ctcd) (type_City ?mcvhh_hcvhh_ctco) (type_Hub ?mcvhh_hcvhh_h) (type_Package ?mcvhh_hcvhh_p) (type_Region ?mcvhh_hcvhh_rctcd) (type_Region ?mcvhh_hcvhh_rctco) (type_TCenter ?mcvhh_hcvhh_tcd) (type_TCenter ?mcvhh_hcvhh_tco)
)
((helper_carry_via_hub_hazardous ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_ctco ?mcvhh_hcvhh_rctco ?mcvhh_hcvhh_h ?mcvhh_hcvhh_ch ?mcvhh_hcvhh_tcd ?mcvhh_hcvhh_ctcd ?mcvhh_hcvhh_rctcd))
)
(:method (deliver ?mddp_dp_p)
method_deliver_dp
(
(type_Package ?mddp_dp_p)
(type_Package ?mddp_dp_p)
)
((!deliver_p ?mddp_dp_p))
)
(:method (deliver ?mddv_dv_v)
method_deliver_dv
(
(type_Package ?mddv_dv_v)
(type_Valuable ?mddv_dv_v)
)
((!deliver_v ?mddv_dv_v))
)
(:method (deliver ?mddh_dh_h)
method_deliver_dh
(
(type_Package ?mddh_dh_h)
(type_Hazardous ?mddh_dh_h)
)
((!deliver_h ?mddh_dh_h))
)
(:method (helper_carry_cc ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_co ?mhccc_gttc_tc ?mhccc_gttc_ld ?mhccc_gttc_cd)
method_helper_carry_cd_cd
(
(type_Package ?mhccc_cdd_p) (type_Not_TCenter ?mhccc_gttc_lo) (type_City ?mhccc_gttc_co) (type_TCenter ?mhccc_gttc_tc) (type_Not_TCenter ?mhccc_gttc_ld) (type_City ?mhccc_gttc_cd)
(type_Package ?mhccc_cdd_p) (type_City ?mhccc_gttc_cd) (type_City ?mhccc_gttc_co) (type_Not_TCenter ?mhccc_gttc_ld) (type_Not_TCenter ?mhccc_gttc_lo) (type_TCenter ?mhccc_gttc_tc)
)
((carry_direct ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_tc) (!go_through_tcenter_cc ?mhccc_gttc_lo ?mhccc_gttc_ld ?mhccc_gttc_co ?mhccc_gttc_cd ?mhccc_gttc_tc) (carry_direct ?mhccc_cdd_p ?mhccc_gttc_tc ?mhccc_gttc_ld))
)
(:method (helper_carry_direct ?mhcd_ult_v ?mhcd_ult_p ?mhcd_mvd_lo ?mhcd_ult_l)
method_helper_carry_direct
(
(type_Vehicle ?mhcd_ult_v) (type_Package ?mhcd_ult_p) (type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_ult_l)
(type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_mvo_lo) (type_Location ?mhcd_ult_l) (type_Package ?mhcd_ult_p) (type_Vehicle ?mhcd_ult_v)
)
((move ?mhcd_ult_v ?mhcd_mvo_lo ?mhcd_mvd_lo) (load_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_mvd_lo) (move ?mhcd_ult_v ?mhcd_mvd_lo ?mhcd_ult_l) (unload_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_ult_l))
)
(:method (helper_carry_direct ?mhcdo_ult_v ?mhcdo_ult_p ?mhcdo_m_lo ?mhcdo_ult_l)
method_helper_carry_direct_noMoveFirst
(
(type_Vehicle ?mhcdo_ult_v) (type_Package ?mhcdo_ult_p) (type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l)
(type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l) (type_Package ?mhcdo_ult_p) (type_Vehicle ?mhcdo_ult_v)
)
((load_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_m_lo) (move ?mhcdo_ult_v ?mhcdo_m_lo ?mhcdo_ult_l) (unload_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_ult_l))
)
(:method (helper_carry_otd ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_cd)
method_helper_carry_cbtc_cd
(
(type_Package ?mhcctc_cd_p) (type_TCenter ?mhcctc_gtttccotd_o) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_t1) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_cd)
(type_Package ?mhcctc_cd_p) (type_City ?mhcctc_gtttccotd_cd) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_o) (type_TCenter ?mhcctc_gtttccotd_t1)
)
((carry_between_tcenters ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (!go_through_two_tcenters_cities_otd ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_cd ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (carry_direct ?mhcctc_cd_p ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl))
)
(:method (helper_carry_ott ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_to ?mhccct_gtttccott_td ?mhccct_gtttccott_cd)
method_helper_carry_cd_cbtc
(
(type_Package ?mhccct_cbt_p) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_to) (type_TCenter ?mhccct_gtttccott_td) (type_City ?mhccct_gtttccott_cd)
(type_Package ?mhccct_cbt_p) (type_City ?mhccct_gtttccott_cd) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_td) (type_TCenter ?mhccct_gtttccott_to)
)
((carry_direct ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_to) (!go_through_two_tcenters_cities_ott ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_cd ?mhccct_gtttccott_to ?mhccct_gtttccott_td) (carry_between_tcenters ?mhccct_cbt_p ?mhccct_gtttccott_to ?mhccct_gtttccott_td))
)
(:method (helper_carry_ottd ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_co ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld ?mhcccc_gtttc_cd)
method_helper_carry_cd_cbtc_cd
(
(type_Package ?mhcccc_cdd_p) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_City ?mhcccc_gtttc_co) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_City ?mhcccc_gtttc_cd)
(type_Package ?mhcccc_cdd_p) (type_City ?mhcccc_gtttc_cd) (type_City ?mhcccc_gtttc_co) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2)
)
((carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_t1) (!go_through_two_tcenters_cities_ottd ?mhcccc_gtttc_lo ?mhcccc_gtttc_ld ?mhcccc_gtttc_co ?mhcccc_gtttc_cd ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_between_tcenters ?mhcccc_cdd_p ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld))
)
(:method (helper_carry_tt ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_co ?mhch_gtttctt_td ?mhch_gtttctt_cd)
method_helper_carry_cvh
(
(type_Package ?mhch_tch_p) (type_TCenter ?mhch_gtttctt_to) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_City ?mhch_gtttctt_cd)
(type_City ?mhch_gtttctt_cd) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_TCenter ?mhch_gtttctt_to) (type_Package ?mhch_tch_p)
)
((carry_via_hub ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_td) (!go_through_two_tcenters_tt ?mhch_gtttctt_to ?mhch_gtttctt_td ?mhch_gtttctt_co ?mhch_gtttctt_cd))
)
(:method (helper_carry_via_hub_hazardous ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_rd)
method_helper_carry_via_hub_hazardous
(
(type_Package ?mhcvhh_cd2_p) (type_TCenter ?mhcvhh_gtttcvhh_to) (type_City ?mhcvhh_gtttcvhh_co) (type_Region ?mhcvhh_gtttcvhh_ro) (type_Hub ?mhcvhh_gtttcvhh_h) (type_City ?mhcvhh_gtttcvhh_ch) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_City ?mhcvhh_gtttcvhh_cd) (type_Region ?mhcvhh_gtttcvhh_rd)
(type_Package ?mhcvhh_cd2_p) (type_City ?mhcvhh_gtttcvhh_cd) (type_City ?mhcvhh_gtttcvhh_ch) (type_City ?mhcvhh_gtttcvhh_co) (type_Hub ?mhcvhh_gtttcvhh_h) (type_Region ?mhcvhh_gtttcvhh_rd) (type_Region ?mhcvhh_gtttcvhh_ro) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_TCenter ?mhcvhh_gtttcvhh_to)
)
((carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_h) (!go_through_two_tcenters_via_hub_hazardous ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_rd) (carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_td))
)
(:method (helper_carry_via_hub_not_hazardous ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_rd)
method_helper_carry_via_hub_not_hazardous
(
(type_Package ?mhcvhn_cd2_p) (type_TCenter ?mhcvhn_gtttcvhnh_to) (type_City ?mhcvhn_gtttcvhnh_co) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_City ?mhcvhn_gtttcvhnh_cd) (type_Region ?mhcvhn_gtttcvhnh_rd)
(type_Package ?mhcvhn_cd2_p) (type_City ?mhcvhn_gtttcvhnh_cd) (type_City ?mhcvhn_gtttcvhnh_co) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_Region ?mhcvhn_gtttcvhnh_rd) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_TCenter ?mhcvhn_gtttcvhnh_to)
)
((carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_h) (!go_through_two_tcenters_via_hub_not_hazardous ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_rd ?mhcvhn_gtttcvhnh_h) (carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td))
)
(:method (helper_move_traincar ?mhmt_dtc_tc ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l)
method_helper_move_traincar
(
(type_Traincar ?mhmt_dtc_tc) (type_Train ?mhmt_dtc_t) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_dtc_l)
(type_Location ?mhmt_dtc_l) (type_Train ?mhmt_dtc_t) (type_Traincar ?mhmt_dtc_tc) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_mo_lo)
)
((move ?mhmt_dtc_t ?mhmt_mo_lo ?mhmt_md_lo) (!attach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_md_lo) (move ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l) (!detach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_dtc_l))
)
(:method (helper_move_traincar ?mhmtn_dtc_tc ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l)
method_helper_move_traincar_noMoveFirst
(
(type_Traincar ?mhmtn_dtc_tc) (type_Train ?mhmtn_dtc_t) (type_Location ?mhmtn_md_lo) (type_Location ?mhmtn_dtc_l)
(type_Location ?mhmtn_dtc_l) (type_Train ?mhmtn_dtc_t) (type_Traincar ?mhmtn_dtc_tc) (type_Location ?mhmtn_md_lo)
)
((!attach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_md_lo) (move ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l) (!detach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_dtc_l))
)
(:method (load ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l)
method_load_regular
(
(type_Package ?mlr_lp_p) (type_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l)
(type_Regular_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l) (type_Package ?mlr_lp_p)
)
((!open_door ?mlr_cd_rv) (!load_package ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l) (!close_door ?mlr_cd_rv))
)
(:method (load ?mlf_pdpv_p ?mlf_pdpv_fv ?mlf_pdpv_l)
method_load_flatbed
(
(type_Package ?mlf_pdpv_p) (type_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l)
(type_Crane ?mlf_pdpv_c) (type_Flatbed_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l) (type_Package ?mlf_pdpv_p)
)
((!pick_up_package_ground ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_l) (!put_down_package_vehicle ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_fv ?mlf_pdpv_l))
)
(:method (load ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l)
method_load_hopper
(
(type_Package ?mlh_fh_p) (type_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l)
(type_Hopper_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l) (type_Package ?mlh_fh_p)
)
((!connect_chute ?mlh_dc_h) (!fill_hopper ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l) (!disconnect_chute ?mlh_dc_h))
)
(:method (load ?mlt_dch_l ?mlt_dch_tv ?mlt_ft_lo)
method_load_tanker
(
(type_Package ?mlt_dch_l) (type_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
(type_Liquid ?mlt_dch_l) (type_Tanker_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
)
((!connect_hose ?mlt_dch_tv ?mlt_dch_l) (!open_valve ?mlt_dch_tv) (!fill_tank ?mlt_dch_tv ?mlt_dch_l ?mlt_ft_lo) (!close_valve ?mlt_dch_tv) (!disconnect_hose ?mlt_dch_tv ?mlt_dch_l))
)
(:method (load ?mll_ll_p ?mll_rr_v ?mll_ll_l)
method_load_livestock
(
(type_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v) (type_Location ?mll_ll_l)
(type_Location ?mll_ll_l) (type_Livestock_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v)
)
((!lower_ramp ?mll_rr_v) (!fill_trough ?mll_rr_v) (!load_livestock ?mll_ll_p ?mll_rr_v ?mll_ll_l) (!raise_ramp ?mll_rr_v))
)
(:method (load ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l)
method_load_cars
(
(type_Package ?mlc_lc_c) (type_Vehicle ?mlc_rr_v) (type_Location ?mlc_lc_l)
(type_Cars ?mlc_lc_c) (type_Location ?mlc_lc_l) (type_Vehicle ?mlc_rr_v)
)
((!lower_ramp ?mlc_rr_v) (!load_cars ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l) (!raise_ramp ?mlc_rr_v))
)
(:method (load ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l)
method_load_airplane
(
(type_Package ?mla_lp_p) (type_Vehicle ?mla_dcr_ap) (type_Location ?mla_dcr_l)
(type_Airplane ?mla_dcr_ap) (type_Location ?mla_dcr_l) (type_Plane_Ramp ?mla_dcr_pr) (type_Package ?mla_lp_p)
)
((!attach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l) (!open_door ?mla_dcr_ap) (!load_package ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l) (!close_door ?mla_dcr_ap) (!detach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l))
)
(:method (load_top ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l)
method_load_top_normal
(
(type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v) (type_Location ?mlmn_l_l)
(type_Location ?mlmn_l_l) (type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v)
)
((load ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l))
)
(:method (load_top ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l)
method_load_top_hazardous
(
(type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v) (type_Location ?mlmh_l_l)
(type_Location ?mlmh_l_l) (type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v)
)
((!affix_warning_signs ?mlmh_l_v) (load ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l))
)
(:method (load_top ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l)
method_load_top_valuable
(
(type_Package ?mlmv_l_p) (type_Vehicle ?mlmv_pci_a) (type_Location ?mlmv_l_l)
(type_Location ?mlmv_l_l) (type_Package ?mlmv_l_p) (type_Armored ?mlmv_pci_a)
)
((!post_guard_outside ?mlmv_pci_a) (load ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l) (!post_guard_inside ?mlmv_pci_a))
)
(:method (move ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_d)
method_move_no_traincar
(
(type_Vehicle ?mmnt_mvnt_v) (type_Location ?mmnt_mvnt_o) (type_Location ?mmnt_mvnt_d)
(type_Location ?mmnt_mvnt_d) (type_Location ?mmnt_mvnt_o) (type_Route ?mmnt_mvnt_r) (type_Vehicle ?mmnt_mvnt_v)
)
((!move_vehicle_no_traincar ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_r ?mmnt_mvnt_d))
)
(:method (move ?mmt_hmt_v ?mmt_hmt_o ?mmt_hmt_d)
method_move_traincar
(
(type_Vehicle ?mmt_hmt_v) (type_Location ?mmt_hmt_o) (type_Location ?mmt_hmt_d)
(type_Location ?mmt_hmt_d) (type_Location ?mmt_hmt_o) (type_Train ?mmt_hmt_t) (type_Traincar ?mmt_hmt_v)
)
((helper_move_traincar ?mmt_hmt_v ?mmt_hmt_t ?mmt_hmt_o ?mmt_hmt_d))
)
(:method (pickup ?mpn_cf_p)
method_pickup_normal
(
(type_Package ?mpn_cf_p)
(type_Package ?mpn_cf_p)
)
((!collect_fees ?mpn_cf_p))
)
(:method (pickup ?mph_op_h)
method_pickup_hazardous
(
(type_Package ?mph_op_h)
(type_Hazardous ?mph_op_h)
)
((!collect_fees ?mph_op_h) (!obtain_permit ?mph_op_h))
)
(:method (pickup ?mpv_ci_v)
method_pickup_valuable
(
(type_Package ?mpv_ci_v)
(type_Valuable ?mpv_ci_v)
)
((!collect_fees ?mpv_ci_v) (!collect_insurance ?mpv_ci_v))
)
(:method (transport ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld)
method_transport_pi_ca_de
(
(type_Package ?mtpcd_de_p) (type_Location ?mtpcd_ca_lo) (type_Location ?mtpcd_ca_ld)
(type_Location ?mtpcd_ca_ld) (type_Location ?mtpcd_ca_lo) (type_Package ?mtpcd_de_p)
)
((pickup ?mtpcd_de_p) (carry ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld) (deliver ?mtpcd_de_p))
)
(:method (unload ?mur_up_p ?mur_cd_rv ?mur_up_l)
method_unload_regular
(
(type_Package ?mur_up_p) (type_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l)
(type_Regular_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l) (type_Package ?mur_up_p)
)
((!open_door ?mur_cd_rv) (!unload_package ?mur_up_p ?mur_cd_rv ?mur_up_l) (!close_door ?mur_cd_rv))
)
(:method (unload ?muf_pdpg_p ?muf_pupv_fv ?muf_pdpg_l)
method_unload_flatbed
(
(type_Package ?muf_pdpg_p) (type_Vehicle ?muf_pupv_fv) (type_Location ?muf_pdpg_l)
(type_Crane ?muf_pdpg_c) (type_Location ?muf_pdpg_l) (type_Package ?muf_pdpg_p) (type_Flatbed_Vehicle ?muf_pupv_fv)
)
((!pick_up_package_vehicle ?muf_pdpg_p ?muf_pdpg_c ?muf_pupv_fv ?muf_pdpg_l) (!put_down_package_ground ?muf_pdpg_p ?muf_pdpg_c ?muf_pdpg_l))
)
(:method (unload ?muh_eh_p ?muh_dc_h ?muh_eh_l)
method_unload_hopper
(
(type_Package ?muh_eh_p) (type_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l)
(type_Hopper_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l) (type_Package ?muh_eh_p)
)
((!connect_chute ?muh_dc_h) (!empty_hopper ?muh_eh_p ?muh_dc_h ?muh_eh_l) (!disconnect_chute ?muh_dc_h))
)
(:method (unload ?mut_dch_l ?mut_dch_tv ?mut_et_lo)
method_unload_tanker
(
(type_Package ?mut_dch_l) (type_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
(type_Liquid ?mut_dch_l) (type_Tanker_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
)
((!connect_hose ?mut_dch_tv ?mut_dch_l) (!open_valve ?mut_dch_tv) (!empty_tank ?mut_dch_tv ?mut_dch_l ?mut_et_lo) (!close_valve ?mut_dch_tv) (!disconnect_hose ?mut_dch_tv ?mut_dch_l))
)
(:method (unload ?mul_ull_p ?mul_rr_v ?mul_ull_l)
method_unload_livestock
(
(type_Package ?mul_ull_p) (type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l)
(type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l) (type_Livestock_Package ?mul_ull_p)
)
((!lower_ramp ?mul_rr_v) (!unload_livestock ?mul_ull_p ?mul_rr_v ?mul_ull_l) (!do_clean_interior ?mul_rr_v) (!raise_ramp ?mul_rr_v))
)
(:method (unload ?muc_uc_c ?muc_rr_v ?muc_uc_l)
method_unload_cars
(
(type_Package ?muc_uc_c) (type_Vehicle ?muc_rr_v) (type_Location ?muc_uc_l)
(type_Vehicle ?muc_rr_v) (type_Cars ?muc_uc_c) (type_Location ?muc_uc_l)
)
((!lower_ramp ?muc_rr_v) (!unload_cars ?muc_uc_c ?muc_rr_v ?muc_uc_l) (!raise_ramp ?muc_rr_v))
)
(:method (unload ?mua_up_p ?mua_dcr_ap ?mua_dcr_l)
method_unload_airplane
(
(type_Package ?mua_up_p) (type_Vehicle ?mua_dcr_ap) (type_Location ?mua_dcr_l)
(type_Airplane ?mua_dcr_ap) (type_Location ?mua_dcr_l) (type_Plane_Ramp ?mua_dcr_pr) (type_Package ?mua_up_p)
)
((!attach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l) (!open_door ?mua_dcr_ap) (!unload_package ?mua_up_p ?mua_dcr_ap ?mua_dcr_l) (!close_door ?mua_dcr_ap) (!detach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l))
)
(:method (unload_top ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l)
method_unload_top_normal
(
(type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v) (type_Location ?mumn_ul_l)
(type_Location ?mumn_ul_l) (type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v)
)
((unload ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l))
)
(:method (unload_top ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l)
method_unload_top_hazardous
(
(type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v) (type_Location ?mumh_ul_l)
(type_Location ?mumh_ul_l) (type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v)
)
((unload ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l) (!decontaminate_interior ?mumh_ul_v) (!remove_warning_signs ?mumh_ul_v))
)
(:method (unload_top ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l)
method_unload_top_valuable
(
(type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v) (type_Location ?mumv_ul_l)
(type_Location ?mumv_ul_l) (type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v)
)
((!post_guard_outside ?mumv_ul_v) (unload ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l) (!remove_guard ?mumv_ul_v))
)
))
| null | https://raw.githubusercontent.com/panda-planner-dev/ipc2020-domains/9adb54325d3df35907adc7115fcc65f0ce5953cc/partial-order/UM-Translog/other/SHOP2/d-07.lisp | lisp | preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects
preconditions
delete effects
add effects | (defdomain domain (
(:operator (!obtain_permit ?op_h)
(
(type_Hazardous ?op_h)
(not (Have_Permit ?op_h))
)
()
((Have_Permit ?op_h))
)
(:operator (!collect_fees ?cf_p)
(
(type_Package ?cf_p)
(not (Fees_Collected ?cf_p))
)
()
((Fees_Collected ?cf_p))
)
(:operator (!collect_insurance ?ci_v)
(
(type_Valuable ?ci_v)
(not (Insured ?ci_v))
)
()
((Insured ?ci_v))
)
(:operator (!go_through_tcenter_cc ?gttc_lo ?gttc_ld ?gttc_co ?gttc_cd ?gttc_tc)
(
(type_Not_TCenter ?gttc_lo) (type_Not_TCenter ?gttc_ld) (type_City ?gttc_co) (type_City ?gttc_cd) (type_TCenter ?gttc_tc)
(In_City ?gttc_lo ?gttc_co) (In_City ?gttc_ld ?gttc_cd) (Serves ?gttc_tc ?gttc_co) (Serves ?gttc_tc ?gttc_cd) (Available ?gttc_tc)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_ottd ?gtttcc_lo ?gtttcc_ld ?gtttcc_co ?gtttcc_cd ?gtttcc_t1 ?gtttcc_t2)
(
(type_Not_TCenter ?gtttcc_lo) (type_Not_TCenter ?gtttcc_ld) (type_City ?gtttcc_co) (type_City ?gtttcc_cd) (type_TCenter ?gtttcc_t1) (type_TCenter ?gtttcc_t2)
(In_City ?gtttcc_lo ?gtttcc_co) (In_City ?gtttcc_ld ?gtttcc_cd) (Serves ?gtttcc_t1 ?gtttcc_co) (Serves ?gtttcc_t2 ?gtttcc_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_otd ?gtttccotd_ld ?gtttccotd_co ?gtttccotd_cd ?gtttccotd_to ?gtttccotd_t1)
(
(type_Not_TCenter ?gtttccotd_ld) (type_City ?gtttccotd_co) (type_City ?gtttccotd_cd) (type_TCenter ?gtttccotd_to) (type_TCenter ?gtttccotd_t1)
(In_City ?gtttccotd_to ?gtttccotd_co) (In_City ?gtttccotd_ld ?gtttccotd_cd) (Serves ?gtttccotd_t1 ?gtttccotd_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_cities_ott ?gtttccott_ld ?gtttccott_co ?gtttccott_cd ?gtttccott_to ?gtttccott_td)
(
(type_City_Location ?gtttccott_ld) (type_City ?gtttccott_co) (type_City ?gtttccott_cd) (type_TCenter ?gtttccott_to) (type_TCenter ?gtttccott_td)
(In_City ?gtttccott_ld ?gtttccott_co) (In_City ?gtttccott_td ?gtttccott_cd) (Serves ?gtttccott_to ?gtttccott_co)
)
()
()
)
(:operator (!go_through_two_tcenters ?gtttc_to ?gtttc_td)
(
(type_TCenter ?gtttc_to) (type_TCenter ?gtttc_td)
(Available ?gtttc_to) (Available ?gtttc_td)
)
()
()
)
(:operator (!go_through_two_tcenters_tt ?gtttctt_to ?gtttctt_td ?gtttctt_co ?gtttctt_cd)
(
(type_TCenter ?gtttctt_to) (type_TCenter ?gtttctt_td) (type_City ?gtttctt_co) (type_City ?gtttctt_cd)
(In_City ?gtttctt_to ?gtttctt_co) (In_City ?gtttctt_td ?gtttctt_cd)
)
()
()
)
(:operator (!go_through_two_tcenters_via_hub_hazardous ?gtttcvhh_to ?gtttcvhh_td ?gtttcvhh_h ?gtttcvhh_co ?gtttcvhh_ch ?gtttcvhh_cd ?gtttcvhh_ro ?gtttcvhh_rd)
(
(type_TCenter ?gtttcvhh_to) (type_TCenter ?gtttcvhh_td) (type_Hub ?gtttcvhh_h) (type_City ?gtttcvhh_co) (type_City ?gtttcvhh_ch) (type_City ?gtttcvhh_cd) (type_Region ?gtttcvhh_ro) (type_Region ?gtttcvhh_rd)
(Available ?gtttcvhh_to) (Available ?gtttcvhh_td) (In_City ?gtttcvhh_h ?gtttcvhh_ch) (City_Hazardous_Compatible ?gtttcvhh_ch) (In_City ?gtttcvhh_to ?gtttcvhh_co) (In_City ?gtttcvhh_td ?gtttcvhh_cd) (In_Region ?gtttcvhh_co ?gtttcvhh_ro) (In_Region ?gtttcvhh_cd ?gtttcvhh_rd) (Serves ?gtttcvhh_h ?gtttcvhh_ro) (Serves ?gtttcvhh_h ?gtttcvhh_rd) (Available ?gtttcvhh_h)
)
()
()
)
(:operator (!go_through_two_tcenters_via_hub_not_hazardous ?gtttcvhnh_to ?gtttcvhnh_td ?gtttcvhnh_co ?gtttcvhnh_cd ?gtttcvhnh_ro ?gtttcvhnh_rd ?gtttcvhnh_h)
(
(type_TCenter ?gtttcvhnh_to) (type_TCenter ?gtttcvhnh_td) (type_City ?gtttcvhnh_co) (type_City ?gtttcvhnh_cd) (type_Region ?gtttcvhnh_ro) (type_Region ?gtttcvhnh_rd) (type_Hub ?gtttcvhnh_h)
(Available ?gtttcvhnh_to) (Available ?gtttcvhnh_td) (In_City ?gtttcvhnh_to ?gtttcvhnh_co) (In_City ?gtttcvhnh_td ?gtttcvhnh_cd) (In_Region ?gtttcvhnh_co ?gtttcvhnh_ro) (In_Region ?gtttcvhnh_cd ?gtttcvhnh_rd) (Serves ?gtttcvhnh_h ?gtttcvhnh_ro) (Serves ?gtttcvhnh_h ?gtttcvhnh_rd) (Available ?gtttcvhnh_h)
)
()
()
)
(:operator (!deliver_p ?dp_p)
(
(type_Package ?dp_p)
(Fees_Collected ?dp_p)
)
((Fees_Collected ?dp_p))
((Delivered ?dp_p))
)
(:operator (!deliver_h ?dh_h)
(
(type_Hazardous ?dh_h)
(Fees_Collected ?dh_h) (Have_Permit ?dh_h)
)
((Have_Permit ?dh_h) (Fees_Collected ?dh_h))
((Delivered ?dh_h))
)
(:operator (!deliver_v ?dv_v)
(
(type_Valuable ?dv_v)
(Fees_Collected ?dv_v) (Insured ?dv_v)
)
((Fees_Collected ?dv_v) (Insured ?dv_v))
((Delivered ?dv_v))
)
(:operator (!post_guard_outside ?pco_a)
(
(type_Armored ?pco_a)
)
((Guard_Inside ?pco_a))
((Guard_Outside ?pco_a))
)
(:operator (!post_guard_inside ?pci_a)
(
(type_Armored ?pci_a)
)
((Guard_Outside ?pci_a))
((Guard_Inside ?pci_a))
)
(:operator (!remove_guard ?mc_a)
(
(type_Armored ?mc_a)
)
((Guard_Outside ?mc_a) (Guard_Inside ?mc_a))
()
)
(:operator (!decontaminate_interior ?di_v)
(
(type_Vehicle ?di_v)
)
()
((Decontaminated_Interior ?di_v))
)
(:operator (!affix_warning_signs ?fws_v)
(
(type_Vehicle ?fws_v)
(not (Warning_Signs_Affixed ?fws_v))
)
()
((Warning_Signs_Affixed ?fws_v))
)
(:operator (!remove_warning_signs ?mws_v)
(
(type_Vehicle ?mws_v)
(Warning_Signs_Affixed ?mws_v)
)
((Warning_Signs_Affixed ?mws_v))
()
)
(:operator (!attach_train_car ?atc_t ?atc_tc ?atc_l)
(
(type_Train ?atc_t) (type_Traincar ?atc_tc) (type_Location ?atc_l)
(At_Vehicle ?atc_tc ?atc_l) (At_Vehicle ?atc_t ?atc_l) (not (Connected_To ?atc_tc ?atc_t))
)
((At_Vehicle ?atc_tc ?atc_l))
((Connected_To ?atc_tc ?atc_t))
)
(:operator (!detach_train_car ?dtc_t ?dtc_tc ?dtc_l)
(
(type_Train ?dtc_t) (type_Traincar ?dtc_tc) (type_Location ?dtc_l)
(At_Vehicle ?dtc_t ?dtc_l) (Connected_To ?dtc_tc ?dtc_t)
)
((Connected_To ?dtc_tc ?dtc_t))
((At_Vehicle ?dtc_tc ?dtc_l))
)
(:operator (!connect_hose ?ch_tv ?ch_l)
(
(type_Tanker_Vehicle ?ch_tv) (type_Liquid ?ch_l)
(not (Hose_Connected ?ch_tv ?ch_l))
)
()
((Hose_Connected ?ch_tv ?ch_l))
)
(:operator (!disconnect_hose ?dch_tv ?dch_l)
(
(type_Tanker_Vehicle ?dch_tv) (type_Liquid ?dch_l)
(Hose_Connected ?dch_tv ?dch_l)
)
((Hose_Connected ?dch_tv ?dch_l))
()
)
(:operator (!open_valve ?ov_tv)
(
(type_Tanker_Vehicle ?ov_tv)
(not (Valve_Open ?ov_tv))
)
()
((Valve_Open ?ov_tv))
)
(:operator (!close_valve ?cv_tv)
(
(type_Tanker_Vehicle ?cv_tv)
(Valve_Open ?cv_tv)
)
((Valve_Open ?cv_tv))
()
)
(:operator (!fill_tank ?ft_tv ?ft_li ?ft_lo)
(
(type_Tanker_Vehicle ?ft_tv) (type_Liquid ?ft_li) (type_Location ?ft_lo)
(Hose_Connected ?ft_tv ?ft_li) (Valve_Open ?ft_tv) (At_Package ?ft_li ?ft_lo) (At_Vehicle ?ft_tv ?ft_lo) (PV_Compatible ?ft_li ?ft_tv)
)
((At_Package ?ft_li ?ft_lo))
((At_Package ?ft_li ?ft_tv))
)
(:operator (!empty_tank ?et_tv ?et_li ?et_lo)
(
(type_Tanker_Vehicle ?et_tv) (type_Liquid ?et_li) (type_Location ?et_lo)
(Hose_Connected ?et_tv ?et_li) (Valve_Open ?et_tv) (At_Package ?et_li ?et_tv) (At_Vehicle ?et_tv ?et_lo)
)
((At_Package ?et_li ?et_tv))
((At_Package ?et_li ?et_lo))
)
(:operator (!load_cars ?lc_c ?lc_v ?lc_l)
(
(type_Cars ?lc_c) (type_Auto_Vehicle ?lc_v) (type_Location ?lc_l)
(At_Package ?lc_c ?lc_l) (At_Vehicle ?lc_v ?lc_l) (Ramp_Down ?lc_v) (PV_Compatible ?lc_c ?lc_v)
)
((At_Package ?lc_c ?lc_l))
((At_Package ?lc_c ?lc_v))
)
(:operator (!unload_cars ?uc_c ?uc_v ?uc_l)
(
(type_Cars ?uc_c) (type_Auto_Vehicle ?uc_v) (type_Location ?uc_l)
(At_Package ?uc_c ?uc_v) (At_Vehicle ?uc_v ?uc_l) (Ramp_Down ?uc_v)
)
((At_Package ?uc_c ?uc_v))
((At_Package ?uc_c ?uc_l))
)
(:operator (!raise_ramp ?rr_v)
(
(type_Vehicle ?rr_v)
(Ramp_Down ?rr_v)
)
((Ramp_Down ?rr_v))
()
)
(:operator (!lower_ramp ?lr_v)
(
(type_Vehicle ?lr_v)
(not (Ramp_Down ?lr_v))
)
()
((Ramp_Down ?lr_v))
)
(:operator (!load_livestock ?ll_p ?ll_v ?ll_l)
(
(type_Livestock_Package ?ll_p) (type_Livestock_Vehicle ?ll_v) (type_Location ?ll_l)
(At_Package ?ll_p ?ll_l) (At_Vehicle ?ll_v ?ll_l) (Ramp_Down ?ll_v) (PV_Compatible ?ll_p ?ll_v)
)
((At_Package ?ll_p ?ll_l) (Clean_Interior ?ll_v))
((At_Package ?ll_p ?ll_v))
)
(:operator (!unload_livestock ?ull_p ?ull_v ?ull_l)
(
(type_Livestock_Package ?ull_p) (type_Livestock_Vehicle ?ull_v) (type_Location ?ull_l)
(At_Package ?ull_p ?ull_v) (At_Vehicle ?ull_v ?ull_l) (Ramp_Down ?ull_v)
)
((At_Package ?ull_p ?ull_v) (Trough_Full ?ull_v))
((At_Package ?ull_p ?ull_l))
)
(:operator (!fill_trough ?ftr_v)
(
(type_Livestock_Vehicle ?ftr_v)
)
()
((Trough_Full ?ftr_v))
)
(:operator (!do_clean_interior ?cli_v)
(
(type_Vehicle ?cli_v)
)
()
((Clean_Interior ?cli_v))
)
(:operator (!attach_conveyor_ramp ?acr_ap ?acr_pr ?acr_l)
(
(type_Airplane ?acr_ap) (type_Plane_Ramp ?acr_pr) (type_Location ?acr_l)
(Available ?acr_pr) (At_Equipment ?acr_pr ?acr_l) (At_Vehicle ?acr_ap ?acr_l)
)
((Available ?acr_pr))
((Ramp_Connected ?acr_pr ?acr_ap))
)
(:operator (!detach_conveyor_ramp ?dcr_ap ?dcr_pr ?dcr_l)
(
(type_Airplane ?dcr_ap) (type_Plane_Ramp ?dcr_pr) (type_Location ?dcr_l)
(Ramp_Connected ?dcr_pr ?dcr_ap) (At_Equipment ?dcr_pr ?dcr_l) (At_Vehicle ?dcr_ap ?dcr_l)
)
((Ramp_Connected ?dcr_pr ?dcr_ap))
((Available ?dcr_pr))
)
(:operator (!connect_chute ?cc_h)
(
(type_Hopper_Vehicle ?cc_h)
(not (Chute_Connected ?cc_h))
)
()
((Chute_Connected ?cc_h))
)
(:operator (!disconnect_chute ?dc_h)
(
(type_Hopper_Vehicle ?dc_h)
(Chute_Connected ?dc_h)
)
((Chute_Connected ?dc_h))
()
)
(:operator (!fill_hopper ?fh_p ?fh_hv ?fh_l)
(
(type_Package ?fh_p) (type_Hopper_Vehicle ?fh_hv) (type_Location ?fh_l)
(Chute_Connected ?fh_hv) (At_Vehicle ?fh_hv ?fh_l) (At_Package ?fh_p ?fh_l) (PV_Compatible ?fh_p ?fh_hv)
)
((At_Package ?fh_p ?fh_l))
((At_Package ?fh_p ?fh_hv))
)
(:operator (!empty_hopper ?eh_p ?eh_hv ?eh_l)
(
(type_Package ?eh_p) (type_Hopper_Vehicle ?eh_hv) (type_Location ?eh_l)
(Chute_Connected ?eh_hv) (At_Vehicle ?eh_hv ?eh_l) (At_Package ?eh_p ?eh_hv)
)
((At_Package ?eh_p ?eh_hv))
((At_Package ?eh_p ?eh_l))
)
(:operator (!pick_up_package_ground ?pupg_p ?pupg_c ?pupg_l)
(
(type_Package ?pupg_p) (type_Crane ?pupg_c) (type_Location ?pupg_l)
(Empty ?pupg_c) (Available ?pupg_c) (At_Equipment ?pupg_c ?pupg_l) (At_Package ?pupg_p ?pupg_l)
)
((Empty ?pupg_c) (At_Package ?pupg_p ?pupg_l))
((At_Package ?pupg_p ?pupg_c))
)
(:operator (!put_down_package_ground ?pdpg_p ?pdpg_c ?pdpg_l)
(
(type_Package ?pdpg_p) (type_Crane ?pdpg_c) (type_Location ?pdpg_l)
(Available ?pdpg_c) (At_Equipment ?pdpg_c ?pdpg_l) (At_Package ?pdpg_p ?pdpg_c)
)
((At_Package ?pdpg_p ?pdpg_c))
((At_Package ?pdpg_p ?pdpg_l) (Empty ?pdpg_c))
)
(:operator (!pick_up_package_vehicle ?pupv_p ?pupv_c ?pupv_fv ?pupv_l)
(
(type_Package ?pupv_p) (type_Crane ?pupv_c) (type_Flatbed_Vehicle ?pupv_fv) (type_Location ?pupv_l)
(Empty ?pupv_c) (Available ?pupv_c) (At_Equipment ?pupv_c ?pupv_l) (At_Package ?pupv_p ?pupv_fv) (At_Vehicle ?pupv_fv ?pupv_l)
)
((Empty ?pupv_c) (At_Package ?pupv_p ?pupv_fv))
((At_Package ?pupv_p ?pupv_c))
)
(:operator (!put_down_package_vehicle ?pdpv_p ?pdpv_c ?pdpv_fv ?pdpv_l)
(
(type_Package ?pdpv_p) (type_Crane ?pdpv_c) (type_Flatbed_Vehicle ?pdpv_fv) (type_Location ?pdpv_l)
(Available ?pdpv_c) (At_Package ?pdpv_p ?pdpv_c) (At_Equipment ?pdpv_c ?pdpv_l) (At_Vehicle ?pdpv_fv ?pdpv_l) (PV_Compatible ?pdpv_p ?pdpv_fv)
)
((At_Package ?pdpv_p ?pdpv_c))
((Empty ?pdpv_c) (At_Package ?pdpv_p ?pdpv_fv))
)
(:operator (!open_door ?od_rv)
(
(type_Regular_Vehicle ?od_rv)
(not (Door_Open ?od_rv))
)
()
((Door_Open ?od_rv))
)
(:operator (!close_door ?cd_rv)
(
(type_Regular_Vehicle ?cd_rv)
(Door_Open ?cd_rv)
)
((Door_Open ?cd_rv))
()
)
(:operator (!load_package ?lp_p ?lp_v ?lp_l)
(
(type_Package ?lp_p) (type_Vehicle ?lp_v) (type_Location ?lp_l)
(At_Package ?lp_p ?lp_l) (At_Vehicle ?lp_v ?lp_l) (PV_Compatible ?lp_p ?lp_v)
)
((At_Package ?lp_p ?lp_l))
((At_Package ?lp_p ?lp_v))
)
(:operator (!unload_package ?up_p ?up_v ?up_l)
(
(type_Package ?up_p) (type_Vehicle ?up_v) (type_Location ?up_l)
(At_Package ?up_p ?up_v) (At_Vehicle ?up_v ?up_l)
)
((At_Package ?up_p ?up_v))
((At_Package ?up_p ?up_l))
)
(:operator (!move_vehicle_no_traincar ?hmnt_v ?hmnt_o ?hmnt_r ?hmnt_d)
(
(type_Vehicle ?hmnt_v) (type_Location ?hmnt_o) (type_Route ?hmnt_r) (type_Location ?hmnt_d)
(Connects ?hmnt_r ?hmnt_o ?hmnt_d) (Available ?hmnt_v) (Available ?hmnt_r) (RV_Compatible ?hmnt_r ?hmnt_v) (At_Vehicle ?hmnt_v ?hmnt_o)
)
((At_Vehicle ?hmnt_v ?hmnt_o))
((At_Vehicle ?hmnt_v ?hmnt_d))
)
(:method (__top)
__top_method
(
(type_sort_for_Holz ?var_for_Holz_1) (type_sort_for_O27 ?var_for_O27_2) (type_sort_for_O28 ?var_for_O28_3)
)
((transport ?var_for_Holz_1 ?var_for_O27_2 ?var_for_O28_3))
)
(:method (carry ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld)
method_carry_cd
(
(type_Package ?mccd_cd_p) (type_Location ?mccd_cd_lo) (type_Location ?mccd_cd_ld)
(type_Location ?mccd_cd_ld) (type_Location ?mccd_cd_lo) (type_Package ?mccd_cd_p)
)
((carry_direct ?mccd_cd_p ?mccd_cd_lo ?mccd_cd_ld))
)
(:method (carry ?mch_hctt_p ?mch_hctt_o ?mch_hctt_d)
method_carry_cvh
(
(type_Package ?mch_hctt_p) (type_Location ?mch_hctt_o) (type_Location ?mch_hctt_d)
(type_City ?mch_hctt_cd) (type_City ?mch_hctt_co) (type_TCenter ?mch_hctt_d) (type_TCenter ?mch_hctt_o) (type_Package ?mch_hctt_p)
)
((helper_carry_tt ?mch_hctt_p ?mch_hctt_o ?mch_hctt_co ?mch_hctt_d ?mch_hctt_cd))
)
(:method (carry ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_d)
method_carry_cd_cbtc
(
(type_Package ?mccct_hcott_p) (type_Location ?mccct_hcott_o) (type_Location ?mccct_hcott_d)
(type_City ?mccct_hcott_cd) (type_City ?mccct_hcott_co) (type_TCenter ?mccct_hcott_d) (type_City_Location ?mccct_hcott_o) (type_Package ?mccct_hcott_p) (type_TCenter ?mccct_hcott_t1)
)
((helper_carry_ott ?mccct_hcott_p ?mccct_hcott_o ?mccct_hcott_co ?mccct_hcott_t1 ?mccct_hcott_d ?mccct_hcott_cd))
)
(:method (carry ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_d)
method_carry_cbtc_cd
(
(type_Package ?mcctc_hcotd_p) (type_Location ?mcctc_hcotd_o) (type_Location ?mcctc_hcotd_d)
(type_City ?mcctc_hcotd_cd) (type_City ?mcctc_hcotd_co) (type_Not_TCenter ?mcctc_hcotd_d) (type_TCenter ?mcctc_hcotd_o) (type_Package ?mcctc_hcotd_p) (type_TCenter ?mcctc_hcotd_t1)
)
((helper_carry_otd ?mcctc_hcotd_p ?mcctc_hcotd_o ?mcctc_hcotd_co ?mcctc_hcotd_t1 ?mcctc_hcotd_d ?mcctc_hcotd_cd))
)
(:method (carry ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_d)
method_carry_cd_cbtc_cd
(
(type_Package ?mcccc_hcottd_p) (type_Location ?mcccc_hcottd_o) (type_Location ?mcccc_hcottd_d)
(type_City ?mcccc_hcottd_cd) (type_City ?mcccc_hcottd_co) (type_Not_TCenter ?mcccc_hcottd_d) (type_Not_TCenter ?mcccc_hcottd_o) (type_Package ?mcccc_hcottd_p) (type_TCenter ?mcccc_hcottd_t1) (type_TCenter ?mcccc_hcottd_t2)
)
((helper_carry_ottd ?mcccc_hcottd_p ?mcccc_hcottd_o ?mcccc_hcottd_co ?mcccc_hcottd_t1 ?mcccc_hcottd_t2 ?mcccc_hcottd_d ?mcccc_hcottd_cd))
)
(:method (carry ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_d)
method_carry_cd_cd
(
(type_Package ?mccc_hccc_p) (type_Location ?mccc_hccc_o) (type_Location ?mccc_hccc_d)
(type_City ?mccc_hccc_cd) (type_City ?mccc_hccc_co) (type_Not_TCenter ?mccc_hccc_d) (type_Not_TCenter ?mccc_hccc_o) (type_Package ?mccc_hccc_p) (type_TCenter ?mccc_hccc_t)
)
((helper_carry_cc ?mccc_hccc_p ?mccc_hccc_o ?mccc_hccc_co ?mccc_hccc_t ?mccc_hccc_d ?mccc_hccc_cd))
)
(:method (carry_between_tcenters ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td)
method_carry_between_tcenters_cd
(
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_to) (type_TCenter ?mcbtc_gtttc_td)
(type_Package ?mcbtc_cd_p) (type_TCenter ?mcbtc_gtttc_td) (type_TCenter ?mcbtc_gtttc_to)
)
(:unordered (!go_through_two_tcenters ?mcbtc_gtttc_to ?mcbtc_gtttc_td) (carry_direct ?mcbtc_cd_p ?mcbtc_gtttc_to ?mcbtc_gtttc_td))
)
(:method (carry_between_tcenters ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd)
method_carry_between_tcenters_cvh
(
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tco) (type_TCenter ?mcbth_tch_tcd)
(type_Package ?mcbth_tch_p) (type_TCenter ?mcbth_tch_tcd) (type_TCenter ?mcbth_tch_tco)
)
((carry_via_hub ?mcbth_tch_p ?mcbth_tch_tco ?mcbth_tch_tcd))
)
(:method (carry_direct ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d)
method_carry_direct
(
(type_Package ?mcd_hmcd_p) (type_Location ?mcd_hmcd_o) (type_Location ?mcd_hmcd_d)
(type_Location ?mcd_hmcd_d) (type_Location ?mcd_hmcd_o) (type_Package ?mcd_hmcd_p) (type_Vehicle ?mcd_hmcd_v)
)
((helper_carry_direct ?mcd_hmcd_v ?mcd_hmcd_p ?mcd_hmcd_o ?mcd_hmcd_d))
)
(:method (carry_via_hub ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_tcd)
method_carry_via_hub_not_hazardous
(
(type_Package ?mcvhn_hcvhn_p) (type_TCenter ?mcvhn_hcvhn_tco) (type_TCenter ?mcvhn_hcvhn_tcd)
(type_City ?mcvhn_hcvhn_ctcd) (type_City ?mcvhn_hcvhn_ctco) (type_Hub ?mcvhn_hcvhn_h) (type_Package ?mcvhn_hcvhn_p) (type_Region ?mcvhn_hcvhn_rctcd) (type_Region ?mcvhn_hcvhn_rctco) (type_TCenter ?mcvhn_hcvhn_tcd) (type_TCenter ?mcvhn_hcvhn_tco)
)
((helper_carry_via_hub_not_hazardous ?mcvhn_hcvhn_p ?mcvhn_hcvhn_tco ?mcvhn_hcvhn_ctco ?mcvhn_hcvhn_rctco ?mcvhn_hcvhn_h ?mcvhn_hcvhn_tcd ?mcvhn_hcvhn_ctcd ?mcvhn_hcvhn_rctcd))
)
(:method (carry_via_hub ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_tcd)
method_carry_via_hub_hazardous
(
(type_Package ?mcvhh_hcvhh_p) (type_TCenter ?mcvhh_hcvhh_tco) (type_TCenter ?mcvhh_hcvhh_tcd)
(type_City ?mcvhh_hcvhh_ch) (type_City ?mcvhh_hcvhh_ctcd) (type_City ?mcvhh_hcvhh_ctco) (type_Hub ?mcvhh_hcvhh_h) (type_Package ?mcvhh_hcvhh_p) (type_Region ?mcvhh_hcvhh_rctcd) (type_Region ?mcvhh_hcvhh_rctco) (type_TCenter ?mcvhh_hcvhh_tcd) (type_TCenter ?mcvhh_hcvhh_tco)
)
((helper_carry_via_hub_hazardous ?mcvhh_hcvhh_p ?mcvhh_hcvhh_tco ?mcvhh_hcvhh_ctco ?mcvhh_hcvhh_rctco ?mcvhh_hcvhh_h ?mcvhh_hcvhh_ch ?mcvhh_hcvhh_tcd ?mcvhh_hcvhh_ctcd ?mcvhh_hcvhh_rctcd))
)
(:method (deliver ?mddp_dp_p)
method_deliver_dp
(
(type_Package ?mddp_dp_p)
(type_Package ?mddp_dp_p)
)
((!deliver_p ?mddp_dp_p))
)
(:method (deliver ?mddv_dv_v)
method_deliver_dv
(
(type_Package ?mddv_dv_v)
(type_Valuable ?mddv_dv_v)
)
((!deliver_v ?mddv_dv_v))
)
(:method (deliver ?mddh_dh_h)
method_deliver_dh
(
(type_Package ?mddh_dh_h)
(type_Hazardous ?mddh_dh_h)
)
((!deliver_h ?mddh_dh_h))
)
(:method (helper_carry_cc ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_co ?mhccc_gttc_tc ?mhccc_gttc_ld ?mhccc_gttc_cd)
method_helper_carry_cd_cd
(
(type_Package ?mhccc_cdd_p) (type_Not_TCenter ?mhccc_gttc_lo) (type_City ?mhccc_gttc_co) (type_TCenter ?mhccc_gttc_tc) (type_Not_TCenter ?mhccc_gttc_ld) (type_City ?mhccc_gttc_cd)
(type_Package ?mhccc_cdd_p) (type_City ?mhccc_gttc_cd) (type_City ?mhccc_gttc_co) (type_Not_TCenter ?mhccc_gttc_ld) (type_Not_TCenter ?mhccc_gttc_lo) (type_TCenter ?mhccc_gttc_tc)
)
((carry_direct ?mhccc_cdd_p ?mhccc_gttc_lo ?mhccc_gttc_tc) (!go_through_tcenter_cc ?mhccc_gttc_lo ?mhccc_gttc_ld ?mhccc_gttc_co ?mhccc_gttc_cd ?mhccc_gttc_tc) (carry_direct ?mhccc_cdd_p ?mhccc_gttc_tc ?mhccc_gttc_ld))
)
(:method (helper_carry_direct ?mhcd_ult_v ?mhcd_ult_p ?mhcd_mvd_lo ?mhcd_ult_l)
method_helper_carry_direct
(
(type_Vehicle ?mhcd_ult_v) (type_Package ?mhcd_ult_p) (type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_ult_l)
(type_Location ?mhcd_mvd_lo) (type_Location ?mhcd_mvo_lo) (type_Location ?mhcd_ult_l) (type_Package ?mhcd_ult_p) (type_Vehicle ?mhcd_ult_v)
)
((move ?mhcd_ult_v ?mhcd_mvo_lo ?mhcd_mvd_lo) (load_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_mvd_lo) (move ?mhcd_ult_v ?mhcd_mvd_lo ?mhcd_ult_l) (unload_top ?mhcd_ult_p ?mhcd_ult_v ?mhcd_ult_l))
)
(:method (helper_carry_direct ?mhcdo_ult_v ?mhcdo_ult_p ?mhcdo_m_lo ?mhcdo_ult_l)
method_helper_carry_direct_noMoveFirst
(
(type_Vehicle ?mhcdo_ult_v) (type_Package ?mhcdo_ult_p) (type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l)
(type_Location ?mhcdo_m_lo) (type_Location ?mhcdo_ult_l) (type_Package ?mhcdo_ult_p) (type_Vehicle ?mhcdo_ult_v)
)
((load_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_m_lo) (move ?mhcdo_ult_v ?mhcdo_m_lo ?mhcdo_ult_l) (unload_top ?mhcdo_ult_p ?mhcdo_ult_v ?mhcdo_ult_l))
)
(:method (helper_carry_otd ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_cd)
method_helper_carry_cbtc_cd
(
(type_Package ?mhcctc_cd_p) (type_TCenter ?mhcctc_gtttccotd_o) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_t1) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_cd)
(type_Package ?mhcctc_cd_p) (type_City ?mhcctc_gtttccotd_cd) (type_Not_TCenter ?mhcctc_gtttccotd_cl) (type_City ?mhcctc_gtttccotd_co) (type_TCenter ?mhcctc_gtttccotd_o) (type_TCenter ?mhcctc_gtttccotd_t1)
)
((carry_between_tcenters ?mhcctc_cd_p ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (!go_through_two_tcenters_cities_otd ?mhcctc_gtttccotd_cl ?mhcctc_gtttccotd_co ?mhcctc_gtttccotd_cd ?mhcctc_gtttccotd_o ?mhcctc_gtttccotd_t1) (carry_direct ?mhcctc_cd_p ?mhcctc_gtttccotd_t1 ?mhcctc_gtttccotd_cl))
)
(:method (helper_carry_ott ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_to ?mhccct_gtttccott_td ?mhccct_gtttccott_cd)
method_helper_carry_cd_cbtc
(
(type_Package ?mhccct_cbt_p) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_to) (type_TCenter ?mhccct_gtttccott_td) (type_City ?mhccct_gtttccott_cd)
(type_Package ?mhccct_cbt_p) (type_City ?mhccct_gtttccott_cd) (type_City_Location ?mhccct_gtttccott_cl) (type_City ?mhccct_gtttccott_co) (type_TCenter ?mhccct_gtttccott_td) (type_TCenter ?mhccct_gtttccott_to)
)
((carry_direct ?mhccct_cbt_p ?mhccct_gtttccott_cl ?mhccct_gtttccott_to) (!go_through_two_tcenters_cities_ott ?mhccct_gtttccott_cl ?mhccct_gtttccott_co ?mhccct_gtttccott_cd ?mhccct_gtttccott_to ?mhccct_gtttccott_td) (carry_between_tcenters ?mhccct_cbt_p ?mhccct_gtttccott_to ?mhccct_gtttccott_td))
)
(:method (helper_carry_ottd ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_co ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld ?mhcccc_gtttc_cd)
method_helper_carry_cd_cbtc_cd
(
(type_Package ?mhcccc_cdd_p) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_City ?mhcccc_gtttc_co) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_City ?mhcccc_gtttc_cd)
(type_Package ?mhcccc_cdd_p) (type_City ?mhcccc_gtttc_cd) (type_City ?mhcccc_gtttc_co) (type_Not_TCenter ?mhcccc_gtttc_ld) (type_Not_TCenter ?mhcccc_gtttc_lo) (type_TCenter ?mhcccc_gtttc_t1) (type_TCenter ?mhcccc_gtttc_t2)
)
((carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_lo ?mhcccc_gtttc_t1) (!go_through_two_tcenters_cities_ottd ?mhcccc_gtttc_lo ?mhcccc_gtttc_ld ?mhcccc_gtttc_co ?mhcccc_gtttc_cd ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_between_tcenters ?mhcccc_cdd_p ?mhcccc_gtttc_t1 ?mhcccc_gtttc_t2) (carry_direct ?mhcccc_cdd_p ?mhcccc_gtttc_t2 ?mhcccc_gtttc_ld))
)
(:method (helper_carry_tt ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_co ?mhch_gtttctt_td ?mhch_gtttctt_cd)
method_helper_carry_cvh
(
(type_Package ?mhch_tch_p) (type_TCenter ?mhch_gtttctt_to) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_City ?mhch_gtttctt_cd)
(type_City ?mhch_gtttctt_cd) (type_City ?mhch_gtttctt_co) (type_TCenter ?mhch_gtttctt_td) (type_TCenter ?mhch_gtttctt_to) (type_Package ?mhch_tch_p)
)
((carry_via_hub ?mhch_tch_p ?mhch_gtttctt_to ?mhch_gtttctt_td) (!go_through_two_tcenters_tt ?mhch_gtttctt_to ?mhch_gtttctt_td ?mhch_gtttctt_co ?mhch_gtttctt_cd))
)
(:method (helper_carry_via_hub_hazardous ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_rd)
method_helper_carry_via_hub_hazardous
(
(type_Package ?mhcvhh_cd2_p) (type_TCenter ?mhcvhh_gtttcvhh_to) (type_City ?mhcvhh_gtttcvhh_co) (type_Region ?mhcvhh_gtttcvhh_ro) (type_Hub ?mhcvhh_gtttcvhh_h) (type_City ?mhcvhh_gtttcvhh_ch) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_City ?mhcvhh_gtttcvhh_cd) (type_Region ?mhcvhh_gtttcvhh_rd)
(type_Package ?mhcvhh_cd2_p) (type_City ?mhcvhh_gtttcvhh_cd) (type_City ?mhcvhh_gtttcvhh_ch) (type_City ?mhcvhh_gtttcvhh_co) (type_Hub ?mhcvhh_gtttcvhh_h) (type_Region ?mhcvhh_gtttcvhh_rd) (type_Region ?mhcvhh_gtttcvhh_ro) (type_TCenter ?mhcvhh_gtttcvhh_td) (type_TCenter ?mhcvhh_gtttcvhh_to)
)
((carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_h) (!go_through_two_tcenters_via_hub_hazardous ?mhcvhh_gtttcvhh_to ?mhcvhh_gtttcvhh_td ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_co ?mhcvhh_gtttcvhh_ch ?mhcvhh_gtttcvhh_cd ?mhcvhh_gtttcvhh_ro ?mhcvhh_gtttcvhh_rd) (carry_direct ?mhcvhh_cd2_p ?mhcvhh_gtttcvhh_h ?mhcvhh_gtttcvhh_td))
)
(:method (helper_carry_via_hub_not_hazardous ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_rd)
method_helper_carry_via_hub_not_hazardous
(
(type_Package ?mhcvhn_cd2_p) (type_TCenter ?mhcvhn_gtttcvhnh_to) (type_City ?mhcvhn_gtttcvhnh_co) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_City ?mhcvhn_gtttcvhnh_cd) (type_Region ?mhcvhn_gtttcvhnh_rd)
(type_Package ?mhcvhn_cd2_p) (type_City ?mhcvhn_gtttcvhnh_cd) (type_City ?mhcvhn_gtttcvhnh_co) (type_Hub ?mhcvhn_gtttcvhnh_h) (type_Region ?mhcvhn_gtttcvhnh_rd) (type_Region ?mhcvhn_gtttcvhnh_ro) (type_TCenter ?mhcvhn_gtttcvhnh_td) (type_TCenter ?mhcvhn_gtttcvhnh_to)
)
((carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_h) (!go_through_two_tcenters_via_hub_not_hazardous ?mhcvhn_gtttcvhnh_to ?mhcvhn_gtttcvhnh_td ?mhcvhn_gtttcvhnh_co ?mhcvhn_gtttcvhnh_cd ?mhcvhn_gtttcvhnh_ro ?mhcvhn_gtttcvhnh_rd ?mhcvhn_gtttcvhnh_h) (carry_direct ?mhcvhn_cd2_p ?mhcvhn_gtttcvhnh_h ?mhcvhn_gtttcvhnh_td))
)
(:method (helper_move_traincar ?mhmt_dtc_tc ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l)
method_helper_move_traincar
(
(type_Traincar ?mhmt_dtc_tc) (type_Train ?mhmt_dtc_t) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_dtc_l)
(type_Location ?mhmt_dtc_l) (type_Train ?mhmt_dtc_t) (type_Traincar ?mhmt_dtc_tc) (type_Location ?mhmt_md_lo) (type_Location ?mhmt_mo_lo)
)
((move ?mhmt_dtc_t ?mhmt_mo_lo ?mhmt_md_lo) (!attach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_md_lo) (move ?mhmt_dtc_t ?mhmt_md_lo ?mhmt_dtc_l) (!detach_train_car ?mhmt_dtc_t ?mhmt_dtc_tc ?mhmt_dtc_l))
)
(:method (helper_move_traincar ?mhmtn_dtc_tc ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l)
method_helper_move_traincar_noMoveFirst
(
(type_Traincar ?mhmtn_dtc_tc) (type_Train ?mhmtn_dtc_t) (type_Location ?mhmtn_md_lo) (type_Location ?mhmtn_dtc_l)
(type_Location ?mhmtn_dtc_l) (type_Train ?mhmtn_dtc_t) (type_Traincar ?mhmtn_dtc_tc) (type_Location ?mhmtn_md_lo)
)
((!attach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_md_lo) (move ?mhmtn_dtc_t ?mhmtn_md_lo ?mhmtn_dtc_l) (!detach_train_car ?mhmtn_dtc_t ?mhmtn_dtc_tc ?mhmtn_dtc_l))
)
(:method (load ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l)
method_load_regular
(
(type_Package ?mlr_lp_p) (type_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l)
(type_Regular_Vehicle ?mlr_cd_rv) (type_Location ?mlr_lp_l) (type_Package ?mlr_lp_p)
)
((!open_door ?mlr_cd_rv) (!load_package ?mlr_lp_p ?mlr_cd_rv ?mlr_lp_l) (!close_door ?mlr_cd_rv))
)
(:method (load ?mlf_pdpv_p ?mlf_pdpv_fv ?mlf_pdpv_l)
method_load_flatbed
(
(type_Package ?mlf_pdpv_p) (type_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l)
(type_Crane ?mlf_pdpv_c) (type_Flatbed_Vehicle ?mlf_pdpv_fv) (type_Location ?mlf_pdpv_l) (type_Package ?mlf_pdpv_p)
)
((!pick_up_package_ground ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_l) (!put_down_package_vehicle ?mlf_pdpv_p ?mlf_pdpv_c ?mlf_pdpv_fv ?mlf_pdpv_l))
)
(:method (load ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l)
method_load_hopper
(
(type_Package ?mlh_fh_p) (type_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l)
(type_Hopper_Vehicle ?mlh_dc_h) (type_Location ?mlh_fh_l) (type_Package ?mlh_fh_p)
)
((!connect_chute ?mlh_dc_h) (!fill_hopper ?mlh_fh_p ?mlh_dc_h ?mlh_fh_l) (!disconnect_chute ?mlh_dc_h))
)
(:method (load ?mlt_dch_l ?mlt_dch_tv ?mlt_ft_lo)
method_load_tanker
(
(type_Package ?mlt_dch_l) (type_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
(type_Liquid ?mlt_dch_l) (type_Tanker_Vehicle ?mlt_dch_tv) (type_Location ?mlt_ft_lo)
)
((!connect_hose ?mlt_dch_tv ?mlt_dch_l) (!open_valve ?mlt_dch_tv) (!fill_tank ?mlt_dch_tv ?mlt_dch_l ?mlt_ft_lo) (!close_valve ?mlt_dch_tv) (!disconnect_hose ?mlt_dch_tv ?mlt_dch_l))
)
(:method (load ?mll_ll_p ?mll_rr_v ?mll_ll_l)
method_load_livestock
(
(type_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v) (type_Location ?mll_ll_l)
(type_Location ?mll_ll_l) (type_Livestock_Package ?mll_ll_p) (type_Vehicle ?mll_rr_v)
)
((!lower_ramp ?mll_rr_v) (!fill_trough ?mll_rr_v) (!load_livestock ?mll_ll_p ?mll_rr_v ?mll_ll_l) (!raise_ramp ?mll_rr_v))
)
(:method (load ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l)
method_load_cars
(
(type_Package ?mlc_lc_c) (type_Vehicle ?mlc_rr_v) (type_Location ?mlc_lc_l)
(type_Cars ?mlc_lc_c) (type_Location ?mlc_lc_l) (type_Vehicle ?mlc_rr_v)
)
((!lower_ramp ?mlc_rr_v) (!load_cars ?mlc_lc_c ?mlc_rr_v ?mlc_lc_l) (!raise_ramp ?mlc_rr_v))
)
(:method (load ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l)
method_load_airplane
(
(type_Package ?mla_lp_p) (type_Vehicle ?mla_dcr_ap) (type_Location ?mla_dcr_l)
(type_Airplane ?mla_dcr_ap) (type_Location ?mla_dcr_l) (type_Plane_Ramp ?mla_dcr_pr) (type_Package ?mla_lp_p)
)
((!attach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l) (!open_door ?mla_dcr_ap) (!load_package ?mla_lp_p ?mla_dcr_ap ?mla_dcr_l) (!close_door ?mla_dcr_ap) (!detach_conveyor_ramp ?mla_dcr_ap ?mla_dcr_pr ?mla_dcr_l))
)
(:method (load_top ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l)
method_load_top_normal
(
(type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v) (type_Location ?mlmn_l_l)
(type_Location ?mlmn_l_l) (type_Package ?mlmn_l_p) (type_Vehicle ?mlmn_l_v)
)
((load ?mlmn_l_p ?mlmn_l_v ?mlmn_l_l))
)
(:method (load_top ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l)
method_load_top_hazardous
(
(type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v) (type_Location ?mlmh_l_l)
(type_Location ?mlmh_l_l) (type_Package ?mlmh_l_p) (type_Vehicle ?mlmh_l_v)
)
((!affix_warning_signs ?mlmh_l_v) (load ?mlmh_l_p ?mlmh_l_v ?mlmh_l_l))
)
(:method (load_top ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l)
method_load_top_valuable
(
(type_Package ?mlmv_l_p) (type_Vehicle ?mlmv_pci_a) (type_Location ?mlmv_l_l)
(type_Location ?mlmv_l_l) (type_Package ?mlmv_l_p) (type_Armored ?mlmv_pci_a)
)
((!post_guard_outside ?mlmv_pci_a) (load ?mlmv_l_p ?mlmv_pci_a ?mlmv_l_l) (!post_guard_inside ?mlmv_pci_a))
)
(:method (move ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_d)
method_move_no_traincar
(
(type_Vehicle ?mmnt_mvnt_v) (type_Location ?mmnt_mvnt_o) (type_Location ?mmnt_mvnt_d)
(type_Location ?mmnt_mvnt_d) (type_Location ?mmnt_mvnt_o) (type_Route ?mmnt_mvnt_r) (type_Vehicle ?mmnt_mvnt_v)
)
((!move_vehicle_no_traincar ?mmnt_mvnt_v ?mmnt_mvnt_o ?mmnt_mvnt_r ?mmnt_mvnt_d))
)
(:method (move ?mmt_hmt_v ?mmt_hmt_o ?mmt_hmt_d)
method_move_traincar
(
(type_Vehicle ?mmt_hmt_v) (type_Location ?mmt_hmt_o) (type_Location ?mmt_hmt_d)
(type_Location ?mmt_hmt_d) (type_Location ?mmt_hmt_o) (type_Train ?mmt_hmt_t) (type_Traincar ?mmt_hmt_v)
)
((helper_move_traincar ?mmt_hmt_v ?mmt_hmt_t ?mmt_hmt_o ?mmt_hmt_d))
)
(:method (pickup ?mpn_cf_p)
method_pickup_normal
(
(type_Package ?mpn_cf_p)
(type_Package ?mpn_cf_p)
)
((!collect_fees ?mpn_cf_p))
)
(:method (pickup ?mph_op_h)
method_pickup_hazardous
(
(type_Package ?mph_op_h)
(type_Hazardous ?mph_op_h)
)
((!collect_fees ?mph_op_h) (!obtain_permit ?mph_op_h))
)
(:method (pickup ?mpv_ci_v)
method_pickup_valuable
(
(type_Package ?mpv_ci_v)
(type_Valuable ?mpv_ci_v)
)
((!collect_fees ?mpv_ci_v) (!collect_insurance ?mpv_ci_v))
)
(:method (transport ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld)
method_transport_pi_ca_de
(
(type_Package ?mtpcd_de_p) (type_Location ?mtpcd_ca_lo) (type_Location ?mtpcd_ca_ld)
(type_Location ?mtpcd_ca_ld) (type_Location ?mtpcd_ca_lo) (type_Package ?mtpcd_de_p)
)
((pickup ?mtpcd_de_p) (carry ?mtpcd_de_p ?mtpcd_ca_lo ?mtpcd_ca_ld) (deliver ?mtpcd_de_p))
)
(:method (unload ?mur_up_p ?mur_cd_rv ?mur_up_l)
method_unload_regular
(
(type_Package ?mur_up_p) (type_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l)
(type_Regular_Vehicle ?mur_cd_rv) (type_Location ?mur_up_l) (type_Package ?mur_up_p)
)
((!open_door ?mur_cd_rv) (!unload_package ?mur_up_p ?mur_cd_rv ?mur_up_l) (!close_door ?mur_cd_rv))
)
(:method (unload ?muf_pdpg_p ?muf_pupv_fv ?muf_pdpg_l)
method_unload_flatbed
(
(type_Package ?muf_pdpg_p) (type_Vehicle ?muf_pupv_fv) (type_Location ?muf_pdpg_l)
(type_Crane ?muf_pdpg_c) (type_Location ?muf_pdpg_l) (type_Package ?muf_pdpg_p) (type_Flatbed_Vehicle ?muf_pupv_fv)
)
((!pick_up_package_vehicle ?muf_pdpg_p ?muf_pdpg_c ?muf_pupv_fv ?muf_pdpg_l) (!put_down_package_ground ?muf_pdpg_p ?muf_pdpg_c ?muf_pdpg_l))
)
(:method (unload ?muh_eh_p ?muh_dc_h ?muh_eh_l)
method_unload_hopper
(
(type_Package ?muh_eh_p) (type_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l)
(type_Hopper_Vehicle ?muh_dc_h) (type_Location ?muh_eh_l) (type_Package ?muh_eh_p)
)
((!connect_chute ?muh_dc_h) (!empty_hopper ?muh_eh_p ?muh_dc_h ?muh_eh_l) (!disconnect_chute ?muh_dc_h))
)
(:method (unload ?mut_dch_l ?mut_dch_tv ?mut_et_lo)
method_unload_tanker
(
(type_Package ?mut_dch_l) (type_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
(type_Liquid ?mut_dch_l) (type_Tanker_Vehicle ?mut_dch_tv) (type_Location ?mut_et_lo)
)
((!connect_hose ?mut_dch_tv ?mut_dch_l) (!open_valve ?mut_dch_tv) (!empty_tank ?mut_dch_tv ?mut_dch_l ?mut_et_lo) (!close_valve ?mut_dch_tv) (!disconnect_hose ?mut_dch_tv ?mut_dch_l))
)
(:method (unload ?mul_ull_p ?mul_rr_v ?mul_ull_l)
method_unload_livestock
(
(type_Package ?mul_ull_p) (type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l)
(type_Vehicle ?mul_rr_v) (type_Location ?mul_ull_l) (type_Livestock_Package ?mul_ull_p)
)
((!lower_ramp ?mul_rr_v) (!unload_livestock ?mul_ull_p ?mul_rr_v ?mul_ull_l) (!do_clean_interior ?mul_rr_v) (!raise_ramp ?mul_rr_v))
)
(:method (unload ?muc_uc_c ?muc_rr_v ?muc_uc_l)
method_unload_cars
(
(type_Package ?muc_uc_c) (type_Vehicle ?muc_rr_v) (type_Location ?muc_uc_l)
(type_Vehicle ?muc_rr_v) (type_Cars ?muc_uc_c) (type_Location ?muc_uc_l)
)
((!lower_ramp ?muc_rr_v) (!unload_cars ?muc_uc_c ?muc_rr_v ?muc_uc_l) (!raise_ramp ?muc_rr_v))
)
(:method (unload ?mua_up_p ?mua_dcr_ap ?mua_dcr_l)
method_unload_airplane
(
(type_Package ?mua_up_p) (type_Vehicle ?mua_dcr_ap) (type_Location ?mua_dcr_l)
(type_Airplane ?mua_dcr_ap) (type_Location ?mua_dcr_l) (type_Plane_Ramp ?mua_dcr_pr) (type_Package ?mua_up_p)
)
((!attach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l) (!open_door ?mua_dcr_ap) (!unload_package ?mua_up_p ?mua_dcr_ap ?mua_dcr_l) (!close_door ?mua_dcr_ap) (!detach_conveyor_ramp ?mua_dcr_ap ?mua_dcr_pr ?mua_dcr_l))
)
(:method (unload_top ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l)
method_unload_top_normal
(
(type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v) (type_Location ?mumn_ul_l)
(type_Location ?mumn_ul_l) (type_Package ?mumn_ul_p) (type_Vehicle ?mumn_ul_v)
)
((unload ?mumn_ul_p ?mumn_ul_v ?mumn_ul_l))
)
(:method (unload_top ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l)
method_unload_top_hazardous
(
(type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v) (type_Location ?mumh_ul_l)
(type_Location ?mumh_ul_l) (type_Package ?mumh_ul_p) (type_Vehicle ?mumh_ul_v)
)
((unload ?mumh_ul_p ?mumh_ul_v ?mumh_ul_l) (!decontaminate_interior ?mumh_ul_v) (!remove_warning_signs ?mumh_ul_v))
)
(:method (unload_top ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l)
method_unload_top_valuable
(
(type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v) (type_Location ?mumv_ul_l)
(type_Location ?mumv_ul_l) (type_Package ?mumv_ul_p) (type_Vehicle ?mumv_ul_v)
)
((!post_guard_outside ?mumv_ul_v) (unload ?mumv_ul_p ?mumv_ul_v ?mumv_ul_l) (!remove_guard ?mumv_ul_v))
)
))
|
b5889e04924c06e32cf41819b481f3c6baaf0e49ab69f3af2c952f73180779d1 | Paczesiowa/virthualenv | Types.hs | # LANGUAGE GeneralizedNewtypeDeriving #
module Types ( GhcSource(..)
, Options(..)
, MyState(..)
, DirStructure(..)
, MyException(..)
, Verbosity(..)
) where
import Control.Monad.Error (Error)
Use System 's copy of GHC
Use GHC from tarball
data Verbosity = Quiet
| Verbose
| VeryVerbose
deriving (Eq, Ord)
data Options = Options { verbosity :: Verbosity
, skipSanityCheck :: Bool
Virtual Haskell Environment name
, ghcSource :: GhcSource
make substitute used for ' make install ' of external GHC
}
data MyState = MyState { logDepth :: Integer -- used for indentation of logging messages
}
newtype MyException = MyException { getExceptionMessage :: String }
deriving Error
-- Only absolute paths!
data DirStructure = DirStructure { virthualEnv :: FilePath -- dir containing .virthualenv dir (usually dir with cabal project)
.virthualenv dir
file ( < ghc-6.12 ) or dir ( > = ghc-6.12 ) containing private GHC pkg db
, cabalDir :: FilePath -- directory with private cabal dir
, cabalBinDir :: FilePath -- cabal's bin/ dir (used in $PATH)
, virthualEnvBinDir :: FilePath -- dir with haskell tools wrappers and activate script
directory with private copy of external GHC ( only used when using GHC from tarball )
ghc 's bin/ dir ( with ghc[i|-pkg ] ) ( only used when using GHC from tarball )
}
| null | https://raw.githubusercontent.com/Paczesiowa/virthualenv/aab89dad9de7dac5268472eaa50c11eb40b02380/src/Types.hs | haskell | used for indentation of logging messages
Only absolute paths!
dir containing .virthualenv dir (usually dir with cabal project)
directory with private cabal dir
cabal's bin/ dir (used in $PATH)
dir with haskell tools wrappers and activate script | # LANGUAGE GeneralizedNewtypeDeriving #
module Types ( GhcSource(..)
, Options(..)
, MyState(..)
, DirStructure(..)
, MyException(..)
, Verbosity(..)
) where
import Control.Monad.Error (Error)
Use System 's copy of GHC
Use GHC from tarball
data Verbosity = Quiet
| Verbose
| VeryVerbose
deriving (Eq, Ord)
data Options = Options { verbosity :: Verbosity
, skipSanityCheck :: Bool
Virtual Haskell Environment name
, ghcSource :: GhcSource
make substitute used for ' make install ' of external GHC
}
}
newtype MyException = MyException { getExceptionMessage :: String }
deriving Error
.virthualenv dir
file ( < ghc-6.12 ) or dir ( > = ghc-6.12 ) containing private GHC pkg db
directory with private copy of external GHC ( only used when using GHC from tarball )
ghc 's bin/ dir ( with ghc[i|-pkg ] ) ( only used when using GHC from tarball )
}
|
9e292eeae7b8f0dd5e99f4ea68fb15004f9bdf6aac4e8c9a1eae89c7f73c3895 | lem-project/lem | syntax-parse.lisp | (defpackage :lem-scheme-syntax.parse
(:use :cl :lem-base)
(:export :parse-for-swank-autodoc))
(in-package :lem-scheme-syntax.parse)
(defvar *cursor-marker* 'swank::%cursor-marker%)
(defun parsing-safe-p (point)
(not (in-string-or-comment-p point)))
(defun parse-for-swank-autodoc (point)
(and (parsing-safe-p point)
;; for r7rs-swank
( parse - form - upto - toplevel point 10 )
(parse-form-upto-toplevel point 1)
))
(defun compare-char (point offset fn &optional unescape)
(and (funcall fn (character-at point offset))
(if unescape
(not (syntax-escape-char-p
(character-at point (1- offset))))
t)))
(defun parse-form-upto-toplevel (point &optional limit-levels)
(with-point ((point point))
(let ((suffix (list *cursor-marker*)))
(cond ((compare-char point 0 #'syntax-open-paren-char-p t)
(and (form-offset point 1)
;; for r7rs-swank
;(push "" suffix)
))
((or (start-line-p point)
(compare-char point -1 #'syntax-space-char-p t))
(push "" suffix))
((compare-char point -1 #'syntax-open-paren-char-p t)
(push "" suffix))
(t
(skip-symbol-forward point)))
(with-point ((end point))
(loop :repeat (or limit-levels most-positive-fixnum)
:while (scan-lists point -1 1 t)
:do (when (start-line-p point) (return)))
(scan-lists point 1 -1 t)
(parse-region point end suffix)))))
(defun parse-region (start end suffix)
(with-point ((tmp start))
(labels ((f (start end)
(let ((p start)
(sexp '()))
(loop
(skip-space-and-comment-forward p)
(when (point<= end p)
(dolist (s suffix) (push s sexp))
(setq suffix nil)
(return-from f (nreverse sexp)))
(let ((c (character-at p)))
(cond ((syntax-open-paren-char-p c)
(character-offset p 1)
(push (f p end) sexp))
((syntax-closed-paren-char-p c)
(character-offset p 1)
(return))
(t
(move-point tmp p)
(unless (form-offset p 1) (return))
(push (points-to-string tmp p) sexp)))))
(nreverse sexp))))
(f start end))))
| null | https://raw.githubusercontent.com/lem-project/lem/4f620f94a1fd3bdfb8b2364185e7db16efab57a1/modes/scheme-mode/syntax-parse.lisp | lisp | for r7rs-swank
for r7rs-swank
(push "" suffix) | (defpackage :lem-scheme-syntax.parse
(:use :cl :lem-base)
(:export :parse-for-swank-autodoc))
(in-package :lem-scheme-syntax.parse)
(defvar *cursor-marker* 'swank::%cursor-marker%)
(defun parsing-safe-p (point)
(not (in-string-or-comment-p point)))
(defun parse-for-swank-autodoc (point)
(and (parsing-safe-p point)
( parse - form - upto - toplevel point 10 )
(parse-form-upto-toplevel point 1)
))
(defun compare-char (point offset fn &optional unescape)
(and (funcall fn (character-at point offset))
(if unescape
(not (syntax-escape-char-p
(character-at point (1- offset))))
t)))
(defun parse-form-upto-toplevel (point &optional limit-levels)
(with-point ((point point))
(let ((suffix (list *cursor-marker*)))
(cond ((compare-char point 0 #'syntax-open-paren-char-p t)
(and (form-offset point 1)
))
((or (start-line-p point)
(compare-char point -1 #'syntax-space-char-p t))
(push "" suffix))
((compare-char point -1 #'syntax-open-paren-char-p t)
(push "" suffix))
(t
(skip-symbol-forward point)))
(with-point ((end point))
(loop :repeat (or limit-levels most-positive-fixnum)
:while (scan-lists point -1 1 t)
:do (when (start-line-p point) (return)))
(scan-lists point 1 -1 t)
(parse-region point end suffix)))))
(defun parse-region (start end suffix)
(with-point ((tmp start))
(labels ((f (start end)
(let ((p start)
(sexp '()))
(loop
(skip-space-and-comment-forward p)
(when (point<= end p)
(dolist (s suffix) (push s sexp))
(setq suffix nil)
(return-from f (nreverse sexp)))
(let ((c (character-at p)))
(cond ((syntax-open-paren-char-p c)
(character-offset p 1)
(push (f p end) sexp))
((syntax-closed-paren-char-p c)
(character-offset p 1)
(return))
(t
(move-point tmp p)
(unless (form-offset p 1) (return))
(push (points-to-string tmp p) sexp)))))
(nreverse sexp))))
(f start end))))
|
373984436c47288fcd9209770280e0bd3a47aa05aad6fe3eb6878b67960ed4ac | UU-ComputerScience/uu-cco | Tree.hs | -------------------------------------------------------------------------------
-- |
-- Module : CCO.Tree
Copyright : ( c ) 2008 Utrecht University
-- License : All rights reserved
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- A straightforward implementation of the ATerm format for exchanging
-- tree-structured data; see
--
* , Hayco de Jong , , and .
-- Efficient annotated terms.
/Software - Practice and Experience ( SPE)/ , 30(3):259 - 291 , 2000 .
--
-------------------------------------------------------------------------------
module CCO.Tree (
* The @ATerm@ type
ATerm (..) -- instances: Eq, Read, Show, Printable
, Con -- = String
* The @Tree@ class
, Tree (..)
*
, parser -- :: Component String ATerm
) where
import CCO.Tree.ATerm (Con, ATerm (..))
import CCO.Tree.ATerm.Parser (parser)
import CCO.Tree.Base (Tree (fromTree, toTree))
import CCO.Tree.Instances () | null | https://raw.githubusercontent.com/UU-ComputerScience/uu-cco/cca433c8a6f4d27407800404dea80c08fd567093/uu-cco/src/CCO/Tree.hs | haskell | -----------------------------------------------------------------------------
|
Module : CCO.Tree
License : All rights reserved
Maintainer :
Stability : provisional
Portability : portable
A straightforward implementation of the ATerm format for exchanging
tree-structured data; see
Efficient annotated terms.
-----------------------------------------------------------------------------
instances: Eq, Read, Show, Printable
= String
:: Component String ATerm | Copyright : ( c ) 2008 Utrecht University
* , Hayco de Jong , , and .
/Software - Practice and Experience ( SPE)/ , 30(3):259 - 291 , 2000 .
module CCO.Tree (
* The @ATerm@ type
* The @Tree@ class
, Tree (..)
*
) where
import CCO.Tree.ATerm (Con, ATerm (..))
import CCO.Tree.ATerm.Parser (parser)
import CCO.Tree.Base (Tree (fromTree, toTree))
import CCO.Tree.Instances () |
c91581e2056b3b7cca1501a74909140c9899490cb11404d6d11029065f8e1b46 | ocaml-omake/omake | lm_thread_core_null.ml | let debug_mutex =
Lm_debug.create_debug (**)
{ debug_name = "mutex";
debug_description = "Show Mutex locking operations";
debug_value = false
}
(*
* Locks are not required when not using threads.
* We only track the "locked" state to produce the correct results in the try_lock function.
*)
module MutexCore =
struct
(* true = free; false = locked *)
type t = bool ref
let create _ =
ref true
let lock l =
l := false
let try_lock l =
let res = !l in
l := false;
res
let unlock l =
l := true
end
(*
* Conditions are not required when not using threads.
*)
module ConditionCore =
struct
type t = unit
type mutex = MutexCore.t
let create () =
()
let wait _ l =
l := false
let signal () =
()
let broadcast () =
()
end
(* module MutexCoreDebug = MutexCore *)
module = ConditionCore
(*
* Threads are null. The create function doesn't work without
* threads, so raise an exception.
*)
module ThreadCore =
struct
type t = unit
type id = unit
let enabled = false
let create _f _x =
raise (Invalid_argument "Lm_thread.Thread.create: threads are not enabled in this application")
let join _t =
raise (Invalid_argument "Lm_thread.Thread.join: threads are not enabled in this application")
let self () =
()
let id () =
0
let sigmask _ mask =
mask
let raise_ctrl_c_wrapper f x = f x
end
| null | https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/libmojave/lm_thread_core_null.ml | ocaml |
* Locks are not required when not using threads.
* We only track the "locked" state to produce the correct results in the try_lock function.
true = free; false = locked
* Conditions are not required when not using threads.
module MutexCoreDebug = MutexCore
* Threads are null. The create function doesn't work without
* threads, so raise an exception.
| let debug_mutex =
{ debug_name = "mutex";
debug_description = "Show Mutex locking operations";
debug_value = false
}
module MutexCore =
struct
type t = bool ref
let create _ =
ref true
let lock l =
l := false
let try_lock l =
let res = !l in
l := false;
res
let unlock l =
l := true
end
module ConditionCore =
struct
type t = unit
type mutex = MutexCore.t
let create () =
()
let wait _ l =
l := false
let signal () =
()
let broadcast () =
()
end
module = ConditionCore
module ThreadCore =
struct
type t = unit
type id = unit
let enabled = false
let create _f _x =
raise (Invalid_argument "Lm_thread.Thread.create: threads are not enabled in this application")
let join _t =
raise (Invalid_argument "Lm_thread.Thread.join: threads are not enabled in this application")
let self () =
()
let id () =
0
let sigmask _ mask =
mask
let raise_ctrl_c_wrapper f x = f x
end
|
c772bdeac04a32403b1e5b8f7d479a0592af93c31be7ca67fab406f1aa4315d8 | thizanne/cormoran | test_cfg.ml | open Batteries
open Printf
let use_litmus = ref false
let speclist = [
"--litmus", Arg.Set use_litmus, "Use litmus syntax";
]
( * Useless with only one arg in the speclist
(* Useless with only one arg in the speclist *)
let speclist =
speclist
|> List.map (fun (a, b, c) -> (a, b, " " ^ c))
|> Arg.align
*)
module Dot = ExportCfg.Dot (Top)
let data _ = Top.bottom
let print_cfg file =
try
let use_litmus = !use_litmus in
let program, _cond = Param.Parse.parse_filename ~use_litmus file in
let g = Cfg.of_program program in
Dot.output_graph IO.stdout data g
with
| Error.Error e -> prerr_endline (Error.to_string e)
let () =
Arg.parse speclist print_cfg
"Prints the Control Flow Graph of a program. Options available:"
| null | https://raw.githubusercontent.com/thizanne/cormoran/46d13330ebd1c8224a0603fd473d8e6bed48bf53/src/test_cfg.ml | ocaml | Useless with only one arg in the speclist | open Batteries
open Printf
let use_litmus = ref false
let speclist = [
"--litmus", Arg.Set use_litmus, "Use litmus syntax";
]
( * Useless with only one arg in the speclist
let speclist =
speclist
|> List.map (fun (a, b, c) -> (a, b, " " ^ c))
|> Arg.align
*)
module Dot = ExportCfg.Dot (Top)
let data _ = Top.bottom
let print_cfg file =
try
let use_litmus = !use_litmus in
let program, _cond = Param.Parse.parse_filename ~use_litmus file in
let g = Cfg.of_program program in
Dot.output_graph IO.stdout data g
with
| Error.Error e -> prerr_endline (Error.to_string e)
let () =
Arg.parse speclist print_cfg
"Prints the Control Flow Graph of a program. Options available:"
|
74c819f14be5001d29f0121368dbec816c2a2cb7a304ea3a942281821b977e34 | soupi/strema-mirror | Strema.hs | | Exporting the important stuff from the strema frontend
-}
module Language.Strema
* frontend
module Language.Strema
* language definition
, module Language.Strema.Syntax.Ast
* parser extra
, module Text.Megaparsec
-- * Strema Type Inference
, module Language.Strema.Types.Infer
* builtin functions and types
, module Language.Strema.Builtins
* Rewrites
, module Language.Strema.Rewrites
, module Language.Strema.Rewrites.RemoveAnn
)
where
import qualified Data.Text.IO as T
import Utils
import Language.Strema.Syntax.Ast
import Language.Strema.Syntax.Parser (runParser, parseFile)
import Language.Strema.Types.Infer (infer, Ann(..), TypeError(..), TypeErrorA)
import Language.Strema.Builtins
import Language.Strema.Rewrites
import Language.Strema.Rewrites.RemoveAnn (removeAnn, removeAnn')
import Text.Megaparsec (SourcePos)
*
| Parse a source file from text
parse :: FilePath -> Text -> Either Text (File SourcePos)
parse = runParser parseFile
-- * Strema Type Inference
| Parse and infer a source file from text
inferPipeline :: FilePath -> Text -> Either Text (File Ann)
inferPipeline path src = do
parsed <- parse path src
inferred <- first pShow $ infer parsed
pure inferred
| Parse and infer a sourcefile and output the result to stdout
testInfer :: Text -> IO ()
testInfer = either T.putStrLn (T.putStrLn . pShow) . inferPipeline "test"
| null | https://raw.githubusercontent.com/soupi/strema-mirror/35f2b7b7ccb9f35127d048a3e693f78f8702def1/src/strema/src/Language/Strema.hs | haskell | * Strema Type Inference
* Strema Type Inference | | Exporting the important stuff from the strema frontend
-}
module Language.Strema
* frontend
module Language.Strema
* language definition
, module Language.Strema.Syntax.Ast
* parser extra
, module Text.Megaparsec
, module Language.Strema.Types.Infer
* builtin functions and types
, module Language.Strema.Builtins
* Rewrites
, module Language.Strema.Rewrites
, module Language.Strema.Rewrites.RemoveAnn
)
where
import qualified Data.Text.IO as T
import Utils
import Language.Strema.Syntax.Ast
import Language.Strema.Syntax.Parser (runParser, parseFile)
import Language.Strema.Types.Infer (infer, Ann(..), TypeError(..), TypeErrorA)
import Language.Strema.Builtins
import Language.Strema.Rewrites
import Language.Strema.Rewrites.RemoveAnn (removeAnn, removeAnn')
import Text.Megaparsec (SourcePos)
*
| Parse a source file from text
parse :: FilePath -> Text -> Either Text (File SourcePos)
parse = runParser parseFile
| Parse and infer a source file from text
inferPipeline :: FilePath -> Text -> Either Text (File Ann)
inferPipeline path src = do
parsed <- parse path src
inferred <- first pShow $ infer parsed
pure inferred
| Parse and infer a sourcefile and output the result to stdout
testInfer :: Text -> IO ()
testInfer = either T.putStrLn (T.putStrLn . pShow) . inferPipeline "test"
|
844ffa3ae84c63cc9eb79654f61868944aea3f15e3f2c9897f513f3d143a7976 | ghollisjr/cl-ana | h5ex-t-vlstringatt.lisp | Copyright by The HDF Group .
;;;; All rights reserved.
;;;;
This file is part of hdf5 - cffi .
The full hdf5 - cffi copyright notice , including terms governing
;;;; use, modification, and redistribution, is contained in the file COPYING,
;;;; which can be found at the root of the source code distribution tree.
;;;; If you do not have access to this file, you may request a copy from
help @hdfgroup.org .
;;; This example shows how to read and write variable-length
string datatypes to a dataset . The program first writes
;;; variable-length strings to a dataset with a dataspace of
DIM0 , then closes the file . Next , it reopens the file ,
;;; reads back the data, and outputs it to the screen.
;;; See h5ex_t_vlstring.c at -c.html
(in-package :hdf5)
(defparameter *FILE* (namestring (merge-pathnames "h5ex_t_vlstring.h5" *load-pathname*)))
(defparameter *DATASET* "DS1")
(defparameter *ATTRIBUTE* "A1")
(defparameter *DIM0* 4)
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fcreate *FILE* +H5F-ACC-TRUNC+ +H5P-DEFAULT+ fapl))))
(unwind-protect
(let* ((wdata (cffi:foreign-alloc
:string :initial-contents
'("Parting" "is such" "sweet" "sorrow")))
(filetype (h5ex:create-f-string-type))
(memtype (h5ex:create-c-string-type))
(dshape (h5ex:create-null-dataspace))
(ashape (h5ex:create-simple-dataspace `(,*DIM0*)))
;; Create dataset with a null dataspace.
(dset (h5dcreate2 file *DATASET* +H5T-STD-I32LE+ dshape
+H5P-DEFAULT+ +H5P-DEFAULT+ +H5P-DEFAULT+))
;; Create the attribute and write the variable-length string data
;; to it.
(attr (h5acreate2 dset *ATTRIBUTE* filetype ashape +H5P-DEFAULT+
+H5P-DEFAULT+)))
(h5awrite attr memtype wdata)
;; Close and release resources.
(h5ex:close-handles (list attr dset ashape dshape memtype filetype))
(cffi:foreign-free wdata))
(h5ex:close-handles (list file fapl))))
;; Now we begin the read section of this example. Here we assume
;; the attribute has the same name and rank, but can have any size.
;; Therefore we must allocate a new array to read in data dynamically.
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fopen *FILE* +H5F-ACC-RDONLY+ fapl))))
(unwind-protect
(let* ((dset (h5dopen2 file *DATASET* +H5P-DEFAULT+))
(attr (h5aopen dset *ATTRIBUTE* +H5P-DEFAULT+))
(shape (h5aget-space attr))
(memtype (h5ex:create-c-string-type)))
(cffi:with-foreign-object (dims 'hsize-t 1)
(h5sget-simple-extent-dims shape dims +NULL+)
(let ((dims[0] (cffi:mem-aref dims 'hsize-t 0)))
(cffi:with-foreign-object (rdata '(:pointer :char) dims[0])
;; Read the data.
(h5aread attr memtype rdata)
;; Output the data to the screen.
(dotimes (i dims[0])
(format t "~a[~s]: ~a~%" *ATTRIBUTE* i
(cffi:foreign-string-to-lisp
(cffi:mem-aref rdata '(:pointer :char) i))))
Close and release resources . Note that works
;; for variable-length strings as well as variable-length arrays.
;; H5Tvlen_reclaim only frees the data these point to.
(h5dvlen-reclaim memtype shape +H5P-DEFAULT+ rdata))))
(h5ex:close-handles (list memtype shape attr dset))
(h5ex:close-handles (list file fapl)))))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/hdf-cffi/examples/datatypes/h5ex-t-vlstringatt.lisp | lisp | All rights reserved.
use, modification, and redistribution, is contained in the file COPYING,
which can be found at the root of the source code distribution tree.
If you do not have access to this file, you may request a copy from
This example shows how to read and write variable-length
variable-length strings to a dataset with a dataspace of
reads back the data, and outputs it to the screen.
See h5ex_t_vlstring.c at -c.html
Create dataset with a null dataspace.
Create the attribute and write the variable-length string data
to it.
Close and release resources.
Now we begin the read section of this example. Here we assume
the attribute has the same name and rank, but can have any size.
Therefore we must allocate a new array to read in data dynamically.
Read the data.
Output the data to the screen.
for variable-length strings as well as variable-length arrays.
H5Tvlen_reclaim only frees the data these point to. | Copyright by The HDF Group .
This file is part of hdf5 - cffi .
The full hdf5 - cffi copyright notice , including terms governing
help @hdfgroup.org .
string datatypes to a dataset . The program first writes
DIM0 , then closes the file . Next , it reopens the file ,
(in-package :hdf5)
(defparameter *FILE* (namestring (merge-pathnames "h5ex_t_vlstring.h5" *load-pathname*)))
(defparameter *DATASET* "DS1")
(defparameter *ATTRIBUTE* "A1")
(defparameter *DIM0* 4)
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fcreate *FILE* +H5F-ACC-TRUNC+ +H5P-DEFAULT+ fapl))))
(unwind-protect
(let* ((wdata (cffi:foreign-alloc
:string :initial-contents
'("Parting" "is such" "sweet" "sorrow")))
(filetype (h5ex:create-f-string-type))
(memtype (h5ex:create-c-string-type))
(dshape (h5ex:create-null-dataspace))
(ashape (h5ex:create-simple-dataspace `(,*DIM0*)))
(dset (h5dcreate2 file *DATASET* +H5T-STD-I32LE+ dshape
+H5P-DEFAULT+ +H5P-DEFAULT+ +H5P-DEFAULT+))
(attr (h5acreate2 dset *ATTRIBUTE* filetype ashape +H5P-DEFAULT+
+H5P-DEFAULT+)))
(h5awrite attr memtype wdata)
(h5ex:close-handles (list attr dset ashape dshape memtype filetype))
(cffi:foreign-free wdata))
(h5ex:close-handles (list file fapl))))
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fopen *FILE* +H5F-ACC-RDONLY+ fapl))))
(unwind-protect
(let* ((dset (h5dopen2 file *DATASET* +H5P-DEFAULT+))
(attr (h5aopen dset *ATTRIBUTE* +H5P-DEFAULT+))
(shape (h5aget-space attr))
(memtype (h5ex:create-c-string-type)))
(cffi:with-foreign-object (dims 'hsize-t 1)
(h5sget-simple-extent-dims shape dims +NULL+)
(let ((dims[0] (cffi:mem-aref dims 'hsize-t 0)))
(cffi:with-foreign-object (rdata '(:pointer :char) dims[0])
(h5aread attr memtype rdata)
(dotimes (i dims[0])
(format t "~a[~s]: ~a~%" *ATTRIBUTE* i
(cffi:foreign-string-to-lisp
(cffi:mem-aref rdata '(:pointer :char) i))))
Close and release resources . Note that works
(h5dvlen-reclaim memtype shape +H5P-DEFAULT+ rdata))))
(h5ex:close-handles (list memtype shape attr dset))
(h5ex:close-handles (list file fapl)))))
|
544d10ba01ddc873e84de6a77514a5f897a245ac8d3958635ed2fcc8ade91159 | deobald/jok | mp4_track.clj | (ns jukebox-player.mp4-track
(:use [jukebox-player.playable])
(:import [javax.sound.sampled AudioFormat]
[net.sourceforge.jaad.aac Decoder SampleBuffer]
[net.sourceforge.jaad.mp4 MP4Container]
[net.sourceforge.jaad.mp4.api AudioTrack$AudioCodec Frame Movie Track]
[java.io ByteArrayInputStream ByteArrayOutputStream RandomAccessFile]))
(defrecord MP4Track [track-data])
(defn- read-track-data [track-data]
(let [decoder (Decoder. (.getDecoderSpecificInfo track-data))
buffer (SampleBuffer.)
output (ByteArrayOutputStream.)]
(loop [frame (.readNextFrame track-data)]
(when-not (nil? frame)
(.decodeFrame decoder (.getData frame) buffer)
(.write output (.getData buffer) 0 (alength (.getData buffer)))
(recur (.readNextFrame track-data))))
(.toByteArray output)))
(defn load-mp4-track [file]
(let [container (MP4Container. (RandomAccessFile. file "r"))
tracks (.getTracks (.getMovie container) AudioTrack$AudioCodec/AAC)]
(MP4Track. (first tracks))))
(extend-type MP4Track
Playable
(in-stream [mp4-track]
(ByteArrayInputStream. (read-track-data (:track-data mp4-track))))
(out-format [mp4-track]
(let [track-data (:track-data mp4-track)]
(AudioFormat. (.getSampleRate track-data)
(.getSampleSize track-data)
(.getChannelCount track-data)
true
true))))
| null | https://raw.githubusercontent.com/deobald/jok/e1b9373603ad7fcc3dbc7304cb8b88b8163e73bc/src/jukebox_player/mp4_track.clj | clojure | (ns jukebox-player.mp4-track
(:use [jukebox-player.playable])
(:import [javax.sound.sampled AudioFormat]
[net.sourceforge.jaad.aac Decoder SampleBuffer]
[net.sourceforge.jaad.mp4 MP4Container]
[net.sourceforge.jaad.mp4.api AudioTrack$AudioCodec Frame Movie Track]
[java.io ByteArrayInputStream ByteArrayOutputStream RandomAccessFile]))
(defrecord MP4Track [track-data])
(defn- read-track-data [track-data]
(let [decoder (Decoder. (.getDecoderSpecificInfo track-data))
buffer (SampleBuffer.)
output (ByteArrayOutputStream.)]
(loop [frame (.readNextFrame track-data)]
(when-not (nil? frame)
(.decodeFrame decoder (.getData frame) buffer)
(.write output (.getData buffer) 0 (alength (.getData buffer)))
(recur (.readNextFrame track-data))))
(.toByteArray output)))
(defn load-mp4-track [file]
(let [container (MP4Container. (RandomAccessFile. file "r"))
tracks (.getTracks (.getMovie container) AudioTrack$AudioCodec/AAC)]
(MP4Track. (first tracks))))
(extend-type MP4Track
Playable
(in-stream [mp4-track]
(ByteArrayInputStream. (read-track-data (:track-data mp4-track))))
(out-format [mp4-track]
(let [track-data (:track-data mp4-track)]
(AudioFormat. (.getSampleRate track-data)
(.getSampleSize track-data)
(.getChannelCount track-data)
true
true))))
| |
8e6150d7fe8eb7e2a2b0060902d0828b97aee2c3301cdf60406a93cc93539bb7 | ml4tp/tcoq | logic_monad.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
* This file implements the low - level monadic operations used by the
tactic monad . The monad is divided into two layers : a non - logical
layer which consists in operations which will not ( or can not ) be
backtracked in case of failure ( input / output or persistent state )
and a logical layer which handles backtracking , proof
manipulation , and any other effect which needs to backtrack .
tactic monad. The monad is divided into two layers: a non-logical
layer which consists in operations which will not (or cannot) be
backtracked in case of failure (input/output or persistent state)
and a logical layer which handles backtracking, proof
manipulation, and any other effect which needs to backtrack. *)
* { 6 Exceptions }
* To help distinguish between exceptions raised by the IO monad from
the one used natively by Coq , the former are wrapped in
[ Exception ] . It is only used internally so that [ catch ] blocks of
the IO monad would only catch exceptions raised by the [ raise ]
function of the IO monad , and not for instance , by system
interrupts . Also used in [ Proofview ] to avoid capturing exception
from the IO monad ( [ Proofview ] catches errors in its compatibility
layer , and when lifting goal - level expressions ) .
the one used natively by Coq, the former are wrapped in
[Exception]. It is only used internally so that [catch] blocks of
the IO monad would only catch exceptions raised by the [raise]
function of the IO monad, and not for instance, by system
interrupts. Also used in [Proofview] to avoid capturing exception
from the IO monad ([Proofview] catches errors in its compatibility
layer, and when lifting goal-level expressions). *)
exception Exception of exn
(** This exception is used to signal abortion in [timeout] functions. *)
exception Timeout
(** This exception is used by the tactics to signal failure by lack of
successes, rather than some other exceptions (like system
interrupts). *)
exception TacticFailure of exn
* { 6 Non - logical layer }
(** The non-logical monad is a simple [unit -> 'a] (i/o) monad. The
operations are simple wrappers around corresponding usual
operations and require little documentation. *)
module NonLogical : sig
include Monad.S
val ignore : 'a t -> unit t
type 'a ref
val ref : 'a -> 'a ref t
(** [Pervasives.(:=)] *)
val (:=) : 'a ref -> 'a -> unit t
(** [Pervasives.(!)] *)
val (!) : 'a ref -> 'a t
val read_line : string t
val print_char : char -> unit t
(** Loggers. The buffer is also flushed. *)
val print_debug : Pp.std_ppcmds -> unit t
val print_warning : Pp.std_ppcmds -> unit t
val print_notice : Pp.std_ppcmds -> unit t
val print_info : Pp.std_ppcmds -> unit t
val print_error : Pp.std_ppcmds -> unit t
(** [Pervasives.raise]. Except that exceptions are wrapped with
{!Exception}. *)
val raise : ?info:Exninfo.info -> exn -> 'a t
(** [try ... with ...] but restricted to {!Exception}. *)
val catch : 'a t -> (Exninfo.iexn -> 'a t) -> 'a t
val timeout : int -> 'a t -> 'a t
(** Construct a monadified side-effect. Exceptions raised by the argument are
wrapped with {!Exception}. *)
val make : (unit -> 'a) -> 'a t
(** [run] performs effects. *)
val run : 'a t -> 'a
end
* { 6 Logical layer }
* The logical monad is a backtracking monad on top of which is
layered a state monad ( which is used to implement all of read / write ,
read only , and write only effects ) . The state monad being layered on
top of the backtracking monad makes it so that the state is
backtracked on failure .
Backtracking differs from regular exception in that , writing ( + )
for exception catching and ( > > =) for bind , we require the
following extra distributivity laws :
x+(y+z ) = ( x+y)+z
zero+x = x
= x
( = ( )
layered a state monad (which is used to implement all of read/write,
read only, and write only effects). The state monad being layered on
top of the backtracking monad makes it so that the state is
backtracked on failure.
Backtracking differs from regular exception in that, writing (+)
for exception catching and (>>=) for bind, we require the
following extra distributivity laws:
x+(y+z) = (x+y)+z
zero+x = x
x+zero = x
(x+y)>>=k = (x>>=k)+(y>>=k) *)
(** A view type for the logical monad, which is a form of list, hence
we can decompose it with as a list. *)
type ('a, 'b, 'e) list_view =
| Nil of 'e
| Cons of 'a * ('e -> 'b)
module BackState : sig
type (+'a, -'i, +'o, 'e) t
val return : 'a -> ('a, 's, 's, 'e) t
val (>>=) : ('a, 'i, 'm, 'e) t -> ('a -> ('b, 'm, 'o, 'e) t) -> ('b, 'i, 'o, 'e) t
val (>>) : (unit, 'i, 'm, 'e) t -> ('b, 'm, 'o, 'e) t -> ('b, 'i, 'o, 'e) t
val map : ('a -> 'b) -> ('a, 'i, 'o, 'e) t -> ('b, 'i, 'o, 'e) t
val ignore : ('a, 'i, 'o, 'e) t -> (unit, 'i, 'o, 'e) t
val set : 'o -> (unit, 'i, 'o, 'e) t
val get : ('s, 's, 's, 'e) t
val modify : ('i -> 'o) -> (unit, 'i, 'o, 'e) t
val interleave : ('e1 -> 'e2) -> ('e2 -> 'e1) -> ('a, 'i, 'o, 'e1) t ->
('a, 'i, 'o, 'e2) t
(** [interleave src dst m] adapts the exceptional content of the monad
according to the functions [src] and [dst]. To ensure a meaningful result,
those functions must form a retraction, i.e. [dst (src e1) = e1] for all
[e1]. This is typically the case when the type ['e1] is [unit]. *)
val zero : 'e -> ('a, 'i, 'o, 'e) t
val plus : ('a, 'i, 'o, 'e) t -> ('e -> ('a, 'i, 'o, 'e) t) -> ('a, 'i, 'o, 'e) t
val split : ('a, 's, 's, 'e) t ->
(('a, ('a, 'i, 's, 'e) t, 'e) list_view, 's, 's, 'e) t
val once : ('a, 'i, 'o, 'e) t -> ('a, 'i, 'o, 'e) t
val break : ('e -> 'e option) -> ('a, 'i, 'o, 'e) t -> ('a, 'i, 'o, 'e) t
val lift : 'a NonLogical.t -> ('a, 's, 's, 'e) t
type ('a, 'e) reified
val repr : ('a, 'e) reified -> ('a, ('a, 'e) reified, 'e) list_view NonLogical.t
val run : ('a, 'i, 'o, 'e) t -> 'i -> ('a * 'o, 'e) reified
end
(** The monad is parametrised in the types of state, environment and
writer. *)
module type Param = sig
(** Read only *)
type e
(** Write only *)
type w
(** [w] must be a monoid *)
val wunit : w
val wprod : w -> w -> w
(** Read-write *)
type s
(** Update-only. Essentially a writer on [u->u]. *)
type u
(** [u] must be pointed. *)
val uunit : u
end
module Logical (P:Param) : sig
include Monad.S
val ignore : 'a t -> unit t
val set : P.s -> unit t
val get : P.s t
val modify : (P.s -> P.s) -> unit t
val put : P.w -> unit t
val current : P.e t
val local : P.e -> 'a t -> 'a t
val update : (P.u -> P.u) -> unit t
val zero : Exninfo.iexn -> 'a t
val plus : 'a t -> (Exninfo.iexn -> 'a t) -> 'a t
val split : 'a t -> ('a, 'a t, Exninfo.iexn) list_view t
val once : 'a t -> 'a t
val break : (Exninfo.iexn -> Exninfo.iexn option) -> 'a t -> 'a t
val lift : 'a NonLogical.t -> 'a t
type 'a reified = ('a, Exninfo.iexn) BackState.reified
val repr : 'a reified -> ('a, 'a reified, Exninfo.iexn) list_view NonLogical.t
val run : 'a t -> P.e -> P.s -> ('a * P.s * P.w * P.u) reified
module Unsafe :
sig
type state = {
rstate : P.e;
ustate : P.u;
wstate : P.w;
sstate : P.s;
}
val make : ('a, state, state, Exninfo.iexn) BackState.t -> 'a t
val repr : 'a t -> ('a, state, state, Exninfo.iexn) BackState.t
end
end
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/engine/logic_monad.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* This exception is used to signal abortion in [timeout] functions.
* This exception is used by the tactics to signal failure by lack of
successes, rather than some other exceptions (like system
interrupts).
* The non-logical monad is a simple [unit -> 'a] (i/o) monad. The
operations are simple wrappers around corresponding usual
operations and require little documentation.
* [Pervasives.(:=)]
* [Pervasives.(!)]
* Loggers. The buffer is also flushed.
* [Pervasives.raise]. Except that exceptions are wrapped with
{!Exception}.
* [try ... with ...] but restricted to {!Exception}.
* Construct a monadified side-effect. Exceptions raised by the argument are
wrapped with {!Exception}.
* [run] performs effects.
* A view type for the logical monad, which is a form of list, hence
we can decompose it with as a list.
* [interleave src dst m] adapts the exceptional content of the monad
according to the functions [src] and [dst]. To ensure a meaningful result,
those functions must form a retraction, i.e. [dst (src e1) = e1] for all
[e1]. This is typically the case when the type ['e1] is [unit].
* The monad is parametrised in the types of state, environment and
writer.
* Read only
* Write only
* [w] must be a monoid
* Read-write
* Update-only. Essentially a writer on [u->u].
* [u] must be pointed. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2017
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* This file implements the low - level monadic operations used by the
tactic monad . The monad is divided into two layers : a non - logical
layer which consists in operations which will not ( or can not ) be
backtracked in case of failure ( input / output or persistent state )
and a logical layer which handles backtracking , proof
manipulation , and any other effect which needs to backtrack .
tactic monad. The monad is divided into two layers: a non-logical
layer which consists in operations which will not (or cannot) be
backtracked in case of failure (input/output or persistent state)
and a logical layer which handles backtracking, proof
manipulation, and any other effect which needs to backtrack. *)
* { 6 Exceptions }
* To help distinguish between exceptions raised by the IO monad from
the one used natively by Coq , the former are wrapped in
[ Exception ] . It is only used internally so that [ catch ] blocks of
the IO monad would only catch exceptions raised by the [ raise ]
function of the IO monad , and not for instance , by system
interrupts . Also used in [ Proofview ] to avoid capturing exception
from the IO monad ( [ Proofview ] catches errors in its compatibility
layer , and when lifting goal - level expressions ) .
the one used natively by Coq, the former are wrapped in
[Exception]. It is only used internally so that [catch] blocks of
the IO monad would only catch exceptions raised by the [raise]
function of the IO monad, and not for instance, by system
interrupts. Also used in [Proofview] to avoid capturing exception
from the IO monad ([Proofview] catches errors in its compatibility
layer, and when lifting goal-level expressions). *)
exception Exception of exn
exception Timeout
exception TacticFailure of exn
* { 6 Non - logical layer }
module NonLogical : sig
include Monad.S
val ignore : 'a t -> unit t
type 'a ref
val ref : 'a -> 'a ref t
val (:=) : 'a ref -> 'a -> unit t
val (!) : 'a ref -> 'a t
val read_line : string t
val print_char : char -> unit t
val print_debug : Pp.std_ppcmds -> unit t
val print_warning : Pp.std_ppcmds -> unit t
val print_notice : Pp.std_ppcmds -> unit t
val print_info : Pp.std_ppcmds -> unit t
val print_error : Pp.std_ppcmds -> unit t
val raise : ?info:Exninfo.info -> exn -> 'a t
val catch : 'a t -> (Exninfo.iexn -> 'a t) -> 'a t
val timeout : int -> 'a t -> 'a t
val make : (unit -> 'a) -> 'a t
val run : 'a t -> 'a
end
* { 6 Logical layer }
* The logical monad is a backtracking monad on top of which is
layered a state monad ( which is used to implement all of read / write ,
read only , and write only effects ) . The state monad being layered on
top of the backtracking monad makes it so that the state is
backtracked on failure .
Backtracking differs from regular exception in that , writing ( + )
for exception catching and ( > > =) for bind , we require the
following extra distributivity laws :
x+(y+z ) = ( x+y)+z
zero+x = x
= x
( = ( )
layered a state monad (which is used to implement all of read/write,
read only, and write only effects). The state monad being layered on
top of the backtracking monad makes it so that the state is
backtracked on failure.
Backtracking differs from regular exception in that, writing (+)
for exception catching and (>>=) for bind, we require the
following extra distributivity laws:
x+(y+z) = (x+y)+z
zero+x = x
x+zero = x
(x+y)>>=k = (x>>=k)+(y>>=k) *)
type ('a, 'b, 'e) list_view =
| Nil of 'e
| Cons of 'a * ('e -> 'b)
module BackState : sig
type (+'a, -'i, +'o, 'e) t
val return : 'a -> ('a, 's, 's, 'e) t
val (>>=) : ('a, 'i, 'm, 'e) t -> ('a -> ('b, 'm, 'o, 'e) t) -> ('b, 'i, 'o, 'e) t
val (>>) : (unit, 'i, 'm, 'e) t -> ('b, 'm, 'o, 'e) t -> ('b, 'i, 'o, 'e) t
val map : ('a -> 'b) -> ('a, 'i, 'o, 'e) t -> ('b, 'i, 'o, 'e) t
val ignore : ('a, 'i, 'o, 'e) t -> (unit, 'i, 'o, 'e) t
val set : 'o -> (unit, 'i, 'o, 'e) t
val get : ('s, 's, 's, 'e) t
val modify : ('i -> 'o) -> (unit, 'i, 'o, 'e) t
val interleave : ('e1 -> 'e2) -> ('e2 -> 'e1) -> ('a, 'i, 'o, 'e1) t ->
('a, 'i, 'o, 'e2) t
val zero : 'e -> ('a, 'i, 'o, 'e) t
val plus : ('a, 'i, 'o, 'e) t -> ('e -> ('a, 'i, 'o, 'e) t) -> ('a, 'i, 'o, 'e) t
val split : ('a, 's, 's, 'e) t ->
(('a, ('a, 'i, 's, 'e) t, 'e) list_view, 's, 's, 'e) t
val once : ('a, 'i, 'o, 'e) t -> ('a, 'i, 'o, 'e) t
val break : ('e -> 'e option) -> ('a, 'i, 'o, 'e) t -> ('a, 'i, 'o, 'e) t
val lift : 'a NonLogical.t -> ('a, 's, 's, 'e) t
type ('a, 'e) reified
val repr : ('a, 'e) reified -> ('a, ('a, 'e) reified, 'e) list_view NonLogical.t
val run : ('a, 'i, 'o, 'e) t -> 'i -> ('a * 'o, 'e) reified
end
module type Param = sig
type e
type w
val wunit : w
val wprod : w -> w -> w
type s
type u
val uunit : u
end
module Logical (P:Param) : sig
include Monad.S
val ignore : 'a t -> unit t
val set : P.s -> unit t
val get : P.s t
val modify : (P.s -> P.s) -> unit t
val put : P.w -> unit t
val current : P.e t
val local : P.e -> 'a t -> 'a t
val update : (P.u -> P.u) -> unit t
val zero : Exninfo.iexn -> 'a t
val plus : 'a t -> (Exninfo.iexn -> 'a t) -> 'a t
val split : 'a t -> ('a, 'a t, Exninfo.iexn) list_view t
val once : 'a t -> 'a t
val break : (Exninfo.iexn -> Exninfo.iexn option) -> 'a t -> 'a t
val lift : 'a NonLogical.t -> 'a t
type 'a reified = ('a, Exninfo.iexn) BackState.reified
val repr : 'a reified -> ('a, 'a reified, Exninfo.iexn) list_view NonLogical.t
val run : 'a t -> P.e -> P.s -> ('a * P.s * P.w * P.u) reified
module Unsafe :
sig
type state = {
rstate : P.e;
ustate : P.u;
wstate : P.w;
sstate : P.s;
}
val make : ('a, state, state, Exninfo.iexn) BackState.t -> 'a t
val repr : 'a t -> ('a, state, state, Exninfo.iexn) BackState.t
end
end
|
6f535f87ba1a2f81d605fb46914944d434f006d54d792e3717fbfcdbbaab4572 | haskell-tools/haskell-tools | Daemon.hs | # LANGUAGE MonoLocalBinds #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
| The central module for the background process of Haskell - tools . Starts the daemon process and
-- updates it for each client request in a loop. After this releases the resources and terminates.
module Language.Haskell.Tools.Daemon where
import Control.Concurrent.MVar
import Control.Exception (catches)
import Control.Monad
import Control.Monad.State.Strict
import Control.Reference hiding (modifyMVarMasked_)
import Data.Tuple (swap)
import Data.Version (showVersion)
import Network.Socket hiding (send, sendTo, recv, recvFrom, KeepAlive)
import System.IO
import GhcMonad (Session(..), reflectGhc)
import Language.Haskell.Tools.Daemon.ErrorHandling (userExceptionHandlers, exceptionHandlers)
import Language.Haskell.Tools.Daemon.Mode (WorkingMode(..), socketMode)
import Language.Haskell.Tools.Daemon.Options as Options (SharedDaemonOptions(..), DaemonOptions(..))
import Language.Haskell.Tools.Daemon.Protocol
import Language.Haskell.Tools.Daemon.State (DaemonSessionState(..), initSession, exiting)
import Language.Haskell.Tools.Daemon.Update (updateClient, initGhcSession)
import Language.Haskell.Tools.Daemon.Watch (createWatchProcess', stopWatch)
import Language.Haskell.Tools.Refactor (RefactoringChoice(..), QueryChoice(..))
import Paths_haskell_tools_daemon (version)
-- | Starts the daemon process. This will not return until the daemon stops. You can use this entry
-- point when the other endpoint of the client connection is not needed, for example, when you use
-- socket connection to connect to the daemon process.
runDaemon' :: [RefactoringChoice] -> [QueryChoice] -> DaemonOptions -> IO ()
runDaemon' refactorings queries args
= do store <- newEmptyMVar
runDaemon refactorings queries socketMode store args
-- | Starts the daemon process. This will not return until the daemon stops.
-- The daemon process is parameterized by the refactorings you can use in it. This entry point gives
-- back the other endpoint of the connection so it can be used to run the daemon in the same process.
runDaemon :: [RefactoringChoice] -> [QueryChoice] -> WorkingMode a -> MVar a -> DaemonOptions -> IO ()
runDaemon _ _ _ _ DaemonOptions{..} | daemonVersion
= putStrLn $ showVersion version
runDaemon refactorings queries mode connStore config@DaemonOptions{..} = withSocketsDo $
do when (not silentMode) $ putStrLn $ "Starting Haskell Tools daemon"
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
conn <- daemonConnect mode portNumber
putMVar connStore conn
when (not silentMode) $ putStrLn $ "Connection established"
(ghcSess, warnMVar) <- initGhcSession (generateCode sharedOptions)
state <- newMVar initSession
set the ghc flags given by command line
case Options.ghcFlags sharedOptions of
Just flags -> void $ respondTo config refactorings queries ghcSess state (daemonSend mode conn) warnMVar (SetGHCFlags flags)
Nothing -> return ()
case projectType sharedOptions of
Just t -> void $ respondTo config refactorings queries ghcSess state (daemonSend mode conn) warnMVar (SetPackageDB t)
Nothing -> return ()
-- set up the file watch
(wp,th) <- if noWatch sharedOptions
then return (Nothing, [])
else createWatchProcess'
(watchExe sharedOptions) ghcSess state warnMVar (daemonSend mode conn)
modifyMVarMasked_ state ( \s -> return s { _watchProc = wp, _watchThreads = th })
-- start the server loop
serverLoop refactorings queries mode conn config ghcSess state warnMVar
-- free allocated resources
case wp of Just watchProcess -> stopWatch watchProcess th
Nothing -> return ()
daemonDisconnect mode conn
-- | Starts the server loop, receiving requests from the client and updated the server state
-- according to these.
serverLoop :: [RefactoringChoice] -> [QueryChoice] -> WorkingMode a -> a -> DaemonOptions -> Session
-> MVar DaemonSessionState -> MVar [Marker] -> IO ()
serverLoop refactorings queries mode conn options ghcSess state warnMVar =
do msgs <- daemonReceive mode conn
continue <- mapM respondToMsg msgs
sessionData <- readMVar state
when (not (sessionData ^. exiting) && all (== True) continue)
$ serverLoop refactorings queries mode conn options ghcSess state warnMVar
`catches` exceptionHandlers (serverLoop refactorings queries mode conn options ghcSess state warnMVar)
(daemonSend mode conn . ErrorMessage)
where respondToMsg (Right req)
= do when (not (silentMode options)) $ putStrLn $ "Message received: " ++ show req
respondTo options refactorings queries ghcSess state (daemonSend mode conn) warnMVar req
`catches` userExceptionHandlers
(\s -> daemonSend mode conn (ErrorMessage s) >> return True)
(\err hint -> daemonSend mode conn (CompilationProblem err hint) >> return True)
respondToMsg (Left msg) = do daemonSend mode conn $ ErrorMessage $ "MALFORMED MESSAGE: " ++ msg
return True
| Responds to a client request by modifying the daemon and GHC state accordingly .
respondTo :: DaemonOptions -> [RefactoringChoice] -> [QueryChoice] -> Session
-> MVar DaemonSessionState -> (ResponseMsg -> IO ()) -> MVar [Marker]
-> ClientMessage -> IO Bool
respondTo options refactorings queries ghcSess state next warnMVar req
= modifyMVar state (\st -> swap <$> reflectGhc (runStateT upClient st) ghcSess)
where upClient = updateClient options warnMVar refactorings queries next req
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/daemon/Language/Haskell/Tools/Daemon.hs | haskell | updates it for each client request in a loop. After this releases the resources and terminates.
| Starts the daemon process. This will not return until the daemon stops. You can use this entry
point when the other endpoint of the client connection is not needed, for example, when you use
socket connection to connect to the daemon process.
| Starts the daemon process. This will not return until the daemon stops.
The daemon process is parameterized by the refactorings you can use in it. This entry point gives
back the other endpoint of the connection so it can be used to run the daemon in the same process.
set up the file watch
start the server loop
free allocated resources
| Starts the server loop, receiving requests from the client and updated the server state
according to these. | # LANGUAGE MonoLocalBinds #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
| The central module for the background process of Haskell - tools . Starts the daemon process and
module Language.Haskell.Tools.Daemon where
import Control.Concurrent.MVar
import Control.Exception (catches)
import Control.Monad
import Control.Monad.State.Strict
import Control.Reference hiding (modifyMVarMasked_)
import Data.Tuple (swap)
import Data.Version (showVersion)
import Network.Socket hiding (send, sendTo, recv, recvFrom, KeepAlive)
import System.IO
import GhcMonad (Session(..), reflectGhc)
import Language.Haskell.Tools.Daemon.ErrorHandling (userExceptionHandlers, exceptionHandlers)
import Language.Haskell.Tools.Daemon.Mode (WorkingMode(..), socketMode)
import Language.Haskell.Tools.Daemon.Options as Options (SharedDaemonOptions(..), DaemonOptions(..))
import Language.Haskell.Tools.Daemon.Protocol
import Language.Haskell.Tools.Daemon.State (DaemonSessionState(..), initSession, exiting)
import Language.Haskell.Tools.Daemon.Update (updateClient, initGhcSession)
import Language.Haskell.Tools.Daemon.Watch (createWatchProcess', stopWatch)
import Language.Haskell.Tools.Refactor (RefactoringChoice(..), QueryChoice(..))
import Paths_haskell_tools_daemon (version)
runDaemon' :: [RefactoringChoice] -> [QueryChoice] -> DaemonOptions -> IO ()
runDaemon' refactorings queries args
= do store <- newEmptyMVar
runDaemon refactorings queries socketMode store args
runDaemon :: [RefactoringChoice] -> [QueryChoice] -> WorkingMode a -> MVar a -> DaemonOptions -> IO ()
runDaemon _ _ _ _ DaemonOptions{..} | daemonVersion
= putStrLn $ showVersion version
runDaemon refactorings queries mode connStore config@DaemonOptions{..} = withSocketsDo $
do when (not silentMode) $ putStrLn $ "Starting Haskell Tools daemon"
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
conn <- daemonConnect mode portNumber
putMVar connStore conn
when (not silentMode) $ putStrLn $ "Connection established"
(ghcSess, warnMVar) <- initGhcSession (generateCode sharedOptions)
state <- newMVar initSession
set the ghc flags given by command line
case Options.ghcFlags sharedOptions of
Just flags -> void $ respondTo config refactorings queries ghcSess state (daemonSend mode conn) warnMVar (SetGHCFlags flags)
Nothing -> return ()
case projectType sharedOptions of
Just t -> void $ respondTo config refactorings queries ghcSess state (daemonSend mode conn) warnMVar (SetPackageDB t)
Nothing -> return ()
(wp,th) <- if noWatch sharedOptions
then return (Nothing, [])
else createWatchProcess'
(watchExe sharedOptions) ghcSess state warnMVar (daemonSend mode conn)
modifyMVarMasked_ state ( \s -> return s { _watchProc = wp, _watchThreads = th })
serverLoop refactorings queries mode conn config ghcSess state warnMVar
case wp of Just watchProcess -> stopWatch watchProcess th
Nothing -> return ()
daemonDisconnect mode conn
serverLoop :: [RefactoringChoice] -> [QueryChoice] -> WorkingMode a -> a -> DaemonOptions -> Session
-> MVar DaemonSessionState -> MVar [Marker] -> IO ()
serverLoop refactorings queries mode conn options ghcSess state warnMVar =
do msgs <- daemonReceive mode conn
continue <- mapM respondToMsg msgs
sessionData <- readMVar state
when (not (sessionData ^. exiting) && all (== True) continue)
$ serverLoop refactorings queries mode conn options ghcSess state warnMVar
`catches` exceptionHandlers (serverLoop refactorings queries mode conn options ghcSess state warnMVar)
(daemonSend mode conn . ErrorMessage)
where respondToMsg (Right req)
= do when (not (silentMode options)) $ putStrLn $ "Message received: " ++ show req
respondTo options refactorings queries ghcSess state (daemonSend mode conn) warnMVar req
`catches` userExceptionHandlers
(\s -> daemonSend mode conn (ErrorMessage s) >> return True)
(\err hint -> daemonSend mode conn (CompilationProblem err hint) >> return True)
respondToMsg (Left msg) = do daemonSend mode conn $ ErrorMessage $ "MALFORMED MESSAGE: " ++ msg
return True
| Responds to a client request by modifying the daemon and GHC state accordingly .
respondTo :: DaemonOptions -> [RefactoringChoice] -> [QueryChoice] -> Session
-> MVar DaemonSessionState -> (ResponseMsg -> IO ()) -> MVar [Marker]
-> ClientMessage -> IO Bool
respondTo options refactorings queries ghcSess state next warnMVar req
= modifyMVar state (\st -> swap <$> reflectGhc (runStateT upClient st) ghcSess)
where upClient = updateClient options warnMVar refactorings queries next req
|
4d0117967855db19db6c2eb8cf6f67d27dd2800fdcdab36f84aea9ccd4bf568a | Naproche-SAD/Naproche-SAD | Evaluation.hs | module SAD.Data.Evaluation where
import SAD.Data.Formula (Formula)
data Evaluation = EV {
term :: Formula, -- the term to be reduced
positives :: Formula, -- reduction for positive positions
negatives :: Formula, -- reduction for negative positions
conditions :: [Formula] -- conditions
} deriving Show | null | https://raw.githubusercontent.com/Naproche-SAD/Naproche-SAD/da131a6eaf65d4e02e82082a50a4febb6d42db3d/src/SAD/Data/Evaluation.hs | haskell | the term to be reduced
reduction for positive positions
reduction for negative positions
conditions | module SAD.Data.Evaluation where
import SAD.Data.Formula (Formula)
data Evaluation = EV {
} deriving Show |
d25d7162fbbaf887fcacf4efd8254d85181d5d9636893957f5442a320408cb20 | singleheart/programming-in-haskell | ex6.hs | data Tree
= Leaf Int
| Node Tree Tree
deriving (Show)
countLeaves :: Tree -> Int
countLeaves (Leaf _) = 1
countLeaves (Node l r) = countLeaves l + countLeaves r
countNodes :: Tree -> Int
countNodes (Leaf _) = 0
countNodes (Node l r) = countNodes l + 1 + countNodes r
| null | https://raw.githubusercontent.com/singleheart/programming-in-haskell/9c2a8010479714aa51b99b7be91ad9b5903f2ea4/ch16/ex6.hs | haskell | data Tree
= Leaf Int
| Node Tree Tree
deriving (Show)
countLeaves :: Tree -> Int
countLeaves (Leaf _) = 1
countLeaves (Node l r) = countLeaves l + countLeaves r
countNodes :: Tree -> Int
countNodes (Leaf _) = 0
countNodes (Node l r) = countNodes l + 1 + countNodes r
| |
b34ede4cebc061ee6368f2c8d3b32b1094d9692137dea99e70f44de7bf89a115 | HugoPeters1024/hs-sleuth | Search.hs | -- | Search for a pattern in a file, find the number of occurences
--
-- Tested in this benchmark:
--
-- * Searching all occurences of a pattern using library routines
--
module Benchmarks.Search
( initEnv
, benchmark
) where
import Test.Tasty.Bench (Benchmark, bench, bgroup, whnf)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
type Env = (T.Text, TL.Text)
initEnv :: FilePath -> IO Env
initEnv fp = do
t <- T.readFile fp
tl <- TL.readFile fp
return (t, tl)
benchmark :: T.Text -> Env -> Benchmark
benchmark needleT ~(t, tl) =
bgroup "FileIndices"
[ bench "Text" $ whnf (text needleT) t
, bench "LazyText" $ whnf (lazyText needleTL) tl
]
where
needleTL = TL.fromChunks [needleT]
text :: T.Text -> T.Text -> Int
text = T.count
lazyText :: TL.Text -> TL.Text -> Int
lazyText needle = fromIntegral . TL.count needle
| null | https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/91aa2806ea71b7a26add3801383b3133200971a5/test-project/text-nofusion/benchmarks/haskell/Benchmarks/Search.hs | haskell | | Search for a pattern in a file, find the number of occurences
Tested in this benchmark:
* Searching all occurences of a pattern using library routines
| module Benchmarks.Search
( initEnv
, benchmark
) where
import Test.Tasty.Bench (Benchmark, bench, bgroup, whnf)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
type Env = (T.Text, TL.Text)
initEnv :: FilePath -> IO Env
initEnv fp = do
t <- T.readFile fp
tl <- TL.readFile fp
return (t, tl)
benchmark :: T.Text -> Env -> Benchmark
benchmark needleT ~(t, tl) =
bgroup "FileIndices"
[ bench "Text" $ whnf (text needleT) t
, bench "LazyText" $ whnf (lazyText needleTL) tl
]
where
needleTL = TL.fromChunks [needleT]
text :: T.Text -> T.Text -> Int
text = T.count
lazyText :: TL.Text -> TL.Text -> Int
lazyText needle = fromIntegral . TL.count needle
|
8bf6b25812172edad32034557b091609c054eb293210d6f59f8acbe0686f2cbe | ghollisjr/cl-ana | h5ex-d-extern.lisp | Copyright by The HDF Group .
;;;; All rights reserved.
;;;;
This file is part of hdf5 - cffi .
The full hdf5 - cffi copyright notice , including terms governing
;;;; use, modification, and redistribution, is contained in the file COPYING,
;;;; which can be found at the root of the source code distribution tree.
;;;; If you do not have access to this file, you may request a copy from
;;;; .
;;; This example shows how to read and write data to an
external dataset . The program first writes integers to an
;;; external dataset with dataspace dimensions of DIM0xDIM1,
then closes the file . Next , it reopens the file , reads
;;; back the data, and outputs the name of the external data
;;; file and the data to the screen.
;;; -by-api/hdf5-examples/1_8/C/H5D/h5ex_d_extern.c
(in-package :hdf5)
(defvar *FILE* (namestring (merge-pathnames "h5ex_d_extern.h5" *load-pathname*)))
(defvar *EXTERNAL* (namestring (merge-pathnames "h5ex_d_extern.data" *load-pathname*)))
(defvar *DATASET* "DS1")
(defvar *DIM0* 4)
(defvar *DIM1* 7)
(defvar *NAME-BUF-SIZE* 32)
(cffi:with-foreign-objects ((name :char *NAME-BUF-SIZE*)
(wdata :int (* *DIM0* *DIM1*))
(rdata :int (* *DIM0* *DIM1*)))
Initialize data .
(dotimes (i *DIM0*)
(dotimes (j *DIM1*)
(setf (cffi:mem-aref wdata :int (h5ex:pos2D *DIM1* i j)) (- (* i j) j))))
;; Create a new file using the default properties.
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fcreate *FILE* +H5F-ACC-TRUNC+ +H5P-DEFAULT+ fapl))))
(unwind-protect
(let* ((space (h5ex:create-simple-dataspace `(,*DIM0* ,*DIM1*)))
(dcpl (h5pcreate +H5P-DATASET-CREATE+))
(dset (prog2
;; Create the dataset creation property list, and
;; set the external file.
(h5pset-external dcpl *EXTERNAL* 0 +H5F-UNLIMITED+)
;; Create the external dataset
(h5dcreate2 file *DATASET* +H5T-STD-I32LE+ space
+H5P-DEFAULT+ dcpl +H5P-DEFAULT+))))
;; Write the data to the dataset.
(h5dwrite dset +H5T-NATIVE-INT+ +H5S-ALL+ space +H5P-DEFAULT+ wdata)
;; Close and release resources.
(h5ex:close-handles (list dset dcpl space)))
(h5ex:close-handles (list file fapl))))
;; Now we begin the read section of this example.
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fopen *FILE* +H5F-ACC-RDONLY+ fapl))))
(unwind-protect
(let* ((dset (h5dopen2 file *DATASET* +H5P-DEFAULT+))
(dcpl (h5dget-create-plist dset)))
;; Retrieve and print the name of the external file. Here we
;; manually set the last field in name to null, in case the name of
;; the file is longer than the buffer.
(h5pget-external dcpl 0 *NAME-BUF-SIZE* name +NULL+ +NULL+)
(setf (cffi:mem-aref name :char (1- *NAME-BUF-SIZE*)) 0)
(format t "~a is stored in file: ~a~%" *DATASET*
(cffi:foreign-string-to-lisp name))
;;Read the data using the default properties.
(h5dread dset +H5T-NATIVE-INT+ +H5S-ALL+ +H5S-ALL+ +H5P-DEFAULT+
rdata)
;; Output the data to the screen.
(format t "~a:~%" *DATASET*)
(dotimes (i *DIM0*)
(format t " [")
(dotimes (j *DIM1*)
(format t " ~3d" (cffi:mem-aref rdata :int
(h5ex:pos2D *DIM1* i j))))
(format t "]~%"))
;; Close and release resources.
(h5ex:close-handles (list dcpl dset)))
(h5ex:close-handles (list file fapl)))))
| null | https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/hdf-cffi/examples/datasets/h5ex-d-extern.lisp | lisp | All rights reserved.
use, modification, and redistribution, is contained in the file COPYING,
which can be found at the root of the source code distribution tree.
If you do not have access to this file, you may request a copy from
.
This example shows how to read and write data to an
external dataset with dataspace dimensions of DIM0xDIM1,
back the data, and outputs the name of the external data
file and the data to the screen.
-by-api/hdf5-examples/1_8/C/H5D/h5ex_d_extern.c
Create a new file using the default properties.
Create the dataset creation property list, and
set the external file.
Create the external dataset
Write the data to the dataset.
Close and release resources.
Now we begin the read section of this example.
Retrieve and print the name of the external file. Here we
manually set the last field in name to null, in case the name of
the file is longer than the buffer.
Read the data using the default properties.
Output the data to the screen.
Close and release resources. | Copyright by The HDF Group .
This file is part of hdf5 - cffi .
The full hdf5 - cffi copyright notice , including terms governing
external dataset . The program first writes integers to an
then closes the file . Next , it reopens the file , reads
(in-package :hdf5)
(defvar *FILE* (namestring (merge-pathnames "h5ex_d_extern.h5" *load-pathname*)))
(defvar *EXTERNAL* (namestring (merge-pathnames "h5ex_d_extern.data" *load-pathname*)))
(defvar *DATASET* "DS1")
(defvar *DIM0* 4)
(defvar *DIM1* 7)
(defvar *NAME-BUF-SIZE* 32)
(cffi:with-foreign-objects ((name :char *NAME-BUF-SIZE*)
(wdata :int (* *DIM0* *DIM1*))
(rdata :int (* *DIM0* *DIM1*)))
Initialize data .
(dotimes (i *DIM0*)
(dotimes (j *DIM1*)
(setf (cffi:mem-aref wdata :int (h5ex:pos2D *DIM1* i j)) (- (* i j) j))))
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fcreate *FILE* +H5F-ACC-TRUNC+ +H5P-DEFAULT+ fapl))))
(unwind-protect
(let* ((space (h5ex:create-simple-dataspace `(,*DIM0* ,*DIM1*)))
(dcpl (h5pcreate +H5P-DATASET-CREATE+))
(dset (prog2
(h5pset-external dcpl *EXTERNAL* 0 +H5F-UNLIMITED+)
(h5dcreate2 file *DATASET* +H5T-STD-I32LE+ space
+H5P-DEFAULT+ dcpl +H5P-DEFAULT+))))
(h5dwrite dset +H5T-NATIVE-INT+ +H5S-ALL+ space +H5P-DEFAULT+ wdata)
(h5ex:close-handles (list dset dcpl space)))
(h5ex:close-handles (list file fapl))))
(let* ((fapl (h5pcreate +H5P-FILE-ACCESS+))
(file (prog2 (h5pset-fclose-degree fapl :H5F-CLOSE-STRONG)
(h5fopen *FILE* +H5F-ACC-RDONLY+ fapl))))
(unwind-protect
(let* ((dset (h5dopen2 file *DATASET* +H5P-DEFAULT+))
(dcpl (h5dget-create-plist dset)))
(h5pget-external dcpl 0 *NAME-BUF-SIZE* name +NULL+ +NULL+)
(setf (cffi:mem-aref name :char (1- *NAME-BUF-SIZE*)) 0)
(format t "~a is stored in file: ~a~%" *DATASET*
(cffi:foreign-string-to-lisp name))
(h5dread dset +H5T-NATIVE-INT+ +H5S-ALL+ +H5S-ALL+ +H5P-DEFAULT+
rdata)
(format t "~a:~%" *DATASET*)
(dotimes (i *DIM0*)
(format t " [")
(dotimes (j *DIM1*)
(format t " ~3d" (cffi:mem-aref rdata :int
(h5ex:pos2D *DIM1* i j))))
(format t "]~%"))
(h5ex:close-handles (list dcpl dset)))
(h5ex:close-handles (list file fapl)))))
|
cdda989ece08a94390276170f1248580440843bace4c0786225ce1fb8b3184e9 | bennn/dissertation | core.rkt | #lang racket/base
(provide
(all-defined-out))
;; -----------------------------------------------------------------------------
(require
"untyped.rkt")
;; =============================================================================
(define QuadName? symbol?)
(define QuadAttrKey? symbol?)
(define (QuadAttrValue? x)
(or (flonum? x) (index? x) (string? x) (symbol? x) (boolean? x) (quad? x) (QuadAttrs? x) (QuadList? x) (exact-integer? x)))
;; QuadAttr could be a list, but that would take twice as many cons cells.
;; try the economical approach.
(define (QuadAttr? x)
(and (pair? x)
(QuadAttrKey? (car x))
(QuadAttrValue? (cdr x))))
(define (QuadAttrs? x)
(and (list? x)
(andmap QuadAttr? x)))
(define quad-attrs? QuadAttrs?)
(define (QuadListItem? x)
(or (string? x)
(quad? x)))
(define (QuadList? x)
(and (list? x)
(andmap QuadListItem? x)))
;; funky implementation
(define (quad? x)
(and (pair? x)
(let ((a (car x))
(b (cdr x)))
(and (QuadName? a)
(pair? b)
(let ((aa (car b))
(bb (cdr b)))
(and (QuadAttrs? aa)
(QuadList? bb)))))))
;; quad wants to be generic
;; if it's a function, it must impose a type on its output value
;; whereas if it's syntax, it can avoid demanding or imposing any typing
(define-syntax-rule (quad name attrs items)
(list* name attrs items))
(define GroupQuadListItem? quad?)
(define (GroupQuadList? x)
(and (list? x)
(andmap GroupQuadListItem? x)))
(define Font-Name? string?)
(define (Font-Size? x)
(and (flonum? x) (< 0 x)))
(define (Font-Weight? x)
(or (eq? x 'normal)
(eq? x 'bold)
(eq? x 'light)))
(define (Font-Style? x)
(or (eq? x 'normal)
(eq? x 'italic)
(eq? x 'slant)))
Index is arguably the stricter type for ,
;; but in practice it's annoying because doing math with Indexes
;; often leads to non-Index values.
(define (Breakpoint? x)
(and (exact-integer? x) (<= 0 x)))
(define (listof-quad? x)
(and (list? x)
(andmap quad? x)))
| null | https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/dissertation/scrbl/jfp-2019/benchmarks/quadT/base/core.rkt | racket | -----------------------------------------------------------------------------
=============================================================================
QuadAttr could be a list, but that would take twice as many cons cells.
try the economical approach.
funky implementation
quad wants to be generic
if it's a function, it must impose a type on its output value
whereas if it's syntax, it can avoid demanding or imposing any typing
but in practice it's annoying because doing math with Indexes
often leads to non-Index values. | #lang racket/base
(provide
(all-defined-out))
(require
"untyped.rkt")
(define QuadName? symbol?)
(define QuadAttrKey? symbol?)
(define (QuadAttrValue? x)
(or (flonum? x) (index? x) (string? x) (symbol? x) (boolean? x) (quad? x) (QuadAttrs? x) (QuadList? x) (exact-integer? x)))
(define (QuadAttr? x)
(and (pair? x)
(QuadAttrKey? (car x))
(QuadAttrValue? (cdr x))))
(define (QuadAttrs? x)
(and (list? x)
(andmap QuadAttr? x)))
(define quad-attrs? QuadAttrs?)
(define (QuadListItem? x)
(or (string? x)
(quad? x)))
(define (QuadList? x)
(and (list? x)
(andmap QuadListItem? x)))
(define (quad? x)
(and (pair? x)
(let ((a (car x))
(b (cdr x)))
(and (QuadName? a)
(pair? b)
(let ((aa (car b))
(bb (cdr b)))
(and (QuadAttrs? aa)
(QuadList? bb)))))))
(define-syntax-rule (quad name attrs items)
(list* name attrs items))
(define GroupQuadListItem? quad?)
(define (GroupQuadList? x)
(and (list? x)
(andmap GroupQuadListItem? x)))
(define Font-Name? string?)
(define (Font-Size? x)
(and (flonum? x) (< 0 x)))
(define (Font-Weight? x)
(or (eq? x 'normal)
(eq? x 'bold)
(eq? x 'light)))
(define (Font-Style? x)
(or (eq? x 'normal)
(eq? x 'italic)
(eq? x 'slant)))
Index is arguably the stricter type for ,
(define (Breakpoint? x)
(and (exact-integer? x) (<= 0 x)))
(define (listof-quad? x)
(and (list? x)
(andmap quad? x)))
|
c1143b816c5f3e079431c71aa1f726dcda2e0a5f681398d32d24316b63c5a394 | cartazio/tlaps | toolbox_msg.mli |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
val print_warning : string -> unit;;
(* Send a "type:warning" message to the toolbox.
Displays the message in a dialog box.
*)
val print_error : string -> string -> unit;;
(* [print_error msg url]
Send a "type:error" message to the toolbox.
Displays the message in a dialog box along with the (clickable) URL.
*)
val print_obligationsnumber : int -> unit;;
(* Send a "type:obligationsnumber" message to the toolbox. *)
val print_obligation :
id : int ->
loc : Loc.locus ->
status : string ->
fp : string option ->
prover : string option ->
meth : string option ->
reason : string option ->
already : bool option ->
obl : string option ->
unit
;;
(* Send a "type:obligation" message to the toolbox. *)
| null | https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/toolbox_msg.mli | ocaml | Send a "type:warning" message to the toolbox.
Displays the message in a dialog box.
[print_error msg url]
Send a "type:error" message to the toolbox.
Displays the message in a dialog box along with the (clickable) URL.
Send a "type:obligationsnumber" message to the toolbox.
Send a "type:obligation" message to the toolbox. |
* Copyright ( C ) 2011 INRIA and Microsoft Corporation
* Copyright (C) 2011 INRIA and Microsoft Corporation
*)
val print_warning : string -> unit;;
val print_error : string -> string -> unit;;
val print_obligationsnumber : int -> unit;;
val print_obligation :
id : int ->
loc : Loc.locus ->
status : string ->
fp : string option ->
prover : string option ->
meth : string option ->
reason : string option ->
already : bool option ->
obl : string option ->
unit
;;
|
78eea31cce913c3dde571dd2446ea13701b71957a439bf360427aeabc8d8f6b0 | AdaCore/why3 | diffmap.ml | (********************************************************************)
(* *)
The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
(* *)
(* This software is distributed under the terms of the GNU Lesser *)
General Public License version 2.1 , with the special exception
(* on linking described in file LICENSE. *)
(* *)
(********************************************************************)
exception Duplicate
module type S = sig
module M : Extmap.S
type key = M.key
type 'a t
val empty: unit -> 'a t
val create: 'a M.t -> 'a t
val union: 'a t -> 'a M.t -> 'a t
val get: 'a t -> 'a M.t
end
module MakeOfMap (M: Extmap.S) = struct
module M = M
type key = M.key
type 'a diff =
| Madd of 'a M.t * 'a t
| Msub of 'a M.t * 'a t
| Mmap of 'a M.t
and 'a t = { mutable diff : 'a diff }
let empty () = { diff = Mmap M.empty }
let create m = { diff = Mmap m }
let rec get x =
match x.diff with
| Madd (d,y) ->
let my = get y in
let mx = M.union (fun _ _ _ -> raise Duplicate) my d in
y.diff <- Msub (d, x);
x.diff <- Mmap mx;
mx
| Msub (d,y) ->
let my = get y in
let mx = M.set_diff my d in
y.diff <- Madd (d, x);
x.diff <- Mmap mx;
mx
| Mmap mx -> mx
let union x d =
if M.is_empty d then x
else
let mx = get x in
let my = M.union (fun _ _ _ -> raise Duplicate) mx d in
let y = { diff = Mmap my } in
x.diff <- Msub (d, y);
y
end
module type OrderedType = Map.OrderedType
module Make (Ord: OrderedType) = MakeOfMap(Extmap.Make(Ord))
| null | https://raw.githubusercontent.com/AdaCore/why3/4441127004d53cf2cb0f722fed4a930ccf040ee4/src/util/diffmap.ml | ocaml | ******************************************************************
This software is distributed under the terms of the GNU Lesser
on linking described in file LICENSE.
****************************************************************** | The Why3 Verification Platform / The Why3 Development Team
Copyright 2010 - 2022 -- Inria - CNRS - Paris - Saclay University
General Public License version 2.1 , with the special exception
exception Duplicate
module type S = sig
module M : Extmap.S
type key = M.key
type 'a t
val empty: unit -> 'a t
val create: 'a M.t -> 'a t
val union: 'a t -> 'a M.t -> 'a t
val get: 'a t -> 'a M.t
end
module MakeOfMap (M: Extmap.S) = struct
module M = M
type key = M.key
type 'a diff =
| Madd of 'a M.t * 'a t
| Msub of 'a M.t * 'a t
| Mmap of 'a M.t
and 'a t = { mutable diff : 'a diff }
let empty () = { diff = Mmap M.empty }
let create m = { diff = Mmap m }
let rec get x =
match x.diff with
| Madd (d,y) ->
let my = get y in
let mx = M.union (fun _ _ _ -> raise Duplicate) my d in
y.diff <- Msub (d, x);
x.diff <- Mmap mx;
mx
| Msub (d,y) ->
let my = get y in
let mx = M.set_diff my d in
y.diff <- Madd (d, x);
x.diff <- Mmap mx;
mx
| Mmap mx -> mx
let union x d =
if M.is_empty d then x
else
let mx = get x in
let my = M.union (fun _ _ _ -> raise Duplicate) mx d in
let y = { diff = Mmap my } in
x.diff <- Msub (d, y);
y
end
module type OrderedType = Map.OrderedType
module Make (Ord: OrderedType) = MakeOfMap(Extmap.Make(Ord))
|
ee8ce83bb1dae7732df21fb89ecf530239eab5edfecc692aa86b395368a10af0 | NorfairKing/easyspec | CodeUtils.hs | # LANGUAGE FlexibleContexts #
module EasySpec.Discover.CodeUtils where
import Import hiding (Alt)
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.Syntax
import EasySpec.Discover.Types
{-# ANN module "HLint: ignore Use const" #-}
{-# ANN module "HLint: ignore Use record patterns" #-}
{-# ANN module "HLint: ignore Avoid lambda" #-}
{-# ANN module "HLint: ignore Collapse lambdas" #-}
getTyVars :: Type t -> [Name t]
getTyVars =
foldType
(\_ _ _ -> id)
(\_ -> (++))
(\_ _ -> concat)
(\_ -> id)
(\_ -> id)
(\_ -> (++))
(\_ -> (: []))
(\_ _ -> [])
(\_ -> id)
(\_ v1 _ v2 -> v1 ++ v2)
(\_ vs _ -> vs)
(\_ _ -> [])
(\_ -> (++))
(\_ _ -> [])
(\_ _ _ -> id)
(\_ _ -> [])
(\_ _ _ -> [])
getPatSymbols :: Pat l -> [QName l]
getPatSymbols =
foldPat
(\_ _ -> []) -- Don't count variables
-- TODO maybe we should count variables?
(\_ _ _ -> [])
(\_ _ _ -> []) -- Don't count n + k patterns
(\_ b1 qn b2 -> b1 ++ [qn] ++ b2)
(\_ qn bs -> qn : concat bs)
(\_ _ bs -> concat bs)
(\_ bs -> concat bs)
(\_ b -> b)
(\_ qn pfs -> qn : concatMap pfpv pfs)
(\_ _ b -> b) -- Don't count renamings (@)
(\_ -> [])
(\_ b -> b)
(\_ b _ -> b) -- Don't go into types
(\_ e b -> getExpSymbols e ++ b)
(\_ rps -> concatMap getRPatSymbols rps)
(\_ _ _ mb bs -> fromMaybe [] mb ++ concat bs)
(\_ _ _ mb -> fromMaybe [] mb)
(\_ _ -> [])
(\_ b -> b)
(\_ rpats -> concatMap getRPatSymbols rpats)
(\_ _ _ -> [])
(\_ b -> b)
where
pfpv :: PatField l -> [QName l]
pfpv (PFieldPat _ qn p) = qn : getPatSymbols p
pfpv (PFieldPun _ qn) = [qn]
pfpv (PFieldWildcard _) = []
getRPatSymbols :: RPat l -> [QName l]
getRPatSymbols = undefined
getQNameSymbols :: QName l -> [Name l]
getQNameSymbols (Qual _ _ n) = [n]
getQNameSymbols (UnQual _ n) = [n]
getQNameSymbols (Special l sc) -- This is kind-of cheating but I'll allow it here.
= [Ident l $ prettyPrintOneLine sc]
getQOpSymbols :: QOp l -> [QName l]
Do n't count variables , TODO see above TODO
getQOpSymbols (QConOp _ qn) = [qn]
getBindsSymbols :: Binds l -> [QName l]
getBindsSymbols (BDecls _ ds) = concatMap getDeclSymbols ds
getBindsSymbols (IPBinds _ ipbs) =
concat [getExpSymbols e | IPBind _ _ e <- ipbs]
getDeclSymbols :: Decl l -> [QName l]
getDeclSymbols d =
case d of
FunBind _ ms -> concatMap getMatchSymbols ms
PatBind _ p1 rhs mbs ->
getPatSymbols p1 ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
PatSyn _ p1 p2 _ -> getPatSymbols p1 ++ getPatSymbols p2 -- what about patSynDirection?
_ -> []
getMatchSymbols :: Match l -> [QName l]
TODO do something with the LHS ?
=
concatMap getPatSymbols ps ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
TODO do something with the LHS ?
=
getPatSymbols p1 ++
concatMap getPatSymbols ps ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
getRhsSymbols :: Rhs l -> [QName l]
getRhsSymbols (UnGuardedRhs _ e) = getExpSymbols e
getRhsSymbols (GuardedRhss _ grhss) = concatMap getGuardedRhsSymbols grhss
getGuardedRhsSymbols :: GuardedRhs l -> [QName l]
getGuardedRhsSymbols (GuardedRhs _ stmts e) =
concatMap getStmtSymbols stmts ++ getExpSymbols e
getAltSymbols :: Alt l -> [QName l]
getAltSymbols (Alt _ p rhs mbs) =
getPatSymbols p ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
getStmtSymbols :: Stmt l -> [QName l]
getStmtSymbols (Generator _ p e) = getPatSymbols p ++ getExpSymbols e
getStmtSymbols (Qualifier _ e) = getExpSymbols e
getStmtSymbols (LetStmt _ bs) = getBindsSymbols bs
getStmtSymbols (RecStmt _ stmts) = concatMap getStmtSymbols stmts
getFieldUpdateSymbols :: FieldUpdate l -> [QName l]
getFieldUpdateSymbols = undefined
getQualStmtSymbols :: QualStmt l -> [QName l]
getQualStmtSymbols = undefined
getExpSymbols :: Exp l -> [QName l]
getExpSymbols =
foldExp
Do n't count variables , TODO see above TODO
(\_ _ -> [])
(\_ _ -> []) -- Don't count variables see above
(\_ qn -> [qn])
(\_ _ -> [])
(\_ b1 qo b2 -> b1 ++ getQOpSymbols qo ++ b2)
(\_ -> (++))
(\_ -> id)
(\_ ps b -> concatMap getPatSymbols ps ++ b)
(\_ bs b -> getBindsSymbols bs ++ b)
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ grhss -> concatMap getGuardedRhsSymbols grhss)
(\_ b as -> b ++ concatMap getAltSymbols as)
(\_ stmts -> concatMap getStmtSymbols stmts)
(\_ stmts -> concatMap getStmtSymbols stmts)
(\_ _ bs -> concat bs)
(\_ _ mbs -> concat $ catMaybes mbs)
(\_ bs -> concat bs)
(\_ bs -> concat bs)
(\_ b -> b)
(\_ b qo -> b ++ getQOpSymbols qo)
(\_ qo b -> getQOpSymbols qo ++ b)
(\_ qn fus -> qn : concatMap getFieldUpdateSymbols fus)
(\_ b fus -> b ++ concatMap getFieldUpdateSymbols fus)
(\_ b -> b)
(\_ -> (++))
(\_ -> (++))
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ -> (++))
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ b qstms -> b ++ concatMap getQualStmtSymbols qstms)
(\_ b qstmss -> b ++ concatMap (concatMap getQualStmtSymbols) qstmss)
(\_ b qstmss -> b ++ concatMap (concatMap getQualStmtSymbols) qstmss)
(\_ b _ -> b) -- Don't count type symbols
(\_ _ -> [])
(\_ _ -> [])
(\_ _ -> [])
(\_ _ -> [])
(\_ _ _ -> [])
(\_ _ -> []) -- Don't count type symbols
(\_ _ _ mb bs -> fromMaybe [] mb ++ concat bs)
(\_ _ _ mb -> fromMaybe [] mb)
(\_ _ -> [])
(\_ b -> b)
(\_ bs -> concat bs)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ _ _ _ b -> b)
(\_ p b -> getPatSymbols p ++ b)
(\_ -> (++))
(\_ -> (++))
(\_ -> (++))
(\_ -> (++))
(\_ as -> concatMap getAltSymbols as)
(\_ -> [])
foldPat ::
(l -> Name l -> b)
-> (l -> Sign l -> Literal l -> b)
-> (l -> Name l -> Integer -> b)
-> (l -> b -> QName l -> b -> b)
-> (l -> QName l -> [b] -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> [b] -> b)
-> (l -> b -> b)
-> (l -> QName l -> [PatField l] -> b)
-> (l -> Name l -> b -> b)
-> (l -> b)
-> (l -> b -> b)
-> (l -> b -> Type l -> b)
-> (l -> Exp l -> b -> b)
-> (l -> [RPat l] -> b)
-> (l -> XName l -> [PXAttr l] -> Maybe b -> [b] -> b)
-> (l -> XName l -> [PXAttr l] -> Maybe b -> b)
-> (l -> String -> b)
-> (l -> b -> b)
-> (l -> [RPat l] -> b)
-> (l -> String -> String -> b)
-> (l -> b -> b)
-> Pat l
-> b
foldPat f01 f02 f03 f04 f05 f06 f07 f08 f09 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 =
go
where
go (PVar l n) = f01 l n
go (PLit l sn lt) = f02 l sn lt
go (PNPlusK l n int) = f03 l n int
go (PInfixApp l b1 qn b2) = f04 l (go b1) qn (go b2)
go (PApp l qn bs) = f05 l qn (map go bs)
go (PTuple l bxd bs) = f06 l bxd (map go bs)
go (PList l bs) = f07 l (map go bs)
go (PParen l b) = f08 l (go b)
go (PRec l qn patfs) = f09 l qn patfs
go (PAsPat l n b) = f10 l n (go b)
go (PWildCard l) = f11 l
go (PIrrPat l b) = f12 l (go b)
go (PatTypeSig l b t) = f13 l (go b) t
go (PViewPat l e b) = f14 l e (go b)
go (PRPat l rpats) = f15 l rpats
go (PXTag l xn pxattrs mb bs) = f16 l xn pxattrs (go <$> mb) (map go bs)
go (PXETag l xn pxattrs mb) = f17 l xn pxattrs (go <$> mb)
go (PXPcdata l s) = f18 l s
go (PXPatTag l b) = f19 l (go b)
go (PXRPats l rpats) = f20 l rpats
go (PQuasiQuote l s1 s2) = f21 l s1 s2
go (PBangPat l b) = f22 l (go b)
foldRPatVars :: RPat l -> b
foldRPatVars = undefined
foldType ::
(l -> Maybe [TyVarBind l] -> Maybe (Context l) -> b -> b)
-> (l -> b -> b -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> b -> b)
-> (l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> Name l -> b)
-> (l -> QName l -> b)
-> (l -> b -> b)
-> (l -> b -> QName l -> b -> b)
-> (l -> b -> Kind l -> b)
-> (l -> Promoted l -> b)
-> (l -> b -> b -> b)
-> (l -> Splice l -> b)
-> (l -> BangType l -> Unpackedness l -> b -> b)
-> (l -> Maybe (Name l) -> b)
-> (l -> String -> String -> b)
-> Type l
-> b
foldType ffa ff ft fl fpa fa fv fc fp fi fk fpr fe fspl fbng fwc fqq = go
where
go (TyForall l mtvbs btc t) = ffa l mtvbs btc (go t)
go (TyFun l t1 t2) = ff l (go t1) (go t2)
go (TyTuple l b ts) = ft l b (map go ts)
go (TyList l lt) = fl l (go lt)
go (TyParArray l lt) = fpa l (go lt)
go (TyApp l t1 t2) = fa l (go t1) (go t2)
go (TyVar l n) = fv l n
go (TyCon l qn) = fc l qn
go (TyParen l t) = fp l (go t)
go (TyInfix l t1 qn t2) = fi l (go t1) qn (go t2)
go (TyKind l t k) = fk l (go t) k
go (TyPromoted l p) = fpr l p
go (TyEquals l t1 t2) = fe l (go t1) (go t2)
go (TySplice l spl) = fspl l spl
go (TyBang l bt up t) = fbng l bt up (go t)
go (TyWildCard l mn) = fwc l mn
go (TyQuasiQuote l s1 s2) = fqq l s1 s2
mentionsEq :: EasyQName -> EasyEq -> Bool
mentionsEq n (EasyEq e1 e2) = mentions n e1 || mentions n e2
mentions :: Eq l => QName l -> Exp l -> Bool
mentions n e = occurrences n e > 0
occurrencesEq :: EasyQName -> EasyEq -> Int
occurrencesEq n (EasyEq e1 e2) = occurrences n e1 + occurrences n e2
occurrences :: Eq l => QName l -> Exp l -> Int
occurrences n =
foldExp
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ b1 _ b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b -> b)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ _ -> 0)
(\_ b _ -> b)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ _ bs -> sum bs)
(\_ _ mbs -> sum $ catMaybes mbs)
(\_ bs -> sum bs)
(\_ bs -> sum bs)
(\_ b -> b)
(\_ b _ -> b)
(\_ _ b -> b)
(\_ qn _ -> q qn)
(\_ b _ -> b)
(\_ b -> b)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ qn -> q qn)
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ _ _ -> 0)
(\_ _ -> 0)
(\_ _ _ mb bs -> fromMaybe 0 mb + sum bs)
(\_ _ _ mb -> fromMaybe 0 mb)
(\_ _ -> 0)
(\_ b -> b)
(\_ bs -> sum bs)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ _ _ _ b -> b)
(\_ _ b -> b)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ _ -> 0)
(\_ -> 0)
where
q qn =
if qn == n
then 1
else 0
foldExp ::
(l -> QName l -> b)
-> (l -> String -> b)
-> (l -> IPName l -> b)
-> (l -> QName l -> b)
-> (l -> Literal l -> b)
-> (l -> b -> QOp l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b)
-> (l -> [Pat l] -> b -> b)
-> (l -> Binds l -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> [GuardedRhs l] -> b)
-> (l -> b -> [Alt l] -> b)
-> (l -> [Stmt l] -> b)
-> (l -> [Stmt l] -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> Boxed -> [Maybe b] -> b)
-> (l -> [b] -> b)
-> (l -> [b] -> b)
-> (l -> b -> b)
-> (l -> b -> QOp l -> b)
-> (l -> QOp l -> b -> b)
-> (l -> QName l -> [FieldUpdate l] -> b)
-> (l -> b -> [FieldUpdate l] -> b)
-> (l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> b -> [QualStmt l] -> b)
-> (l -> b -> [[QualStmt l]] -> b)
-> (l -> b -> [[QualStmt l]] -> b)
-> (l -> b -> Type l -> b)
-> (l -> QName l -> b)
-> (l -> QName l -> b)
-> (l -> Bracket l -> b)
-> (l -> Splice l -> b)
-> (l -> String -> String -> b)
-> (l -> Type l -> b)
-> (l -> XName l -> [XAttr l] -> Maybe b -> [b] -> b)
-> (l -> XName l -> [XAttr l] -> Maybe b -> b)
-> (l -> String -> b)
-> (l -> b -> b)
-> (l -> [b] -> b)
-> (l -> String -> b -> b)
-> (l -> String -> b -> b)
-> (l -> String -> (Int, Int) -> (Int, Int) -> b -> b)
-> (l -> Pat l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> [Alt l] -> b)
-> (l -> b)
-> Exp l
-> b
foldExp ff1 ff2 ff3 ff4 ff5 ff6 ff7 ff8 ff9 ff10 ff11 ff12 ff13 ff14 ff15 ff16 ff17 ff18 ff19 ff20 ff21 ff22 ff23 ff24 ff25 ff26 ff27 ff28 ff29 ff30 ff31 ff32 ff33 ff34 ff35 ff36 ff37 ff38 ff39 ff40 ff41 ff42 ff43 ff44 ff45 ff46 ff47 ff48 ff49 ff50 ff51 ff52 ff53 ff54 ff55 =
go
where
go (Var l qn) = ff1 l qn
go (OverloadedLabel l s) = ff2 l s
go (IPVar l ipn) = ff3 l ipn
go (Con l qn) = ff4 l qn
go (Lit l lit) = ff5 l lit
go (InfixApp l b1 qop b2) = ff6 l (go b1) qop (go b2)
go (App l b1 b2) = ff7 l (go b1) (go b2)
go (NegApp l b) = ff8 l (go b)
go (Lambda l pats b) = ff9 l pats (go b)
go (Let l bnds b) = ff10 l bnds (go b)
go (If l b1 b2 b3) = ff11 l (go b1) (go b2) (go b3)
go (MultiIf l grhs) = ff12 l grhs
go (Case l b as) = ff13 l (go b) as
go (Do l stmts) = ff14 l stmts
go (MDo l stmts) = ff15 l stmts
go (Tuple l bd bs) = ff16 l bd (map go bs)
go (TupleSection l bxd mbs) = ff17 l bxd (map (fmap go) mbs)
go (List l bs) = ff18 l (map go bs)
go (ParArray l bs) = ff19 l (map go bs)
go (Paren l b) = ff20 l (go b)
go (LeftSection l b qop) = ff21 l (go b) qop
go (RightSection l qop b) = ff22 l qop (go b)
go (RecConstr l qn fos) = ff23 l qn fos
go (RecUpdate l b fos) = ff24 l (go b) fos
go (EnumFrom l b) = ff25 l (go b)
go (EnumFromTo l b1 b2) = ff26 l (go b1) (go b2)
go (EnumFromThen l b1 b2) = ff27 l (go b1) (go b2)
go (EnumFromThenTo l b1 b2 b3) = ff28 l (go b1) (go b2) (go b3)
go (ParArrayFromTo l b1 b2) = ff29 l (go b1) (go b2)
go (ParArrayFromThenTo l b1 b2 b3) = ff30 l (go b1) (go b2) (go b3)
go (ListComp l b qstms) = ff31 l (go b) qstms
go (ParComp l b qstmss) = ff32 l (go b) qstmss
go (ParArrayComp l b qstmss) = ff33 l (go b) qstmss
go (ExpTypeSig l b ts) = ff34 l (go b) ts
go (VarQuote l qn) = ff35 l qn
go (TypQuote l qn) = ff36 l qn
go (BracketExp l braq) = ff37 l braq
go (SpliceExp l splice) = ff38 l splice
go (QuasiQuote l s s2) = ff39 l s s2
go (TypeApp l t) = ff40 l t
go (XTag l xnam xas mb bs) = ff41 l xnam xas (go <$> mb) (map go bs)
go (XETag l xnam xas mb) = ff42 l xnam xas (go <$> mb)
go (XPcdata l s) = ff43 l s
go (XExpTag l b) = ff44 l (go b)
go (XChildTag l bs) = ff45 l (map go bs)
go (CorePragma l s b) = ff46 l s (go b)
go (SCCPragma l s b) = ff47 l s (go b)
go (GenPragma l s t1 t2 b) = ff48 l s t1 t2 (go b)
go (Proc l pat b) = ff49 l pat (go b)
go (LeftArrApp l b1 b2) = ff50 l (go b1) (go b2)
go (RightArrApp l b1 b2) = ff51 l (go b1) (go b2)
go (LeftArrHighApp l b1 b2) = ff52 l (go b1) (go b2)
go (RightArrHighApp l b1 b2) = ff53 l (go b1) (go b2)
go (LCase l as) = ff54 l as
go (ExprHole l) = ff55 l
prettyPrintOneLine :: Pretty a => a -> String
prettyPrintOneLine =
prettyPrintStyleMode (style {mode = OneLineMode}) defaultMode
| null | https://raw.githubusercontent.com/NorfairKing/easyspec/b038b45a375cc0bed2b00c255b508bc06419c986/easyspec/src/EasySpec/Discover/CodeUtils.hs | haskell | # ANN module "HLint: ignore Use const" #
# ANN module "HLint: ignore Use record patterns" #
# ANN module "HLint: ignore Avoid lambda" #
# ANN module "HLint: ignore Collapse lambdas" #
Don't count variables
TODO maybe we should count variables?
Don't count n + k patterns
Don't count renamings (@)
Don't go into types
This is kind-of cheating but I'll allow it here.
what about patSynDirection?
Don't count variables see above
Don't count type symbols
Don't count type symbols | # LANGUAGE FlexibleContexts #
module EasySpec.Discover.CodeUtils where
import Import hiding (Alt)
import Language.Haskell.Exts.Pretty
import Language.Haskell.Exts.Syntax
import EasySpec.Discover.Types
getTyVars :: Type t -> [Name t]
getTyVars =
foldType
(\_ _ _ -> id)
(\_ -> (++))
(\_ _ -> concat)
(\_ -> id)
(\_ -> id)
(\_ -> (++))
(\_ -> (: []))
(\_ _ -> [])
(\_ -> id)
(\_ v1 _ v2 -> v1 ++ v2)
(\_ vs _ -> vs)
(\_ _ -> [])
(\_ -> (++))
(\_ _ -> [])
(\_ _ _ -> id)
(\_ _ -> [])
(\_ _ _ -> [])
getPatSymbols :: Pat l -> [QName l]
getPatSymbols =
foldPat
(\_ _ _ -> [])
(\_ b1 qn b2 -> b1 ++ [qn] ++ b2)
(\_ qn bs -> qn : concat bs)
(\_ _ bs -> concat bs)
(\_ bs -> concat bs)
(\_ b -> b)
(\_ qn pfs -> qn : concatMap pfpv pfs)
(\_ -> [])
(\_ b -> b)
(\_ e b -> getExpSymbols e ++ b)
(\_ rps -> concatMap getRPatSymbols rps)
(\_ _ _ mb bs -> fromMaybe [] mb ++ concat bs)
(\_ _ _ mb -> fromMaybe [] mb)
(\_ _ -> [])
(\_ b -> b)
(\_ rpats -> concatMap getRPatSymbols rpats)
(\_ _ _ -> [])
(\_ b -> b)
where
pfpv :: PatField l -> [QName l]
pfpv (PFieldPat _ qn p) = qn : getPatSymbols p
pfpv (PFieldPun _ qn) = [qn]
pfpv (PFieldWildcard _) = []
getRPatSymbols :: RPat l -> [QName l]
getRPatSymbols = undefined
getQNameSymbols :: QName l -> [Name l]
getQNameSymbols (Qual _ _ n) = [n]
getQNameSymbols (UnQual _ n) = [n]
= [Ident l $ prettyPrintOneLine sc]
getQOpSymbols :: QOp l -> [QName l]
Do n't count variables , TODO see above TODO
getQOpSymbols (QConOp _ qn) = [qn]
getBindsSymbols :: Binds l -> [QName l]
getBindsSymbols (BDecls _ ds) = concatMap getDeclSymbols ds
getBindsSymbols (IPBinds _ ipbs) =
concat [getExpSymbols e | IPBind _ _ e <- ipbs]
getDeclSymbols :: Decl l -> [QName l]
getDeclSymbols d =
case d of
FunBind _ ms -> concatMap getMatchSymbols ms
PatBind _ p1 rhs mbs ->
getPatSymbols p1 ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
_ -> []
getMatchSymbols :: Match l -> [QName l]
TODO do something with the LHS ?
=
concatMap getPatSymbols ps ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
TODO do something with the LHS ?
=
getPatSymbols p1 ++
concatMap getPatSymbols ps ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
getRhsSymbols :: Rhs l -> [QName l]
getRhsSymbols (UnGuardedRhs _ e) = getExpSymbols e
getRhsSymbols (GuardedRhss _ grhss) = concatMap getGuardedRhsSymbols grhss
getGuardedRhsSymbols :: GuardedRhs l -> [QName l]
getGuardedRhsSymbols (GuardedRhs _ stmts e) =
concatMap getStmtSymbols stmts ++ getExpSymbols e
getAltSymbols :: Alt l -> [QName l]
getAltSymbols (Alt _ p rhs mbs) =
getPatSymbols p ++
getRhsSymbols rhs ++ fromMaybe [] (getBindsSymbols <$> mbs)
getStmtSymbols :: Stmt l -> [QName l]
getStmtSymbols (Generator _ p e) = getPatSymbols p ++ getExpSymbols e
getStmtSymbols (Qualifier _ e) = getExpSymbols e
getStmtSymbols (LetStmt _ bs) = getBindsSymbols bs
getStmtSymbols (RecStmt _ stmts) = concatMap getStmtSymbols stmts
getFieldUpdateSymbols :: FieldUpdate l -> [QName l]
getFieldUpdateSymbols = undefined
getQualStmtSymbols :: QualStmt l -> [QName l]
getQualStmtSymbols = undefined
getExpSymbols :: Exp l -> [QName l]
getExpSymbols =
foldExp
Do n't count variables , TODO see above TODO
(\_ _ -> [])
(\_ qn -> [qn])
(\_ _ -> [])
(\_ b1 qo b2 -> b1 ++ getQOpSymbols qo ++ b2)
(\_ -> (++))
(\_ -> id)
(\_ ps b -> concatMap getPatSymbols ps ++ b)
(\_ bs b -> getBindsSymbols bs ++ b)
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ grhss -> concatMap getGuardedRhsSymbols grhss)
(\_ b as -> b ++ concatMap getAltSymbols as)
(\_ stmts -> concatMap getStmtSymbols stmts)
(\_ stmts -> concatMap getStmtSymbols stmts)
(\_ _ bs -> concat bs)
(\_ _ mbs -> concat $ catMaybes mbs)
(\_ bs -> concat bs)
(\_ bs -> concat bs)
(\_ b -> b)
(\_ b qo -> b ++ getQOpSymbols qo)
(\_ qo b -> getQOpSymbols qo ++ b)
(\_ qn fus -> qn : concatMap getFieldUpdateSymbols fus)
(\_ b fus -> b ++ concatMap getFieldUpdateSymbols fus)
(\_ b -> b)
(\_ -> (++))
(\_ -> (++))
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ -> (++))
(\_ b1 b2 b3 -> b1 ++ b2 ++ b3)
(\_ b qstms -> b ++ concatMap getQualStmtSymbols qstms)
(\_ b qstmss -> b ++ concatMap (concatMap getQualStmtSymbols) qstmss)
(\_ b qstmss -> b ++ concatMap (concatMap getQualStmtSymbols) qstmss)
(\_ _ -> [])
(\_ _ -> [])
(\_ _ -> [])
(\_ _ -> [])
(\_ _ _ -> [])
(\_ _ _ mb bs -> fromMaybe [] mb ++ concat bs)
(\_ _ _ mb -> fromMaybe [] mb)
(\_ _ -> [])
(\_ b -> b)
(\_ bs -> concat bs)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ _ _ _ b -> b)
(\_ p b -> getPatSymbols p ++ b)
(\_ -> (++))
(\_ -> (++))
(\_ -> (++))
(\_ -> (++))
(\_ as -> concatMap getAltSymbols as)
(\_ -> [])
foldPat ::
(l -> Name l -> b)
-> (l -> Sign l -> Literal l -> b)
-> (l -> Name l -> Integer -> b)
-> (l -> b -> QName l -> b -> b)
-> (l -> QName l -> [b] -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> [b] -> b)
-> (l -> b -> b)
-> (l -> QName l -> [PatField l] -> b)
-> (l -> Name l -> b -> b)
-> (l -> b)
-> (l -> b -> b)
-> (l -> b -> Type l -> b)
-> (l -> Exp l -> b -> b)
-> (l -> [RPat l] -> b)
-> (l -> XName l -> [PXAttr l] -> Maybe b -> [b] -> b)
-> (l -> XName l -> [PXAttr l] -> Maybe b -> b)
-> (l -> String -> b)
-> (l -> b -> b)
-> (l -> [RPat l] -> b)
-> (l -> String -> String -> b)
-> (l -> b -> b)
-> Pat l
-> b
foldPat f01 f02 f03 f04 f05 f06 f07 f08 f09 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 =
go
where
go (PVar l n) = f01 l n
go (PLit l sn lt) = f02 l sn lt
go (PNPlusK l n int) = f03 l n int
go (PInfixApp l b1 qn b2) = f04 l (go b1) qn (go b2)
go (PApp l qn bs) = f05 l qn (map go bs)
go (PTuple l bxd bs) = f06 l bxd (map go bs)
go (PList l bs) = f07 l (map go bs)
go (PParen l b) = f08 l (go b)
go (PRec l qn patfs) = f09 l qn patfs
go (PAsPat l n b) = f10 l n (go b)
go (PWildCard l) = f11 l
go (PIrrPat l b) = f12 l (go b)
go (PatTypeSig l b t) = f13 l (go b) t
go (PViewPat l e b) = f14 l e (go b)
go (PRPat l rpats) = f15 l rpats
go (PXTag l xn pxattrs mb bs) = f16 l xn pxattrs (go <$> mb) (map go bs)
go (PXETag l xn pxattrs mb) = f17 l xn pxattrs (go <$> mb)
go (PXPcdata l s) = f18 l s
go (PXPatTag l b) = f19 l (go b)
go (PXRPats l rpats) = f20 l rpats
go (PQuasiQuote l s1 s2) = f21 l s1 s2
go (PBangPat l b) = f22 l (go b)
foldRPatVars :: RPat l -> b
foldRPatVars = undefined
foldType ::
(l -> Maybe [TyVarBind l] -> Maybe (Context l) -> b -> b)
-> (l -> b -> b -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> b -> b)
-> (l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> Name l -> b)
-> (l -> QName l -> b)
-> (l -> b -> b)
-> (l -> b -> QName l -> b -> b)
-> (l -> b -> Kind l -> b)
-> (l -> Promoted l -> b)
-> (l -> b -> b -> b)
-> (l -> Splice l -> b)
-> (l -> BangType l -> Unpackedness l -> b -> b)
-> (l -> Maybe (Name l) -> b)
-> (l -> String -> String -> b)
-> Type l
-> b
foldType ffa ff ft fl fpa fa fv fc fp fi fk fpr fe fspl fbng fwc fqq = go
where
go (TyForall l mtvbs btc t) = ffa l mtvbs btc (go t)
go (TyFun l t1 t2) = ff l (go t1) (go t2)
go (TyTuple l b ts) = ft l b (map go ts)
go (TyList l lt) = fl l (go lt)
go (TyParArray l lt) = fpa l (go lt)
go (TyApp l t1 t2) = fa l (go t1) (go t2)
go (TyVar l n) = fv l n
go (TyCon l qn) = fc l qn
go (TyParen l t) = fp l (go t)
go (TyInfix l t1 qn t2) = fi l (go t1) qn (go t2)
go (TyKind l t k) = fk l (go t) k
go (TyPromoted l p) = fpr l p
go (TyEquals l t1 t2) = fe l (go t1) (go t2)
go (TySplice l spl) = fspl l spl
go (TyBang l bt up t) = fbng l bt up (go t)
go (TyWildCard l mn) = fwc l mn
go (TyQuasiQuote l s1 s2) = fqq l s1 s2
mentionsEq :: EasyQName -> EasyEq -> Bool
mentionsEq n (EasyEq e1 e2) = mentions n e1 || mentions n e2
mentions :: Eq l => QName l -> Exp l -> Bool
mentions n e = occurrences n e > 0
occurrencesEq :: EasyQName -> EasyEq -> Int
occurrencesEq n (EasyEq e1 e2) = occurrences n e1 + occurrences n e2
occurrences :: Eq l => QName l -> Exp l -> Int
occurrences n =
foldExp
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ b1 _ b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b -> b)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ _ -> 0)
(\_ b _ -> b)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ _ bs -> sum bs)
(\_ _ mbs -> sum $ catMaybes mbs)
(\_ bs -> sum bs)
(\_ bs -> sum bs)
(\_ b -> b)
(\_ b _ -> b)
(\_ _ b -> b)
(\_ qn _ -> q qn)
(\_ b _ -> b)
(\_ b -> b)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 b3 -> b1 + b2 + b3)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ b _ -> b)
(\_ qn -> q qn)
(\_ qn -> q qn)
(\_ _ -> 0)
(\_ _ -> 0)
(\_ _ _ -> 0)
(\_ _ -> 0)
(\_ _ _ mb bs -> fromMaybe 0 mb + sum bs)
(\_ _ _ mb -> fromMaybe 0 mb)
(\_ _ -> 0)
(\_ b -> b)
(\_ bs -> sum bs)
(\_ _ b -> b)
(\_ _ b -> b)
(\_ _ _ _ b -> b)
(\_ _ b -> b)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ b1 b2 -> b1 + b2)
(\_ _ -> 0)
(\_ -> 0)
where
q qn =
if qn == n
then 1
else 0
foldExp ::
(l -> QName l -> b)
-> (l -> String -> b)
-> (l -> IPName l -> b)
-> (l -> QName l -> b)
-> (l -> Literal l -> b)
-> (l -> b -> QOp l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b)
-> (l -> [Pat l] -> b -> b)
-> (l -> Binds l -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> [GuardedRhs l] -> b)
-> (l -> b -> [Alt l] -> b)
-> (l -> [Stmt l] -> b)
-> (l -> [Stmt l] -> b)
-> (l -> Boxed -> [b] -> b)
-> (l -> Boxed -> [Maybe b] -> b)
-> (l -> [b] -> b)
-> (l -> [b] -> b)
-> (l -> b -> b)
-> (l -> b -> QOp l -> b)
-> (l -> QOp l -> b -> b)
-> (l -> QName l -> [FieldUpdate l] -> b)
-> (l -> b -> [FieldUpdate l] -> b)
-> (l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b -> b)
-> (l -> b -> [QualStmt l] -> b)
-> (l -> b -> [[QualStmt l]] -> b)
-> (l -> b -> [[QualStmt l]] -> b)
-> (l -> b -> Type l -> b)
-> (l -> QName l -> b)
-> (l -> QName l -> b)
-> (l -> Bracket l -> b)
-> (l -> Splice l -> b)
-> (l -> String -> String -> b)
-> (l -> Type l -> b)
-> (l -> XName l -> [XAttr l] -> Maybe b -> [b] -> b)
-> (l -> XName l -> [XAttr l] -> Maybe b -> b)
-> (l -> String -> b)
-> (l -> b -> b)
-> (l -> [b] -> b)
-> (l -> String -> b -> b)
-> (l -> String -> b -> b)
-> (l -> String -> (Int, Int) -> (Int, Int) -> b -> b)
-> (l -> Pat l -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> b -> b -> b)
-> (l -> [Alt l] -> b)
-> (l -> b)
-> Exp l
-> b
foldExp ff1 ff2 ff3 ff4 ff5 ff6 ff7 ff8 ff9 ff10 ff11 ff12 ff13 ff14 ff15 ff16 ff17 ff18 ff19 ff20 ff21 ff22 ff23 ff24 ff25 ff26 ff27 ff28 ff29 ff30 ff31 ff32 ff33 ff34 ff35 ff36 ff37 ff38 ff39 ff40 ff41 ff42 ff43 ff44 ff45 ff46 ff47 ff48 ff49 ff50 ff51 ff52 ff53 ff54 ff55 =
go
where
go (Var l qn) = ff1 l qn
go (OverloadedLabel l s) = ff2 l s
go (IPVar l ipn) = ff3 l ipn
go (Con l qn) = ff4 l qn
go (Lit l lit) = ff5 l lit
go (InfixApp l b1 qop b2) = ff6 l (go b1) qop (go b2)
go (App l b1 b2) = ff7 l (go b1) (go b2)
go (NegApp l b) = ff8 l (go b)
go (Lambda l pats b) = ff9 l pats (go b)
go (Let l bnds b) = ff10 l bnds (go b)
go (If l b1 b2 b3) = ff11 l (go b1) (go b2) (go b3)
go (MultiIf l grhs) = ff12 l grhs
go (Case l b as) = ff13 l (go b) as
go (Do l stmts) = ff14 l stmts
go (MDo l stmts) = ff15 l stmts
go (Tuple l bd bs) = ff16 l bd (map go bs)
go (TupleSection l bxd mbs) = ff17 l bxd (map (fmap go) mbs)
go (List l bs) = ff18 l (map go bs)
go (ParArray l bs) = ff19 l (map go bs)
go (Paren l b) = ff20 l (go b)
go (LeftSection l b qop) = ff21 l (go b) qop
go (RightSection l qop b) = ff22 l qop (go b)
go (RecConstr l qn fos) = ff23 l qn fos
go (RecUpdate l b fos) = ff24 l (go b) fos
go (EnumFrom l b) = ff25 l (go b)
go (EnumFromTo l b1 b2) = ff26 l (go b1) (go b2)
go (EnumFromThen l b1 b2) = ff27 l (go b1) (go b2)
go (EnumFromThenTo l b1 b2 b3) = ff28 l (go b1) (go b2) (go b3)
go (ParArrayFromTo l b1 b2) = ff29 l (go b1) (go b2)
go (ParArrayFromThenTo l b1 b2 b3) = ff30 l (go b1) (go b2) (go b3)
go (ListComp l b qstms) = ff31 l (go b) qstms
go (ParComp l b qstmss) = ff32 l (go b) qstmss
go (ParArrayComp l b qstmss) = ff33 l (go b) qstmss
go (ExpTypeSig l b ts) = ff34 l (go b) ts
go (VarQuote l qn) = ff35 l qn
go (TypQuote l qn) = ff36 l qn
go (BracketExp l braq) = ff37 l braq
go (SpliceExp l splice) = ff38 l splice
go (QuasiQuote l s s2) = ff39 l s s2
go (TypeApp l t) = ff40 l t
go (XTag l xnam xas mb bs) = ff41 l xnam xas (go <$> mb) (map go bs)
go (XETag l xnam xas mb) = ff42 l xnam xas (go <$> mb)
go (XPcdata l s) = ff43 l s
go (XExpTag l b) = ff44 l (go b)
go (XChildTag l bs) = ff45 l (map go bs)
go (CorePragma l s b) = ff46 l s (go b)
go (SCCPragma l s b) = ff47 l s (go b)
go (GenPragma l s t1 t2 b) = ff48 l s t1 t2 (go b)
go (Proc l pat b) = ff49 l pat (go b)
go (LeftArrApp l b1 b2) = ff50 l (go b1) (go b2)
go (RightArrApp l b1 b2) = ff51 l (go b1) (go b2)
go (LeftArrHighApp l b1 b2) = ff52 l (go b1) (go b2)
go (RightArrHighApp l b1 b2) = ff53 l (go b1) (go b2)
go (LCase l as) = ff54 l as
go (ExprHole l) = ff55 l
prettyPrintOneLine :: Pretty a => a -> String
prettyPrintOneLine =
prettyPrintStyleMode (style {mode = OneLineMode}) defaultMode
|
5a66bb585c91b4569fe75f6a4a0d0a8cb736a618611bcb4c393f73bcb18549b3 | rtoy/ansi-cl-tests | lognot.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Sep 9 06:16:20 2003
;;;; Contains: Tests of LOGNOT
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
;;; Error tests
(deftest lognot.error.1
(check-type-error #'lognot #'integerp)
nil)
(deftest lognot.error.2
(signals-error (lognot) program-error)
t)
(deftest lognot.error.3
(signals-error (lognot 0 0) program-error)
t)
;;; Non-error tests
(deftest lognot.1
(lognot 0)
-1)
(deftest lognot.2
(lognot -1)
0)
(deftest lognot.3
(lognot 123)
-124)
(deftest lognot.4
(loop for x = (random-from-interval (ash 1 (random 200)))
for z = (lognot x)
repeat 1000
unless (and (if (>= x 0) (< z 0) (>= z 0))
(loop for i from 1 to 210
always (if (not (logbitp i x))
(logbitp i z)
(not (logbitp i z)))))
collect (list x z))
nil)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/lognot.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of LOGNOT
Error tests
Non-error tests | Author :
Created : Tue Sep 9 06:16:20 2003
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(deftest lognot.error.1
(check-type-error #'lognot #'integerp)
nil)
(deftest lognot.error.2
(signals-error (lognot) program-error)
t)
(deftest lognot.error.3
(signals-error (lognot 0 0) program-error)
t)
(deftest lognot.1
(lognot 0)
-1)
(deftest lognot.2
(lognot -1)
0)
(deftest lognot.3
(lognot 123)
-124)
(deftest lognot.4
(loop for x = (random-from-interval (ash 1 (random 200)))
for z = (lognot x)
repeat 1000
unless (and (if (>= x 0) (< z 0) (>= z 0))
(loop for i from 1 to 210
always (if (not (logbitp i x))
(logbitp i z)
(not (logbitp i z)))))
collect (list x z))
nil)
|
406f4822629356e98aed2840249c8fafd7f56b06adebae2b3769315cead7c86c | Shinmera/beamer | test.lisp | (in-package "test")
(use-package :cl+trial)
(define-shader-subject slide-subject (located-entity rotated-entity selectable)
()
(:default-initargs
:location (vec 400 300 0)))
(defmethod initialize-instance :after ((subject slide-subject) &key &allow-other-keys))
(define-slide welcome
(h "Welcome to Beamer")
(p "Paragraph!")
(items
"Something something"
"Well this is going to be a rather large list entry so hopefully it'll line wrap."
"Fart")
(c "(michael-rosen:click :nice)"))
(define-pool slide
:base :trial)
(define-asset (slide cube) mesh
(make-cube 100))
(Define-asset (slide cat) image
#p"cat.png")
(define-shader-subject cube (vertex-entity
textured-entity
colored-entity
slide-subject)
())
(define-handler (cube tick) (ev dt tt)
(incf (vx (rotation cube)) (* dt 0.1))
(incf (vy (rotation cube)) dt))
(define-slide editor
(p "Lisp Source:" :size 30 :margin (vec 20 0 0 0))
(define-shader-subject cube (vertex-entity
; textured-entity
; colored-entity
slide-subject)
())
(enter-instance 'cube
:location (vec 600 200 0)
:vertex-array (asset 'slide 'cube)
:texture (asset 'slide 'cat)
:color (vec 0.2 0.2 0.8))
(editor "test.lisp" :start 41 :end 52 :trim 2 :size 22 :language :lisp :margin (vec 0 20))
(p "Fragment Shader:" :size 30 :margin (vec 20 0 0 0))
(c (getf (effective-shaders 'cube) :fragment-shader) :size 22 :language :glsl))
| null | https://raw.githubusercontent.com/Shinmera/beamer/46be98df952f10cece64d1b73d4a3cd930c9bc15/test/test.lisp | lisp | textured-entity
colored-entity | (in-package "test")
(use-package :cl+trial)
(define-shader-subject slide-subject (located-entity rotated-entity selectable)
()
(:default-initargs
:location (vec 400 300 0)))
(defmethod initialize-instance :after ((subject slide-subject) &key &allow-other-keys))
(define-slide welcome
(h "Welcome to Beamer")
(p "Paragraph!")
(items
"Something something"
"Well this is going to be a rather large list entry so hopefully it'll line wrap."
"Fart")
(c "(michael-rosen:click :nice)"))
(define-pool slide
:base :trial)
(define-asset (slide cube) mesh
(make-cube 100))
(Define-asset (slide cat) image
#p"cat.png")
(define-shader-subject cube (vertex-entity
textured-entity
colored-entity
slide-subject)
())
(define-handler (cube tick) (ev dt tt)
(incf (vx (rotation cube)) (* dt 0.1))
(incf (vy (rotation cube)) dt))
(define-slide editor
(p "Lisp Source:" :size 30 :margin (vec 20 0 0 0))
(define-shader-subject cube (vertex-entity
slide-subject)
())
(enter-instance 'cube
:location (vec 600 200 0)
:vertex-array (asset 'slide 'cube)
:texture (asset 'slide 'cat)
:color (vec 0.2 0.2 0.8))
(editor "test.lisp" :start 41 :end 52 :trim 2 :size 22 :language :lisp :margin (vec 0 20))
(p "Fragment Shader:" :size 30 :margin (vec 20 0 0 0))
(c (getf (effective-shaders 'cube) :fragment-shader) :size 22 :language :glsl))
|
e829a9dfd2bdc3c9a46a1da7f9eecf18e23eea1bd4ffae43b5aa30cce1f277ae | brandur/redis-haskell | Core.hs | {-# LANGUAGE DeriveDataTypeable, FlexibleContexts #-}
module Database.Redis.Core where
import Control.Exception ( Exception(..), finally )
import Data.Convertible.Base ( ConvertSuccess, convertSuccess )
import Data.Convertible.Instances ( )
import Data.Typeable ( Typeable )
import Network ( HostName, PortID(..), PortNumber,
connectTo, withSocketsDo )
import System.IO ( BufferMode(..), Handle, Newline(..),
NewlineMode(..), hClose, hSetBuffering,
hSetNewlineMode )
import qualified Data.Text as T
-- ---------------------------------------------------------------------------
-- Types
--
-- | Provides a wrapper for a handle to a Redis server.
newtype Server = Server { handle :: Handle }
-- | Provides a type for a key parameter for Redis commands.
type RedisKey = T.Text
-- | Provides a type for a value parameter for Redis commands, where a value
-- parameter is any parameter that isn't a key.
type RedisParam = T.Text
| Converts some type to a @RedisKey@ using a @ConvertSuccess@ instance .
toKey :: ConvertSuccess a T.Text => a -> RedisKey
toKey = convertSuccess
| Converts some type to a @RedisParam@ using a @ConvertSuccess@ instance .
toParam :: ConvertSuccess a T.Text => a -> RedisParam
toParam = convertSuccess
-- | Convenience function for converting an @Int@ to RedisParam.
iToParam :: Int -> T.Text
iToParam = convertSuccess
-- | Data type representing a return value from a Redis command.
data RedisValue = RedisString T.Text
| RedisInteger Int
| RedisMulti [RedisValue]
| RedisNil
deriving (Eq, Show)
-- ---------------------------------------------------------------------------
-- Failure
--
data RedisError = ServerError T.Text
deriving (Show, Typeable)
instance Exception RedisError
-- ---------------------------------------------------------------------------
Connection
--
-- | Establishes a connection with the Redis server at the given host and
-- port.
connect :: HostName -> PortNumber -> IO Server
connect host port =
withSocketsDo $ do
h <- connectTo host (PortNumber port)
hSetNewlineMode h (NewlineMode CRLF CRLF)
hSetBuffering h NoBuffering
return $ Server h
-- | Disconnects a server handle.
disconnect :: Server -> IO ()
disconnect = hClose . handle
-- | Runs some action with a connection to the Redis server at the given host
-- and port.
withRedisConn :: HostName -> PortNumber -> (Server -> IO ()) -> IO ()
withRedisConn host port action = do
r <- connect host port
action r `finally` disconnect r
-- | Runs some action with a connection to the Redis server operation at
localhost on port 6379 ( this is the default Redis port ) .
withRedisConn' :: (Server -> IO ()) -> IO ()
withRedisConn' = withRedisConn "localhost" 6379
| null | https://raw.githubusercontent.com/brandur/redis-haskell/a346b4b7989a7b2d33b4c70962a23dfc5773f446/src/Database/Redis/Core.hs | haskell | # LANGUAGE DeriveDataTypeable, FlexibleContexts #
---------------------------------------------------------------------------
Types
| Provides a wrapper for a handle to a Redis server.
| Provides a type for a key parameter for Redis commands.
| Provides a type for a value parameter for Redis commands, where a value
parameter is any parameter that isn't a key.
| Convenience function for converting an @Int@ to RedisParam.
| Data type representing a return value from a Redis command.
---------------------------------------------------------------------------
Failure
---------------------------------------------------------------------------
| Establishes a connection with the Redis server at the given host and
port.
| Disconnects a server handle.
| Runs some action with a connection to the Redis server at the given host
and port.
| Runs some action with a connection to the Redis server operation at |
module Database.Redis.Core where
import Control.Exception ( Exception(..), finally )
import Data.Convertible.Base ( ConvertSuccess, convertSuccess )
import Data.Convertible.Instances ( )
import Data.Typeable ( Typeable )
import Network ( HostName, PortID(..), PortNumber,
connectTo, withSocketsDo )
import System.IO ( BufferMode(..), Handle, Newline(..),
NewlineMode(..), hClose, hSetBuffering,
hSetNewlineMode )
import qualified Data.Text as T
newtype Server = Server { handle :: Handle }
type RedisKey = T.Text
type RedisParam = T.Text
| Converts some type to a @RedisKey@ using a @ConvertSuccess@ instance .
toKey :: ConvertSuccess a T.Text => a -> RedisKey
toKey = convertSuccess
| Converts some type to a @RedisParam@ using a @ConvertSuccess@ instance .
toParam :: ConvertSuccess a T.Text => a -> RedisParam
toParam = convertSuccess
iToParam :: Int -> T.Text
iToParam = convertSuccess
data RedisValue = RedisString T.Text
| RedisInteger Int
| RedisMulti [RedisValue]
| RedisNil
deriving (Eq, Show)
data RedisError = ServerError T.Text
deriving (Show, Typeable)
instance Exception RedisError
Connection
connect :: HostName -> PortNumber -> IO Server
connect host port =
withSocketsDo $ do
h <- connectTo host (PortNumber port)
hSetNewlineMode h (NewlineMode CRLF CRLF)
hSetBuffering h NoBuffering
return $ Server h
disconnect :: Server -> IO ()
disconnect = hClose . handle
withRedisConn :: HostName -> PortNumber -> (Server -> IO ()) -> IO ()
withRedisConn host port action = do
r <- connect host port
action r `finally` disconnect r
localhost on port 6379 ( this is the default Redis port ) .
withRedisConn' :: (Server -> IO ()) -> IO ()
withRedisConn' = withRedisConn "localhost" 6379
|
bda8e684a74c7b521f6550b268c39c7f6d0b1b435d96a81ca114198a88b7dc7a | tmfg/mmtis-national-access-point | ytj.clj | (ns ote.integration.import.ytj
"YTJ (Finnish company register) API client."
(:require [clj-http.client :as http-client]
[taoensso.timbre :as log]
[clojure.walk :as walk]
[clj-time.format :as format]
[clj-time.core :as t]
[ote.components.http :as http]
[com.stuartsierra.component :as component]
[compojure.core :refer [routes GET]]
[ote.util.feature :as feature]))
(defn parse-iso8601-date [s]
(when (string? s)
(format/parse (:date format/formatters) s)))
(def http-get http-client/get) ;; redef'd to mock in test
(defn without-expired-items [ytj-map]
(let [now (t/now)
date-in-past? (fn [d]
(if (nil? d)
false
(t/before? d now)))
end-date-expired? (fn [m]
(let [ds (:endDate m)
d (when (string? ds)
(parse-iso8601-date ds))]
(date-in-past? d)))
walk-fn (fn [x]
(if (and (vector? x) (map? (first x)))
(filterv (complement end-date-expired?) x)
x))]
(walk/postwalk walk-fn ytj-map)))
(defn- compose-result [response]
(into
{:status (:status response)}
(-> response
:body
:results
first
(select-keys [:name :auxiliaryNames :businessId :addresses :contactDetails])
without-expired-items)))
(defn fetch-by-company-id [company-id]
(when (and (string? company-id) (re-matches #"[0-9-]{2,20}" company-id))
(let [url (str "=" company-id)
response (try
(http-get url {:accept :json
:as :json})
(catch clojure.lang.ExceptionInfo e
;; sadly clj-http wants to communicate status as exceptions
(-> e ex-data)))]
;(log/debug "ytj fetch: got response" (pr-str response))
(if (or (-> response :status (not= 200))
(-> response :body :totalResults str (not= "1")))
(log/debug "YTJ: all is not good, status=" (-> response :status (= 200)) " body=" (-> response :body pr-str)))
(compose-result response))))
(defrecord YTJFetch [config]
component/Lifecycle
(start [{http :http :as this}]
(assoc this ::stop
(when (feature/feature-enabled? config :open-ytj-integration)
require authentication because we do n't want to be an open proxy for PRH API ( and also there may be rate limits )
(http/publish! http {:authenticated? true}
(routes
(GET "/fetch/ytj" [company-id]
(let [r (fetch-by-company-id company-id)]
( println " YTJ : sending as transit : " ( pr - str r ) )
(http/transit-response r))))))))
(stop [{stop ::stop :as this}]
(when stop
(stop))
(dissoc this ::stop)))
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/clj/ote/integration/import/ytj.clj | clojure | redef'd to mock in test
sadly clj-http wants to communicate status as exceptions
(log/debug "ytj fetch: got response" (pr-str response)) | (ns ote.integration.import.ytj
"YTJ (Finnish company register) API client."
(:require [clj-http.client :as http-client]
[taoensso.timbre :as log]
[clojure.walk :as walk]
[clj-time.format :as format]
[clj-time.core :as t]
[ote.components.http :as http]
[com.stuartsierra.component :as component]
[compojure.core :refer [routes GET]]
[ote.util.feature :as feature]))
(defn parse-iso8601-date [s]
(when (string? s)
(format/parse (:date format/formatters) s)))
(defn without-expired-items [ytj-map]
(let [now (t/now)
date-in-past? (fn [d]
(if (nil? d)
false
(t/before? d now)))
end-date-expired? (fn [m]
(let [ds (:endDate m)
d (when (string? ds)
(parse-iso8601-date ds))]
(date-in-past? d)))
walk-fn (fn [x]
(if (and (vector? x) (map? (first x)))
(filterv (complement end-date-expired?) x)
x))]
(walk/postwalk walk-fn ytj-map)))
(defn- compose-result [response]
(into
{:status (:status response)}
(-> response
:body
:results
first
(select-keys [:name :auxiliaryNames :businessId :addresses :contactDetails])
without-expired-items)))
(defn fetch-by-company-id [company-id]
(when (and (string? company-id) (re-matches #"[0-9-]{2,20}" company-id))
(let [url (str "=" company-id)
response (try
(http-get url {:accept :json
:as :json})
(catch clojure.lang.ExceptionInfo e
(-> e ex-data)))]
(if (or (-> response :status (not= 200))
(-> response :body :totalResults str (not= "1")))
(log/debug "YTJ: all is not good, status=" (-> response :status (= 200)) " body=" (-> response :body pr-str)))
(compose-result response))))
(defrecord YTJFetch [config]
component/Lifecycle
(start [{http :http :as this}]
(assoc this ::stop
(when (feature/feature-enabled? config :open-ytj-integration)
require authentication because we do n't want to be an open proxy for PRH API ( and also there may be rate limits )
(http/publish! http {:authenticated? true}
(routes
(GET "/fetch/ytj" [company-id]
(let [r (fetch-by-company-id company-id)]
( println " YTJ : sending as transit : " ( pr - str r ) )
(http/transit-response r))))))))
(stop [{stop ::stop :as this}]
(when stop
(stop))
(dissoc this ::stop)))
|
cc42d20b4b206ce54820a1d44943fe2b957e17761cf765ac2ba872db34bcb0e1 | narkisr-deprecated/core | schedule.clj | (ns re-core.schedule
"Scheduled tasks"
(:require
[re-core.common :refer (get* resolve- import-logging)]
[chime :refer [chime-ch]]
[components.core :refer (Lifecyle)]
[clj-time.core :as t]
[clj-time.periodic :refer [periodic-seq]]
[clojure.core.async :as a :refer [<! close! go-loop]]))
(import-logging)
(defn schedule [f chimes args]
(go-loop []
(if-let [msg (<! chimes)]
(do (f args) (recur))
(info f "scheduled task stopped")
)))
(defn time-fn [unit]
(resolve- (symbol (str "clj-time.core/" (name unit)))))
(defn load-schedules
"Load all scheduled tasks"
[]
(doseq [[f m] (get* :scheduled) :let [{:keys [every args]} m]]
(let [[t unit] every]
(schedule (resolve- f) (chime-ch (periodic-seq (t/now) ((time-fn unit) t))) args))))
(defn schedules []
(map
(fn [[f {:keys [every args]}]]
(let [[t unit] every]
[(resolve- f) (chime-ch (periodic-seq (t/now) ((time-fn unit) t))) args])) (get* :scheduled)))
(defn close-and-flush
"See /#!topic/clojure-dev/HLWrb57JIjs"
[c]
(close! c)
(clojure.core.async/reduce (fn [_ _] nil) [] c))
(defrecord Schedule
[scs]
Lifecyle
(setup [this])
(start [this]
(info "Starting scheduled tasks")
(doseq [s scs] (apply schedule s)))
(stop [this]
(doseq [[_ c _] scs] (close-and-flush c))))
(defn instance []
(Schedule. (schedules)))
| null | https://raw.githubusercontent.com/narkisr-deprecated/core/85b4a768ef4b3a4eae86695bce36d270dd51dbae/src/re_core/schedule.clj | clojure | (ns re-core.schedule
"Scheduled tasks"
(:require
[re-core.common :refer (get* resolve- import-logging)]
[chime :refer [chime-ch]]
[components.core :refer (Lifecyle)]
[clj-time.core :as t]
[clj-time.periodic :refer [periodic-seq]]
[clojure.core.async :as a :refer [<! close! go-loop]]))
(import-logging)
(defn schedule [f chimes args]
(go-loop []
(if-let [msg (<! chimes)]
(do (f args) (recur))
(info f "scheduled task stopped")
)))
(defn time-fn [unit]
(resolve- (symbol (str "clj-time.core/" (name unit)))))
(defn load-schedules
"Load all scheduled tasks"
[]
(doseq [[f m] (get* :scheduled) :let [{:keys [every args]} m]]
(let [[t unit] every]
(schedule (resolve- f) (chime-ch (periodic-seq (t/now) ((time-fn unit) t))) args))))
(defn schedules []
(map
(fn [[f {:keys [every args]}]]
(let [[t unit] every]
[(resolve- f) (chime-ch (periodic-seq (t/now) ((time-fn unit) t))) args])) (get* :scheduled)))
(defn close-and-flush
"See /#!topic/clojure-dev/HLWrb57JIjs"
[c]
(close! c)
(clojure.core.async/reduce (fn [_ _] nil) [] c))
(defrecord Schedule
[scs]
Lifecyle
(setup [this])
(start [this]
(info "Starting scheduled tasks")
(doseq [s scs] (apply schedule s)))
(stop [this]
(doseq [[_ c _] scs] (close-and-flush c))))
(defn instance []
(Schedule. (schedules)))
| |
9ea00a1ae52ee85705e387e5ec434d37fd63a892d8f1e316af916186c4b24780 | appleshan/cl-http | distribution.lisp | -*- Mode : LISP ; Package : HTTP ; BASE : 10 ; Syntax : ANSI - Common - Lisp ; Default - Character - Style : ( : FIX : ROMAN : NORMAL);-*-
;;;
( c ) Copyright 1995 , 2003 ,
;;; All Rights Reserved.
;;;
(in-package :http)
;;;-------------------------------------------------------------------
;;;
;;; DISTRIBUTION FACILITY FOR CL-HTTP
;;;
#+Genera
(load #p"http:ai-lab;copyf")
(eval-when (:execute :load-toplevel :compile-toplevel)
(setf (logical-pathname-translations "http-dis")
`(("**;*.*" #+Genera"wilson:>http>**>*.*"
#+MCL"wilson:http:**:*.*"
#+LispWorks "/Volumes/wilson.csail.mit.edu/http/**/*.*")))
) ;close eval when
(defparameter *binary-pathname-extensions* '("class" "gif" "ico" "jpeg" "jpg" "au" "mpeg" "mpg" "png" "pdf" "tar" "gz"))
(defparameter *standard-extensions* `("lisp" "html" "htm" "text" "css" "txt" "xml" "ps" "cern-map" "mak" "ncsa-map"
"c" "script" "translations" "hqx"
,.*binary-pathname-extensions*))
(defparameter *distribution-directories* `("http-dis:client;"
"http-dis:clim;"
"http-dis:contrib;"
"http-dis:examples;"
"http-dis:proxy;"
"http-dis:server;"
"http-dis:smtp;"
"http-dis:w3p;"
"http-dis:w4;"
"http-dis:www;"
Ports
"http-dis:mcl;" "http-dis:acl;""http-dis:cmucl;"
"http-dis:lcl;" "http-dis:lispm;" "http-dis:lw;"
;; Modules
"http-dis:html-parser;" "http-dis:lambda-ir;"
;; Protocol Documumentation
#+ignore "http-dis:standards;"))
(defparameter *distribution-files* '("http-dis:-license-.text"
"http-dis:-release-notes-.text"
"http-dis:acl-read-me.text"
"http-dis:lcl-read-me.text"
"http-dis:lw-read-me.text"
"http-dis:mcl-read-me.text"))
;;;-------------------------------------------------------------------
;;;
;;; COPYING CODE
;;;
(defun %copy-file (pathname to-directory &optional (extensions :wild) (default-version :newest)
(report-stream *standard-output*))
(labels ((copy-a-file (from-pathname to-pathname &optional (mode :text)
(create-directories t) (report-stream *standard-output*))
#+Genera
(zl:copyf from-pathname to-pathname :create-directories create-directories :if-exists :new-version
:strip-styles t :report-stream report-stream
:element-type (ecase mode
(:text 'scl:string-char)
(:binary '(unsigned-byte 8))))
#-Genera
(copy-file from-pathname to-pathname :copy-mode mode
:create-directories create-directories :report-stream report-stream))
(extension-match-p (pathname)
(case extensions
(:wild t)
(t (member (pathname-type pathname) extensions :test #'equalp))))
(binary-p (pathname)
(member (pathname-type pathname) *binary-pathname-extensions* :test #'equalp))
(target-pathname (pathname to-directory)
(make-pathname :name (pathname-name pathname) :type (pathname-type pathname)
:version default-version :defaults to-directory))
(copy-text-file (pathname)
(copy-a-file pathname (target-pathname pathname to-directory) :text t report-stream))
(copy-binary-file (pathname)
(copy-a-file pathname (target-pathname pathname to-directory) :binary t report-stream)))
(declare (inline binary-p copy-text-file copy-binary-file extension-match-p))
(when (extension-match-p pathname)
(if (binary-p pathname)
(copy-binary-file pathname)
(copy-text-file pathname)))))
(defvar *undistributed-directories* (make-hash-table :test #'equalp))
(defun clear-undistributed-directories ()
(clrhash *undistributed-directories*))
(declaim (notinline pathname-directory-key))
;; This key generator may need to change across lisp implementations.
ANSI is vague on whether physical pathname need : unspecific when
;; no device is specified, whereas it is required for logical pathanmes.
(defun pathname-directory-key (pathname)
(let ((path (translated-pathname (pathname pathname))))
(make-pathname :host (or (pathname-host path) :unspecific)
:device (or (pathname-device path) :unspecific)
:directory (pathname-directory path)
:name :unspecific
:type :unspecific
:version :newest)))
(defun distribute-directory-p (pathname)
(let ((key (pathname-directory-key pathname)))
(declare (dynamic-extent key))
(not (gethash key *undistributed-directories*))))
(defun %define-undistributed-directories (pathnames)
(loop initially (clear-undistributed-directories)
for path in pathnames
for key = (pathname-directory-key path)
do (setf (gethash key *undistributed-directories*) t))
pathnames)
(defmacro define-undistributed-directories (&rest directories)
`(%define-undistributed-directories ',directories))
(define-undistributed-directories
"http-dis:contrib;janderson;xml-1998-02-27;"
"http-dis:contrib;janderson;xml-1999-05-03;"
"http-dis:contrib;janderson;xml-2000-05-27;"
"http-dis:contrib;janderson;xml;"
"http-dis;examples;twistdown-tree;java;old;"
Utilities
"http:html-parser;v9;"
"http:html-parser;v10;"
"http-dis:lispm;html-parser;dtd-compiler-3;"
"http-dis:lispm;html-parser;html-parser-9;"
"http-dis:lispm;html-parser;html-parser-10;"
"http-dis:lispm;lambda-ir;patch;lambda-ir-21;"
"http-dis:lispm;uri;"
"http-dis:lispm;urn;"
Core components
"http-dis:clim;patch;cl-http-clim-39;"
"http-dis:lispm;client;patch;http-client-substrate-1;"
"http-dis:lispm;client;patch;http-client-substrate-3;"
"http-dis:lispm;client;patch;http-base-client-49;"
"http-dis:lispm;client;patch;http-base-client-50;"
"http-dis:lispm;server;patch;cl-http-58;"
"http-dis:lispm;server;patch;cl-http-63;"
"http-dis:lispm;server;patch;cl-http-67;"
"http-dis:lispm;proxy;patch;http-proxy-4;"
"http-dis:lispm;proxy;patch;http-proxy-5;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-51;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-52;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-53;"
"http-dis:lispm;docs;patch;cl-http-doc-2;")
(defun %copy-directory (to-directory from-directory &optional (extensions :wild)
(default-version :newest) (report-stream *standard-output*))
(flet ((push-directory-level (directory pattern)
(make-pathname :host (pathname-host directory)
:device (pathname-device directory)
:directory (append (pathname-directory directory)
#+Genera (list (pathname-name pattern))
#-Genera (last (pathname-directory pattern)))))
(down-directory (directory)
(make-pathname :host (pathname-host directory)
:device (pathname-device directory)
:directory #+Genera (append (pathname-directory directory)
(list (pathname-name directory)))
#-Genera (pathname-directory directory)))
(directory-p (plist)
(getf plist :directory))
(extension-match-p (pathname)
(case extensions
(:wild t)
(t (member (pathname-type pathname) extensions :test #'equalp)))))
(when (distribute-directory-p from-directory)
(pathname-create-directory-if-needed to-directory)
(loop for pathname in (directory (make-pathname :name :wild :type :wild :version :newest
:version :newest :defaults from-directory)
:directories t
#+LispWorks :link-transparency #+LispWorks nil
#+MCL :files #+MCL t #+MCL :directory-pathnames #+MCL t)
do (cond ((pathname-directory-p pathname)
(%copy-directory (push-directory-level to-directory pathname)
(down-directory pathname)
extensions default-version report-stream))
((extension-match-p pathname)
(%copy-file pathname to-directory :wild default-version report-stream))
(t nil))))))
(defun copy-directory (to-directory from-directory &key (default-version :newest)
(extensions :wild)
(report-stream *standard-output*))
(flet ((directory-pathname (pathname version)
(let ((path (translated-pathname pathname)))
(make-pathname :host (pathname-host path)
:device (pathname-device path)
:directory (pathname-directory path)
:name :wild
:type :wild
:version version))))
(declare (inline translated-pathname))
(%copy-directory (directory-pathname to-directory :wild)
(directory-pathname from-directory default-version)
(or extensions :wild)
(or default-version :newest)
report-stream)))
;;;-------------------------------------------------------------------
;;;
CL - HTTP DISTRIBUTIONS
;;;
(defun copy-cl-http-distribution (target &key (extensions *standard-extensions*)
(default-version :newest)
(standard-line-break #+LispWorks :lf #+(or MCL Genera) :cr)
(report-stream *standard-output*))
(setq target (translated-pathname target))
(loop for directory in *distribution-directories*
for pathname = (translated-pathname directory)
for down-target = (make-pathname :host (pathname-host target)
:device (pathname-device target)
:directory (append (pathname-directory target)
(last (pathname-directory pathname))))
do (copy-directory down-target pathname
:extensions extensions
:default-version default-version
:report-stream report-stream))
(loop for file in *distribution-files*
for pathname = (translated-pathname file)
do (%copy-file pathname target extensions default-version report-stream))
(when standard-line-break
(standardize-line-breaks target standard-line-break report-stream))
target)
#+ignore
(http::copy-cl-http-distribution "CL-HTTP-HD1:cl-http-70-167-devo:")
#+ignore
(http::copy-cl-http-distribution "/volumes/CL-HTTP-HD1/cl-http/builds/cl-http-70-209a-devo/")
#+Genera
(cp:define-command
(com-write-cl-http-distribution
:command-table "User"
:provide-output-destination-keyword t)
((to '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "To Directory"))
(copy-cl-http-distribution to
:extensions *standard-extensions*
:default-version :newest
:report-stream *standard-output*))
#+Genera
(cp:define-command
(com-copy-http-directory
:command-table "User"
:provide-output-destination-keyword t)
((from '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "From Directory")
(to '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "To Directory"))
(copy-directory to from
:extensions *standard-extensions*
:default-version :newest
:report-stream *standard-output*))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lw/utilities/distribution.lisp | lisp | Package : HTTP ; BASE : 10 ; Syntax : ANSI - Common - Lisp ; Default - Character - Style : ( : FIX : ROMAN : NORMAL);-*-
All Rights Reserved.
-------------------------------------------------------------------
DISTRIBUTION FACILITY FOR CL-HTTP
close eval when
Modules
Protocol Documumentation
-------------------------------------------------------------------
COPYING CODE
This key generator may need to change across lisp implementations.
no device is specified, whereas it is required for logical pathanmes.
-------------------------------------------------------------------
|
( c ) Copyright 1995 , 2003 ,
(in-package :http)
#+Genera
(load #p"http:ai-lab;copyf")
(eval-when (:execute :load-toplevel :compile-toplevel)
(setf (logical-pathname-translations "http-dis")
`(("**;*.*" #+Genera"wilson:>http>**>*.*"
#+MCL"wilson:http:**:*.*"
#+LispWorks "/Volumes/wilson.csail.mit.edu/http/**/*.*")))
(defparameter *binary-pathname-extensions* '("class" "gif" "ico" "jpeg" "jpg" "au" "mpeg" "mpg" "png" "pdf" "tar" "gz"))
(defparameter *standard-extensions* `("lisp" "html" "htm" "text" "css" "txt" "xml" "ps" "cern-map" "mak" "ncsa-map"
"c" "script" "translations" "hqx"
,.*binary-pathname-extensions*))
(defparameter *distribution-directories* `("http-dis:client;"
"http-dis:clim;"
"http-dis:contrib;"
"http-dis:examples;"
"http-dis:proxy;"
"http-dis:server;"
"http-dis:smtp;"
"http-dis:w3p;"
"http-dis:w4;"
"http-dis:www;"
Ports
"http-dis:mcl;" "http-dis:acl;""http-dis:cmucl;"
"http-dis:lcl;" "http-dis:lispm;" "http-dis:lw;"
"http-dis:html-parser;" "http-dis:lambda-ir;"
#+ignore "http-dis:standards;"))
(defparameter *distribution-files* '("http-dis:-license-.text"
"http-dis:-release-notes-.text"
"http-dis:acl-read-me.text"
"http-dis:lcl-read-me.text"
"http-dis:lw-read-me.text"
"http-dis:mcl-read-me.text"))
(defun %copy-file (pathname to-directory &optional (extensions :wild) (default-version :newest)
(report-stream *standard-output*))
(labels ((copy-a-file (from-pathname to-pathname &optional (mode :text)
(create-directories t) (report-stream *standard-output*))
#+Genera
(zl:copyf from-pathname to-pathname :create-directories create-directories :if-exists :new-version
:strip-styles t :report-stream report-stream
:element-type (ecase mode
(:text 'scl:string-char)
(:binary '(unsigned-byte 8))))
#-Genera
(copy-file from-pathname to-pathname :copy-mode mode
:create-directories create-directories :report-stream report-stream))
(extension-match-p (pathname)
(case extensions
(:wild t)
(t (member (pathname-type pathname) extensions :test #'equalp))))
(binary-p (pathname)
(member (pathname-type pathname) *binary-pathname-extensions* :test #'equalp))
(target-pathname (pathname to-directory)
(make-pathname :name (pathname-name pathname) :type (pathname-type pathname)
:version default-version :defaults to-directory))
(copy-text-file (pathname)
(copy-a-file pathname (target-pathname pathname to-directory) :text t report-stream))
(copy-binary-file (pathname)
(copy-a-file pathname (target-pathname pathname to-directory) :binary t report-stream)))
(declare (inline binary-p copy-text-file copy-binary-file extension-match-p))
(when (extension-match-p pathname)
(if (binary-p pathname)
(copy-binary-file pathname)
(copy-text-file pathname)))))
(defvar *undistributed-directories* (make-hash-table :test #'equalp))
(defun clear-undistributed-directories ()
(clrhash *undistributed-directories*))
(declaim (notinline pathname-directory-key))
ANSI is vague on whether physical pathname need : unspecific when
(defun pathname-directory-key (pathname)
(let ((path (translated-pathname (pathname pathname))))
(make-pathname :host (or (pathname-host path) :unspecific)
:device (or (pathname-device path) :unspecific)
:directory (pathname-directory path)
:name :unspecific
:type :unspecific
:version :newest)))
(defun distribute-directory-p (pathname)
(let ((key (pathname-directory-key pathname)))
(declare (dynamic-extent key))
(not (gethash key *undistributed-directories*))))
(defun %define-undistributed-directories (pathnames)
(loop initially (clear-undistributed-directories)
for path in pathnames
for key = (pathname-directory-key path)
do (setf (gethash key *undistributed-directories*) t))
pathnames)
(defmacro define-undistributed-directories (&rest directories)
`(%define-undistributed-directories ',directories))
(define-undistributed-directories
"http-dis:contrib;janderson;xml-1998-02-27;"
"http-dis:contrib;janderson;xml-1999-05-03;"
"http-dis:contrib;janderson;xml-2000-05-27;"
"http-dis:contrib;janderson;xml;"
"http-dis;examples;twistdown-tree;java;old;"
Utilities
"http:html-parser;v9;"
"http:html-parser;v10;"
"http-dis:lispm;html-parser;dtd-compiler-3;"
"http-dis:lispm;html-parser;html-parser-9;"
"http-dis:lispm;html-parser;html-parser-10;"
"http-dis:lispm;lambda-ir;patch;lambda-ir-21;"
"http-dis:lispm;uri;"
"http-dis:lispm;urn;"
Core components
"http-dis:clim;patch;cl-http-clim-39;"
"http-dis:lispm;client;patch;http-client-substrate-1;"
"http-dis:lispm;client;patch;http-client-substrate-3;"
"http-dis:lispm;client;patch;http-base-client-49;"
"http-dis:lispm;client;patch;http-base-client-50;"
"http-dis:lispm;server;patch;cl-http-58;"
"http-dis:lispm;server;patch;cl-http-63;"
"http-dis:lispm;server;patch;cl-http-67;"
"http-dis:lispm;proxy;patch;http-proxy-4;"
"http-dis:lispm;proxy;patch;http-proxy-5;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-51;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-52;"
"http-dis:lispm;clim;old-ui;patch;cl-http-clim-53;"
"http-dis:lispm;docs;patch;cl-http-doc-2;")
(defun %copy-directory (to-directory from-directory &optional (extensions :wild)
(default-version :newest) (report-stream *standard-output*))
(flet ((push-directory-level (directory pattern)
(make-pathname :host (pathname-host directory)
:device (pathname-device directory)
:directory (append (pathname-directory directory)
#+Genera (list (pathname-name pattern))
#-Genera (last (pathname-directory pattern)))))
(down-directory (directory)
(make-pathname :host (pathname-host directory)
:device (pathname-device directory)
:directory #+Genera (append (pathname-directory directory)
(list (pathname-name directory)))
#-Genera (pathname-directory directory)))
(directory-p (plist)
(getf plist :directory))
(extension-match-p (pathname)
(case extensions
(:wild t)
(t (member (pathname-type pathname) extensions :test #'equalp)))))
(when (distribute-directory-p from-directory)
(pathname-create-directory-if-needed to-directory)
(loop for pathname in (directory (make-pathname :name :wild :type :wild :version :newest
:version :newest :defaults from-directory)
:directories t
#+LispWorks :link-transparency #+LispWorks nil
#+MCL :files #+MCL t #+MCL :directory-pathnames #+MCL t)
do (cond ((pathname-directory-p pathname)
(%copy-directory (push-directory-level to-directory pathname)
(down-directory pathname)
extensions default-version report-stream))
((extension-match-p pathname)
(%copy-file pathname to-directory :wild default-version report-stream))
(t nil))))))
(defun copy-directory (to-directory from-directory &key (default-version :newest)
(extensions :wild)
(report-stream *standard-output*))
(flet ((directory-pathname (pathname version)
(let ((path (translated-pathname pathname)))
(make-pathname :host (pathname-host path)
:device (pathname-device path)
:directory (pathname-directory path)
:name :wild
:type :wild
:version version))))
(declare (inline translated-pathname))
(%copy-directory (directory-pathname to-directory :wild)
(directory-pathname from-directory default-version)
(or extensions :wild)
(or default-version :newest)
report-stream)))
CL - HTTP DISTRIBUTIONS
(defun copy-cl-http-distribution (target &key (extensions *standard-extensions*)
(default-version :newest)
(standard-line-break #+LispWorks :lf #+(or MCL Genera) :cr)
(report-stream *standard-output*))
(setq target (translated-pathname target))
(loop for directory in *distribution-directories*
for pathname = (translated-pathname directory)
for down-target = (make-pathname :host (pathname-host target)
:device (pathname-device target)
:directory (append (pathname-directory target)
(last (pathname-directory pathname))))
do (copy-directory down-target pathname
:extensions extensions
:default-version default-version
:report-stream report-stream))
(loop for file in *distribution-files*
for pathname = (translated-pathname file)
do (%copy-file pathname target extensions default-version report-stream))
(when standard-line-break
(standardize-line-breaks target standard-line-break report-stream))
target)
#+ignore
(http::copy-cl-http-distribution "CL-HTTP-HD1:cl-http-70-167-devo:")
#+ignore
(http::copy-cl-http-distribution "/volumes/CL-HTTP-HD1/cl-http/builds/cl-http-70-209a-devo/")
#+Genera
(cp:define-command
(com-write-cl-http-distribution
:command-table "User"
:provide-output-destination-keyword t)
((to '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "To Directory"))
(copy-cl-http-distribution to
:extensions *standard-extensions*
:default-version :newest
:report-stream *standard-output*))
#+Genera
(cp:define-command
(com-copy-http-directory
:command-table "User"
:provide-output-destination-keyword t)
((from '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "From Directory")
(to '((fs:pathname) :default-name nil :default-type nil :default-version nil) :prompt "To Directory"))
(copy-directory to from
:extensions *standard-extensions*
:default-version :newest
:report-stream *standard-output*))
|
e19074bb430b2a7a913d1f5d1891c64b06b17e6d31135d24d9a2d69ccf57780e | semilin/layoup | zugyug.lisp |
(MAKE-LAYOUT :NAME "zugyug" :MATRIX
(APPLY #'KEY-MATRIX '("k,pbj;'chv" "yugsxoetrn" "q.wfziadlm"))
:SHIFT-MATRIX NIL :KEYBOARD NIL) | null | https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/zugyug.lisp | lisp |
(MAKE-LAYOUT :NAME "zugyug" :MATRIX
(APPLY #'KEY-MATRIX '("k,pbj;'chv" "yugsxoetrn" "q.wfziadlm"))
:SHIFT-MATRIX NIL :KEYBOARD NIL) | |
0a3bb07ad2996c8ac79511d40e7bad99f939da4b8c2d9640717a43c2f0d78fd4 | avsm/ocaml-orm-sqlite | list_tuple.ml | TYPE_CONV_PATH "List_tuple"
type x = {
foo: (int * char list) list;
bar: string
} with orm
open OUnit
open Test_utils
let x1 = {foo=[(1,['x';'y'])] ; bar="hello world" }
let x2 = {foo=[(2,[]); (3,['a';'b';'c']); (4,['a'])] ; bar="world hello" }
let x3 = {foo=[] ; bar="world hello" }
let name = "list_tuple.db"
let test_init () =
ignore(open_db x_init name);
ignore(open_db ~rm:false x_init name);
ignore(open_db ~rm:false x_init name)
let test_save () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x3
let test_update () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x2;
x_save db x1;
x_save db x2;
x_save db x3
let test_get () =
let db = open_db ~rm:false x_init name in
"3 x in db" @? (List.length (x_get db) = 3)
let test_save_get () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x3;
match x_get db with
|[a1;a2;a3] ->
"structural values equal" @? ( x1 = a1);
"physical values equal" @? ( x1 == a1);
"structural values equal" @? ( x2 = a2);
"physical values equal" @? ( x2 == a2);
"structural values equal" @? ( x3 = a3);
"physical values equal" @? ( x3 == a3)
|_ -> assert false
let suite = [
"list_tuple_init" >:: test_init;
"list_tuple_save" >:: test_save;
"list_tuple_update" >:: test_update;
"list_tuple_get" >:: test_get;
"list_tuple_save_get" >:: test_save_get;
]
| null | https://raw.githubusercontent.com/avsm/ocaml-orm-sqlite/0c41dee6e254abd75706edcb785f657bfe55d08b/lib_test/list_tuple.ml | ocaml | TYPE_CONV_PATH "List_tuple"
type x = {
foo: (int * char list) list;
bar: string
} with orm
open OUnit
open Test_utils
let x1 = {foo=[(1,['x';'y'])] ; bar="hello world" }
let x2 = {foo=[(2,[]); (3,['a';'b';'c']); (4,['a'])] ; bar="world hello" }
let x3 = {foo=[] ; bar="world hello" }
let name = "list_tuple.db"
let test_init () =
ignore(open_db x_init name);
ignore(open_db ~rm:false x_init name);
ignore(open_db ~rm:false x_init name)
let test_save () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x3
let test_update () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x2;
x_save db x1;
x_save db x2;
x_save db x3
let test_get () =
let db = open_db ~rm:false x_init name in
"3 x in db" @? (List.length (x_get db) = 3)
let test_save_get () =
let db = open_db x_init name in
x_save db x1;
x_save db x2;
x_save db x3;
match x_get db with
|[a1;a2;a3] ->
"structural values equal" @? ( x1 = a1);
"physical values equal" @? ( x1 == a1);
"structural values equal" @? ( x2 = a2);
"physical values equal" @? ( x2 == a2);
"structural values equal" @? ( x3 = a3);
"physical values equal" @? ( x3 == a3)
|_ -> assert false
let suite = [
"list_tuple_init" >:: test_init;
"list_tuple_save" >:: test_save;
"list_tuple_update" >:: test_update;
"list_tuple_get" >:: test_get;
"list_tuple_save_get" >:: test_save_get;
]
| |
c57a08ceb0cca0abaf494ea1b2bd442512a455046eb77565dea712c28c7194b8 | jumarko/clojure-experiments | mastering_clojure_macros.clj | (ns clojure-experiments.macros.mastering-clojure-macros
"Examples from the book Mastering Clojure Macros.")
Chapter 1 - Build a Solid Foundation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(read-string "(+ 1 2 3 4 5)")
(class (read-string "(+ 1 2 3 4 5)"))
(eval (read-string "(+ 1 2 3 4 5)"))
(class (eval (read-string "(+ 1 2 3 4 5)")))
;; we can now programatically replace addition with multiplication
(let [expression (read-string "(+ 1 2 3 4 5)")]
(cons (read-string "*")
(rest expression)))
#_(eval *1)
;; let's now use real data structures instead of string (and `read-string`)
(let [expression (quote (+ 1 2 3 4 5))]
(cons (quote *)
(rest expression)))
#_(eval *1)
;; finally simplifying using '
(let [expression '(+ 1 2 3 4 5)]
(cons '* (rest expression)))
#_(eval *1)
;; when macro
(defmacro my-when [test & body]
(list 'if test (cons 'do body)))
(my-when (= 2 (+ 1 1))
(print "you got")
(print " the touch!")
(println))
;; substituted it looks like this:
(list 'if
'(= 2 (+ 1 1))
(cons 'do
'((print "You got")
(print " the touch!") (println))))
;; my cond macro
(defmacro my-cond
[& clauses]
(when (seq clauses)
`(if ~(first clauses)
~(second clauses)
(my-cond ~@(drop 2 clauses)))))
(my-cond
(> 1 10) 10
(= 3 2) 5
(= 2 2) 1000
(> 10 2) 1000000)
;; expanded form
(if (> 1 10)
10
(if (= 3 2) 5 (if (= 2 2) 1000 (if (> 10 2) 1000000 nil))))
;; cond macro from the book
(defmacro book-cond [& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException. "cond requires even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
(book-cond
(> 1 10) 10
(= 3 2) 5
(= 2 2) 1000
(> 10 2) 1000000)
(macroexpand-1 '(when-falsy (= 1 2) (println "hi!")))
;=> (when (not (= 1 2)) (do (println "hi!")))
(macroexpand '(when-falsy (= 1 2) (println "hi!")))
;=> (if (not (= 1 2)) (do (do (println "hi!"))))
macroexpand works only when the inner macro is in the first position
;; macroexpand-all covers some cases inside macro too
(macroexpand '(if-let [x (range 10)]
(println "Computing...")
(when (< (first x) (second x))
(println "True."))))
;; expanded as:
(comment
(let*
[temp__5533__auto__ (range 10)]
(if
temp__5533__auto__
(clojure.core/let [x temp__5533__auto__] (println "Computing..."))
(when (< (first x) (second x)) (println "True."))))
)
(clojure.walk/macroexpand-all '(if-let [x (range 10)]
(println "Computing...")
(when (< (first x) (second x))
(println "True."))))
;; espanded as:
(comment
(let*
[temp__5533__auto__ (range 10)]
(if
temp__5533__auto__
(let* [x temp__5533__auto__] (println "Computing..."))
(if (< (first x) (second x)) (do (println "True."))))))
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/macros/mastering_clojure_macros.clj | clojure |
we can now programatically replace addition with multiplication
let's now use real data structures instead of string (and `read-string`)
finally simplifying using '
when macro
substituted it looks like this:
my cond macro
expanded form
cond macro from the book
=> (when (not (= 1 2)) (do (println "hi!")))
=> (if (not (= 1 2)) (do (do (println "hi!"))))
macroexpand-all covers some cases inside macro too
expanded as:
espanded as: | (ns clojure-experiments.macros.mastering-clojure-macros
"Examples from the book Mastering Clojure Macros.")
Chapter 1 - Build a Solid Foundation
(read-string "(+ 1 2 3 4 5)")
(class (read-string "(+ 1 2 3 4 5)"))
(eval (read-string "(+ 1 2 3 4 5)"))
(class (eval (read-string "(+ 1 2 3 4 5)")))
(let [expression (read-string "(+ 1 2 3 4 5)")]
(cons (read-string "*")
(rest expression)))
#_(eval *1)
(let [expression (quote (+ 1 2 3 4 5))]
(cons (quote *)
(rest expression)))
#_(eval *1)
(let [expression '(+ 1 2 3 4 5)]
(cons '* (rest expression)))
#_(eval *1)
(defmacro my-when [test & body]
(list 'if test (cons 'do body)))
(my-when (= 2 (+ 1 1))
(print "you got")
(print " the touch!")
(println))
(list 'if
'(= 2 (+ 1 1))
(cons 'do
'((print "You got")
(print " the touch!") (println))))
(defmacro my-cond
[& clauses]
(when (seq clauses)
`(if ~(first clauses)
~(second clauses)
(my-cond ~@(drop 2 clauses)))))
(my-cond
(> 1 10) 10
(= 3 2) 5
(= 2 2) 1000
(> 10 2) 1000000)
(if (> 1 10)
10
(if (= 3 2) 5 (if (= 2 2) 1000 (if (> 10 2) 1000000 nil))))
(defmacro book-cond [& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (IllegalArgumentException. "cond requires even number of forms")))
(cons 'clojure.core/cond (next (next clauses))))))
(book-cond
(> 1 10) 10
(= 3 2) 5
(= 2 2) 1000
(> 10 2) 1000000)
(macroexpand-1 '(when-falsy (= 1 2) (println "hi!")))
(macroexpand '(when-falsy (= 1 2) (println "hi!")))
macroexpand works only when the inner macro is in the first position
(macroexpand '(if-let [x (range 10)]
(println "Computing...")
(when (< (first x) (second x))
(println "True."))))
(comment
(let*
[temp__5533__auto__ (range 10)]
(if
temp__5533__auto__
(clojure.core/let [x temp__5533__auto__] (println "Computing..."))
(when (< (first x) (second x)) (println "True."))))
)
(clojure.walk/macroexpand-all '(if-let [x (range 10)]
(println "Computing...")
(when (< (first x) (second x))
(println "True."))))
(comment
(let*
[temp__5533__auto__ (range 10)]
(if
temp__5533__auto__
(let* [x temp__5533__auto__] (println "Computing..."))
(if (< (first x) (second x)) (do (println "True."))))))
|
96720516f3656fc944de4ea3ec745e6eaea20fcf24967108161723a0d601ee2c | stamourv/racket-benchmark | plot.rkt | #lang racket
(require "types.rkt" "bootstrap-ci.rkt")
(require plot/no-gui plot/utils math/statistics)
(provide render-benchmark-alts
current-benchmark-color-scheme
bright-color-scheme
pastel-color-scheme
black-white-color-scheme-short
black-white-color-scheme-medium-1
black-white-color-scheme-medium-2
black-white-color-scheme-long
benchmark-show-legend?)
TODO document those
(define bright-color-scheme
(cons '("red" "blue" "dark green" "Light Gray" "purple" "DimGray" "yellow")
'(solid)))
(define pastel-color-scheme
(cons '("Salmon" "DarkBlue" "Yellow Green" "DimGray" "MediumOrchid"
"Light Gray" "Gold")
'(solid)))
TODO automatically pick between those depending on n of bars
(define black-white-color-scheme-short
(cons '("white" "Dark Gray" "black")
'(solid)))
(define black-white-color-scheme-medium-1
(cons '("Dark Gray" "white" "gray" "black" "Light Gray")
'(solid)))
(define black-white-color-scheme-medium-2
(cons '("black" "white" "black" "black" "black")
'(bdiagonal-hatch solid horizontal-hatch solid fdiagonal-hatch)))
(define black-white-color-scheme-long
(cons '("Dim Gray" "black" "white" "black" "black" "black" "Dark Gray"
"black")
'(solid bdiagonal-hatch solid horizontal-hatch solid
fdiagonal-hatch solid vertical-hatch)))
(define current-benchmark-color-scheme (make-parameter pastel-color-scheme))
(define benchmark-show-legend? (make-parameter #t))
(struct bootstrapped-ci (name opts mean conf-lb conf-ub))
render - benchmark - alts : ( listof any / c ) ( listof benchmark - result ? )
;; -> renderer2d?
(define (render-benchmark-alts
norm-opts
brs
#:format-opts
[format-opts (lambda (opts) (apply ~a opts #:separator " "))]
#:normalize?
[normalize #t])
(define names (remove-duplicates (map benchmark-result-name brs)))
(define opts (remove-duplicates (map benchmark-result-opts brs)))
(define (norm-br name)
(define filtered-brs
(filter (lambda (br)
(and (equal? name (benchmark-result-name br))
(equal? norm-opts (benchmark-result-opts br))))
brs))
(if (null? filtered-brs)
(error (format
"Could not find standard benchmark: name ~a, opts ~a"
name
norm-opts))
(car filtered-brs)))
(define norm-brs
(make-immutable-hash
(map (lambda (n) (cons n (norm-br n))) names)))
(define (speedup-bootstrapped-ci norm-br br)
;; (define br/norm-br
;; (map /
;; (benchmark-result-trial-times br)
;; (benchmark-result-trial-times norm-br)))
;; TODO bootstrapping + confidence intervals doesn't work for baseline:
;; we end up computing confidence interval of the ratio X/X, which has
;; a clear dependency between num and den, so doesn't work
⊥ suggests shuffling X 's samples , to remove dependency , but that
;; doesn't work.
for now , using 1 standard dev on each side for error bars .
TODO investigate
;; (define bootstrapped-sample
;; (nonparametric2d-bootstrap
;; mean-quotient
;; (benchmark-result-trial-times br)
;; (benchmark-result-trial-times norm-br)))
(define name (benchmark-result-name br))
(define opts (benchmark-result-opts br))
(define mean-br ; scaling down mean by mean of baseline
(if normalize
(with-handlers ([exn:fail:contract:divide-by-zero? (λ (e) 0)])
(/ (mean (benchmark-result-trial-times br))
(mean (benchmark-result-trial-times norm-br))))
(mean (benchmark-result-trial-times br))))
(define stddev-br ; scaling down stddev by mean of baseline
(if normalize
(with-handlers ([exn:fail:contract:divide-by-zero? (λ (e) 0)])
(/ (stddev (benchmark-result-trial-times br))
(mean (benchmark-result-trial-times norm-br))))
(stddev (benchmark-result-trial-times br))))
;; New attempt at confidence intervals, using a straight formula instead of
's stuff .
(define margin-of-error
Z value for a 95 % confidence interval
(/ stddev-br
(sqrt (length (benchmark-result-trial-times br))))))
(log-message benchmark-logger 'info
(~a name " " opts
"; normalized mean = " (exact->inexact mean-br)
"; normalized stddev = " stddev-br)
#f)
(bootstrapped-ci
name
opts
;; TODO: is this the proper way to calculate mean?
mean-br
;; TODO not confidence intervals anymore, see above
( bootstrap - bca - conf mean br / norm - br bootstrapped - sample .025 )
( bootstrap - bca - conf mean br / norm - br bootstrapped - sample .975 )
TODO just stddevs , not standard
;; (+ mean-br stddev-br)
;; (- mean-br stddev-br)
(+ mean-br margin-of-error)
(- mean-br margin-of-error)))
(define normalized-benchmarks
(map
(lambda (br)
(speedup-bootstrapped-ci
(hash-ref norm-brs (benchmark-result-name br))
br))
brs))
(define (select-benchmarks opts)
(filter (lambda (br) (equal? opts (bootstrapped-ci-opts br)))
normalized-benchmarks))
(define num-alts (length opts))
(define alt-nums (for/list ([i (in-range 0 num-alts)]) i))
(define colors
(for/list ([i (in-range num-alts)]
[c (in-cycle (car (current-benchmark-color-scheme)))])
c))
(define styles
(for/list ([i (in-range num-alts)]
[c (in-cycle (cdr (current-benchmark-color-scheme)))])
c))
(define start-xs (linear-seq 0 (- num-alts 1) num-alts))
(define skip (+ num-alts 1))
(define bar-width (- (/ skip (+ num-alts 1)) (discrete-histogram-gap)))
(append-map
(lambda (o c s x)
(render-benchmark-alt
(format-opts o)
(select-benchmarks o)
c
s
x
skip
bar-width))
opts
colors
styles
start-xs))
;; render-benchmark-alt : string? benchmark-result? plot-color/c
;; plot-brush-style/c rational? (>=/c 0) (>/c 0)
- > ( listof renderer2d ? )
(define (render-benchmark-alt alt-name bcis color style start-x skip bar-width)
(define (data-point bci)
(vector (bootstrapped-ci-name bci) (bootstrapped-ci-mean bci)))
(define (data-error-bars bci i)
(let* ([conf-lb (bootstrapped-ci-conf-lb bci)]
[conf-ub (bootstrapped-ci-conf-ub bci)]
[conf-mean (bootstrapped-ci-mean bci)]
[conf-ht (- conf-ub conf-mean)]
[delta-to-mid-bar (/ (+ bar-width (discrete-histogram-gap)) 2)])
(error-bars (list (vector
(+ start-x (* skip i) delta-to-mid-bar)
conf-mean
conf-ht)))))
(cons
(if (benchmark-show-legend?)
(discrete-histogram (map data-point bcis)
#:skip skip
#:label alt-name
#:color color
#:style style
#:x-min start-x)
(discrete-histogram (map data-point bcis)
#:skip skip
;; no labels, that disables the legend
#:color color
#:style style
#:x-min start-x))
(map data-error-bars bcis (for/list ([i (in-range 0 (length bcis))]) i))))
(define (mean-quotient ys xs)
(mean (map / ys xs)))
| null | https://raw.githubusercontent.com/stamourv/racket-benchmark/de7e84539de23834508dba42e07859cf13bde20c/benchmark/plot.rkt | racket | -> renderer2d?
(define br/norm-br
(map /
(benchmark-result-trial-times br)
(benchmark-result-trial-times norm-br)))
TODO bootstrapping + confidence intervals doesn't work for baseline:
we end up computing confidence interval of the ratio X/X, which has
a clear dependency between num and den, so doesn't work
doesn't work.
(define bootstrapped-sample
(nonparametric2d-bootstrap
mean-quotient
(benchmark-result-trial-times br)
(benchmark-result-trial-times norm-br)))
scaling down mean by mean of baseline
scaling down stddev by mean of baseline
New attempt at confidence intervals, using a straight formula instead of
TODO: is this the proper way to calculate mean?
TODO not confidence intervals anymore, see above
(+ mean-br stddev-br)
(- mean-br stddev-br)
render-benchmark-alt : string? benchmark-result? plot-color/c
plot-brush-style/c rational? (>=/c 0) (>/c 0)
no labels, that disables the legend | #lang racket
(require "types.rkt" "bootstrap-ci.rkt")
(require plot/no-gui plot/utils math/statistics)
(provide render-benchmark-alts
current-benchmark-color-scheme
bright-color-scheme
pastel-color-scheme
black-white-color-scheme-short
black-white-color-scheme-medium-1
black-white-color-scheme-medium-2
black-white-color-scheme-long
benchmark-show-legend?)
TODO document those
(define bright-color-scheme
(cons '("red" "blue" "dark green" "Light Gray" "purple" "DimGray" "yellow")
'(solid)))
(define pastel-color-scheme
(cons '("Salmon" "DarkBlue" "Yellow Green" "DimGray" "MediumOrchid"
"Light Gray" "Gold")
'(solid)))
TODO automatically pick between those depending on n of bars
(define black-white-color-scheme-short
(cons '("white" "Dark Gray" "black")
'(solid)))
(define black-white-color-scheme-medium-1
(cons '("Dark Gray" "white" "gray" "black" "Light Gray")
'(solid)))
(define black-white-color-scheme-medium-2
(cons '("black" "white" "black" "black" "black")
'(bdiagonal-hatch solid horizontal-hatch solid fdiagonal-hatch)))
(define black-white-color-scheme-long
(cons '("Dim Gray" "black" "white" "black" "black" "black" "Dark Gray"
"black")
'(solid bdiagonal-hatch solid horizontal-hatch solid
fdiagonal-hatch solid vertical-hatch)))
(define current-benchmark-color-scheme (make-parameter pastel-color-scheme))
(define benchmark-show-legend? (make-parameter #t))
(struct bootstrapped-ci (name opts mean conf-lb conf-ub))
render - benchmark - alts : ( listof any / c ) ( listof benchmark - result ? )
(define (render-benchmark-alts
norm-opts
brs
#:format-opts
[format-opts (lambda (opts) (apply ~a opts #:separator " "))]
#:normalize?
[normalize #t])
(define names (remove-duplicates (map benchmark-result-name brs)))
(define opts (remove-duplicates (map benchmark-result-opts brs)))
(define (norm-br name)
(define filtered-brs
(filter (lambda (br)
(and (equal? name (benchmark-result-name br))
(equal? norm-opts (benchmark-result-opts br))))
brs))
(if (null? filtered-brs)
(error (format
"Could not find standard benchmark: name ~a, opts ~a"
name
norm-opts))
(car filtered-brs)))
(define norm-brs
(make-immutable-hash
(map (lambda (n) (cons n (norm-br n))) names)))
(define (speedup-bootstrapped-ci norm-br br)
⊥ suggests shuffling X 's samples , to remove dependency , but that
for now , using 1 standard dev on each side for error bars .
TODO investigate
(define name (benchmark-result-name br))
(define opts (benchmark-result-opts br))
(if normalize
(with-handlers ([exn:fail:contract:divide-by-zero? (λ (e) 0)])
(/ (mean (benchmark-result-trial-times br))
(mean (benchmark-result-trial-times norm-br))))
(mean (benchmark-result-trial-times br))))
(if normalize
(with-handlers ([exn:fail:contract:divide-by-zero? (λ (e) 0)])
(/ (stddev (benchmark-result-trial-times br))
(mean (benchmark-result-trial-times norm-br))))
(stddev (benchmark-result-trial-times br))))
's stuff .
(define margin-of-error
Z value for a 95 % confidence interval
(/ stddev-br
(sqrt (length (benchmark-result-trial-times br))))))
(log-message benchmark-logger 'info
(~a name " " opts
"; normalized mean = " (exact->inexact mean-br)
"; normalized stddev = " stddev-br)
#f)
(bootstrapped-ci
name
opts
mean-br
( bootstrap - bca - conf mean br / norm - br bootstrapped - sample .025 )
( bootstrap - bca - conf mean br / norm - br bootstrapped - sample .975 )
TODO just stddevs , not standard
(+ mean-br margin-of-error)
(- mean-br margin-of-error)))
(define normalized-benchmarks
(map
(lambda (br)
(speedup-bootstrapped-ci
(hash-ref norm-brs (benchmark-result-name br))
br))
brs))
(define (select-benchmarks opts)
(filter (lambda (br) (equal? opts (bootstrapped-ci-opts br)))
normalized-benchmarks))
(define num-alts (length opts))
(define alt-nums (for/list ([i (in-range 0 num-alts)]) i))
(define colors
(for/list ([i (in-range num-alts)]
[c (in-cycle (car (current-benchmark-color-scheme)))])
c))
(define styles
(for/list ([i (in-range num-alts)]
[c (in-cycle (cdr (current-benchmark-color-scheme)))])
c))
(define start-xs (linear-seq 0 (- num-alts 1) num-alts))
(define skip (+ num-alts 1))
(define bar-width (- (/ skip (+ num-alts 1)) (discrete-histogram-gap)))
(append-map
(lambda (o c s x)
(render-benchmark-alt
(format-opts o)
(select-benchmarks o)
c
s
x
skip
bar-width))
opts
colors
styles
start-xs))
- > ( listof renderer2d ? )
(define (render-benchmark-alt alt-name bcis color style start-x skip bar-width)
(define (data-point bci)
(vector (bootstrapped-ci-name bci) (bootstrapped-ci-mean bci)))
(define (data-error-bars bci i)
(let* ([conf-lb (bootstrapped-ci-conf-lb bci)]
[conf-ub (bootstrapped-ci-conf-ub bci)]
[conf-mean (bootstrapped-ci-mean bci)]
[conf-ht (- conf-ub conf-mean)]
[delta-to-mid-bar (/ (+ bar-width (discrete-histogram-gap)) 2)])
(error-bars (list (vector
(+ start-x (* skip i) delta-to-mid-bar)
conf-mean
conf-ht)))))
(cons
(if (benchmark-show-legend?)
(discrete-histogram (map data-point bcis)
#:skip skip
#:label alt-name
#:color color
#:style style
#:x-min start-x)
(discrete-histogram (map data-point bcis)
#:skip skip
#:color color
#:style style
#:x-min start-x))
(map data-error-bars bcis (for/list ([i (in-range 0 (length bcis))]) i))))
(define (mean-quotient ys xs)
(mean (map / ys xs)))
|
f1f7967a2d5983b8b17fd6268f8b7e54a0f71cdeb6f7a39c5c374659be5208c2 | shirok/Gauche | gdbm.scm | ;;;
gdbm - gdbm interface
;;;
Copyright ( c ) 2000 - 2022 < >
;;;
;;; 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.
;;;
;;; 3. Neither the name of the authors 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 THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS 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.
;;;
(define-module dbm.gdbm
(extend dbm)
(export <gdbm>
;; low-level functions
gdbm-open gdbm-close gdbm-closed?
gdbm-store gdbm-fetch gdbm-delete
gdbm-firstkey gdbm-nextkey gdbm-reorganize
gdbm-sync gdbm-exists? gdbm-strerror
gdbm-setopt gdbm-version gdbm-file-of
gdbm-errno
GDBM_READER GDBM_WRITER GDBM_WRCREAT
GDBM_NEWDB GDBM_FAST GDBM_SYNC
GDBM_NOLOCK GDBM_INSERT GDBM_REPLACE
GDBM_CACHESIZE GDBM_FASTMODE GDBM_SYNCMODE
GDBM_CENTFREE GDBM_COALESCEBLKS)
)
(select-module dbm.gdbm)
;;;
High - level dbm interface
;;;
(define-class <gdbm-meta> (<dbm-meta>)
())
(define-class <gdbm> (<dbm>)
((gdbm-file :accessor gdbm-file-of :initform #f)
(sync :init-keyword :sync :initform #f)
(nolock :init-keyword :nolock :initform #f)
(bsize :init-keyword :bsize :initform 0)
)
:metaclass <gdbm-meta>)
(define-method dbm-open ((self <gdbm>))
(next-method)
(unless (slot-bound? self 'path)
(error "path must be set to open gdbm database"))
(when (gdbm-file-of self)
(errorf "gdbm ~S already opened" self))
(let* ([path (slot-ref self 'path)]
[rwmode (slot-ref self 'rw-mode)]
[sync (slot-ref self 'sync)]
[nolock (slot-ref self 'nolock)]
[rwopt (case rwmode
[(:read) GDBM_READER]
[(:write) (+ GDBM_WRCREAT
(if sync GDBM_SYNC 0)
(if nolock GDBM_NOLOCK 0))]
[(:create) (+ GDBM_NEWDB
(if sync GDBM_SYNC 0)
(if nolock GDBM_NOLOCK 0))])]
[fp (gdbm-open path
(slot-ref self 'bsize)
rwopt
(slot-ref self 'file-mode))])
(slot-set! self 'gdbm-file fp)
self))
;;
;; close operation
;;
(define-method dbm-close ((self <gdbm>))
(let1 gdbm (gdbm-file-of self)
(and gdbm (gdbm-close gdbm))))
(define-method dbm-closed? ((self <gdbm>))
(let1 gdbm (gdbm-file-of self)
(or (not gdbm) (gdbm-closed? gdbm))))
;;
;; accessors
;;
(define-method dbm-put! ((self <gdbm>) key value)
(next-method)
(when (positive? (gdbm-store (gdbm-file-of self)
(%dbm-k2s self key)
(%dbm-v2s self value)
GDBM_REPLACE))
(error "dbm-put! failed" self)))
(define-method dbm-get ((self <gdbm>) key . args)
(next-method)
(cond [(gdbm-fetch (gdbm-file-of self) (%dbm-k2s self key))
=> (cut %dbm-s2v self <>)]
[(pair? args) (car args)] ;fall-back value
[else (errorf "gdbm: no data for key ~s in database ~s"
key (gdbm-file-of self))]))
(define-method dbm-exists? ((self <gdbm>) key)
(next-method)
(gdbm-exists? (gdbm-file-of self) (%dbm-k2s self key)))
(define-method dbm-delete! ((self <gdbm>) key)
(next-method)
(when (positive? (gdbm-delete (gdbm-file-of self) (%dbm-k2s self key)))
(errorf "dbm-delete!: deleteting key ~s from ~s failed" key self)))
;;
;; Iterations
;;
(define-method dbm-fold ((self <gdbm>) proc knil)
(let1 gdbm (gdbm-file-of self)
(let loop ([key (gdbm-firstkey gdbm)] [r knil])
(if key
(let1 val (gdbm-fetch gdbm key)
(loop (gdbm-nextkey gdbm key)
(proc (%dbm-s2k self key) (%dbm-s2v self val) r)))
r))))
;;
Metaoperations
;;
(autoload file.util copy-file move-file)
(define (%with-gdbm-locking path thunk)
(let1 db (gdbm-open path 0 GDBM_READER #o664) ;; put read-lock
(unwind-protect (thunk) (gdbm-close db))))
(define-method dbm-db-exists? ((class <gdbm-meta>) name)
(file-exists? name))
(define-method dbm-db-remove ((class <gdbm-meta>) name)
(sys-unlink name))
(define-method dbm-db-copy ((class <gdbm-meta>) from to . keys)
(%with-gdbm-locking from
(^[] (apply copy-file from to :safe #t keys))))
(define-method dbm-db-move ((class <gdbm-meta>) from to . keys)
(%with-gdbm-locking from
(^[] (apply move-file from to :safe #t keys))))
;;;
;;; Low-level bindings
;;;
(inline-stub
(declcode
(.include <gdbm.h>)
(.include <stdlib.h>))
(define-ctype ScmGdbmFile::(.struct
(SCM_HEADER :: ""
name
dbf::GDBM_FILE ; NULL if closed
)))
(define-cclass <gdbm-file> :private ScmGdbmFile* "Scm_GdbmFileClass" ()
()
[printer
(Scm_Printf port "#<gdbm-file %S>" (-> (SCM_GDBM_FILE obj) name))])
(define-cfn gdbm_finalize (obj _::void*) ::void :static
(let* ((g :: ScmGdbmFile* (SCM_GDBM_FILE obj)))
(when (-> g dbf)
(gdbm_close (-> g dbf))
(set! (-> g dbf) NULL))))
;; data conversion macros
(define-cise-stmt TO_DATUM
[(_ datum scm)
(let ((tmp (gensym)))
`(let* ((,tmp :: (const ScmStringBody*) (SCM_STRING_BODY ,scm)))
(set! (ref ,datum dptr) (cast char* (SCM_STRING_BODY_START ,tmp)))
(set! (ref ,datum dsize) (SCM_STRING_BODY_SIZE ,tmp))))])
(define-cise-stmt FROM_DATUM
[(_ scm datum)
`(cond [(ref ,datum dptr)
(set! ,scm (Scm_MakeString (ref ,datum dptr) (ref ,datum dsize)
-1 SCM_STRING_COPYING))
(free (ref ,datum dptr))]
[else
(set! ,scm SCM_FALSE)])])
(define-cise-stmt CHECK_GDBM
[(_ g)
`(unless (-> ,g dbf) (Scm_Error "gdbm file already closed: %S" ,g))])
Those symbols may not be defined in the older gdbm
(.unless (defined GDBM_SYNC) (.define GDBM_SYNC 0))
(.unless (defined GDBM_NOLOCK) (.define GDBM_NOLOCK 0))
(.unless (defined GDBM_SYNCMODE) (.define GDBM_SYNCMODE 0))
(.unless (defined GDBM_CENTFREE) (.define GDBM_CENTFREE 0))
(.unless (defined GDBM_COALESCEBLKS) (.define GDBM_COALESCEBLKS 0))
(define-cproc gdbm-open
(name::<string> :optional (size::<fixnum> 0)
(rwmode::<fixnum> (c "SCM_MAKE_INT(GDBM_READER)"))
(fmode::<fixnum> (c "SCM_MAKE_INT(0666)")))
(let* ([z::ScmGdbmFile* (SCM_NEW ScmGdbmFile)])
(SCM_SET_CLASS z (& Scm_GdbmFileClass))
(Scm_RegisterFinalizer (SCM_OBJ z) gdbm_finalize NULL)
(set! (-> z name) (SCM_OBJ name))
(set! (-> z dbf) (gdbm_open (Scm_GetString name) size rwmode fmode NULL))
(when (== (-> z dbf) NULL)
(Scm_Error "couldn't open gdbm file %S (gdbm_errno=%d)" name gdbm_errno))
(return (SCM_OBJ z))))
(define-cproc gdbm-close (gdbm::<gdbm-file>) ::<void>
(when (-> gdbm dbf)
(gdbm_close (-> gdbm dbf))
(set! (-> gdbm dbf) NULL)))
(define-cproc gdbm-closed? (gdbm::<gdbm-file>) ::<boolean>
(return (== (-> gdbm dbf) NULL)))
(define-cproc gdbm-store (gdbm::<gdbm-file>
key::<string> val::<string>
:optional (flags::<fixnum> 0))
::<int>
(let* ([dkey::datum] [dval::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(TO_DATUM dval val)
(return (gdbm_store (-> gdbm dbf) dkey dval flags))))
(define-cproc gdbm-fetch (gdbm::<gdbm-file> key::<string>)
(let* ([dkey::datum] [dval::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(set! dval (gdbm_fetch (-> gdbm dbf) dkey))
(FROM_DATUM SCM_RESULT dval)))
(define-cproc gdbm-delete (gdbm::<gdbm-file> key::<string>) ::<int>
(let* ([dkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(return (gdbm_delete (-> gdbm dbf) dkey))))
(define-cproc gdbm-firstkey (gdbm::<gdbm-file>)
(let* ([dkey::datum (gdbm_firstkey (-> gdbm dbf))])
(FROM_DATUM SCM_RESULT dkey)))
(define-cproc gdbm-nextkey (gdbm::<gdbm-file> key::<string>)
(let* ([dkey::datum] [dnkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(set! dnkey (gdbm_nextkey (-> gdbm dbf) dkey))
(FROM_DATUM SCM_RESULT dnkey)))
(define-cproc gdbm-reorganize (gdbm::<gdbm-file>) ::<int>
(CHECK_GDBM gdbm)
(return (gdbm_reorganize (-> gdbm dbf))))
(define-cproc gdbm-sync (gdbm::<gdbm-file>) ::<void>
(CHECK_GDBM gdbm)
(gdbm_sync (-> gdbm dbf)))
(define-cproc gdbm-exists? (gdbm::<gdbm-file> key::<string>) ::<boolean>
(let* ([dkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(return (gdbm_exists (-> gdbm dbf) dkey))))
(define-cproc gdbm-strerror (err_num::<fixnum>)
(return (SCM_MAKE_STR_IMMUTABLE (gdbm_strerror err_num))))
(define-cproc gdbm-setopt (gdbm::<gdbm-file> option::<fixnum> val) ::<int>
(let* ([ival::int])
(CHECK_GDBM gdbm)
(if (SCM_EXACTP val)
(set! ival (Scm_GetUInteger val))
(set! ival (not (SCM_FALSEP val))))
(return (gdbm_setopt (-> gdbm dbf) option (& ival) (sizeof (int))))))
(define-cproc gdbm-version ()
(return (SCM_MAKE_STR_IMMUTABLE gdbm_version)))
(define-cproc gdbm-errno () ::<int>
(let* ([r::int gdbm_errno])
(set! gdbm_errno 0)
(return r)))
(define-enum GDBM_READER)
(define-enum GDBM_WRITER)
(define-enum GDBM_WRCREAT)
(define-enum GDBM_NEWDB)
(define-enum GDBM_FAST)
(define-enum GDBM_SYNC)
(define-enum GDBM_NOLOCK)
(define-enum GDBM_INSERT)
(define-enum GDBM_REPLACE)
(define-enum GDBM_CACHESIZE)
(define-enum GDBM_FASTMODE)
(define-enum GDBM_SYNCMODE)
(define-enum GDBM_CENTFREE)
(define-enum GDBM_COALESCEBLKS)
)
| null | https://raw.githubusercontent.com/shirok/Gauche/b773899dbe0b2955e1c4f1daa066da874070c1e4/ext/dbm/gdbm.scm | scheme |
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.
3. Neither the name of the authors 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
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
low-level functions
close operation
accessors
fall-back value
Iterations
put read-lock
Low-level bindings
NULL if closed
data conversion macros | gdbm - gdbm interface
Copyright ( c ) 2000 - 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
(define-module dbm.gdbm
(extend dbm)
(export <gdbm>
gdbm-open gdbm-close gdbm-closed?
gdbm-store gdbm-fetch gdbm-delete
gdbm-firstkey gdbm-nextkey gdbm-reorganize
gdbm-sync gdbm-exists? gdbm-strerror
gdbm-setopt gdbm-version gdbm-file-of
gdbm-errno
GDBM_READER GDBM_WRITER GDBM_WRCREAT
GDBM_NEWDB GDBM_FAST GDBM_SYNC
GDBM_NOLOCK GDBM_INSERT GDBM_REPLACE
GDBM_CACHESIZE GDBM_FASTMODE GDBM_SYNCMODE
GDBM_CENTFREE GDBM_COALESCEBLKS)
)
(select-module dbm.gdbm)
High - level dbm interface
(define-class <gdbm-meta> (<dbm-meta>)
())
(define-class <gdbm> (<dbm>)
((gdbm-file :accessor gdbm-file-of :initform #f)
(sync :init-keyword :sync :initform #f)
(nolock :init-keyword :nolock :initform #f)
(bsize :init-keyword :bsize :initform 0)
)
:metaclass <gdbm-meta>)
(define-method dbm-open ((self <gdbm>))
(next-method)
(unless (slot-bound? self 'path)
(error "path must be set to open gdbm database"))
(when (gdbm-file-of self)
(errorf "gdbm ~S already opened" self))
(let* ([path (slot-ref self 'path)]
[rwmode (slot-ref self 'rw-mode)]
[sync (slot-ref self 'sync)]
[nolock (slot-ref self 'nolock)]
[rwopt (case rwmode
[(:read) GDBM_READER]
[(:write) (+ GDBM_WRCREAT
(if sync GDBM_SYNC 0)
(if nolock GDBM_NOLOCK 0))]
[(:create) (+ GDBM_NEWDB
(if sync GDBM_SYNC 0)
(if nolock GDBM_NOLOCK 0))])]
[fp (gdbm-open path
(slot-ref self 'bsize)
rwopt
(slot-ref self 'file-mode))])
(slot-set! self 'gdbm-file fp)
self))
(define-method dbm-close ((self <gdbm>))
(let1 gdbm (gdbm-file-of self)
(and gdbm (gdbm-close gdbm))))
(define-method dbm-closed? ((self <gdbm>))
(let1 gdbm (gdbm-file-of self)
(or (not gdbm) (gdbm-closed? gdbm))))
(define-method dbm-put! ((self <gdbm>) key value)
(next-method)
(when (positive? (gdbm-store (gdbm-file-of self)
(%dbm-k2s self key)
(%dbm-v2s self value)
GDBM_REPLACE))
(error "dbm-put! failed" self)))
(define-method dbm-get ((self <gdbm>) key . args)
(next-method)
(cond [(gdbm-fetch (gdbm-file-of self) (%dbm-k2s self key))
=> (cut %dbm-s2v self <>)]
[else (errorf "gdbm: no data for key ~s in database ~s"
key (gdbm-file-of self))]))
(define-method dbm-exists? ((self <gdbm>) key)
(next-method)
(gdbm-exists? (gdbm-file-of self) (%dbm-k2s self key)))
(define-method dbm-delete! ((self <gdbm>) key)
(next-method)
(when (positive? (gdbm-delete (gdbm-file-of self) (%dbm-k2s self key)))
(errorf "dbm-delete!: deleteting key ~s from ~s failed" key self)))
(define-method dbm-fold ((self <gdbm>) proc knil)
(let1 gdbm (gdbm-file-of self)
(let loop ([key (gdbm-firstkey gdbm)] [r knil])
(if key
(let1 val (gdbm-fetch gdbm key)
(loop (gdbm-nextkey gdbm key)
(proc (%dbm-s2k self key) (%dbm-s2v self val) r)))
r))))
Metaoperations
(autoload file.util copy-file move-file)
(define (%with-gdbm-locking path thunk)
(unwind-protect (thunk) (gdbm-close db))))
(define-method dbm-db-exists? ((class <gdbm-meta>) name)
(file-exists? name))
(define-method dbm-db-remove ((class <gdbm-meta>) name)
(sys-unlink name))
(define-method dbm-db-copy ((class <gdbm-meta>) from to . keys)
(%with-gdbm-locking from
(^[] (apply copy-file from to :safe #t keys))))
(define-method dbm-db-move ((class <gdbm-meta>) from to . keys)
(%with-gdbm-locking from
(^[] (apply move-file from to :safe #t keys))))
(inline-stub
(declcode
(.include <gdbm.h>)
(.include <stdlib.h>))
(define-ctype ScmGdbmFile::(.struct
(SCM_HEADER :: ""
name
)))
(define-cclass <gdbm-file> :private ScmGdbmFile* "Scm_GdbmFileClass" ()
()
[printer
(Scm_Printf port "#<gdbm-file %S>" (-> (SCM_GDBM_FILE obj) name))])
(define-cfn gdbm_finalize (obj _::void*) ::void :static
(let* ((g :: ScmGdbmFile* (SCM_GDBM_FILE obj)))
(when (-> g dbf)
(gdbm_close (-> g dbf))
(set! (-> g dbf) NULL))))
(define-cise-stmt TO_DATUM
[(_ datum scm)
(let ((tmp (gensym)))
`(let* ((,tmp :: (const ScmStringBody*) (SCM_STRING_BODY ,scm)))
(set! (ref ,datum dptr) (cast char* (SCM_STRING_BODY_START ,tmp)))
(set! (ref ,datum dsize) (SCM_STRING_BODY_SIZE ,tmp))))])
(define-cise-stmt FROM_DATUM
[(_ scm datum)
`(cond [(ref ,datum dptr)
(set! ,scm (Scm_MakeString (ref ,datum dptr) (ref ,datum dsize)
-1 SCM_STRING_COPYING))
(free (ref ,datum dptr))]
[else
(set! ,scm SCM_FALSE)])])
(define-cise-stmt CHECK_GDBM
[(_ g)
`(unless (-> ,g dbf) (Scm_Error "gdbm file already closed: %S" ,g))])
Those symbols may not be defined in the older gdbm
(.unless (defined GDBM_SYNC) (.define GDBM_SYNC 0))
(.unless (defined GDBM_NOLOCK) (.define GDBM_NOLOCK 0))
(.unless (defined GDBM_SYNCMODE) (.define GDBM_SYNCMODE 0))
(.unless (defined GDBM_CENTFREE) (.define GDBM_CENTFREE 0))
(.unless (defined GDBM_COALESCEBLKS) (.define GDBM_COALESCEBLKS 0))
(define-cproc gdbm-open
(name::<string> :optional (size::<fixnum> 0)
(rwmode::<fixnum> (c "SCM_MAKE_INT(GDBM_READER)"))
(fmode::<fixnum> (c "SCM_MAKE_INT(0666)")))
(let* ([z::ScmGdbmFile* (SCM_NEW ScmGdbmFile)])
(SCM_SET_CLASS z (& Scm_GdbmFileClass))
(Scm_RegisterFinalizer (SCM_OBJ z) gdbm_finalize NULL)
(set! (-> z name) (SCM_OBJ name))
(set! (-> z dbf) (gdbm_open (Scm_GetString name) size rwmode fmode NULL))
(when (== (-> z dbf) NULL)
(Scm_Error "couldn't open gdbm file %S (gdbm_errno=%d)" name gdbm_errno))
(return (SCM_OBJ z))))
(define-cproc gdbm-close (gdbm::<gdbm-file>) ::<void>
(when (-> gdbm dbf)
(gdbm_close (-> gdbm dbf))
(set! (-> gdbm dbf) NULL)))
(define-cproc gdbm-closed? (gdbm::<gdbm-file>) ::<boolean>
(return (== (-> gdbm dbf) NULL)))
(define-cproc gdbm-store (gdbm::<gdbm-file>
key::<string> val::<string>
:optional (flags::<fixnum> 0))
::<int>
(let* ([dkey::datum] [dval::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(TO_DATUM dval val)
(return (gdbm_store (-> gdbm dbf) dkey dval flags))))
(define-cproc gdbm-fetch (gdbm::<gdbm-file> key::<string>)
(let* ([dkey::datum] [dval::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(set! dval (gdbm_fetch (-> gdbm dbf) dkey))
(FROM_DATUM SCM_RESULT dval)))
(define-cproc gdbm-delete (gdbm::<gdbm-file> key::<string>) ::<int>
(let* ([dkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(return (gdbm_delete (-> gdbm dbf) dkey))))
(define-cproc gdbm-firstkey (gdbm::<gdbm-file>)
(let* ([dkey::datum (gdbm_firstkey (-> gdbm dbf))])
(FROM_DATUM SCM_RESULT dkey)))
(define-cproc gdbm-nextkey (gdbm::<gdbm-file> key::<string>)
(let* ([dkey::datum] [dnkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(set! dnkey (gdbm_nextkey (-> gdbm dbf) dkey))
(FROM_DATUM SCM_RESULT dnkey)))
(define-cproc gdbm-reorganize (gdbm::<gdbm-file>) ::<int>
(CHECK_GDBM gdbm)
(return (gdbm_reorganize (-> gdbm dbf))))
(define-cproc gdbm-sync (gdbm::<gdbm-file>) ::<void>
(CHECK_GDBM gdbm)
(gdbm_sync (-> gdbm dbf)))
(define-cproc gdbm-exists? (gdbm::<gdbm-file> key::<string>) ::<boolean>
(let* ([dkey::datum])
(CHECK_GDBM gdbm)
(TO_DATUM dkey key)
(return (gdbm_exists (-> gdbm dbf) dkey))))
(define-cproc gdbm-strerror (err_num::<fixnum>)
(return (SCM_MAKE_STR_IMMUTABLE (gdbm_strerror err_num))))
(define-cproc gdbm-setopt (gdbm::<gdbm-file> option::<fixnum> val) ::<int>
(let* ([ival::int])
(CHECK_GDBM gdbm)
(if (SCM_EXACTP val)
(set! ival (Scm_GetUInteger val))
(set! ival (not (SCM_FALSEP val))))
(return (gdbm_setopt (-> gdbm dbf) option (& ival) (sizeof (int))))))
(define-cproc gdbm-version ()
(return (SCM_MAKE_STR_IMMUTABLE gdbm_version)))
(define-cproc gdbm-errno () ::<int>
(let* ([r::int gdbm_errno])
(set! gdbm_errno 0)
(return r)))
(define-enum GDBM_READER)
(define-enum GDBM_WRITER)
(define-enum GDBM_WRCREAT)
(define-enum GDBM_NEWDB)
(define-enum GDBM_FAST)
(define-enum GDBM_SYNC)
(define-enum GDBM_NOLOCK)
(define-enum GDBM_INSERT)
(define-enum GDBM_REPLACE)
(define-enum GDBM_CACHESIZE)
(define-enum GDBM_FASTMODE)
(define-enum GDBM_SYNCMODE)
(define-enum GDBM_CENTFREE)
(define-enum GDBM_COALESCEBLKS)
)
|
614992ad59a24eb6b88f54525ec6206032f5c099fcb3b638c90deab2f5779fe4 | input-output-hk/cardano-wallet | Delta.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Database.Persist.Delta (
-- * Synopsis
-- | Manipulating SQL database tables using delta encodings
-- via the "persistent" package.
-- * Store
newEntityStore, newSqlStore
) where
import Prelude hiding
( all )
import Control.Monad
( forM_, void, when )
import Control.Monad.IO.Class
( MonadIO, liftIO )
import Data.Bifunctor
( first )
import Data.DBVar
( Store (..), updateLoad )
import Data.Delta
( Delta (..) )
import Data.Proxy
( Proxy (..) )
import Data.Table
( DeltaDB (..), Pile (..), Table (..) )
import Database.Persist
( Filter, Key, PersistRecordBackend, ToBackendKey )
import Database.Persist.Sql
( SqlBackend, SqlPersistM, fromSqlKey, toSqlKey )
import Database.Schema
( (:.) (..), Col (..), IsRow, Primary (..) )
import Say
( say, sayShow )
FIXME : Replace with stuff later .
import Data.IORef
( newIORef, readIORef, writeIORef )
import qualified Data.Table as Table
import qualified Database.Persist as Persist
import qualified Database.Schema as Sql
{-------------------------------------------------------------------------------
Database operations
-------------------------------------------------------------------------------}
| Helper abstraction for a Database backend
data Database m key row = Database
{ selectAll :: m [(key, row)]
, deleteAll :: m ()
, repsertMany :: [(key, row)] -> m ()
, deleteOne :: key -> m ()
, updateOne :: (key, row) -> m ()
}
-- | Database table for 'Entity'.
persistDB
:: forall row. ( PersistRecordBackend row SqlBackend
, ToBackendKey SqlBackend row )
=> Database SqlPersistM Int row
persistDB = Database
{ selectAll = map toPair <$> Persist.selectList all []
, deleteAll = Persist.deleteWhere all
, repsertMany = Persist.repsertMany . map (first toKey)
, deleteOne = Persist.delete . toKey
, updateOne = \(key,val) -> Persist.replace (toKey key) val
}
where
all = [] :: [Filter row]
toPair (Persist.Entity key val) = (fromKey key, val)
fromKey = fromIntegral . fromSqlKey
toKey :: Int -> Key row
toKey = toSqlKey . fromIntegral
-- | SQL database backend
sqlDB
:: forall row. (IsRow row, IsRow (row :. Col "id" Primary))
=> Database SqlPersistM Int row
sqlDB = Database
{ selectAll = map toPair <$> Sql.callSql Sql.selectAll
, deleteAll = Sql.runSql $ Sql.deleteAll proxy
, repsertMany = \zs -> forM_ zs $
Sql.runSql . Sql.repsertOne . fromPair
, deleteOne = Sql.runSql . Sql.deleteOne proxy . Col . Primary
, updateOne = Sql.runSql . Sql.updateOne . fromPair
}
where
proxy = Proxy :: Proxy row
fromPair :: (Int,row) -> (row :. Col "id" Primary)
fromPair (key,row) = row :. (Col (Primary key) :: Col "id" Primary)
toPair :: (row :. Col "id" Primary) -> (Int,row)
toPair (row :. Col (Primary key)) = (key,row)
{-------------------------------------------------------------------------------
Database operations
-------------------------------------------------------------------------------}
-- | Construct a 'Store' from an SQL table.
--
-- The unique IDs will be stored in a column "id" at the end of
-- each row in the database table.
newSqlStore
:: (MonadIO m, IsRow row, IsRow (row :. Col "id" Primary), Show row)
=> m (Store SqlPersistM [DeltaDB Int row])
newSqlStore = newDatabaseStore sqlDB
-- | Construct a 'Store' for 'Entity'.
--
-- FIXME: This function should also do \"migrations\", i.e.
create the database table in the first place .
newEntityStore
:: forall row m.
( PersistRecordBackend row SqlBackend
, ToBackendKey SqlBackend row, Show row
, MonadIO m
)
=> m (Store SqlPersistM [DeltaDB Int row])
newEntityStore = newDatabaseStore persistDB
-- | Helper function to create a 'Store' using a 'Database' backend.
newDatabaseStore
:: forall m n row. (MonadIO m, MonadIO n, Show row)
=> Database m Int row
-> n (Store m [DeltaDB Int row])
newDatabaseStore db = do
ref <- liftIO $ newIORef Nothing
let rememberSupply table = liftIO $ writeIORef ref $ Just $ uids table
load = do
debug $ do
say "\n** loadS"
liftIO . print =<< selectAll db
-- read database table, preserve keys
table <- Table.fromRows <$> selectAll db
-- but use our own unique ID supply
liftIO (readIORef ref) >>= \case
Just supply -> pure $ Right table{uids = supply}
Nothing -> do
rememberSupply table
pure $ Right table
write = \table -> void $ do
delete any old data in the table first
repsertMany db $ getPile $ Table.toRows table
rememberSupply table
update = updateLoad load
(\err -> debug $ do
say "Error in updateLoadEither"
sayShow err
)
$ \table ds -> do
debug $ do
say "\n** updateS table deltas"
sayShow table
sayShow ds
mapM_ (update1 table) ds
rememberSupply (apply ds table) -- need to use updated supply
pure $ Store
{ loadS = load
, writeS = write
, updateS = update
}
where
debug = when False
update1 _ (InsertManyDB zs) = void $ repsertMany db zs
update1 _ (DeleteManyDB ks) = forM_ ks $ deleteOne db
update1 _ (UpdateManyDB zs) = forM_ zs $ updateOne db
Note [ Unique ID supply in newDBStore ]
We expect that updating the store and loading the value
is the same as first loading the value and then apply the delta ,
i.e. we expect that the two actions
> > = \a - > updateS a da > > = > > = \a - > pure $ apply da a
are operationally equivalent .
However , this is only the case if we keep track of the supply
of unique IDs for the table ! Otherwise , loading the table
from the database again can mess up the supply .
We expect that updating the store and loading the value
is the same as first loading the value and then apply the delta,
i.e. we expect that the two actions
loadS >>= \a -> updateS a da >>= loadS
loadS >>= \a -> pure $ apply da a
are operationally equivalent.
However, this is only the case if we keep track of the supply
of unique IDs for the table! Otherwise, loading the table
from the database again can mess up the supply.
-}
-- FIXME: For clarity, we may want to implement this in terms
-- of a product of stores ("semidirect product").
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/30b98430be2c827df616b58b92e9665579e5e668/lib/delta-table/src/Database/Persist/Delta.hs | haskell | * Synopsis
| Manipulating SQL database tables using delta encodings
via the "persistent" package.
* Store
------------------------------------------------------------------------------
Database operations
------------------------------------------------------------------------------
| Database table for 'Entity'.
| SQL database backend
------------------------------------------------------------------------------
Database operations
------------------------------------------------------------------------------
| Construct a 'Store' from an SQL table.
The unique IDs will be stored in a column "id" at the end of
each row in the database table.
| Construct a 'Store' for 'Entity'.
FIXME: This function should also do \"migrations\", i.e.
| Helper function to create a 'Store' using a 'Database' backend.
read database table, preserve keys
but use our own unique ID supply
need to use updated supply
FIXME: For clarity, we may want to implement this in terms
of a product of stores ("semidirect product"). | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Database.Persist.Delta (
newEntityStore, newSqlStore
) where
import Prelude hiding
( all )
import Control.Monad
( forM_, void, when )
import Control.Monad.IO.Class
( MonadIO, liftIO )
import Data.Bifunctor
( first )
import Data.DBVar
( Store (..), updateLoad )
import Data.Delta
( Delta (..) )
import Data.Proxy
( Proxy (..) )
import Data.Table
( DeltaDB (..), Pile (..), Table (..) )
import Database.Persist
( Filter, Key, PersistRecordBackend, ToBackendKey )
import Database.Persist.Sql
( SqlBackend, SqlPersistM, fromSqlKey, toSqlKey )
import Database.Schema
( (:.) (..), Col (..), IsRow, Primary (..) )
import Say
( say, sayShow )
FIXME : Replace with stuff later .
import Data.IORef
( newIORef, readIORef, writeIORef )
import qualified Data.Table as Table
import qualified Database.Persist as Persist
import qualified Database.Schema as Sql
| Helper abstraction for a Database backend
data Database m key row = Database
{ selectAll :: m [(key, row)]
, deleteAll :: m ()
, repsertMany :: [(key, row)] -> m ()
, deleteOne :: key -> m ()
, updateOne :: (key, row) -> m ()
}
persistDB
:: forall row. ( PersistRecordBackend row SqlBackend
, ToBackendKey SqlBackend row )
=> Database SqlPersistM Int row
persistDB = Database
{ selectAll = map toPair <$> Persist.selectList all []
, deleteAll = Persist.deleteWhere all
, repsertMany = Persist.repsertMany . map (first toKey)
, deleteOne = Persist.delete . toKey
, updateOne = \(key,val) -> Persist.replace (toKey key) val
}
where
all = [] :: [Filter row]
toPair (Persist.Entity key val) = (fromKey key, val)
fromKey = fromIntegral . fromSqlKey
toKey :: Int -> Key row
toKey = toSqlKey . fromIntegral
sqlDB
:: forall row. (IsRow row, IsRow (row :. Col "id" Primary))
=> Database SqlPersistM Int row
sqlDB = Database
{ selectAll = map toPair <$> Sql.callSql Sql.selectAll
, deleteAll = Sql.runSql $ Sql.deleteAll proxy
, repsertMany = \zs -> forM_ zs $
Sql.runSql . Sql.repsertOne . fromPair
, deleteOne = Sql.runSql . Sql.deleteOne proxy . Col . Primary
, updateOne = Sql.runSql . Sql.updateOne . fromPair
}
where
proxy = Proxy :: Proxy row
fromPair :: (Int,row) -> (row :. Col "id" Primary)
fromPair (key,row) = row :. (Col (Primary key) :: Col "id" Primary)
toPair :: (row :. Col "id" Primary) -> (Int,row)
toPair (row :. Col (Primary key)) = (key,row)
newSqlStore
:: (MonadIO m, IsRow row, IsRow (row :. Col "id" Primary), Show row)
=> m (Store SqlPersistM [DeltaDB Int row])
newSqlStore = newDatabaseStore sqlDB
create the database table in the first place .
newEntityStore
:: forall row m.
( PersistRecordBackend row SqlBackend
, ToBackendKey SqlBackend row, Show row
, MonadIO m
)
=> m (Store SqlPersistM [DeltaDB Int row])
newEntityStore = newDatabaseStore persistDB
newDatabaseStore
:: forall m n row. (MonadIO m, MonadIO n, Show row)
=> Database m Int row
-> n (Store m [DeltaDB Int row])
newDatabaseStore db = do
ref <- liftIO $ newIORef Nothing
let rememberSupply table = liftIO $ writeIORef ref $ Just $ uids table
load = do
debug $ do
say "\n** loadS"
liftIO . print =<< selectAll db
table <- Table.fromRows <$> selectAll db
liftIO (readIORef ref) >>= \case
Just supply -> pure $ Right table{uids = supply}
Nothing -> do
rememberSupply table
pure $ Right table
write = \table -> void $ do
delete any old data in the table first
repsertMany db $ getPile $ Table.toRows table
rememberSupply table
update = updateLoad load
(\err -> debug $ do
say "Error in updateLoadEither"
sayShow err
)
$ \table ds -> do
debug $ do
say "\n** updateS table deltas"
sayShow table
sayShow ds
mapM_ (update1 table) ds
pure $ Store
{ loadS = load
, writeS = write
, updateS = update
}
where
debug = when False
update1 _ (InsertManyDB zs) = void $ repsertMany db zs
update1 _ (DeleteManyDB ks) = forM_ ks $ deleteOne db
update1 _ (UpdateManyDB zs) = forM_ zs $ updateOne db
Note [ Unique ID supply in newDBStore ]
We expect that updating the store and loading the value
is the same as first loading the value and then apply the delta ,
i.e. we expect that the two actions
> > = \a - > updateS a da > > = > > = \a - > pure $ apply da a
are operationally equivalent .
However , this is only the case if we keep track of the supply
of unique IDs for the table ! Otherwise , loading the table
from the database again can mess up the supply .
We expect that updating the store and loading the value
is the same as first loading the value and then apply the delta,
i.e. we expect that the two actions
loadS >>= \a -> updateS a da >>= loadS
loadS >>= \a -> pure $ apply da a
are operationally equivalent.
However, this is only the case if we keep track of the supply
of unique IDs for the table! Otherwise, loading the table
from the database again can mess up the supply.
-}
|
b74d7fea39bea74b57bdc884ecc2036adfe463b388d45d1e8c18a9b987cd1293 | vvvvalvalval/reagent-phonecat-tutorial | dev.cljs | (ns ^:figwheel-no-load reagent-phonecat.dev
(:require [reagent-phonecat.core :as core]
[figwheel.client :as figwheel :include-macros true]
[weasel.repl :as weasel]
[reagent.core :as r]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws:3449/figwheel-ws"
:jsload-callback core/mount-root)
(weasel/connect "ws:9001" :verbose true)
(core/init!)
| null | https://raw.githubusercontent.com/vvvvalvalval/reagent-phonecat-tutorial/3207c9cfcb81e423f3074502cba2e570cd2ef274/env/dev/cljs/reagent_phonecat/dev.cljs | clojure | (ns ^:figwheel-no-load reagent-phonecat.dev
(:require [reagent-phonecat.core :as core]
[figwheel.client :as figwheel :include-macros true]
[weasel.repl :as weasel]
[reagent.core :as r]))
(enable-console-print!)
(figwheel/watch-and-reload
:websocket-url "ws:3449/figwheel-ws"
:jsload-callback core/mount-root)
(weasel/connect "ws:9001" :verbose true)
(core/init!)
| |
899a64e83705a3c3ecde2128099625371cf1673642c0cc6829e672e7afd1a453 | korya/efuns | multi_frames.ml | (***********************************************************************)
(* *)
xlib for
(* *)
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
(* *)
(***********************************************************************)
open Efuns
open Text
open Frame
open Top_window
let cut_frame frame =
let window = frame.frm_window in
if window.win_height > 3 then
let h = window.win_height / 2 in
let w1 = Window.create false
(Window window) window.win_xpos window.win_ypos
window.win_width h in
let w2 = Window.create false (Window window) window.win_xpos
(window.win_ypos + h)
window.win_width (window.win_height - h) in
window.win_down <- VComb (w1,w2);
Frame.install w1 frame;
w2
else
window
let remove_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
match window.win_up with
TopWindow _ -> ()
| Window upwin ->
Window.prev (Frame.install upwin) window
let v_cut_frame frame =
if frame.frm_mini_buffer = None then
let _ = Frame.create (cut_frame frame) None frame.frm_buffer in ()
let h_cut_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
if window.win_width > 10 then
let wi = window.win_width / 2 in
let w1 = Window.create false
(Window window) window.win_xpos window.win_ypos
wi window.win_height in
let w2 = Window.create false (Window window) (window.win_xpos + wi)
window.win_ypos
(window.win_width - wi) window.win_height in
window.win_down <- HComb (w1,w2);
Frame.install w1 frame;
let _ = Frame.create w2 None frame.frm_buffer in ()
let delete_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
match window.win_up with
TopWindow _ -> ()
| Window upwin ->
Frame.install upwin frame;
Frame.active frame
let one_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
let top_window = Window.top window in
if not (top_window.top_windows == window) then
begin
Frame.install top_window.top_windows frame;
Frame.active frame
end
let next_frame frame =
let window = frame.frm_window in
Window.next Frame.active window
| null | https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/efuns/multi_frames.ml | ocaml | *********************************************************************
********************************************************************* | xlib for
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
Automatique . Distributed only by permission .
open Efuns
open Text
open Frame
open Top_window
let cut_frame frame =
let window = frame.frm_window in
if window.win_height > 3 then
let h = window.win_height / 2 in
let w1 = Window.create false
(Window window) window.win_xpos window.win_ypos
window.win_width h in
let w2 = Window.create false (Window window) window.win_xpos
(window.win_ypos + h)
window.win_width (window.win_height - h) in
window.win_down <- VComb (w1,w2);
Frame.install w1 frame;
w2
else
window
let remove_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
match window.win_up with
TopWindow _ -> ()
| Window upwin ->
Window.prev (Frame.install upwin) window
let v_cut_frame frame =
if frame.frm_mini_buffer = None then
let _ = Frame.create (cut_frame frame) None frame.frm_buffer in ()
let h_cut_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
if window.win_width > 10 then
let wi = window.win_width / 2 in
let w1 = Window.create false
(Window window) window.win_xpos window.win_ypos
wi window.win_height in
let w2 = Window.create false (Window window) (window.win_xpos + wi)
window.win_ypos
(window.win_width - wi) window.win_height in
window.win_down <- HComb (w1,w2);
Frame.install w1 frame;
let _ = Frame.create w2 None frame.frm_buffer in ()
let delete_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
match window.win_up with
TopWindow _ -> ()
| Window upwin ->
Frame.install upwin frame;
Frame.active frame
let one_frame frame =
if frame.frm_mini_buffer = None then
let window = frame.frm_window in
let top_window = Window.top window in
if not (top_window.top_windows == window) then
begin
Frame.install top_window.top_windows frame;
Frame.active frame
end
let next_frame frame =
let window = frame.frm_window in
Window.next Frame.active window
|
4ca0dbe8c3ff3190a201b1f05171e4ec18d9d9a1a99798fce2155f58675939f1 | ocaml/oasis | OASISFindlib.ml | (******************************************************************************)
OASIS : architecture for building OCaml libraries and applications
(* *)
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
(* *)
(* This library 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 2.1 of the License , or ( at
(* your option) any later version, with the OCaml static compilation *)
(* exception. *)
(* *)
(* This library is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY *)
(* or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more *)
(* details. *)
(* *)
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
(******************************************************************************)
open OASISTypes
open OASISUtils
open OASISGettext
type library_name = name
type findlib_part_name = name
type 'a map_of_findlib_part_name = 'a OASISUtils.MapString.t
exception InternalLibraryNotFound of library_name
exception FindlibPackageNotFound of findlib_name
type group_t =
| Container of findlib_name * group_t list
| Package of (findlib_name *
common_section *
build_section *
[`Library of library | `Object of object_] *
unix_dirname option *
group_t list)
type data = common_section *
build_section *
[`Library of library | `Object of object_]
type tree =
| Node of (data option) * (tree MapString.t)
| Leaf of data
let findlib_mapping pkg =
Map from library name to either full findlib name or parts + parent .
let fndlb_parts_of_lib_name =
let fndlb_parts cs lib =
let name =
match lib.lib_findlib_name with
| Some nm -> nm
| None -> cs.cs_name
in
let name =
String.concat "." (lib.lib_findlib_containers @ [name])
in
name
in
List.fold_left
(fun mp ->
function
| Library (cs, _, lib) ->
begin
let lib_name = cs.cs_name in
let fndlb_parts = fndlb_parts cs lib in
if MapString.mem lib_name mp then
failwithf
(f_ "The library name '%s' is used more than once.")
lib_name;
match lib.lib_findlib_parent with
| Some lib_name_parent ->
MapString.add
lib_name
(`Unsolved (lib_name_parent, fndlb_parts))
mp
| None ->
MapString.add
lib_name
(`Solved fndlb_parts)
mp
end
| Object (cs, _, obj) ->
begin
let obj_name = cs.cs_name in
if MapString.mem obj_name mp then
failwithf
(f_ "The object name '%s' is used more than once.")
obj_name;
let findlib_full_name = match obj.obj_findlib_fullname with
| Some ns -> String.concat "." ns
| None -> obj_name
in
MapString.add
obj_name
(`Solved findlib_full_name)
mp
end
| Executable _ | Test _ | Flag _ | SrcRepo _ | Doc _ ->
mp)
MapString.empty
pkg.sections
in
Solve the above graph to be only library name to full findlib name .
let fndlb_name_of_lib_name =
let rec solve visited mp lib_name lib_name_child =
if SetString.mem lib_name visited then
failwithf
(f_ "Library '%s' is involved in a cycle \
with regard to findlib naming.")
lib_name;
let visited = SetString.add lib_name visited in
try
match MapString.find lib_name mp with
| `Solved fndlb_nm ->
fndlb_nm, mp
| `Unsolved (lib_nm_parent, post_fndlb_nm) ->
let pre_fndlb_nm, mp =
solve visited mp lib_nm_parent lib_name
in
let fndlb_nm = pre_fndlb_nm^"."^post_fndlb_nm in
fndlb_nm, MapString.add lib_name (`Solved fndlb_nm) mp
with Not_found ->
failwithf
(f_ "Library '%s', which is defined as the findlib parent of \
library '%s', doesn't exist.")
lib_name lib_name_child
in
let mp =
MapString.fold
(fun lib_name status mp ->
match status with
| `Solved _ ->
(* Solved initialy, no need to go further *)
mp
| `Unsolved _ ->
let _, mp = solve SetString.empty mp lib_name "<none>" in
mp)
fndlb_parts_of_lib_name
fndlb_parts_of_lib_name
in
MapString.map
(function
| `Solved fndlb_nm -> fndlb_nm
| `Unsolved _ -> assert false)
mp
in
Convert an internal library name to a findlib name .
let findlib_name_of_library_name lib_nm =
try
MapString.find lib_nm fndlb_name_of_lib_name
with Not_found ->
raise (InternalLibraryNotFound lib_nm)
in
(* Add a library to the tree.
*)
let add sct mp =
let fndlb_fullname =
let cs, _, _ = sct in
let lib_name = cs.cs_name in
findlib_name_of_library_name lib_name
in
let rec add_children nm_lst (children: tree MapString.t) =
match nm_lst with
| (hd :: tl) ->
begin
let node =
try
add_node tl (MapString.find hd children)
with Not_found ->
(* New node *)
new_node tl
in
MapString.add hd node children
end
| [] ->
(* Should not have a nameless library. *)
assert false
and add_node tl node =
if tl = [] then
begin
match node with
| Node (None, children) ->
Node (Some sct, children)
| Leaf (cs', _, _) | Node (Some (cs', _, _), _) ->
(* TODO: allow to merge Package, i.e.
* archive(byte) = "foo.cma foo_init.cmo"
*)
let cs, _, _ = sct in
failwithf
(f_ "Library '%s' and '%s' have the same findlib name '%s'")
cs.cs_name cs'.cs_name fndlb_fullname
end
else
begin
match node with
| Leaf data ->
Node (Some data, add_children tl MapString.empty)
| Node (data_opt, children) ->
Node (data_opt, add_children tl children)
end
and new_node =
function
| [] ->
Leaf sct
| hd :: tl ->
Node (None, MapString.add hd (new_node tl) MapString.empty)
in
add_children (OASISString.nsplit fndlb_fullname '.') mp
in
let unix_directory dn lib =
let directory =
match lib with
| `Library lib -> lib.lib_findlib_directory
| `Object obj -> obj.obj_findlib_directory
in
match dn, directory with
| None, None -> None
| None, Some dn | Some dn, None -> Some dn
| Some dn1, Some dn2 -> Some (OASISUnixPath.concat dn1 dn2)
in
let rec group_of_tree dn mp =
MapString.fold
(fun nm node acc ->
let cur =
match node with
| Node (Some (cs, bs, lib), children) ->
let current_dn = unix_directory dn lib in
Package (nm, cs, bs, lib, current_dn, group_of_tree current_dn children)
| Node (None, children) ->
Container (nm, group_of_tree dn children)
| Leaf (cs, bs, lib) ->
let current_dn = unix_directory dn lib in
Package (nm, cs, bs, lib, current_dn, [])
in
cur :: acc)
mp []
in
let group_mp =
List.fold_left
(fun mp ->
function
| Library (cs, bs, lib) ->
add (cs, bs, `Library lib) mp
| Object (cs, bs, obj) ->
add (cs, bs, `Object obj) mp
| _ ->
mp)
MapString.empty
pkg.sections
in
let groups = group_of_tree None group_mp in
let library_name_of_findlib_name =
lazy begin
(* Revert findlib_name_of_library_name. *)
MapString.fold
(fun k v mp -> MapString.add v k mp)
fndlb_name_of_lib_name
MapString.empty
end
in
let library_name_of_findlib_name fndlb_nm =
try
MapString.find fndlb_nm (Lazy.force library_name_of_findlib_name)
with Not_found ->
raise (FindlibPackageNotFound fndlb_nm)
in
groups,
findlib_name_of_library_name,
library_name_of_findlib_name
let findlib_of_group =
function
| Container (fndlb_nm, _)
| Package (fndlb_nm, _, _, _, _, _) -> fndlb_nm
let root_of_group grp =
let rec root_lib_aux =
We do a DFS in the group .
function
| Container (_, children) ->
List.fold_left
(fun res grp ->
if res = None then
root_lib_aux grp
else
res)
None
children
| Package (_, cs, bs, lib, _, _) ->
Some (cs, bs, lib)
in
match root_lib_aux grp with
| Some res ->
res
| None ->
failwithf
(f_ "Unable to determine root library of findlib library '%s'")
(findlib_of_group grp)
(* END EXPORT *)
let () =
Printexc.register_printer
(function
| InternalLibraryNotFound lib_nm ->
Some
(Printf.sprintf
(f_ "Unable to translate internal library name '%s' \
to findlib name.")
lib_nm)
| FindlibPackageNotFound fndlb_nm ->
Some
(Printf.sprintf
(f_ "Unable to translate findlib name '%s' \
to internal library name.")
fndlb_nm)
| _ ->
None)
| null | https://raw.githubusercontent.com/ocaml/oasis/3d1a9421db92a0882ebc58c5df219b18c1e5681d/src/oasis/OASISFindlib.ml | ocaml | ****************************************************************************
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
your option) any later version, with the OCaml static compilation
exception.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the file COPYING for more
details.
****************************************************************************
Solved initialy, no need to go further
Add a library to the tree.
New node
Should not have a nameless library.
TODO: allow to merge Package, i.e.
* archive(byte) = "foo.cma foo_init.cmo"
Revert findlib_name_of_library_name.
END EXPORT | OASIS : architecture for building OCaml libraries and applications
Copyright ( C ) 2011 - 2016 ,
Copyright ( C ) 2008 - 2011 , OCamlCore SARL
the Free Software Foundation ; either version 2.1 of the License , or ( at
You should have received a copy of the GNU Lesser General Public License
along with this library ; if not , write to the Free Software Foundation ,
Inc. , 51 Franklin St , Fifth Floor , Boston , MA 02110 - 1301 USA
open OASISTypes
open OASISUtils
open OASISGettext
type library_name = name
type findlib_part_name = name
type 'a map_of_findlib_part_name = 'a OASISUtils.MapString.t
exception InternalLibraryNotFound of library_name
exception FindlibPackageNotFound of findlib_name
type group_t =
| Container of findlib_name * group_t list
| Package of (findlib_name *
common_section *
build_section *
[`Library of library | `Object of object_] *
unix_dirname option *
group_t list)
type data = common_section *
build_section *
[`Library of library | `Object of object_]
type tree =
| Node of (data option) * (tree MapString.t)
| Leaf of data
let findlib_mapping pkg =
Map from library name to either full findlib name or parts + parent .
let fndlb_parts_of_lib_name =
let fndlb_parts cs lib =
let name =
match lib.lib_findlib_name with
| Some nm -> nm
| None -> cs.cs_name
in
let name =
String.concat "." (lib.lib_findlib_containers @ [name])
in
name
in
List.fold_left
(fun mp ->
function
| Library (cs, _, lib) ->
begin
let lib_name = cs.cs_name in
let fndlb_parts = fndlb_parts cs lib in
if MapString.mem lib_name mp then
failwithf
(f_ "The library name '%s' is used more than once.")
lib_name;
match lib.lib_findlib_parent with
| Some lib_name_parent ->
MapString.add
lib_name
(`Unsolved (lib_name_parent, fndlb_parts))
mp
| None ->
MapString.add
lib_name
(`Solved fndlb_parts)
mp
end
| Object (cs, _, obj) ->
begin
let obj_name = cs.cs_name in
if MapString.mem obj_name mp then
failwithf
(f_ "The object name '%s' is used more than once.")
obj_name;
let findlib_full_name = match obj.obj_findlib_fullname with
| Some ns -> String.concat "." ns
| None -> obj_name
in
MapString.add
obj_name
(`Solved findlib_full_name)
mp
end
| Executable _ | Test _ | Flag _ | SrcRepo _ | Doc _ ->
mp)
MapString.empty
pkg.sections
in
Solve the above graph to be only library name to full findlib name .
let fndlb_name_of_lib_name =
let rec solve visited mp lib_name lib_name_child =
if SetString.mem lib_name visited then
failwithf
(f_ "Library '%s' is involved in a cycle \
with regard to findlib naming.")
lib_name;
let visited = SetString.add lib_name visited in
try
match MapString.find lib_name mp with
| `Solved fndlb_nm ->
fndlb_nm, mp
| `Unsolved (lib_nm_parent, post_fndlb_nm) ->
let pre_fndlb_nm, mp =
solve visited mp lib_nm_parent lib_name
in
let fndlb_nm = pre_fndlb_nm^"."^post_fndlb_nm in
fndlb_nm, MapString.add lib_name (`Solved fndlb_nm) mp
with Not_found ->
failwithf
(f_ "Library '%s', which is defined as the findlib parent of \
library '%s', doesn't exist.")
lib_name lib_name_child
in
let mp =
MapString.fold
(fun lib_name status mp ->
match status with
| `Solved _ ->
mp
| `Unsolved _ ->
let _, mp = solve SetString.empty mp lib_name "<none>" in
mp)
fndlb_parts_of_lib_name
fndlb_parts_of_lib_name
in
MapString.map
(function
| `Solved fndlb_nm -> fndlb_nm
| `Unsolved _ -> assert false)
mp
in
Convert an internal library name to a findlib name .
let findlib_name_of_library_name lib_nm =
try
MapString.find lib_nm fndlb_name_of_lib_name
with Not_found ->
raise (InternalLibraryNotFound lib_nm)
in
let add sct mp =
let fndlb_fullname =
let cs, _, _ = sct in
let lib_name = cs.cs_name in
findlib_name_of_library_name lib_name
in
let rec add_children nm_lst (children: tree MapString.t) =
match nm_lst with
| (hd :: tl) ->
begin
let node =
try
add_node tl (MapString.find hd children)
with Not_found ->
new_node tl
in
MapString.add hd node children
end
| [] ->
assert false
and add_node tl node =
if tl = [] then
begin
match node with
| Node (None, children) ->
Node (Some sct, children)
| Leaf (cs', _, _) | Node (Some (cs', _, _), _) ->
let cs, _, _ = sct in
failwithf
(f_ "Library '%s' and '%s' have the same findlib name '%s'")
cs.cs_name cs'.cs_name fndlb_fullname
end
else
begin
match node with
| Leaf data ->
Node (Some data, add_children tl MapString.empty)
| Node (data_opt, children) ->
Node (data_opt, add_children tl children)
end
and new_node =
function
| [] ->
Leaf sct
| hd :: tl ->
Node (None, MapString.add hd (new_node tl) MapString.empty)
in
add_children (OASISString.nsplit fndlb_fullname '.') mp
in
let unix_directory dn lib =
let directory =
match lib with
| `Library lib -> lib.lib_findlib_directory
| `Object obj -> obj.obj_findlib_directory
in
match dn, directory with
| None, None -> None
| None, Some dn | Some dn, None -> Some dn
| Some dn1, Some dn2 -> Some (OASISUnixPath.concat dn1 dn2)
in
let rec group_of_tree dn mp =
MapString.fold
(fun nm node acc ->
let cur =
match node with
| Node (Some (cs, bs, lib), children) ->
let current_dn = unix_directory dn lib in
Package (nm, cs, bs, lib, current_dn, group_of_tree current_dn children)
| Node (None, children) ->
Container (nm, group_of_tree dn children)
| Leaf (cs, bs, lib) ->
let current_dn = unix_directory dn lib in
Package (nm, cs, bs, lib, current_dn, [])
in
cur :: acc)
mp []
in
let group_mp =
List.fold_left
(fun mp ->
function
| Library (cs, bs, lib) ->
add (cs, bs, `Library lib) mp
| Object (cs, bs, obj) ->
add (cs, bs, `Object obj) mp
| _ ->
mp)
MapString.empty
pkg.sections
in
let groups = group_of_tree None group_mp in
let library_name_of_findlib_name =
lazy begin
MapString.fold
(fun k v mp -> MapString.add v k mp)
fndlb_name_of_lib_name
MapString.empty
end
in
let library_name_of_findlib_name fndlb_nm =
try
MapString.find fndlb_nm (Lazy.force library_name_of_findlib_name)
with Not_found ->
raise (FindlibPackageNotFound fndlb_nm)
in
groups,
findlib_name_of_library_name,
library_name_of_findlib_name
let findlib_of_group =
function
| Container (fndlb_nm, _)
| Package (fndlb_nm, _, _, _, _, _) -> fndlb_nm
let root_of_group grp =
let rec root_lib_aux =
We do a DFS in the group .
function
| Container (_, children) ->
List.fold_left
(fun res grp ->
if res = None then
root_lib_aux grp
else
res)
None
children
| Package (_, cs, bs, lib, _, _) ->
Some (cs, bs, lib)
in
match root_lib_aux grp with
| Some res ->
res
| None ->
failwithf
(f_ "Unable to determine root library of findlib library '%s'")
(findlib_of_group grp)
let () =
Printexc.register_printer
(function
| InternalLibraryNotFound lib_nm ->
Some
(Printf.sprintf
(f_ "Unable to translate internal library name '%s' \
to findlib name.")
lib_nm)
| FindlibPackageNotFound fndlb_nm ->
Some
(Printf.sprintf
(f_ "Unable to translate findlib name '%s' \
to internal library name.")
fndlb_nm)
| _ ->
None)
|
6b89fa84933d399af8a012921c36461df577b3ec5492a593e445bde85aa13d31 | jgoerzen/listlike | String.hs |
Copyright ( C ) 2007 < >
All rights reserved .
For license and copyright information , see the file COPYRIGHT
Copyright (C) 2007 John Goerzen <>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
|
Module : Data . ListLike . String
Copyright : Copyright ( C ) 2007
License : LGPL
Maintainer : < >
Stability : provisional
Portability : portable
String - like functions
Written by , jgoerzen\@complete.org
Module : Data.ListLike.String
Copyright : Copyright (C) 2007 John Goerzen
License : LGPL
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
String-like functions
Written by John Goerzen, jgoerzen\@complete.org
-}
module Data.ListLike.String
( StringLike(..)
)
where
import Prelude hiding (length, head, last, null, tail, map, filter, concat,
any, lookup, init, all, foldl, foldr, foldl1, foldr1,
maximum, minimum, iterate, span, break, takeWhile,
dropWhile, reverse, zip, zipWith, sequence,
sequence_, mapM, mapM_, concatMap, and, or, sum,
product, repeat, replicate, cycle, take, drop,
splitAt, elem, notElem, unzip, lines, words,
unlines, unwords)
import qualified Data.List as L
import Data.ListLike.Base
| An extension to ' ListLike ' for those data types that are similar
to a ' String ' . Minimal complete definition is ' toString ' and
' fromString ' .
to a 'String'. Minimal complete definition is 'toString' and
'fromString'. -}
class StringLike s where
{- | Converts the structure to a 'String' -}
toString :: s -> String
{- | Converts a 'String' to a list -}
fromString :: String -> s
{- | Breaks a string into a list of strings -}
lines :: (ListLike full s) => s -> full
--lines = map fromString . L.lines . toString
lines = myLines
{- | Breaks a string into a list of words -}
words :: ListLike full s => s -> full
words = myWords
{- | Joins lines -}
unlines :: ListLike full s => full -> s
unlines = myUnlines
{- | Joins words -}
unwords :: ListLike full s => full -> s
unwords = myUnwords
For some reason , Hugs required splitting these out into
-- separate functions.
myLines :: (StringLike s, ListLike full s) => s -> full
myLines = map fromString . L.lines . toString
myWords :: (StringLike s, ListLike full s) => s -> full
myWords = map fromString . L.words . toString
myUnlines :: (StringLike s, ListLike full s) => full -> s
myUnlines = fromString . L.unlines . map toString
myUnwords :: (StringLike s, ListLike full s) => full -> s
myUnwords = fromString . L.unwords . map toString
| null | https://raw.githubusercontent.com/jgoerzen/listlike/03d5804191d1fe738e9fad3af409623c014a98f5/src/Data/ListLike/String.hs | haskell | | Converts the structure to a 'String'
| Converts a 'String' to a list
| Breaks a string into a list of strings
lines = map fromString . L.lines . toString
| Breaks a string into a list of words
| Joins lines
| Joins words
separate functions. |
Copyright ( C ) 2007 < >
All rights reserved .
For license and copyright information , see the file COPYRIGHT
Copyright (C) 2007 John Goerzen <>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
|
Module : Data . ListLike . String
Copyright : Copyright ( C ) 2007
License : LGPL
Maintainer : < >
Stability : provisional
Portability : portable
String - like functions
Written by , jgoerzen\@complete.org
Module : Data.ListLike.String
Copyright : Copyright (C) 2007 John Goerzen
License : LGPL
Maintainer : John Goerzen <>
Stability : provisional
Portability: portable
String-like functions
Written by John Goerzen, jgoerzen\@complete.org
-}
module Data.ListLike.String
( StringLike(..)
)
where
import Prelude hiding (length, head, last, null, tail, map, filter, concat,
any, lookup, init, all, foldl, foldr, foldl1, foldr1,
maximum, minimum, iterate, span, break, takeWhile,
dropWhile, reverse, zip, zipWith, sequence,
sequence_, mapM, mapM_, concatMap, and, or, sum,
product, repeat, replicate, cycle, take, drop,
splitAt, elem, notElem, unzip, lines, words,
unlines, unwords)
import qualified Data.List as L
import Data.ListLike.Base
| An extension to ' ListLike ' for those data types that are similar
to a ' String ' . Minimal complete definition is ' toString ' and
' fromString ' .
to a 'String'. Minimal complete definition is 'toString' and
'fromString'. -}
class StringLike s where
toString :: s -> String
fromString :: String -> s
lines :: (ListLike full s) => s -> full
lines = myLines
words :: ListLike full s => s -> full
words = myWords
unlines :: ListLike full s => full -> s
unlines = myUnlines
unwords :: ListLike full s => full -> s
unwords = myUnwords
For some reason , Hugs required splitting these out into
myLines :: (StringLike s, ListLike full s) => s -> full
myLines = map fromString . L.lines . toString
myWords :: (StringLike s, ListLike full s) => s -> full
myWords = map fromString . L.words . toString
myUnlines :: (StringLike s, ListLike full s) => full -> s
myUnlines = fromString . L.unlines . map toString
myUnwords :: (StringLike s, ListLike full s) => full -> s
myUnwords = fromString . L.unwords . map toString
|
d1e5968595e64df5618922a08b1dae35b47df12507f66d5f12a70b34ed99e033 | Relph1119/sicp-solutions-manual | p1-43-rec-compose-repeated.scm | (load "src/practices/ch01/p1-42-compose.scm")
(define (repeated f n)
(if (= n 1)
f
(compose f (repeated f (- n 1))))) | null | https://raw.githubusercontent.com/Relph1119/sicp-solutions-manual/f2ff309a6c898376209c198030c70d6adfac1fc1/src/practices/ch01/p1-43-rec-compose-repeated.scm | scheme | (load "src/practices/ch01/p1-42-compose.scm")
(define (repeated f n)
(if (= n 1)
f
(compose f (repeated f (- n 1))))) | |
2689305c524403137d5e78fb93f1bb9bf922fbd3826992bc795b15c2cf25f992 | antono/guix-debian | gxmessage.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
;;;
;;; 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 gxmessage)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages glib)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages gtk)
#:use-module (gnu packages))
(define-public gxmessage
(package
(name "gxmessage")
(version "2.20.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32 "1b75qjx339c7q0xfxnwb2n5vw6xn8vi6nw2clggfzxnwwx58g2d1"))))
(build-system gnu-build-system)
(inputs
`(("gtk+" ,gtk+-2)))
(native-inputs
`(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Open popup message window with buttons for return")
(description "GNU gxmessage is a program that pops up dialog windows, which display
a message to the user and waits for their action. The program then exits
with an exit code corresponding to the response.")
(license gpl3+)))
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/gxmessage.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.
| Copyright © 2014 < >
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 gxmessage)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages glib)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages gtk)
#:use-module (gnu packages))
(define-public gxmessage
(package
(name "gxmessage")
(version "2.20.1")
(source (origin
(method url-fetch)
(uri (string-append "mirror-"
version ".tar.gz"))
(sha256
(base32 "1b75qjx339c7q0xfxnwb2n5vw6xn8vi6nw2clggfzxnwwx58g2d1"))))
(build-system gnu-build-system)
(inputs
`(("gtk+" ,gtk+-2)))
(native-inputs
`(("intltool" ,intltool)
("pkg-config" ,pkg-config)))
(home-page "/")
(synopsis "Open popup message window with buttons for return")
(description "GNU gxmessage is a program that pops up dialog windows, which display
a message to the user and waits for their action. The program then exits
with an exit code corresponding to the response.")
(license gpl3+)))
|
44bcf6a45343d8dd2883cc8919716ac3e8efdd5cabb3e9ae8093fcf92f70a79b | con-kitty/categorifier-c | Main.hs | {-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Categorifier.C.Generate (writeCFiles)
import F (fCategorified)
-- This generates /tmp/separate_categorification.c
main :: IO ()
main = writeCFiles "/tmp" "separate_categorification" fCategorified
| null | https://raw.githubusercontent.com/con-kitty/categorifier-c/ec3a095ed927cac8a6fc99438cd9ac3ed678f263/examples/separate-categorification/Main.hs | haskell | # LANGUAGE OverloadedStrings #
This generates /tmp/separate_categorification.c |
module Main (main) where
import Categorifier.C.Generate (writeCFiles)
import F (fCategorified)
main :: IO ()
main = writeCFiles "/tmp" "separate_categorification" fCategorified
|
dfb92a7957bd618524012242a17e685bcecf66ff8269455abfabbcf992ee8ee2 | elaforge/karya | CmdTest.hs | Copyright 2013
-- This program is distributed under the terms of the GNU General Public
-- License 3.0, see COPYING or -3.0.txt
-- | Utilities for cmd tests.
module Cmd.CmdTest where
import qualified Control.Concurrent.Async as Async
import qualified Control.Concurrent.Chan as Chan
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified System.IO.Unsafe as Unsafe
import qualified Util.Debug as Debug
import qualified Util.Log as Log
import qualified App.Config as Config
import qualified Cmd.Cmd as Cmd
import qualified Cmd.InputNote as InputNote
import qualified Cmd.Instrument.MidiInst as MidiInst
import qualified Cmd.Msg as Msg
import qualified Cmd.Perf as Perf
import qualified Cmd.Performance as Performance
import Cmd.TestInstances ()
import qualified Derive.Derive as Derive
import qualified Derive.DeriveT as DeriveT
import qualified Derive.DeriveTest as DeriveTest
import qualified Derive.Env as Env
import qualified Derive.EnvKey as EnvKey
import qualified Derive.Expr as Expr
import qualified Derive.Score as Score
import qualified Derive.ScoreT as ScoreT
import qualified Derive.Stream as Stream
import qualified Midi.Interface as Interface
import qualified Midi.Midi as Midi
import qualified Perform.Pitch as Pitch
import qualified Perform.Signal as Signal
import qualified Ui.Diff as Diff
import qualified Ui.Key as Key
import qualified Ui.Sel as Sel
import qualified Ui.Types as Types
import qualified Ui.Ui as Ui
import qualified Ui.UiConfig as UiConfig
import qualified Ui.UiMsg as UiMsg
import qualified Ui.UiTest as UiTest
import qualified Ui.Update as Update
import Global
import Types
-- * running cmds
data Result val = Result {
-- | A Nothing val means it aborted.
result_val :: Either Text (Maybe val)
, result_cmd_state :: Cmd.State
, result_ui_state :: Ui.State
, result_ui_damage :: Update.UiDamage
, result_logs :: [Log.Msg]
, result_thru :: [Cmd.Thru]
}
result_failed :: Result a -> Maybe Text
result_failed = either Just (const Nothing) . result_ok
result_ok :: Result a -> Either Text a
result_ok res = case result_val res of
Right (Just val) -> Right val
Right Nothing -> Left "aborted"
Left err -> Left err
-- | Run cmd with the given tracks.
run_tracks :: [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_tracks tracks = run (make_tracks tracks) default_cmd_state
run_blocks :: [UiTest.BlockSpec] -> Cmd.CmdId a -> Result a
run_blocks blocks = run (snd $ UiTest.run Ui.empty $ UiTest.mkblocks blocks)
default_cmd_state
| Like ' run_tracks ' , but the ruler only extends to the end of the last
-- event.
run_tracks_ruler :: [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_tracks_ruler tracks = run (make_tracks_ruler tracks) default_cmd_state
-- | Derive the tracks and then run the cmd with the performance available.
run_tracks_with_performance :: [UiTest.TrackSpec] -> Cmd.CmdT IO a
-> IO (Result a)
run_tracks_with_performance tracks =
run_with_performance (make_tracks tracks) default_cmd_state
run_with_performance :: Ui.State -> Cmd.State -> Cmd.CmdT IO a
-> IO (Result a)
run_with_performance ustate cstate cmd = do
cstate <- update_performance Ui.empty ustate cstate mempty
run_io ustate cstate cmd
make_tracks :: [UiTest.TrackSpec] -> Ui.State
make_tracks = snd . UiTest.run_mkview
make_tracks_ruler :: [UiTest.TrackSpec] -> Ui.State
make_tracks_ruler = snd . make
where
make tracks = UiTest.run Ui.empty $
UiTest.mkblock_view (UiTest.default_block_name <> "=ruler", tracks)
-- | Run a cmd and return everything you could possibly be interested in.
run :: Ui.State -> Cmd.State -> Cmd.CmdId a -> Result a
run ustate1 cstate1 cmd = Result
{ result_val = val
, result_cmd_state = cstate2
, result_ui_state = ustate2
, result_ui_damage = update
, result_logs = logs
, result_thru = midi_msgs
}
where
(cstate2, midi_msgs, logs, result) = Cmd.run_id ustate1 cstate1 cmd
(val, ustate2, update) = case result of
Left err -> (Left (pretty err), ustate1, mempty)
Right (v, ustate2, update) -> (Right v, ustate2, update)
run_io :: Ui.State -> Cmd.State -> Cmd.CmdT IO a -> IO (Result a)
run_io ustate1 cstate1 cmd = do
(cstate2, thru, logs, result) <-
Cmd.run Nothing ustate1 cstate1 (Just <$> cmd)
let (val, ustate2, update) = case result of
Left err -> (Left (pretty err), ustate1, mempty)
Right (v, ustate2, update) -> (Right v, ustate2, update)
return $ Result val cstate2 ustate2 update logs thru
run_ui :: Ui.State -> Cmd.CmdId a -> Result a
run_ui ustate = run ustate default_cmd_state
run_ui_io :: Ui.State -> Cmd.CmdT IO a -> IO (Result a)
run_ui_io ustate = run_io ustate default_cmd_state
-- | Run a Cmd and return just the value.
eval :: Ui.State -> Cmd.State -> Cmd.CmdId a -> a
eval ustate cstate cmd = case result_val (run ustate cstate cmd) of
Left err -> error $ "eval got StateError: " <> show err
Right Nothing -> error "eval: cmd aborted"
Right (Just val) -> val
-- | Like 'run', but with a selection on the given track at 0 and note
-- duration set to what will be a ScoreTime 1 with the ruler supplied by
-- UiTest.
run_sel :: TrackNum -> [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_sel tracknum track_specs cmd = run_tracks track_specs $ do
Add one because UiTest inserts a rule at track 0 .
set_sel (tracknum+1) 0 (tracknum+1) 0
cmd
run_again :: Result a -> Cmd.CmdId b -> Result b
run_again res = run (result_ui_state res) (result_cmd_state res)
-- | Update performances after running a Cmd and getting its Result.
update_perf :: Ui.State -> Result val -> IO (Result val)
update_perf ui_from res = do
cmd_state <- update_performance ui_from (result_ui_state res)
(result_cmd_state res) (result_ui_damage res)
return $ res { result_cmd_state = cmd_state }
| Run a DeriveTest extractor on a CmdTest Result .
extract_derive :: (Score.Event -> a) -> Result x -> ([a], [Text])
extract_derive ex = DeriveTest.extract ex . extract_derive_result
-- | Reconstruct a Derive.Result from the root performance, or throw an
-- exception if there is a problem getting it.
extract_derive_result :: Result a -> Derive.Result
extract_derive_result res =
maybe (eval (result_ui_state res) (result_cmd_state res) mkres)
(error . (msg<>) . untxt) (result_failed res)
where
msg = "extract_derive_result: cmd failed so result is probably not right: "
mkres = do
Cmd.Performance
{ perf_derive_cache, perf_events, perf_logs
, perf_track_dynamic, perf_integrated, perf_warps
, perf_track_signals
} <- Perf.get_root
let stream = Stream.merge_logs perf_logs $
Stream.from_sorted_events (Vector.toList perf_events)
return $ Derive.Result
{ r_events = stream
, r_cache = perf_derive_cache
, r_track_warps = perf_warps
, r_track_signals = perf_track_signals
, r_track_dynamic = perf_track_dynamic
, r_integrated = perf_integrated
, r_state =
error "can't fake a Derive.State for an extracted Result"
}
-- | Update the performances based on the UI state change and updates. This
-- manually runs that part of the responder, and is needed for tests that rely
-- on the performances.
update_performance :: Ui.State -> Ui.State -> Cmd.State
-> Update.UiDamage -> IO Cmd.State
update_performance ui_from ui_to cmd_state ui_damage = do
let (ui_updates, _) = Diff.diff ui_damage ui_from ui_to
chan <- Chan.newChan
let damage = Diff.derive_diff ui_from ui_to ui_damage ui_updates
cstate <- Performance.update_performance
(\bid status -> Chan.writeChan chan (bid, status))
ui_to (set_immediate cmd_state) damage
-- This will delay until the perform thread has derived enough of the
-- performance to hand over.
(block_id, perf) <- read_perf chan
let insert st = st { Cmd.state_performance = Map.insert block_id perf
(Cmd.state_performance st) }
return $ cstate { Cmd.state_play = insert (Cmd.state_play cstate) }
where
-- Get rid of the derive wait to avoid making tests slow.
set_immediate state = state
{ Cmd.state_derive_immediately = Map.keysSet (Ui.state_blocks ui_to)
}
read_perf chan = do
(block_id, status) <- Chan.readChan chan
case status of
Msg.DeriveComplete perf _ -> return (block_id, perf)
_ -> read_perf chan
| Run several cmds , threading the state through . The first cmd that fails
-- aborts the whole operation.
thread :: Ui.State -> Cmd.State -> [Cmd.CmdId a]
-> Either Text (Ui.State, Cmd.State)
thread ustate cstate cmds = foldl f (Right (ustate, cstate)) cmds
where
f (Right (ustate, cstate)) cmd = case run ustate cstate cmd of
Result (Right _) cstate2 ustate2 _ logs _ ->
DeriveTest.trace_logs logs $ Right (ustate2, cstate2)
Result (Left err) _ _ _ _ _ -> Left (showt err)
f (Left err) _ = Left err
-- | Make some tracks and call 'thread'.
thread_tracks :: [UiTest.TrackSpec] -> (Cmd.State -> Cmd.State)
-> [Cmd.CmdId a] -> Either Text (Ui.State, Cmd.State)
thread_tracks tracks modify_cmd_state cmds =
thread ustate (modify_cmd_state default_cmd_state) cmds
where (_, ustate) = UiTest.run_mkview tracks
default_cmd_state :: Cmd.State
default_cmd_state = mk_cmd_state UiTest.default_db
mk_cmd_state :: Cmd.InstrumentDb -> Cmd.State
mk_cmd_state db = (Cmd.initial_state (DeriveTest.cmd_config db))
{ Cmd.state_focused_view = Just UiTest.default_view_id
, Cmd.state_edit = default_edit_state
, Cmd.state_play = default_play_state
}
default_play_state :: Cmd.PlayState
default_play_state =
Cmd.initial_play_state { Cmd.state_play_step = UiTest.step1 }
default_edit_state :: Cmd.EditState
default_edit_state = Cmd.initial_edit_state
{ Cmd.state_time_step = UiTest.step1
, Cmd.state_note_duration = UiTest.step1
}
* *
-- | This has a hack where if post start_pos and cur_pos are negative, use a
-- negative selection.
set_sel :: Cmd.M m => Types.TrackNum -> ScoreTime -> Types.TrackNum
-> ScoreTime -> m ()
set_sel = set_sel_on UiTest.default_view_id
set_sel_on :: Cmd.M m => ViewId -> Types.TrackNum -> ScoreTime
-> Types.TrackNum -> ScoreTime -> m ()
set_sel_on view_id start_track start_pos cur_track cur_pos = do
Cmd.modify $ \st -> st { Cmd.state_focused_view = Just view_id }
Ui.set_selection view_id Config.insert_selnum (Just sel)
where
sel = Sel.Selection
{ start_track = start_track
, start_pos = abs start_pos
, cur_track = cur_track
, cur_pos = abs cur_pos
, orientation = if start_pos >= 0 && cur_pos >= 0 then Sel.Positive
else if start_pos <= 0 && cur_pos <= 0 then Sel.Negative
else error $ "both start_pos and cur_pos should be + or -: "
<> show (start_pos, cur_pos)
}
set_point_sel :: Ui.M m => Types.TrackNum -> ScoreTime -> m Cmd.Status
set_point_sel tracknum pos = do
set_point_sel_block UiTest.default_block_name tracknum pos
return Cmd.Done
-- | Set a point selection on the default view of the given block name.
set_point_sel_block :: Ui.M m => Text -> Types.TrackNum -> ScoreTime -> m ()
set_point_sel_block block_name tracknum pos =
Ui.set_selection view_id Config.insert_selnum
(Just (Sel.point tracknum pos Sel.Positive))
where view_id = UiTest.mk_vid_name block_name
select_all :: Cmd.M m => m ()
select_all = do
tracks <- Ui.track_count UiTest.default_block_id
end <- Ui.block_end UiTest.default_block_id
set_sel_on UiTest.default_view_id 1 0 (tracks - 1) end
-- * extractors
-- | The output of the 'extract' family of functions:
Either error ( , [ log ] )
type Extracted val = Either Text (val, [Text])
-- | Run this on either 'extract' or 'extract_state' when you don't care about
-- the logs.
trace_logs :: Extracted a -> Either Text a
trace_logs res = case res of
Right (b, logs) -> (if null logs then id else trace logs) (Right b)
Left a -> Left a
where
trace = Debug.trace_str . Text.strip . Text.unlines . ("\tlogged:":)
e_logs :: Result a -> [Text]
e_logs = map DeriveTest.show_log . DeriveTest.trace_low_prio . result_logs
e_performance :: BlockId -> Result a -> Maybe Cmd.Performance
e_performance block_id = Map.lookup block_id . Cmd.state_performance
. Cmd.state_play . result_cmd_state
e_events :: BlockId -> Result a -> [Score.Event]
e_events block_id = maybe [] (Vector.toList . Cmd.perf_events)
. e_performance block_id
e_midi :: Result a -> [Midi.Message]
e_midi result =
[ Midi.wmsg_msg msg
| Cmd.MidiThru (Interface.Midi msg) <- result_thru result
]
-- ** val
-- | Extract the value from a cmd. This is meant to be used as the single
-- check on a cmd operation, so it also returns logs and whether the cmd
-- failed or not (the latter is mandatory since otherwise there is no value).
extract :: (val -> e) -> Result val -> Extracted (Maybe e)
extract f res = case result_val res of
Right val -> Right (fmap f val, e_logs res)
Left err -> Left err
-- ** state
-- | Get something out of the Result from one of the states. Like 'extract',
-- this is meant to be used as the single check on a cmd operation.
extract_state :: (Ui.State -> Cmd.State -> e) -> Result val -> Extracted e
extract_state f res = maybe
(Right (f (result_ui_state res) (result_cmd_state res), e_logs res))
Left (result_failed res)
extract_ui_state :: (Ui.State -> e) -> Result val -> Extracted e
extract_ui_state f = extract_state (\state _ -> f state)
e_tracks :: Result a -> Extracted [UiTest.TrackSpec]
e_tracks = extract_ui_state UiTest.extract_tracks
e_pitch_tracks :: Result a -> Extracted [[UiTest.EventSpec]]
e_pitch_tracks = extract_ui_state $
UiTest.to_pitch_spec . UiTest.to_note_spec . UiTest.extract_tracks
extract_ui :: Ui.StateId e -> Result v -> Extracted e
extract_ui m = extract_ui_state $ \state -> UiTest.eval state m
-- * inst db
-- | Configure ustate and cstate with the given instruments.
set_synths_simple :: [MidiInst.Synth] -> DeriveTest.SimpleAllocations
-> Ui.State -> Cmd.State -> (Ui.State, Cmd.State)
set_synths_simple synths simple_allocs ui_state cmd_state =
( (Ui.config#UiConfig.allocations #= allocs) ui_state
, cmd_state
{ Cmd.state_config = (Cmd.state_config cmd_state)
{ Cmd.config_instrument_db = db }
}
)
where
db = DeriveTest.synths_to_db synths
allocs = DeriveTest.simple_allocs simple_allocs
-- * msg
empty_context :: UiMsg.Context
empty_context = UiMsg.Context Nothing Nothing False
make_key_mods :: [Key.Modifier] -> UiMsg.KbdState -> Key.Key -> Msg.Msg
make_key_mods mods state k = Msg.Ui
(UiMsg.UiMsg empty_context (UiMsg.MsgEvent (UiMsg.Kbd state mods k text)))
where
text = case (k, state) of
(Key.Char c, UiMsg.KeyDown) -> Just c
_ -> Nothing
make_key :: UiMsg.KbdState -> Key.Key -> Msg.Msg
make_key = make_key_mods []
keypress :: Key.Key -> [Msg.Msg]
keypress k = [make_key UiMsg.KeyDown k, make_key UiMsg.KeyUp k]
keypresses :: [Key.Key] -> [Msg.Msg]
keypresses = concatMap keypress
key_down :: Char -> Msg.Msg
key_down = make_key UiMsg.KeyDown . Key.Char
key_up :: Char -> Msg.Msg
key_up = make_key UiMsg.KeyUp . Key.Char
backspace :: Msg.Msg
backspace = make_key UiMsg.KeyDown Key.Backspace
mouse :: Bool -> Types.MouseButton -> TrackNum -> ScoreTime -> Msg.Msg
mouse down btn track pos = Msg.Ui $ UiMsg.UiMsg context $
UiMsg.MsgEvent $ UiMsg.Mouse $ UiMsg.MouseEvent state [] (42, 2) 0 True
where
state = if down then UiMsg.MouseDown btn else UiMsg.MouseUp btn
context = empty_context { UiMsg.ctx_track = Just (track, UiMsg.Track pos) }
drag :: Types.MouseButton -> TrackNum -> ScoreTime -> Msg.Msg
drag btn track pos = Msg.Ui $ UiMsg.UiMsg context $
UiMsg.MsgEvent $ UiMsg.Mouse $
UiMsg.MouseEvent (UiMsg.MouseDrag btn) [] (42, 2) 0 False
where
context = empty_context { UiMsg.ctx_track = Just (track, UiMsg.Track pos) }
make_midi :: Midi.ChannelMessage -> Msg.Msg
make_midi chan_msg = Msg.Midi $
Midi.ReadMessage (Midi.read_device "test") 0
(Midi.ChannelMessage 0 chan_msg)
note_on :: Int -> Pitch.Pitch -> InputNote.Input
note_on note_id pitch = InputNote.NoteOn (InputNote.NoteId note_id)
(Pitch.Input Pitch.AsciiKbd pitch 0) 1
note_on_nn :: Pitch.NoteNumber -> InputNote.Input
note_on_nn nn = InputNote.NoteOn note_id (InputNote.nn_to_input nn) 1
where note_id = InputNote.NoteId $ floor nn
note_off :: Int -> InputNote.GenericInput a
note_off note_id = InputNote.NoteOff (InputNote.NoteId note_id) 1
pitch_change :: Int -> Pitch.Pitch -> InputNote.Input
pitch_change note_id pitch = InputNote.PitchChange (InputNote.NoteId note_id)
(Pitch.Input Pitch.AsciiKbd pitch 0)
pitch_change_nn :: Int -> Pitch.NoteNumber -> InputNote.Input
pitch_change_nn note_id nn =
InputNote.PitchChange (InputNote.NoteId note_id) (InputNote.nn_to_input nn)
control :: Int -> ScoreT.Control -> Signal.Y -> InputNote.GenericInput a
control note_id cont val =
InputNote.Control (InputNote.NoteId note_id) cont val
m_note_on :: Pitch.NoteNumber -> Msg.Msg
m_note_on = Msg.InputNote . note_on_nn
m_note_off :: Int -> Msg.Msg
m_note_off = Msg.InputNote . note_off
m_control :: Int -> ScoreT.Control -> Signal.Y -> Msg.Msg
m_control note_id cont val = Msg.InputNote (control note_id cont val)
m_pitch_change :: Int -> Pitch.NoteNumber -> Msg.Msg
m_pitch_change nid = Msg.InputNote . pitch_change_nn nid
-- * Pitch.Input
ascii_kbd :: Pitch.Pitch -> Pitch.Input
ascii_kbd pitch = Pitch.Input Pitch.AsciiKbd pitch 0
piano_kbd :: Pitch.Pitch -> Pitch.Input
piano_kbd pitch = Pitch.Input Pitch.PianoKbd pitch 0
pitch :: Pitch.Octave -> Pitch.PitchClass -> Pitch.Accidentals -> Pitch.Pitch
pitch oct pc accs = Pitch.Pitch oct (Pitch.Degree pc accs)
oct_pc :: Pitch.Octave -> Pitch.PitchClass -> Pitch.Pitch
oct_pc oct pc = pitch oct pc 0
-- * setup cmds
set_scale :: Cmd.M m => BlockId -> BlockId -> TrackId -> Pitch.ScaleId -> m ()
set_scale root_id block_id track_id scale_id = set_env root_id block_id track_id
[(EnvKey.scale, DeriveT.VStr (Expr.scale_id_to_str scale_id))]
-- | Fake up just enough Performance to have environ in it.
set_env :: Cmd.M m => BlockId -> BlockId -> TrackId
-> [(Env.Key, DeriveT.Val)] -> m ()
set_env root_id block_id track_id environ =
Cmd.modify_play_state $ \st -> st
{ Cmd.state_performance_threads = Map.insert root_id
(Cmd.Thread $ Unsafe.unsafePerformIO $ Async.async (return ()))
(Cmd.state_performance_threads st)
, Cmd.state_performance = Map.insert root_id perf
(Cmd.state_performance st)
}
where
track_dyn = Map.singleton (block_id, track_id)
(Derive.initial_dynamic (Env.from_list environ))
perf = empty_performance { Cmd.perf_track_dynamic = track_dyn }
empty_performance :: Msg.Performance
empty_performance = Cmd.Performance
{ perf_derive_cache = mempty
, perf_events = mempty
, perf_logs = []
, perf_logs_written = True
, perf_track_dynamic = mempty
, perf_integrated = []
, perf_damage = mempty
, perf_warps = []
, perf_track_signals = mempty
, perf_block_deps = mempty
, perf_track_instruments = mempty
, perf_ui_state = Ui.empty
}
| null | https://raw.githubusercontent.com/elaforge/karya/8ea15e6a5fb57e2f15f8c19836751e315f9c09f2/Cmd/CmdTest.hs | haskell | This program is distributed under the terms of the GNU General Public
License 3.0, see COPYING or -3.0.txt
| Utilities for cmd tests.
* running cmds
| A Nothing val means it aborted.
| Run cmd with the given tracks.
event.
| Derive the tracks and then run the cmd with the performance available.
| Run a cmd and return everything you could possibly be interested in.
| Run a Cmd and return just the value.
| Like 'run', but with a selection on the given track at 0 and note
duration set to what will be a ScoreTime 1 with the ruler supplied by
UiTest.
| Update performances after running a Cmd and getting its Result.
| Reconstruct a Derive.Result from the root performance, or throw an
exception if there is a problem getting it.
| Update the performances based on the UI state change and updates. This
manually runs that part of the responder, and is needed for tests that rely
on the performances.
This will delay until the perform thread has derived enough of the
performance to hand over.
Get rid of the derive wait to avoid making tests slow.
aborts the whole operation.
| Make some tracks and call 'thread'.
| This has a hack where if post start_pos and cur_pos are negative, use a
negative selection.
| Set a point selection on the default view of the given block name.
* extractors
| The output of the 'extract' family of functions:
| Run this on either 'extract' or 'extract_state' when you don't care about
the logs.
** val
| Extract the value from a cmd. This is meant to be used as the single
check on a cmd operation, so it also returns logs and whether the cmd
failed or not (the latter is mandatory since otherwise there is no value).
** state
| Get something out of the Result from one of the states. Like 'extract',
this is meant to be used as the single check on a cmd operation.
* inst db
| Configure ustate and cstate with the given instruments.
* msg
* Pitch.Input
* setup cmds
| Fake up just enough Performance to have environ in it. | Copyright 2013
module Cmd.CmdTest where
import qualified Control.Concurrent.Async as Async
import qualified Control.Concurrent.Chan as Chan
import qualified Data.Map as Map
import qualified Data.Text as Text
import qualified Data.Vector as Vector
import qualified System.IO.Unsafe as Unsafe
import qualified Util.Debug as Debug
import qualified Util.Log as Log
import qualified App.Config as Config
import qualified Cmd.Cmd as Cmd
import qualified Cmd.InputNote as InputNote
import qualified Cmd.Instrument.MidiInst as MidiInst
import qualified Cmd.Msg as Msg
import qualified Cmd.Perf as Perf
import qualified Cmd.Performance as Performance
import Cmd.TestInstances ()
import qualified Derive.Derive as Derive
import qualified Derive.DeriveT as DeriveT
import qualified Derive.DeriveTest as DeriveTest
import qualified Derive.Env as Env
import qualified Derive.EnvKey as EnvKey
import qualified Derive.Expr as Expr
import qualified Derive.Score as Score
import qualified Derive.ScoreT as ScoreT
import qualified Derive.Stream as Stream
import qualified Midi.Interface as Interface
import qualified Midi.Midi as Midi
import qualified Perform.Pitch as Pitch
import qualified Perform.Signal as Signal
import qualified Ui.Diff as Diff
import qualified Ui.Key as Key
import qualified Ui.Sel as Sel
import qualified Ui.Types as Types
import qualified Ui.Ui as Ui
import qualified Ui.UiConfig as UiConfig
import qualified Ui.UiMsg as UiMsg
import qualified Ui.UiTest as UiTest
import qualified Ui.Update as Update
import Global
import Types
data Result val = Result {
result_val :: Either Text (Maybe val)
, result_cmd_state :: Cmd.State
, result_ui_state :: Ui.State
, result_ui_damage :: Update.UiDamage
, result_logs :: [Log.Msg]
, result_thru :: [Cmd.Thru]
}
result_failed :: Result a -> Maybe Text
result_failed = either Just (const Nothing) . result_ok
result_ok :: Result a -> Either Text a
result_ok res = case result_val res of
Right (Just val) -> Right val
Right Nothing -> Left "aborted"
Left err -> Left err
run_tracks :: [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_tracks tracks = run (make_tracks tracks) default_cmd_state
run_blocks :: [UiTest.BlockSpec] -> Cmd.CmdId a -> Result a
run_blocks blocks = run (snd $ UiTest.run Ui.empty $ UiTest.mkblocks blocks)
default_cmd_state
| Like ' run_tracks ' , but the ruler only extends to the end of the last
run_tracks_ruler :: [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_tracks_ruler tracks = run (make_tracks_ruler tracks) default_cmd_state
run_tracks_with_performance :: [UiTest.TrackSpec] -> Cmd.CmdT IO a
-> IO (Result a)
run_tracks_with_performance tracks =
run_with_performance (make_tracks tracks) default_cmd_state
run_with_performance :: Ui.State -> Cmd.State -> Cmd.CmdT IO a
-> IO (Result a)
run_with_performance ustate cstate cmd = do
cstate <- update_performance Ui.empty ustate cstate mempty
run_io ustate cstate cmd
make_tracks :: [UiTest.TrackSpec] -> Ui.State
make_tracks = snd . UiTest.run_mkview
make_tracks_ruler :: [UiTest.TrackSpec] -> Ui.State
make_tracks_ruler = snd . make
where
make tracks = UiTest.run Ui.empty $
UiTest.mkblock_view (UiTest.default_block_name <> "=ruler", tracks)
run :: Ui.State -> Cmd.State -> Cmd.CmdId a -> Result a
run ustate1 cstate1 cmd = Result
{ result_val = val
, result_cmd_state = cstate2
, result_ui_state = ustate2
, result_ui_damage = update
, result_logs = logs
, result_thru = midi_msgs
}
where
(cstate2, midi_msgs, logs, result) = Cmd.run_id ustate1 cstate1 cmd
(val, ustate2, update) = case result of
Left err -> (Left (pretty err), ustate1, mempty)
Right (v, ustate2, update) -> (Right v, ustate2, update)
run_io :: Ui.State -> Cmd.State -> Cmd.CmdT IO a -> IO (Result a)
run_io ustate1 cstate1 cmd = do
(cstate2, thru, logs, result) <-
Cmd.run Nothing ustate1 cstate1 (Just <$> cmd)
let (val, ustate2, update) = case result of
Left err -> (Left (pretty err), ustate1, mempty)
Right (v, ustate2, update) -> (Right v, ustate2, update)
return $ Result val cstate2 ustate2 update logs thru
run_ui :: Ui.State -> Cmd.CmdId a -> Result a
run_ui ustate = run ustate default_cmd_state
run_ui_io :: Ui.State -> Cmd.CmdT IO a -> IO (Result a)
run_ui_io ustate = run_io ustate default_cmd_state
eval :: Ui.State -> Cmd.State -> Cmd.CmdId a -> a
eval ustate cstate cmd = case result_val (run ustate cstate cmd) of
Left err -> error $ "eval got StateError: " <> show err
Right Nothing -> error "eval: cmd aborted"
Right (Just val) -> val
run_sel :: TrackNum -> [UiTest.TrackSpec] -> Cmd.CmdId a -> Result a
run_sel tracknum track_specs cmd = run_tracks track_specs $ do
Add one because UiTest inserts a rule at track 0 .
set_sel (tracknum+1) 0 (tracknum+1) 0
cmd
run_again :: Result a -> Cmd.CmdId b -> Result b
run_again res = run (result_ui_state res) (result_cmd_state res)
update_perf :: Ui.State -> Result val -> IO (Result val)
update_perf ui_from res = do
cmd_state <- update_performance ui_from (result_ui_state res)
(result_cmd_state res) (result_ui_damage res)
return $ res { result_cmd_state = cmd_state }
| Run a DeriveTest extractor on a CmdTest Result .
extract_derive :: (Score.Event -> a) -> Result x -> ([a], [Text])
extract_derive ex = DeriveTest.extract ex . extract_derive_result
extract_derive_result :: Result a -> Derive.Result
extract_derive_result res =
maybe (eval (result_ui_state res) (result_cmd_state res) mkres)
(error . (msg<>) . untxt) (result_failed res)
where
msg = "extract_derive_result: cmd failed so result is probably not right: "
mkres = do
Cmd.Performance
{ perf_derive_cache, perf_events, perf_logs
, perf_track_dynamic, perf_integrated, perf_warps
, perf_track_signals
} <- Perf.get_root
let stream = Stream.merge_logs perf_logs $
Stream.from_sorted_events (Vector.toList perf_events)
return $ Derive.Result
{ r_events = stream
, r_cache = perf_derive_cache
, r_track_warps = perf_warps
, r_track_signals = perf_track_signals
, r_track_dynamic = perf_track_dynamic
, r_integrated = perf_integrated
, r_state =
error "can't fake a Derive.State for an extracted Result"
}
update_performance :: Ui.State -> Ui.State -> Cmd.State
-> Update.UiDamage -> IO Cmd.State
update_performance ui_from ui_to cmd_state ui_damage = do
let (ui_updates, _) = Diff.diff ui_damage ui_from ui_to
chan <- Chan.newChan
let damage = Diff.derive_diff ui_from ui_to ui_damage ui_updates
cstate <- Performance.update_performance
(\bid status -> Chan.writeChan chan (bid, status))
ui_to (set_immediate cmd_state) damage
(block_id, perf) <- read_perf chan
let insert st = st { Cmd.state_performance = Map.insert block_id perf
(Cmd.state_performance st) }
return $ cstate { Cmd.state_play = insert (Cmd.state_play cstate) }
where
set_immediate state = state
{ Cmd.state_derive_immediately = Map.keysSet (Ui.state_blocks ui_to)
}
read_perf chan = do
(block_id, status) <- Chan.readChan chan
case status of
Msg.DeriveComplete perf _ -> return (block_id, perf)
_ -> read_perf chan
| Run several cmds , threading the state through . The first cmd that fails
thread :: Ui.State -> Cmd.State -> [Cmd.CmdId a]
-> Either Text (Ui.State, Cmd.State)
thread ustate cstate cmds = foldl f (Right (ustate, cstate)) cmds
where
f (Right (ustate, cstate)) cmd = case run ustate cstate cmd of
Result (Right _) cstate2 ustate2 _ logs _ ->
DeriveTest.trace_logs logs $ Right (ustate2, cstate2)
Result (Left err) _ _ _ _ _ -> Left (showt err)
f (Left err) _ = Left err
thread_tracks :: [UiTest.TrackSpec] -> (Cmd.State -> Cmd.State)
-> [Cmd.CmdId a] -> Either Text (Ui.State, Cmd.State)
thread_tracks tracks modify_cmd_state cmds =
thread ustate (modify_cmd_state default_cmd_state) cmds
where (_, ustate) = UiTest.run_mkview tracks
default_cmd_state :: Cmd.State
default_cmd_state = mk_cmd_state UiTest.default_db
mk_cmd_state :: Cmd.InstrumentDb -> Cmd.State
mk_cmd_state db = (Cmd.initial_state (DeriveTest.cmd_config db))
{ Cmd.state_focused_view = Just UiTest.default_view_id
, Cmd.state_edit = default_edit_state
, Cmd.state_play = default_play_state
}
default_play_state :: Cmd.PlayState
default_play_state =
Cmd.initial_play_state { Cmd.state_play_step = UiTest.step1 }
default_edit_state :: Cmd.EditState
default_edit_state = Cmd.initial_edit_state
{ Cmd.state_time_step = UiTest.step1
, Cmd.state_note_duration = UiTest.step1
}
* *
set_sel :: Cmd.M m => Types.TrackNum -> ScoreTime -> Types.TrackNum
-> ScoreTime -> m ()
set_sel = set_sel_on UiTest.default_view_id
set_sel_on :: Cmd.M m => ViewId -> Types.TrackNum -> ScoreTime
-> Types.TrackNum -> ScoreTime -> m ()
set_sel_on view_id start_track start_pos cur_track cur_pos = do
Cmd.modify $ \st -> st { Cmd.state_focused_view = Just view_id }
Ui.set_selection view_id Config.insert_selnum (Just sel)
where
sel = Sel.Selection
{ start_track = start_track
, start_pos = abs start_pos
, cur_track = cur_track
, cur_pos = abs cur_pos
, orientation = if start_pos >= 0 && cur_pos >= 0 then Sel.Positive
else if start_pos <= 0 && cur_pos <= 0 then Sel.Negative
else error $ "both start_pos and cur_pos should be + or -: "
<> show (start_pos, cur_pos)
}
set_point_sel :: Ui.M m => Types.TrackNum -> ScoreTime -> m Cmd.Status
set_point_sel tracknum pos = do
set_point_sel_block UiTest.default_block_name tracknum pos
return Cmd.Done
set_point_sel_block :: Ui.M m => Text -> Types.TrackNum -> ScoreTime -> m ()
set_point_sel_block block_name tracknum pos =
Ui.set_selection view_id Config.insert_selnum
(Just (Sel.point tracknum pos Sel.Positive))
where view_id = UiTest.mk_vid_name block_name
select_all :: Cmd.M m => m ()
select_all = do
tracks <- Ui.track_count UiTest.default_block_id
end <- Ui.block_end UiTest.default_block_id
set_sel_on UiTest.default_view_id 1 0 (tracks - 1) end
Either error ( , [ log ] )
type Extracted val = Either Text (val, [Text])
trace_logs :: Extracted a -> Either Text a
trace_logs res = case res of
Right (b, logs) -> (if null logs then id else trace logs) (Right b)
Left a -> Left a
where
trace = Debug.trace_str . Text.strip . Text.unlines . ("\tlogged:":)
e_logs :: Result a -> [Text]
e_logs = map DeriveTest.show_log . DeriveTest.trace_low_prio . result_logs
e_performance :: BlockId -> Result a -> Maybe Cmd.Performance
e_performance block_id = Map.lookup block_id . Cmd.state_performance
. Cmd.state_play . result_cmd_state
e_events :: BlockId -> Result a -> [Score.Event]
e_events block_id = maybe [] (Vector.toList . Cmd.perf_events)
. e_performance block_id
e_midi :: Result a -> [Midi.Message]
e_midi result =
[ Midi.wmsg_msg msg
| Cmd.MidiThru (Interface.Midi msg) <- result_thru result
]
extract :: (val -> e) -> Result val -> Extracted (Maybe e)
extract f res = case result_val res of
Right val -> Right (fmap f val, e_logs res)
Left err -> Left err
extract_state :: (Ui.State -> Cmd.State -> e) -> Result val -> Extracted e
extract_state f res = maybe
(Right (f (result_ui_state res) (result_cmd_state res), e_logs res))
Left (result_failed res)
extract_ui_state :: (Ui.State -> e) -> Result val -> Extracted e
extract_ui_state f = extract_state (\state _ -> f state)
e_tracks :: Result a -> Extracted [UiTest.TrackSpec]
e_tracks = extract_ui_state UiTest.extract_tracks
e_pitch_tracks :: Result a -> Extracted [[UiTest.EventSpec]]
e_pitch_tracks = extract_ui_state $
UiTest.to_pitch_spec . UiTest.to_note_spec . UiTest.extract_tracks
extract_ui :: Ui.StateId e -> Result v -> Extracted e
extract_ui m = extract_ui_state $ \state -> UiTest.eval state m
set_synths_simple :: [MidiInst.Synth] -> DeriveTest.SimpleAllocations
-> Ui.State -> Cmd.State -> (Ui.State, Cmd.State)
set_synths_simple synths simple_allocs ui_state cmd_state =
( (Ui.config#UiConfig.allocations #= allocs) ui_state
, cmd_state
{ Cmd.state_config = (Cmd.state_config cmd_state)
{ Cmd.config_instrument_db = db }
}
)
where
db = DeriveTest.synths_to_db synths
allocs = DeriveTest.simple_allocs simple_allocs
empty_context :: UiMsg.Context
empty_context = UiMsg.Context Nothing Nothing False
make_key_mods :: [Key.Modifier] -> UiMsg.KbdState -> Key.Key -> Msg.Msg
make_key_mods mods state k = Msg.Ui
(UiMsg.UiMsg empty_context (UiMsg.MsgEvent (UiMsg.Kbd state mods k text)))
where
text = case (k, state) of
(Key.Char c, UiMsg.KeyDown) -> Just c
_ -> Nothing
make_key :: UiMsg.KbdState -> Key.Key -> Msg.Msg
make_key = make_key_mods []
keypress :: Key.Key -> [Msg.Msg]
keypress k = [make_key UiMsg.KeyDown k, make_key UiMsg.KeyUp k]
keypresses :: [Key.Key] -> [Msg.Msg]
keypresses = concatMap keypress
key_down :: Char -> Msg.Msg
key_down = make_key UiMsg.KeyDown . Key.Char
key_up :: Char -> Msg.Msg
key_up = make_key UiMsg.KeyUp . Key.Char
backspace :: Msg.Msg
backspace = make_key UiMsg.KeyDown Key.Backspace
mouse :: Bool -> Types.MouseButton -> TrackNum -> ScoreTime -> Msg.Msg
mouse down btn track pos = Msg.Ui $ UiMsg.UiMsg context $
UiMsg.MsgEvent $ UiMsg.Mouse $ UiMsg.MouseEvent state [] (42, 2) 0 True
where
state = if down then UiMsg.MouseDown btn else UiMsg.MouseUp btn
context = empty_context { UiMsg.ctx_track = Just (track, UiMsg.Track pos) }
drag :: Types.MouseButton -> TrackNum -> ScoreTime -> Msg.Msg
drag btn track pos = Msg.Ui $ UiMsg.UiMsg context $
UiMsg.MsgEvent $ UiMsg.Mouse $
UiMsg.MouseEvent (UiMsg.MouseDrag btn) [] (42, 2) 0 False
where
context = empty_context { UiMsg.ctx_track = Just (track, UiMsg.Track pos) }
make_midi :: Midi.ChannelMessage -> Msg.Msg
make_midi chan_msg = Msg.Midi $
Midi.ReadMessage (Midi.read_device "test") 0
(Midi.ChannelMessage 0 chan_msg)
note_on :: Int -> Pitch.Pitch -> InputNote.Input
note_on note_id pitch = InputNote.NoteOn (InputNote.NoteId note_id)
(Pitch.Input Pitch.AsciiKbd pitch 0) 1
note_on_nn :: Pitch.NoteNumber -> InputNote.Input
note_on_nn nn = InputNote.NoteOn note_id (InputNote.nn_to_input nn) 1
where note_id = InputNote.NoteId $ floor nn
note_off :: Int -> InputNote.GenericInput a
note_off note_id = InputNote.NoteOff (InputNote.NoteId note_id) 1
pitch_change :: Int -> Pitch.Pitch -> InputNote.Input
pitch_change note_id pitch = InputNote.PitchChange (InputNote.NoteId note_id)
(Pitch.Input Pitch.AsciiKbd pitch 0)
pitch_change_nn :: Int -> Pitch.NoteNumber -> InputNote.Input
pitch_change_nn note_id nn =
InputNote.PitchChange (InputNote.NoteId note_id) (InputNote.nn_to_input nn)
control :: Int -> ScoreT.Control -> Signal.Y -> InputNote.GenericInput a
control note_id cont val =
InputNote.Control (InputNote.NoteId note_id) cont val
m_note_on :: Pitch.NoteNumber -> Msg.Msg
m_note_on = Msg.InputNote . note_on_nn
m_note_off :: Int -> Msg.Msg
m_note_off = Msg.InputNote . note_off
m_control :: Int -> ScoreT.Control -> Signal.Y -> Msg.Msg
m_control note_id cont val = Msg.InputNote (control note_id cont val)
m_pitch_change :: Int -> Pitch.NoteNumber -> Msg.Msg
m_pitch_change nid = Msg.InputNote . pitch_change_nn nid
ascii_kbd :: Pitch.Pitch -> Pitch.Input
ascii_kbd pitch = Pitch.Input Pitch.AsciiKbd pitch 0
piano_kbd :: Pitch.Pitch -> Pitch.Input
piano_kbd pitch = Pitch.Input Pitch.PianoKbd pitch 0
pitch :: Pitch.Octave -> Pitch.PitchClass -> Pitch.Accidentals -> Pitch.Pitch
pitch oct pc accs = Pitch.Pitch oct (Pitch.Degree pc accs)
oct_pc :: Pitch.Octave -> Pitch.PitchClass -> Pitch.Pitch
oct_pc oct pc = pitch oct pc 0
set_scale :: Cmd.M m => BlockId -> BlockId -> TrackId -> Pitch.ScaleId -> m ()
set_scale root_id block_id track_id scale_id = set_env root_id block_id track_id
[(EnvKey.scale, DeriveT.VStr (Expr.scale_id_to_str scale_id))]
set_env :: Cmd.M m => BlockId -> BlockId -> TrackId
-> [(Env.Key, DeriveT.Val)] -> m ()
set_env root_id block_id track_id environ =
Cmd.modify_play_state $ \st -> st
{ Cmd.state_performance_threads = Map.insert root_id
(Cmd.Thread $ Unsafe.unsafePerformIO $ Async.async (return ()))
(Cmd.state_performance_threads st)
, Cmd.state_performance = Map.insert root_id perf
(Cmd.state_performance st)
}
where
track_dyn = Map.singleton (block_id, track_id)
(Derive.initial_dynamic (Env.from_list environ))
perf = empty_performance { Cmd.perf_track_dynamic = track_dyn }
empty_performance :: Msg.Performance
empty_performance = Cmd.Performance
{ perf_derive_cache = mempty
, perf_events = mempty
, perf_logs = []
, perf_logs_written = True
, perf_track_dynamic = mempty
, perf_integrated = []
, perf_damage = mempty
, perf_warps = []
, perf_track_signals = mempty
, perf_block_deps = mempty
, perf_track_instruments = mempty
, perf_ui_state = Ui.empty
}
|
1e269c41fba46b31ab795e0e2ca5b8b4024d5ed0d6f0f41437bef3fc5719d0b5 | sebastiaanvisser/fclabels | Point.hs | | The Point data type which generalizes the different lenses and forms the
basis for vertical composition using the ` Applicative ` type class .
basis for vertical composition using the `Applicative` type class.
-}
# LANGUAGE
TypeOperators
, Arrows
, FlexibleInstances
, MultiParamTypeClasses
, TypeSynonymInstances #
TypeOperators
, Arrows
, FlexibleInstances
, MultiParamTypeClasses
, TypeSynonymInstances #-}
module Data.Label.Point
(
-- * The point data type that generalizes lens.
Point (Point)
, get
, modify
, set
, identity
, compose
-- * Working with isomorphisms.
, Iso (..)
, inv
-- * Specialized lens contexts.
, Total
, Partial
, Failing
-- * Arrow type class for failing with some error.
, ArrowFail (..)
)
where
import Control.Arrow
import Control.Applicative
import Control.Category
import Data.Orphans ()
import Prelude hiding ((.), id, const, curry, uncurry)
{-# INLINE get #-}
{-# INLINE modify #-}
{-# INLINE set #-}
# INLINE identity #
{-# INLINE compose #-}
#
{-# INLINE const #-}
{-# INLINE curry #-}
-------------------------------------------------------------------------------
-- | Abstract Point datatype. The getter and modifier operations work in some
-- category. The type of the value pointed to might change, thereby changing
-- the type of the outer structure.
data Point cat g i f o = Point (cat f o) (cat (cat o i, f) g)
| Get the getter category from a Point .
get :: Point cat g i f o -> cat f o
get (Point g _) = g
| Get the modifier category from a Point .
modify :: Point cat g i f o -> cat (cat o i, f) g
modify (Point _ m) = m
| Get the setter category from a Point .
set :: Arrow arr => Point arr g i f o -> arr (i, f) g
set p = modify p . first (arr const)
-- | Identity Point. Cannot change the type.
identity :: ArrowApply arr => Point arr f f o o
identity = Point id app
-- | Point composition.
compose :: ArrowApply cat
=> Point cat t i b o
-> Point cat g t f b
-> Point cat g i f o
compose (Point f m) (Point g n)
= Point (f . g) (uncurry (curry n . curry m))
-------------------------------------------------------------------------------
instance Arrow arr => Functor (Point arr f i f) where
fmap f x = pure f <*> x
# INLINE fmap #
instance Arrow arr => Applicative (Point arr f i f) where
pure a = Point (const a) (arr snd)
a <*> b = Point (arr app . (get a &&& get b)) $
proc (t, p) -> do (f, v) <- get a &&& get b -< p
q <- modify a -< (t . arr ($ v), p)
modify b -< (t . arr f, q)
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
instance Alternative (Point Partial f view f) where
empty = Point zeroArrow zeroArrow
Point a b <|> Point c d = Point (a <|> c) (b <|> d)
-------------------------------------------------------------------------------
infix 8 `Iso`
| An isomorphism is like a ` Category ` that works in two directions .
data Iso cat i o = Iso { fw :: cat i o, bw :: cat o i }
are categories .
instance Category cat => Category (Iso cat) where
id = Iso id id
Iso a b . Iso c d = Iso (a . c) (d . b)
{-# INLINE id #-}
{-# INLINE (.) #-}
-- | Flip an isomorphism.
inv :: Iso cat i o -> Iso cat o i
inv i = Iso (bw i) (fw i)
-------------------------------------------------------------------------------
-- | Context that represents computations that always produce an output.
type Total = (->)
-- | Context that represents computations that might silently fail.
type Partial = Kleisli Maybe
-- | Context that represents computations that might fail with some error.
type Failing e = Kleisli (Either e)
| The ArrowFail class is similar to ` ArrowZero ` , but additionally embeds
-- some error value in the computation instead of throwing it away.
class Arrow a => ArrowFail e a where
failArrow :: a e c
instance ArrowFail e Partial where
failArrow = Kleisli (const Nothing)
{-# INLINE failArrow #-}
instance ArrowFail e (Failing e) where
failArrow = Kleisli Left
{-# INLINE failArrow #-}
-------------------------------------------------------------------------------
-- Common operations experessed in a generalized form.
const :: Arrow arr => c -> arr b c
const a = arr (\_ -> a)
curry :: Arrow cat => cat (a, b) c -> (a -> cat b c)
curry m i = m . (const i &&& id)
uncurry :: ArrowApply cat => (a -> cat b c) -> cat (a, b) c
uncurry a = app . arr (first a)
| null | https://raw.githubusercontent.com/sebastiaanvisser/fclabels/5592f40af5a3a8af4afa45abf1035ce6495d7442/src/Data/Label/Point.hs | haskell | * The point data type that generalizes lens.
* Working with isomorphisms.
* Specialized lens contexts.
* Arrow type class for failing with some error.
# INLINE get #
# INLINE modify #
# INLINE set #
# INLINE compose #
# INLINE const #
# INLINE curry #
-----------------------------------------------------------------------------
| Abstract Point datatype. The getter and modifier operations work in some
category. The type of the value pointed to might change, thereby changing
the type of the outer structure.
| Identity Point. Cannot change the type.
| Point composition.
-----------------------------------------------------------------------------
# INLINE pure #
# INLINE (<*>) #
-----------------------------------------------------------------------------
# INLINE id #
# INLINE (.) #
| Flip an isomorphism.
-----------------------------------------------------------------------------
| Context that represents computations that always produce an output.
| Context that represents computations that might silently fail.
| Context that represents computations that might fail with some error.
some error value in the computation instead of throwing it away.
# INLINE failArrow #
# INLINE failArrow #
-----------------------------------------------------------------------------
Common operations experessed in a generalized form. | | The Point data type which generalizes the different lenses and forms the
basis for vertical composition using the ` Applicative ` type class .
basis for vertical composition using the `Applicative` type class.
-}
# LANGUAGE
TypeOperators
, Arrows
, FlexibleInstances
, MultiParamTypeClasses
, TypeSynonymInstances #
TypeOperators
, Arrows
, FlexibleInstances
, MultiParamTypeClasses
, TypeSynonymInstances #-}
module Data.Label.Point
(
Point (Point)
, get
, modify
, set
, identity
, compose
, Iso (..)
, inv
, Total
, Partial
, Failing
, ArrowFail (..)
)
where
import Control.Arrow
import Control.Applicative
import Control.Category
import Data.Orphans ()
import Prelude hiding ((.), id, const, curry, uncurry)
# INLINE identity #
#
data Point cat g i f o = Point (cat f o) (cat (cat o i, f) g)
| Get the getter category from a Point .
get :: Point cat g i f o -> cat f o
get (Point g _) = g
| Get the modifier category from a Point .
modify :: Point cat g i f o -> cat (cat o i, f) g
modify (Point _ m) = m
| Get the setter category from a Point .
set :: Arrow arr => Point arr g i f o -> arr (i, f) g
set p = modify p . first (arr const)
identity :: ArrowApply arr => Point arr f f o o
identity = Point id app
compose :: ArrowApply cat
=> Point cat t i b o
-> Point cat g t f b
-> Point cat g i f o
compose (Point f m) (Point g n)
= Point (f . g) (uncurry (curry n . curry m))
instance Arrow arr => Functor (Point arr f i f) where
fmap f x = pure f <*> x
# INLINE fmap #
instance Arrow arr => Applicative (Point arr f i f) where
pure a = Point (const a) (arr snd)
a <*> b = Point (arr app . (get a &&& get b)) $
proc (t, p) -> do (f, v) <- get a &&& get b -< p
q <- modify a -< (t . arr ($ v), p)
modify b -< (t . arr f, q)
instance Alternative (Point Partial f view f) where
empty = Point zeroArrow zeroArrow
Point a b <|> Point c d = Point (a <|> c) (b <|> d)
infix 8 `Iso`
| An isomorphism is like a ` Category ` that works in two directions .
data Iso cat i o = Iso { fw :: cat i o, bw :: cat o i }
are categories .
instance Category cat => Category (Iso cat) where
id = Iso id id
Iso a b . Iso c d = Iso (a . c) (d . b)
inv :: Iso cat i o -> Iso cat o i
inv i = Iso (bw i) (fw i)
type Total = (->)
type Partial = Kleisli Maybe
type Failing e = Kleisli (Either e)
| The ArrowFail class is similar to ` ArrowZero ` , but additionally embeds
class Arrow a => ArrowFail e a where
failArrow :: a e c
instance ArrowFail e Partial where
failArrow = Kleisli (const Nothing)
instance ArrowFail e (Failing e) where
failArrow = Kleisli Left
const :: Arrow arr => c -> arr b c
const a = arr (\_ -> a)
curry :: Arrow cat => cat (a, b) c -> (a -> cat b c)
curry m i = m . (const i &&& id)
uncurry :: ArrowApply cat => (a -> cat b c) -> cat (a, b) c
uncurry a = app . arr (first a)
|
63471fbabe2484db7709baa4caf6aa2fd0792667505807931c184e548af7625b | ardumont/haskell-lab | WriterMonadTryout.hs | -- | Trying to understand by practicing on a small ReaderMonad sample
module Monad.WriterMonadTryout where
-- tell :: w -> Writer w ()
-- execWriter :: Writer w a -> w
: : Writer w a - > ( a , w )
import Data.Monoid
-- Definition
newtype MWriter w a = MWriter { runMWriter :: (a, w) }
instance Monoid w => Monad (MWriter w) where
return a = MWriter (a, mempty)
m >>= k = MWriter $ let
(a, w) = runMWriter m
(b, w') = runMWriter (k a)
in (b, w `mappend` w')
execMWriter :: MWriter w a -> w
execMWriter m = snd (runMWriter m)
mtell :: w -> MWriter w ()
mtell w = MWriter ((), w)
-- Sample
type MyMWriter = MWriter [Int] String
example :: MyMWriter
example = do
mtell [1..5]
mtell [5..10]
return "foo"
output :: (String, [Int])
output = runMWriter example
| null | https://raw.githubusercontent.com/ardumont/haskell-lab/6d1f130300f33dc982c9a6b5d0b6a63af2c2666d/src/Monad/WriterMonadTryout.hs | haskell | | Trying to understand by practicing on a small ReaderMonad sample
tell :: w -> Writer w ()
execWriter :: Writer w a -> w
Definition
Sample |
module Monad.WriterMonadTryout where
: : Writer w a - > ( a , w )
import Data.Monoid
newtype MWriter w a = MWriter { runMWriter :: (a, w) }
instance Monoid w => Monad (MWriter w) where
return a = MWriter (a, mempty)
m >>= k = MWriter $ let
(a, w) = runMWriter m
(b, w') = runMWriter (k a)
in (b, w `mappend` w')
execMWriter :: MWriter w a -> w
execMWriter m = snd (runMWriter m)
mtell :: w -> MWriter w ()
mtell w = MWriter ((), w)
type MyMWriter = MWriter [Int] String
example :: MyMWriter
example = do
mtell [1..5]
mtell [5..10]
return "foo"
output :: (String, [Int])
output = runMWriter example
|
f24881f899b480f054e4628d0672e8d4f69b7eb1a4f9846e67119ced31fe124a | LdBeth/CLFSWM | clfswm-corner.lisp | ;;; --------------------------------------------------------------------------
;;; CLFSWM - FullScreen Window Manager
;;;
;;; --------------------------------------------------------------------------
;;; Documentation: Corner functions
;;; --------------------------------------------------------------------------
;;;
( C ) 2005 - 2015 < >
;;;
;;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or
;;; (at your option) any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; --------------------------------------------------------------------------
(in-package :clfswm)
(symbol-macrolet ((sw (screen-width))
(sh (screen-height))
(cs *corner-size*))
(defun in-corner (corner x y)
"Return t if (x, y) is in corner.
Corner is one of :bottom-right :bottom-left :top-right :top-left"
(multiple-value-bind (xmin ymin xmax ymax)
(case corner
(:bottom-right (values (- sw cs) (- sh cs) sw sh))
(:bottom-left (values 0 (- sh cs) cs sh))
(:top-left (values 0 0 cs cs))
(:top-right (values (- sw cs) 0 sw cs))
(t (values 10 10 0 0)))
(and (<= xmin x xmax)
(<= ymin y ymax)))))
(symbol-macrolet ((sw (screen-width))
(sh (screen-height))
(cs *corner-size*))
(defun find-corner (x y)
(cond ((and (< cs x (- sw cs)) (< cs y (- sh cs))) nil)
((and (<= 0 x cs) (<= 0 y cs)) :top-left)
((and (<= (- sw cs) x sw) (<= 0 y cs)) :top-right)
((and (<= 0 x cs) (<= (- sh cs) y sh)) :bottom-left)
((and (<= (- sw cs) x sw) (<= (- sh cs) y sh)) :bottom-right)
(t nil))))
(defun do-corner-action (x y corner-list)
"Do the action associated with corner. The corner function must return T to
stop the button event"
(when (frame-p (find-current-root))
(let ((corner (find-corner x y)))
(when corner
(let ((fun (second (assoc corner corner-list))))
(when fun
(funcall fun)))))))
;;;***************************************;;;
;;; CONFIG - Corner actions definitions: ;;;
;;;***************************************;;;
(defun find-window-in-query-tree (target-win)
(when target-win
(dolist (win (xlib:query-tree *root*))
(when (child-equal-p win target-win)
(return t)))))
(defun wait-window-in-query-tree (wait-test)
(dotimes (try *corner-command-try-number*)
(dolist (win (xlib:query-tree *root*))
(when (funcall wait-test win)
(return-from wait-window-in-query-tree win)))
(sleep *corner-command-try-delay*)))
(defun generic-present-body (cmd wait-test win &optional focus-p)
(stop-button-event)
(unless (find-window-in-query-tree win)
(do-shell cmd)
(setf win (wait-window-in-query-tree wait-test))
(if win
(progn
(grab-all-buttons win)
(hide-window win))
(notify-message *corner-error-message-delay*
(list (format nil "Error with command ~S" cmd)
*corner-error-message-color*))))
(when win
(cond ((window-hidden-p win)
(unhide-window win)
(when focus-p
(focus-window win))
(raise-window win))
(t (hide-window win)
(show-all-children))))
win)
(let (win)
(defun close-virtual-keyboard ()
(when win
(xlib:destroy-window win)
(xlib:display-finish-output *display*)
(setf win nil)))
(defun present-virtual-keyboard ()
"Present a virtual keyboard"
(setf win (generic-present-body *virtual-keyboard-cmd*
(lambda (win)
(string-equal (xlib:get-wm-class win) "xvkbd"))
win))
t))
(let (win)
(defun equal-clfswm-terminal (window)
(when (and win (xlib:window-p window))
(xlib:window-equal window win)))
(defun close-clfswm-terminal ()
(when win
(xlib:destroy-window win)
(xlib:display-finish-output *display*)
(setf win nil)))
(defun present-clfswm-terminal ()
"Hide/Unhide a terminal"
(setf win (generic-present-body *clfswm-terminal-cmd*
(lambda (win)
(string-equal (xlib:wm-name win) *clfswm-terminal-name*))
win
t))
t))
| null | https://raw.githubusercontent.com/LdBeth/CLFSWM/4e936552d1388718d2947a5f6ca3eada19643e75/src/clfswm-corner.lisp | lisp | --------------------------------------------------------------------------
CLFSWM - FullScreen Window Manager
--------------------------------------------------------------------------
Documentation: Corner functions
--------------------------------------------------------------------------
This program is free software; you can redistribute it and/or modify
either version 3 of the License , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
--------------------------------------------------------------------------
***************************************;;;
CONFIG - Corner actions definitions: ;;;
***************************************;;; | ( C ) 2005 - 2015 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
(in-package :clfswm)
(symbol-macrolet ((sw (screen-width))
(sh (screen-height))
(cs *corner-size*))
(defun in-corner (corner x y)
"Return t if (x, y) is in corner.
Corner is one of :bottom-right :bottom-left :top-right :top-left"
(multiple-value-bind (xmin ymin xmax ymax)
(case corner
(:bottom-right (values (- sw cs) (- sh cs) sw sh))
(:bottom-left (values 0 (- sh cs) cs sh))
(:top-left (values 0 0 cs cs))
(:top-right (values (- sw cs) 0 sw cs))
(t (values 10 10 0 0)))
(and (<= xmin x xmax)
(<= ymin y ymax)))))
(symbol-macrolet ((sw (screen-width))
(sh (screen-height))
(cs *corner-size*))
(defun find-corner (x y)
(cond ((and (< cs x (- sw cs)) (< cs y (- sh cs))) nil)
((and (<= 0 x cs) (<= 0 y cs)) :top-left)
((and (<= (- sw cs) x sw) (<= 0 y cs)) :top-right)
((and (<= 0 x cs) (<= (- sh cs) y sh)) :bottom-left)
((and (<= (- sw cs) x sw) (<= (- sh cs) y sh)) :bottom-right)
(t nil))))
(defun do-corner-action (x y corner-list)
"Do the action associated with corner. The corner function must return T to
stop the button event"
(when (frame-p (find-current-root))
(let ((corner (find-corner x y)))
(when corner
(let ((fun (second (assoc corner corner-list))))
(when fun
(funcall fun)))))))
(defun find-window-in-query-tree (target-win)
(when target-win
(dolist (win (xlib:query-tree *root*))
(when (child-equal-p win target-win)
(return t)))))
(defun wait-window-in-query-tree (wait-test)
(dotimes (try *corner-command-try-number*)
(dolist (win (xlib:query-tree *root*))
(when (funcall wait-test win)
(return-from wait-window-in-query-tree win)))
(sleep *corner-command-try-delay*)))
(defun generic-present-body (cmd wait-test win &optional focus-p)
(stop-button-event)
(unless (find-window-in-query-tree win)
(do-shell cmd)
(setf win (wait-window-in-query-tree wait-test))
(if win
(progn
(grab-all-buttons win)
(hide-window win))
(notify-message *corner-error-message-delay*
(list (format nil "Error with command ~S" cmd)
*corner-error-message-color*))))
(when win
(cond ((window-hidden-p win)
(unhide-window win)
(when focus-p
(focus-window win))
(raise-window win))
(t (hide-window win)
(show-all-children))))
win)
(let (win)
(defun close-virtual-keyboard ()
(when win
(xlib:destroy-window win)
(xlib:display-finish-output *display*)
(setf win nil)))
(defun present-virtual-keyboard ()
"Present a virtual keyboard"
(setf win (generic-present-body *virtual-keyboard-cmd*
(lambda (win)
(string-equal (xlib:get-wm-class win) "xvkbd"))
win))
t))
(let (win)
(defun equal-clfswm-terminal (window)
(when (and win (xlib:window-p window))
(xlib:window-equal window win)))
(defun close-clfswm-terminal ()
(when win
(xlib:destroy-window win)
(xlib:display-finish-output *display*)
(setf win nil)))
(defun present-clfswm-terminal ()
"Hide/Unhide a terminal"
(setf win (generic-present-body *clfswm-terminal-cmd*
(lambda (win)
(string-equal (xlib:wm-name win) *clfswm-terminal-name*))
win
t))
t))
|
a688471771c99fa9a6a65eef1ba35bc11eac907725e3d6f22e5d5df0fcdb853b | facebook/duckling | EL.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Dimensions.EL
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Seal Dimension]
allDimensions =
[ Seal Duration
, Seal Numeral
, Seal Ordinal
, Seal Time
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Dimensions/EL.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Dimensions.EL
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Seal Dimension]
allDimensions =
[ Seal Duration
, Seal Numeral
, Seal Ordinal
, Seal Time
]
|
d9bfd3c6924656198758fd7e4fb15bb022a91d7974ea0d704bae93c89fd100e5 | haskell-servant/servant-elm | generate.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeOperators #-}
import Servant.API ((:<|>), (:>), Capture, Get, JSON, Post, ReqBody)
import Servant.Elm (DefineElm (DefineElm), ElmOptions(urlPrefix),
Proxy (Proxy), UrlPrefix(Static), defaultOptions,
defElmImports, defElmOptions, deriveBoth,
generateElmModuleWith)
data Book = Book
{ name :: String
} deriving (Show, Eq)
deriveBoth defaultOptions ''Book
type BooksApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book
:<|> "books" :> Get '[JSON] [Book]
:<|> "books" :> Capture "bookId" Int :> Get '[JSON] Book
myElmOpts :: ElmOptions
myElmOpts = defElmOptions { urlPrefix = Static ":8000" }
main :: IO ()
main =
generateElmModuleWith
myElmOpts
[ "Generated"
, "BooksApi"
]
defElmImports
"elm"
[ DefineElm (Proxy :: Proxy Book)
]
(Proxy :: Proxy BooksApi)
| null | https://raw.githubusercontent.com/haskell-servant/servant-elm/95c49abe536d8e468efb5a8a0cd750cf817295f4/examples/books/generate.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators # | # LANGUAGE DataKinds #
# LANGUAGE TemplateHaskell #
import Servant.API ((:<|>), (:>), Capture, Get, JSON, Post, ReqBody)
import Servant.Elm (DefineElm (DefineElm), ElmOptions(urlPrefix),
Proxy (Proxy), UrlPrefix(Static), defaultOptions,
defElmImports, defElmOptions, deriveBoth,
generateElmModuleWith)
data Book = Book
{ name :: String
} deriving (Show, Eq)
deriveBoth defaultOptions ''Book
type BooksApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book
:<|> "books" :> Get '[JSON] [Book]
:<|> "books" :> Capture "bookId" Int :> Get '[JSON] Book
myElmOpts :: ElmOptions
myElmOpts = defElmOptions { urlPrefix = Static ":8000" }
main :: IO ()
main =
generateElmModuleWith
myElmOpts
[ "Generated"
, "BooksApi"
]
defElmImports
"elm"
[ DefineElm (Proxy :: Proxy Book)
]
(Proxy :: Proxy BooksApi)
|
092594658b40131085b9d5c85ae1067942583bbdce8cd5d5dad12d09ed829843 | lexi-lambda/racket-r7rs | r5rs.rkt | #lang racket/base
(require racket/require
(only-in r5rs null-environment scheme-report-environment)
(multi-in r7rs (base char complex cxr eval file inexact lazy load read repl write)))
(provide (all-from-out r7rs/cxr)
* + - / < <= = > >= abs acos and angle append apply asin assoc assq assv atan begin boolean?
call-with-current-continuation call-with-input-file call-with-output-file call-with-values
car case cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=?
char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase
char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port
close-output-port complex? cond cons cos current-input-port current-output-port define
define-syntax delay denominator display do dynamic-wind eof-object? eq? equal? eqv? eval
even? exact? exp expt floor for-each force gcd if imag-part inexact? input-port?
integer->char integer? interaction-environment lambda lcm length let let* let-syntax letrec
letrec-syntax list list->string list->vector list-ref list-tail list? load log magnitude
make-polar make-rectangular make-string make-vector map max member memq memv min modulo
negative? newline not null-environment null? number->string number? numerator odd?
open-input-file open-output-file or output-port? pair? peek-char positive? procedure?
quasiquote quote quotient rational? rationalize read read-char real-part real? remainder
reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list
string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=?
string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<?
string=? string>=? string>? string? substring symbol->string symbol? tan truncate values
vector vector->list vector-fill! vector-length vector-ref vector-set! vector?
with-input-from-file with-output-to-file write write-char zero?
(rename-out [inexact exact->inexact]
[exact inexact->exact]))
| null | https://raw.githubusercontent.com/lexi-lambda/racket-r7rs/5834ec6e66f63c61589130aaebd0f25ab3eefc2b/r7rs-lib/r5rs.rkt | racket | #lang racket/base
(require racket/require
(only-in r5rs null-environment scheme-report-environment)
(multi-in r7rs (base char complex cxr eval file inexact lazy load read repl write)))
(provide (all-from-out r7rs/cxr)
* + - / < <= = > >= abs acos and angle append apply asin assoc assq assv atan begin boolean?
call-with-current-continuation call-with-input-file call-with-output-file call-with-values
car case cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=?
char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase
char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port
close-output-port complex? cond cons cos current-input-port current-output-port define
define-syntax delay denominator display do dynamic-wind eof-object? eq? equal? eqv? eval
even? exact? exp expt floor for-each force gcd if imag-part inexact? input-port?
integer->char integer? interaction-environment lambda lcm length let let* let-syntax letrec
letrec-syntax list list->string list->vector list-ref list-tail list? load log magnitude
make-polar make-rectangular make-string make-vector map max member memq memv min modulo
negative? newline not null-environment null? number->string number? numerator odd?
open-input-file open-output-file or output-port? pair? peek-char positive? procedure?
quasiquote quote quotient rational? rationalize read read-char real-part real? remainder
reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list
string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=?
string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<?
string=? string>=? string>? string? substring symbol->string symbol? tan truncate values
vector vector->list vector-fill! vector-length vector-ref vector-set! vector?
with-input-from-file with-output-to-file write write-char zero?
(rename-out [inexact exact->inexact]
[exact inexact->exact]))
| |
464814ab7848dbbeacf31c8487bb7431323803af7b3810bac823549afd0f636e | ds-wizard/engine-backend | ClearReplySpec.hs | module Wizard.Specs.Websocket.Questionnaire.Detail.ClearReplySpec where
import Data.Aeson
import Network.WebSockets
import Test.Hspec hiding (shouldBe)
import Test.Hspec.Expectations.Pretty
import Shared.Database.DAO.Package.PackageDAO
import Shared.Database.Migration.Development.Package.Data.Packages
import Wizard.Api.Resource.Websocket.QuestionnaireActionDTO
import Wizard.Api.Resource.Websocket.WebsocketActionDTO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireEvents
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import Wizard.Database.Migration.Development.Report.Data.Reports
import Wizard.Database.Migration.Development.User.Data.Users
import qualified Wizard.Database.Migration.Development.User.UserMigration as U
import Wizard.Model.Questionnaire.Questionnaire
import Wizard.Service.Questionnaire.Event.QuestionnaireEventMapper
import Wizard.Specs.Common
import Wizard.Specs.Websocket.Common
import Wizard.Specs.Websocket.Questionnaire.Detail.Common
clearReplySpec appContext = describe "clearReply" $ test200 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test200 appContext =
it "WS 200 OK" $
-- GIVEN: Prepare database
do
let qtn = questionnaire10
runInContext U.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO (insertPackage germanyPackage) appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
runInContextIO (insertQuestionnaire questionnaire7) appContext
-- AND: Connect to websocket
((c1, s1), (c2, s2), (c3, s3)) <- connectTestWebsocketUsers appContext questionnaire10.uuid
((c4, s4), (c5, s5), (c6, s6)) <- connectTestWebsocketUsers appContext questionnaire7.uuid
-- WHEN:
write_ClearReply c1 (toEventChangeDTO cre_rQ1' samplePhasesAnsweredIndication)
-- THEN:
read_ClearReply c1 (toEventDTO cre_rQ1' (Just userAlbert))
read_ClearReply c2 (toEventDTO cre_rQ1' (Just userAlbert))
read_ClearReply c3 (toEventDTO cre_rQ1' (Just userAlbert))
nothingWasReceived c4
nothingWasReceived c5
nothingWasReceived c6
-- AND: Close sockets
closeSockets [s1, s2, s3, s4, s5, s6]
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
write_ClearReply connection replyDto = do
let reqDto = SetContent_ClientQuestionnaireActionDTO replyDto
sendMessage connection reqDto
read_ClearReply connection expReplyDto = do
resDto <- receiveData connection
let eResult = eitherDecode resDto :: Either String (Success_ServerActionDTO ServerQuestionnaireActionDTO)
let (Right (Success_ServerActionDTO (SetContent_ServerQuestionnaireActionDTO replyDto))) = eResult
expReplyDto `shouldBe` replyDto
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/test/Wizard/Specs/Websocket/Questionnaire/Detail/ClearReplySpec.hs | haskell | ----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare database
AND: Connect to websocket
WHEN:
THEN:
AND: Close sockets
----------------------------------------------------
----------------------------------------------------
---------------------------------------------------- | module Wizard.Specs.Websocket.Questionnaire.Detail.ClearReplySpec where
import Data.Aeson
import Network.WebSockets
import Test.Hspec hiding (shouldBe)
import Test.Hspec.Expectations.Pretty
import Shared.Database.DAO.Package.PackageDAO
import Shared.Database.Migration.Development.Package.Data.Packages
import Wizard.Api.Resource.Websocket.QuestionnaireActionDTO
import Wizard.Api.Resource.Websocket.WebsocketActionDTO
import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO
import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration
import Wizard.Database.Migration.Development.Questionnaire.Data.QuestionnaireEvents
import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires
import Wizard.Database.Migration.Development.Report.Data.Reports
import Wizard.Database.Migration.Development.User.Data.Users
import qualified Wizard.Database.Migration.Development.User.UserMigration as U
import Wizard.Model.Questionnaire.Questionnaire
import Wizard.Service.Questionnaire.Event.QuestionnaireEventMapper
import Wizard.Specs.Common
import Wizard.Specs.Websocket.Common
import Wizard.Specs.Websocket.Questionnaire.Detail.Common
clearReplySpec appContext = describe "clearReply" $ test200 appContext
test200 appContext =
it "WS 200 OK" $
do
let qtn = questionnaire10
runInContext U.runMigration appContext
runInContextIO TML_Migration.runMigration appContext
runInContextIO (insertPackage germanyPackage) appContext
runInContextIO (insertQuestionnaire questionnaire10) appContext
runInContextIO (insertQuestionnaire questionnaire7) appContext
((c1, s1), (c2, s2), (c3, s3)) <- connectTestWebsocketUsers appContext questionnaire10.uuid
((c4, s4), (c5, s5), (c6, s6)) <- connectTestWebsocketUsers appContext questionnaire7.uuid
write_ClearReply c1 (toEventChangeDTO cre_rQ1' samplePhasesAnsweredIndication)
read_ClearReply c1 (toEventDTO cre_rQ1' (Just userAlbert))
read_ClearReply c2 (toEventDTO cre_rQ1' (Just userAlbert))
read_ClearReply c3 (toEventDTO cre_rQ1' (Just userAlbert))
nothingWasReceived c4
nothingWasReceived c5
nothingWasReceived c6
closeSockets [s1, s2, s3, s4, s5, s6]
write_ClearReply connection replyDto = do
let reqDto = SetContent_ClientQuestionnaireActionDTO replyDto
sendMessage connection reqDto
read_ClearReply connection expReplyDto = do
resDto <- receiveData connection
let eResult = eitherDecode resDto :: Either String (Success_ServerActionDTO ServerQuestionnaireActionDTO)
let (Right (Success_ServerActionDTO (SetContent_ServerQuestionnaireActionDTO replyDto))) = eResult
expReplyDto `shouldBe` replyDto
|
2445f0f4da55ebfb99406ede416bca0312169df02d48bbd6dcc9d2d75b01fe70 | roburio/albatross | vmm_asn.mli | ( c ) 2017 , 2018 , all rights reserved
open Vmm_core
(** ASN.1 encoding of resources and configuration *)
(** {1 Object Identifier} *)
* OID in the Mirage namespace ( enterprise arc 1.3.6.1.4.1.49836.42 )
val oid : Asn.OID.t
val wire_to_cstruct : Vmm_commands.wire -> Cstruct.t
val wire_of_cstruct : Cstruct.t -> (Vmm_commands.wire, [> `Msg of string ]) result
val of_cert_extension :
Cstruct.t -> (Vmm_commands.version * Vmm_commands.t, [> `Msg of string ]) result
val to_cert_extension : Vmm_commands.t -> Cstruct.t
val unikernels_to_cstruct : Unikernel.config Vmm_trie.t -> Cstruct.t
val unikernels_of_cstruct : Cstruct.t -> (Unikernel.config Vmm_trie.t, [> `Msg of string ]) result
| null | https://raw.githubusercontent.com/roburio/albatross/e5a442c84eccb69a84116fec9c919d613a7cb575/src/vmm_asn.mli | ocaml | * ASN.1 encoding of resources and configuration
* {1 Object Identifier} | ( c ) 2017 , 2018 , all rights reserved
open Vmm_core
* OID in the Mirage namespace ( enterprise arc 1.3.6.1.4.1.49836.42 )
val oid : Asn.OID.t
val wire_to_cstruct : Vmm_commands.wire -> Cstruct.t
val wire_of_cstruct : Cstruct.t -> (Vmm_commands.wire, [> `Msg of string ]) result
val of_cert_extension :
Cstruct.t -> (Vmm_commands.version * Vmm_commands.t, [> `Msg of string ]) result
val to_cert_extension : Vmm_commands.t -> Cstruct.t
val unikernels_to_cstruct : Unikernel.config Vmm_trie.t -> Cstruct.t
val unikernels_of_cstruct : Cstruct.t -> (Unikernel.config Vmm_trie.t, [> `Msg of string ]) result
|
48271658f998e8eaccefe45695c8783cda4b813fededeeb5b08adf2fcac5d13e | EFanZh/EOPL-Exercises | exercise-4.x-call-by-reference-lang-test.rkt | #lang racket/base
(require rackunit)
(require "../solutions/exercise-4.x-call-by-reference-lang.rkt")
(check-equal? (run "2") (num-val 2))
(check-equal? (run "-(3, 3)") (num-val 0))
(check-equal? (run "-(3, 4)") (num-val -1))
(check-equal? (run "-(4, 3)") (num-val 1))
(check-equal? (run "zero?(0)") (bool-val #t))
(check-equal? (run "zero?(4)") (bool-val #f))
(check-equal? (run "if zero?(0) then 7 else 11") (num-val 7))
(check-equal? (run "if zero?(2) then 7 else 11") (num-val 11))
(check-equal? (run "let x = 5 in x") (num-val 5))
(check-equal? (run "let x = 5 in let x = 3 in x") (num-val 3))
(check-equal? (run "let f = proc (x) -(x, 11)
in (f (f 77))")
(num-val 55))
(check-equal? (run "(proc (f) (f (f 77))
proc (x) -(x, 11))")
(num-val 55))
(check-equal? (run "let x = 200
in let f = proc (z)
-(z, x)
in let x = 100
in let g = proc (z)
-(z, x)
in -((f 1), (g 1))")
(num-val -100))
(check-equal? (run "letrec double(x) = if zero?(x)
then 0
else -((double -(x, 1)), -2)
in (double 6)")
(num-val 12))
(check-equal? (run "let x = 0
in letrec even(dummy) = if zero?(x)
then 1
else begin set x = -(x, 1);
(odd 888)
end
odd(dummy) = if zero?(x)
then 0
else begin set x = -(x, 1);
(even 888)
end
in begin set x = 13;
(odd 888)
end")
(num-val 1))
(check-equal? (run "let g = let counter = 0
in proc (dummy)
begin set counter = -(counter, -1);
counter
end
in let a = (g 11)
in let b = (g 11)
in -(a, b)")
(num-val -1))
(check-equal? (run "left(newpair(2, 3))") (num-val 2))
(check-equal? (run "right(newpair(2, 3))") (num-val 3))
(check-equal? (run "let p = newpair(2, 3)
in let x = left(p)
in begin setleft p = 4;
let y = left(p)
in -(x, y)
end")
(num-val -2))
(check-equal? (run "let p = newpair(2, 3)
in let x = right(p)
in begin setright p = 4;
let y = right(p)
in -(x, y)
end")
(num-val -1))
(check-equal? (run "let p = proc (x)
set x = 4
in let a = 3
in begin (p a);
a
end")
(num-val 4))
(check-equal? (run "let f = proc (x)
set x = 44
in let g = proc (y)
(f y)
in let z = 55
in begin (g z);
z
end")
(num-val 44))
(check-equal? (run "let swap = proc (x)
proc (y)
let temp = x
in begin set x = y;
set y = temp
end
in let a = 33
in let b = 44
in begin ((swap a) b);
-(a, b)
end")
(num-val 11))
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/tests/exercise-4.x-call-by-reference-lang-test.rkt | racket | #lang racket/base
(require rackunit)
(require "../solutions/exercise-4.x-call-by-reference-lang.rkt")
(check-equal? (run "2") (num-val 2))
(check-equal? (run "-(3, 3)") (num-val 0))
(check-equal? (run "-(3, 4)") (num-val -1))
(check-equal? (run "-(4, 3)") (num-val 1))
(check-equal? (run "zero?(0)") (bool-val #t))
(check-equal? (run "zero?(4)") (bool-val #f))
(check-equal? (run "if zero?(0) then 7 else 11") (num-val 7))
(check-equal? (run "if zero?(2) then 7 else 11") (num-val 11))
(check-equal? (run "let x = 5 in x") (num-val 5))
(check-equal? (run "let x = 5 in let x = 3 in x") (num-val 3))
(check-equal? (run "let f = proc (x) -(x, 11)
in (f (f 77))")
(num-val 55))
(check-equal? (run "(proc (f) (f (f 77))
proc (x) -(x, 11))")
(num-val 55))
(check-equal? (run "let x = 200
in let f = proc (z)
-(z, x)
in let x = 100
in let g = proc (z)
-(z, x)
in -((f 1), (g 1))")
(num-val -100))
(check-equal? (run "letrec double(x) = if zero?(x)
then 0
else -((double -(x, 1)), -2)
in (double 6)")
(num-val 12))
(check-equal? (run "let x = 0
in letrec even(dummy) = if zero?(x)
then 1
(odd 888)
end
odd(dummy) = if zero?(x)
then 0
(even 888)
end
(odd 888)
end")
(num-val 1))
(check-equal? (run "let g = let counter = 0
in proc (dummy)
counter
end
in let a = (g 11)
in let b = (g 11)
in -(a, b)")
(num-val -1))
(check-equal? (run "left(newpair(2, 3))") (num-val 2))
(check-equal? (run "right(newpair(2, 3))") (num-val 3))
(check-equal? (run "let p = newpair(2, 3)
in let x = left(p)
let y = left(p)
in -(x, y)
end")
(num-val -2))
(check-equal? (run "let p = newpair(2, 3)
in let x = right(p)
let y = right(p)
in -(x, y)
end")
(num-val -1))
(check-equal? (run "let p = proc (x)
set x = 4
in let a = 3
a
end")
(num-val 4))
(check-equal? (run "let f = proc (x)
set x = 44
in let g = proc (y)
(f y)
in let z = 55
z
end")
(num-val 44))
(check-equal? (run "let swap = proc (x)
proc (y)
let temp = x
set y = temp
end
in let a = 33
in let b = 44
-(a, b)
end")
(num-val 11))
| |
44105b2180f5163aff251113327a2f6509cdb42be9df87a6de19c9d1641cb41a | runtimeverification/haskell-backend | Overloading.hs | module Test.Kore.Simplify.Overloading (
test_matchOverloading,
test_unifyOverloading,
) where
import Control.Monad.Trans.Except (
runExceptT,
)
import Kore.Builtin.Bool.Bool qualified as Bool
import Kore.Builtin.Int.Int qualified as Int
import Kore.Builtin.String.String qualified as String
import Kore.Internal.Condition qualified as Condition
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
mkConfigVariable,
)
import Kore.Simplify.Overloading
import Pair
import Prelude.Kore
import Test.Kore.Internal.TermLike
import Test.Kore.Rewrite.MockSymbols qualified as Mock
import Test.Kore.Simplify
import Test.Kore.Syntax.Id
import Test.Tasty
import Test.Tasty.HUnit.Ext
type ElementVariable' = ElementVariable RewritingVariableName
test_matchOverloading :: [TestTree]
test_matchOverloading =
[ testGroup
"Matching overloads"
[ matches
"direct overload, left side"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, matches
"direct overload, right side"
( Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, matches
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, matches
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
)
, doesn'tMatch
"overload, both sides, not unifiable"
( Mock.sortInjectionOtherToOtherTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOtherTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
"overloaded constructors not unifiable"
, doesn'tMatch
"overload vs injected constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.aOtherSort)
"different injected ctor"
, doesn'tMatch
"overload vs injected domain value"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop otherDomainValue)
"injected domain value"
, doesn'tMatch
"injected domain value vs overload"
(Mock.sortInjectionOtherToTop otherDomainValue)
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
"injected domain value"
, doesn'tMatch
"overload vs injected int"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Int.asInternal Mock.otherSort 0))
"injected builtin int"
, doesn'tMatch
"overload vs injected bool"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Bool.asInternal Mock.otherSort True))
"injected builtin bool"
, doesn'tMatch
"overload vs injected string"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (String.asInternal Mock.otherSort ""))
"injected builtin string"
, matchNotApplicable
"direct overload vs. variable, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkElemVar Mock.xConfigOtherSort))
, matchNotApplicable
"overload vs injected non-constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.plain00OtherSort)
, matchNotApplicable
"overload vs injected top"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkTop Mock.otherSort))
, matchNotApplicable
"unrelated"
Mock.aOtherSort
Mock.plain00OtherSort
, matchNotApplicableTwice
"direct overload, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
, matchNotApplicableTwice
"direct overload, right side"
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
, matchNotApplicableTwice
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
, matchNotApplicableTwice
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
]
]
test_unifyOverloading :: [TestTree]
test_unifyOverloading =
[ testGroup
"Unifying overloads"
[ unifies
"direct overload, left side"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, unifies
"direct overload, right side"
( Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, unifies
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, unifies
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
)
, narrows
"direct overload vs. variable, left side; var direct"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionSubToTop (mkElemVar Mock.xConfigSubSort)
)
(
( Mock.xConfigSubSort
, Mock.subOverload x1
)
,
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, narrows
"direct overload vs. variable, left side; var inject"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionTestToTop (mkElemVar Mock.xConfig)
)
(
( Mock.xConfig
, Mock.sortInjectionSubToTest (Mock.subOverload x1)
)
,
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, narrows
"injected overload vs injected variable, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionTestToTop (mkElemVar Mock.xConfig)
)
(
( Mock.xConfig
, Mock.sortInjectionSubToTest (Mock.subOverload x1)
)
,
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, doesn'tUnify
"overload, both sides, not unifiable"
( Mock.sortInjectionOtherToOtherTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOtherTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
"overloaded constructors not unifiable"
, doesn'tUnify
"overload vs injected constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.aOtherSort)
"different injected ctor"
, doesn'tUnify
"overload vs injected domain value"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop otherDomainValue)
"injected domain value"
, doesn'tUnify
"injected domain value vs overload"
(Mock.sortInjectionOtherToTop otherDomainValue)
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
"injected domain value"
, doesn'tUnify
"overload vs injected int"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Int.asInternal Mock.otherSort 0))
"injected builtin int"
, doesn'tUnify
"overload vs injected bool"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Bool.asInternal Mock.otherSort True))
"injected builtin bool"
, doesn'tUnify
"overload vs injected string"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (String.asInternal Mock.otherSort ""))
"injected builtin string"
, doesn'tUnify
"injected overload vs injected variable"
( Mock.sortInjectionSubSubToTop
(Mock.subsubOverload Mock.aSubSubsort)
)
( Mock.sortInjectionSubOtherToTop
(mkElemVar Mock.xConfigSubOtherSort)
)
"overloaded constructors not unifiable"
, unifyNotApplicable
"overload vs injected non-constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.plain00OtherSort)
, unifyNotApplicable
"overload vs injected top"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkTop Mock.otherSort))
, unifyNotApplicable
"unrelated"
Mock.aOtherSort
Mock.plain00OtherSort
, unifyNotApplicableTwice
"direct overload, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
, unifyNotApplicableTwice
"direct overload, right side"
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
, unifyNotApplicableTwice
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
, unifyNotApplicableTwice
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
]
]
otherDomainValue :: TermLike RewritingVariableName
otherDomainValue =
mkDomainValue
DomainValue
{ domainValueSort = Mock.otherSort
, domainValueChild = mkStringLiteral "a"
}
matches ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
TestTree
matches comment (term1, term2) (term1', term2') =
withMatching
(assertEqual "" (Right (Pair term1' term2')))
comment
(Pair term1 term2)
doesn'tMatch ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
String ->
TestTree
doesn'tMatch comment term1 term2 reason =
withMatching
(assertEqual "" (Left (Clash reason)))
comment
(Pair term1 term2)
matchNotApplicable ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
matchNotApplicable comment term1 term2 =
withMatching
(assertEqual "" (Left NotApplicable))
comment
(Pair term1 term2)
matchNotApplicableTwice ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
matchNotApplicableTwice comment term1 term2 =
withMatchingTwice
(assertEqual "" (Left NotApplicable))
comment
(Pair term1 term2)
unifies ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
TestTree
unifies comment (term1, term2) (term1', term2') =
withUnification
(assertEqual "" (Just (Resolution (Simple (Pair term1' term2')))))
comment
(Pair term1 term2)
narrows ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
( (ElementVariable', TermLike RewritingVariableName)
, (TermLike RewritingVariableName, TermLike RewritingVariableName)
) ->
TestTree
narrows comment (term1, term2) ((v, term), (term1', term2')) =
withUnification
checkNarrowing
comment
(Pair term1 term2)
where
checkNarrowing :: UnificationResult -> Assertion
checkNarrowing
( Just
( Resolution
( WithNarrowing
Narrowing{narrowingSubst, overloadPair}
)
)
) =
do
assertEqual "" (Pair term1' term2') overloadPair
assertEqual "" expectedSubst narrowingSubst
checkNarrowing _ = assertFailure "Expected narrowing solution"
expectedSubst = Condition.assign (inject v) term
doesn'tUnify ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
String ->
TestTree
doesn'tUnify comment term1 term2 reason =
withUnification
(assertEqual "" (Just (ClashResult reason)))
comment
(Pair term1 term2)
unifyNotApplicable ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
unifyNotApplicable comment term1 term2 =
withUnification
(assertEqual "" Nothing)
comment
(Pair term1 term2)
unifyNotApplicableTwice ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
unifyNotApplicableTwice comment term1 term2 =
withUnificationTwice
(assertEqual "" Nothing)
comment
(Pair term1 term2)
type TestMatchResult =
Either UnifyOverloadingError (Pair (TermLike RewritingVariableName))
match ::
Pair (TermLike RewritingVariableName) ->
IO TestMatchResult
match termPair = testRunSimplifier Mock.env $ runExceptT matchResult
where
matchResult :: MatchOverloadingResult Simplifier RewritingVariableName
matchResult = matchOverloading termPair
withMatching ::
(TestMatchResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withMatching check comment termPair =
testCase comment $ do
actual <- match termPair
check actual
withMatchingTwice ::
(TestMatchResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withMatchingTwice check comment termPair =
testCase comment $ do
actual <- match termPair
case actual of
Left _ -> assertFailure "Expected matching solution."
Right termPair' -> do
actual' <- match termPair'
check actual'
type UnificationResult =
Maybe MatchResult
unify ::
Pair (TermLike RewritingVariableName) ->
IO UnificationResult
unify termPair =
testRunSimplifier Mock.env $ return unifyResult
where
unifyResult :: Maybe MatchResult
unifyResult = matchResult <$> unifyOverloading Mock.overloadSimplifier termPair
withUnification ::
(UnificationResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withUnification check comment termPair =
testCase comment $ do
actual <- unify termPair
check actual
withUnificationTwice ::
(UnificationResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withUnificationTwice check comment termPair =
testCase comment $ do
actual <- unify termPair
case actual of
Just (Resolution (Simple termPair')) -> do
actual' <- unify termPair'
check actual'
Just (Resolution (WithNarrowing Narrowing{overloadPair})) -> do
actual' <- unify overloadPair
check actual'
_ -> assertFailure "Expected matching solution."
x1 :: TermLike RewritingVariableName
x1 =
mkElemVar
( mkElementVariable (testId "x1") Mock.subSort
& mapElementVariable (pure mkConfigVariable)
)
| null | https://raw.githubusercontent.com/runtimeverification/haskell-backend/3c37aabb2ef9f7645e12ae8819e287577969216a/kore/test/Test/Kore/Simplify/Overloading.hs | haskell | module Test.Kore.Simplify.Overloading (
test_matchOverloading,
test_unifyOverloading,
) where
import Control.Monad.Trans.Except (
runExceptT,
)
import Kore.Builtin.Bool.Bool qualified as Bool
import Kore.Builtin.Int.Int qualified as Int
import Kore.Builtin.String.String qualified as String
import Kore.Internal.Condition qualified as Condition
import Kore.Rewrite.RewritingVariable (
RewritingVariableName,
mkConfigVariable,
)
import Kore.Simplify.Overloading
import Pair
import Prelude.Kore
import Test.Kore.Internal.TermLike
import Test.Kore.Rewrite.MockSymbols qualified as Mock
import Test.Kore.Simplify
import Test.Kore.Syntax.Id
import Test.Tasty
import Test.Tasty.HUnit.Ext
type ElementVariable' = ElementVariable RewritingVariableName
test_matchOverloading :: [TestTree]
test_matchOverloading =
[ testGroup
"Matching overloads"
[ matches
"direct overload, left side"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, matches
"direct overload, right side"
( Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, matches
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, matches
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
)
, doesn'tMatch
"overload, both sides, not unifiable"
( Mock.sortInjectionOtherToOtherTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOtherTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
"overloaded constructors not unifiable"
, doesn'tMatch
"overload vs injected constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.aOtherSort)
"different injected ctor"
, doesn'tMatch
"overload vs injected domain value"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop otherDomainValue)
"injected domain value"
, doesn'tMatch
"injected domain value vs overload"
(Mock.sortInjectionOtherToTop otherDomainValue)
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
"injected domain value"
, doesn'tMatch
"overload vs injected int"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Int.asInternal Mock.otherSort 0))
"injected builtin int"
, doesn'tMatch
"overload vs injected bool"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Bool.asInternal Mock.otherSort True))
"injected builtin bool"
, doesn'tMatch
"overload vs injected string"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (String.asInternal Mock.otherSort ""))
"injected builtin string"
, matchNotApplicable
"direct overload vs. variable, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkElemVar Mock.xConfigOtherSort))
, matchNotApplicable
"overload vs injected non-constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.plain00OtherSort)
, matchNotApplicable
"overload vs injected top"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkTop Mock.otherSort))
, matchNotApplicable
"unrelated"
Mock.aOtherSort
Mock.plain00OtherSort
, matchNotApplicableTwice
"direct overload, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
, matchNotApplicableTwice
"direct overload, right side"
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
, matchNotApplicableTwice
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
, matchNotApplicableTwice
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
]
]
test_unifyOverloading :: [TestTree]
test_unifyOverloading =
[ testGroup
"Unifying overloads"
[ unifies
"direct overload, left side"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, unifies
"direct overload, right side"
( Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
)
, unifies
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, unifies
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
( Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
, Mock.sortInjectionTopToOverTheTop
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
)
)
, narrows
"direct overload vs. variable, left side; var direct"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionSubToTop (mkElemVar Mock.xConfigSubSort)
)
(
( Mock.xConfigSubSort
, Mock.subOverload x1
)
,
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, narrows
"direct overload vs. variable, left side; var inject"
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.sortInjectionTestToTop (mkElemVar Mock.xConfig)
)
(
( Mock.xConfig
, Mock.sortInjectionSubToTest (Mock.subOverload x1)
)
,
( Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, narrows
"injected overload vs injected variable, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
, Mock.sortInjectionTestToTop (mkElemVar Mock.xConfig)
)
(
( Mock.xConfig
, Mock.sortInjectionSubToTest (Mock.subOverload x1)
)
,
( Mock.topOverload
(Mock.sortInjectionSubSubToTop Mock.aSubSubsort)
, Mock.topOverload (Mock.sortInjectionSubToTop x1)
)
)
, doesn'tUnify
"overload, both sides, not unifiable"
( Mock.sortInjectionOtherToOtherTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOtherTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
"overloaded constructors not unifiable"
, doesn'tUnify
"overload vs injected constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.aOtherSort)
"different injected ctor"
, doesn'tUnify
"overload vs injected domain value"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop otherDomainValue)
"injected domain value"
, doesn'tUnify
"injected domain value vs overload"
(Mock.sortInjectionOtherToTop otherDomainValue)
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
"injected domain value"
, doesn'tUnify
"overload vs injected int"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Int.asInternal Mock.otherSort 0))
"injected builtin int"
, doesn'tUnify
"overload vs injected bool"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Bool.asInternal Mock.otherSort True))
"injected builtin bool"
, doesn'tUnify
"overload vs injected string"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (String.asInternal Mock.otherSort ""))
"injected builtin string"
, doesn'tUnify
"injected overload vs injected variable"
( Mock.sortInjectionSubSubToTop
(Mock.subsubOverload Mock.aSubSubsort)
)
( Mock.sortInjectionSubOtherToTop
(mkElemVar Mock.xConfigSubOtherSort)
)
"overloaded constructors not unifiable"
, unifyNotApplicable
"overload vs injected non-constructor"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop Mock.plain00OtherSort)
, unifyNotApplicable
"overload vs injected top"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (mkTop Mock.otherSort))
, unifyNotApplicable
"unrelated"
Mock.aOtherSort
Mock.plain00OtherSort
, unifyNotApplicableTwice
"direct overload, left side"
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
, unifyNotApplicableTwice
"direct overload, right side"
(Mock.sortInjectionOtherToTop (Mock.otherOverload Mock.aOtherSort))
(Mock.topOverload (Mock.sortInjectionOtherToTop Mock.aOtherSort))
, unifyNotApplicableTwice
"overload, both sides, unifiable"
( Mock.sortInjectionOtherToTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
, unifyNotApplicableTwice
"overload, both sides, unifiable, with injection"
( Mock.sortInjectionOtherToOverTheTop
( Mock.otherOverload
(Mock.sortInjectionSubSubToOther Mock.aSubSubsort)
)
)
( Mock.sortInjectionSubToOverTheTop
( Mock.subOverload
(Mock.sortInjectionSubSubToSub Mock.aSubSubsort)
)
)
]
]
otherDomainValue :: TermLike RewritingVariableName
otherDomainValue =
mkDomainValue
DomainValue
{ domainValueSort = Mock.otherSort
, domainValueChild = mkStringLiteral "a"
}
matches ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
TestTree
matches comment (term1, term2) (term1', term2') =
withMatching
(assertEqual "" (Right (Pair term1' term2')))
comment
(Pair term1 term2)
doesn'tMatch ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
String ->
TestTree
doesn'tMatch comment term1 term2 reason =
withMatching
(assertEqual "" (Left (Clash reason)))
comment
(Pair term1 term2)
matchNotApplicable ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
matchNotApplicable comment term1 term2 =
withMatching
(assertEqual "" (Left NotApplicable))
comment
(Pair term1 term2)
matchNotApplicableTwice ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
matchNotApplicableTwice comment term1 term2 =
withMatchingTwice
(assertEqual "" (Left NotApplicable))
comment
(Pair term1 term2)
unifies ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
TestTree
unifies comment (term1, term2) (term1', term2') =
withUnification
(assertEqual "" (Just (Resolution (Simple (Pair term1' term2')))))
comment
(Pair term1 term2)
narrows ::
HasCallStack =>
TestName ->
(TermLike RewritingVariableName, TermLike RewritingVariableName) ->
( (ElementVariable', TermLike RewritingVariableName)
, (TermLike RewritingVariableName, TermLike RewritingVariableName)
) ->
TestTree
narrows comment (term1, term2) ((v, term), (term1', term2')) =
withUnification
checkNarrowing
comment
(Pair term1 term2)
where
checkNarrowing :: UnificationResult -> Assertion
checkNarrowing
( Just
( Resolution
( WithNarrowing
Narrowing{narrowingSubst, overloadPair}
)
)
) =
do
assertEqual "" (Pair term1' term2') overloadPair
assertEqual "" expectedSubst narrowingSubst
checkNarrowing _ = assertFailure "Expected narrowing solution"
expectedSubst = Condition.assign (inject v) term
doesn'tUnify ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
String ->
TestTree
doesn'tUnify comment term1 term2 reason =
withUnification
(assertEqual "" (Just (ClashResult reason)))
comment
(Pair term1 term2)
unifyNotApplicable ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
unifyNotApplicable comment term1 term2 =
withUnification
(assertEqual "" Nothing)
comment
(Pair term1 term2)
unifyNotApplicableTwice ::
HasCallStack =>
TestName ->
TermLike RewritingVariableName ->
TermLike RewritingVariableName ->
TestTree
unifyNotApplicableTwice comment term1 term2 =
withUnificationTwice
(assertEqual "" Nothing)
comment
(Pair term1 term2)
type TestMatchResult =
Either UnifyOverloadingError (Pair (TermLike RewritingVariableName))
match ::
Pair (TermLike RewritingVariableName) ->
IO TestMatchResult
match termPair = testRunSimplifier Mock.env $ runExceptT matchResult
where
matchResult :: MatchOverloadingResult Simplifier RewritingVariableName
matchResult = matchOverloading termPair
withMatching ::
(TestMatchResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withMatching check comment termPair =
testCase comment $ do
actual <- match termPair
check actual
withMatchingTwice ::
(TestMatchResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withMatchingTwice check comment termPair =
testCase comment $ do
actual <- match termPair
case actual of
Left _ -> assertFailure "Expected matching solution."
Right termPair' -> do
actual' <- match termPair'
check actual'
type UnificationResult =
Maybe MatchResult
unify ::
Pair (TermLike RewritingVariableName) ->
IO UnificationResult
unify termPair =
testRunSimplifier Mock.env $ return unifyResult
where
unifyResult :: Maybe MatchResult
unifyResult = matchResult <$> unifyOverloading Mock.overloadSimplifier termPair
withUnification ::
(UnificationResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withUnification check comment termPair =
testCase comment $ do
actual <- unify termPair
check actual
withUnificationTwice ::
(UnificationResult -> Assertion) ->
TestName ->
Pair (TermLike RewritingVariableName) ->
TestTree
withUnificationTwice check comment termPair =
testCase comment $ do
actual <- unify termPair
case actual of
Just (Resolution (Simple termPair')) -> do
actual' <- unify termPair'
check actual'
Just (Resolution (WithNarrowing Narrowing{overloadPair})) -> do
actual' <- unify overloadPair
check actual'
_ -> assertFailure "Expected matching solution."
x1 :: TermLike RewritingVariableName
x1 =
mkElemVar
( mkElementVariable (testId "x1") Mock.subSort
& mapElementVariable (pure mkConfigVariable)
)
| |
b4084eb87cf2719dab01c9275983521dfa915c080ee75e6a7cf79d49cb18745f | facebookarchive/pfff | gButton.mli | (**************************************************************************)
(* Lablgtk *)
(* *)
(* This program is free software; you can redistribute it *)
and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
(* comes with the library. *)
(* *)
(* 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 Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library 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
(* *)
(* *)
(**************************************************************************)
$ I d : gButton.mli 1515 2010 - 06 - 08 08:50:23Z garrigue $
open Gtk
open GObj
open GContainer
(** A widget that creates a signal when clicked on *)
* { 3 GtkButton }
(** @gtkdoc gtk GtkButton *)
class button_skel : 'a obj ->
object
inherit GContainer.bin
constraint 'a = [> button]
val obj : 'a obj
method clicked : unit -> unit
method set_relief : Tags.relief_style -> unit
method relief : Tags.relief_style
method set_label : string -> unit
method label : string
method set_use_stock : bool -> unit
method use_stock : bool
method set_use_underline : bool -> unit
method use_underline : bool
method grab_default : unit -> unit
method event : event_ops
method set_focus_on_click : bool -> unit
method focus_on_click : bool
* @since GTK 2.6
* @since GTK 2.6
* @since GTK 2.6
* @since GTK 2.10
method set_image_position : GtkEnums.position_type -> unit
* @since GTK 2.10
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
end
(** @gtkdoc gtk GtkButton *)
class button_signals : 'b obj ->
object ('a)
inherit GContainer.container_signals
constraint 'b = [> button]
val obj : 'b obj
method clicked : callback:(unit -> unit) -> GtkSignal.id
method enter : callback:(unit -> unit) -> GtkSignal.id
method leave : callback:(unit -> unit) -> GtkSignal.id
method pressed : callback:(unit -> unit) -> GtkSignal.id
method released : callback:(unit -> unit) -> GtkSignal.id
end
* A widget that creates a signal when clicked on
@gtkdoc gtk GtkButton
@gtkdoc gtk GtkButton *)
class button : Gtk.button obj ->
object
inherit button_skel
val obj : Gtk.button obj
method connect : button_signals
end
(** @gtkdoc gtk GtkButton *)
val button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?packing:(widget -> unit) -> ?show:bool -> unit -> button
* { 4 GtkToggleButton & GtkRadioButton }
(** @gtkdoc gtk GtkToggleButton *)
class toggle_button_signals : 'b obj ->
object ('a)
inherit button_signals
constraint 'b = [> toggle_button]
val obj : 'b obj
method toggled : callback:(unit -> unit) -> GtkSignal.id
end
* Create buttons which retain their state
@gtkdoc gtk GtkToggleButton
@gtkdoc gtk GtkToggleButton *)
class toggle_button :
'a obj ->
object
inherit button_skel
constraint 'a = [> Gtk.toggle_button]
val obj : 'a obj
method active : bool
method connect : toggle_button_signals
method set_active : bool -> unit
method set_draw_indicator : bool -> unit
end
(** @gtkdoc gtk GtkToggleButton *)
val toggle_button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toggle_button
* @gtkdoc gtk
val check_button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toggle_button
(** A choice from multiple check buttons
@gtkdoc gtk GtkRadioButton *)
class radio_button :
Gtk.radio_button obj ->
object
inherit toggle_button
val obj : Gtk.radio_button obj
method group : Gtk.radio_button group
method set_group : Gtk.radio_button group -> unit
end
(** @gtkdoc gtk GtkRadioButton *)
val radio_button :
?group:Gtk.radio_button group ->
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> radio_button
* { 4 GtkColorButton & GtkFontButton }
* @gtkdoc gtk GtkColorButton
@since GTK 2.4
@since GTK 2.4 *)
class color_button_signals :
([> Gtk.color_button] as 'a) Gtk.obj ->
object
inherit button_signals
val obj : 'a Gtk.obj
method color_set : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkColorButton
@since GTK 2.4
@since GTK 2.4 *)
class color_button :
([> Gtk.color_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method alpha : int
method set_alpha : int -> unit
method color : Gdk.color
method set_color : Gdk.color -> unit
method title : string
method set_title : string -> unit
method use_alpha : bool
method set_use_alpha : bool -> unit
method connect : color_button_signals
end
* A button to launch a color selection dialog
@gtkdoc gtk GtkColorButton
@since GTK 2.4
@gtkdoc gtk GtkColorButton
@since GTK 2.4 *)
val color_button :
?color:Gdk.color ->
?title:string ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> color_button
* @gtkdoc gtk GtkFontButton
@since GTK 2.4
@since GTK 2.4 *)
class font_button_signals :
([> Gtk.font_button] as 'a) Gtk.obj ->
object
inherit button_signals
val obj : 'a Gtk.obj
method font_set : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkFontButton
@since GTK 2.4
@since GTK 2.4 *)
class font_button :
([> Gtk.font_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method font_name : string
method set_font_name : string -> unit
method show_size : bool
method set_show_size : bool -> unit
method show_style : bool
method set_show_style : bool -> unit
method title : string
method set_title : string -> unit
method use_font : bool
method set_use_font : bool -> unit
method use_size : bool
method set_use_size : bool -> unit
method connect : font_button_signals
end
* A button to launch a font selection dialog
@gtkdoc gtk GtkFontButton
@since GTK 2.4
@gtkdoc gtk GtkFontButton
@since GTK 2.4 *)
val font_button :
?font_name:string ->
?title:string ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> font_button
* { 3 GtkToolbar }
class type tool_item_o = object
method as_tool_item : Gtk.tool_item obj
end
* @gtkdoc gtk GtkToolbar
class toolbar_signals :
([> Gtk.toolbar] as 'a) obj ->
object
inherit GContainer.container_signals
method orientation_changed :
callback:(GtkEnums.orientation -> unit) -> GtkSignal.id
method style_changed :
callback:(GtkEnums.toolbar_style -> unit) -> GtkSignal.id
* @since GTK 2.4
method move_focus :
* @since GTK 2.4
method popup_context_menu :
* @since GTK 2.4
end
* Create bars of buttons and other widgets
@gtkdoc gtk GtkToolbar
@gtkdoc gtk GtkToolbar *)
class toolbar :
Gtk.toolbar obj ->
object
inherit GContainer.container
val obj : Gtk.toolbar obj
method connect : toolbar_signals
method insert_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> button
method insert_radio_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> radio_button
method insert_space : ?pos:int -> unit -> unit
method insert_toggle_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> toggle_button
method insert_widget :
?tooltip:string ->
?tooltip_private:string -> ?pos:int -> widget -> unit
method orientation : Tags.orientation
method set_orientation : Tags.orientation -> unit
method style : Tags.toolbar_style
method set_style : Tags.toolbar_style -> unit
method unset_style : unit -> unit
method icon_size : Tags.icon_size
method set_icon_size : Tags.icon_size -> unit
method unset_icon_size : unit -> unit
method get_tooltips : bool
method set_tooltips : bool -> unit
* Extended API , available in GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
method insert : ?pos:int -> #tool_item_o -> unit
* @since GTK 2.4
@param pos default value is [ -1 ] i.e. end of the toolbar
@param pos default value is [-1] i.e. end of the toolbar *)
end
* @gtkdoc gtk GtkToolbar
val toolbar :
?orientation:Tags.orientation ->
?style:Tags.toolbar_style ->
?tooltips:bool ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toolbar
* { 4 ToolItems for the new toolbar API }
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
class tool_item_skel :
([> Gtk.tool_item] as 'a) obj ->
object
inherit GContainer.bin
val obj : 'a obj
method as_tool_item : Gtk.tool_item obj
method is_important : bool
method set_is_important : bool -> unit
method visible_horizontal : bool
method set_visible_horizontal : bool -> unit
method visible_vertical : bool
method set_visible_vertical : bool -> unit
method set_homogeneous : bool -> unit
method get_homogeneous : bool
method set_expand : bool -> unit
method get_expand : bool
method set_tooltip : GData.tooltips -> string -> string -> unit
method set_use_drag_window : bool -> unit
method get_use_drag_window : bool
end
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
class tool_item :
([> Gtk.tool_item] as 'a) obj ->
object
inherit tool_item_skel
val obj : 'a obj
method connect : GContainer.container_signals
end
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
val tool_item :
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> tool_item
* @gtkdoc gtk GtkSeparatorToolItem
@since GTK 2.4
@since GTK 2.4 *)
class separator_tool_item :
([> Gtk.separator_tool_item] as 'a) obj ->
object
inherit tool_item
val obj : 'a obj
method draw : bool
method set_draw : bool -> unit
end
* @gtkdoc gtk GtkSeparatorToolItem
@since GTK 2.4
@since GTK 2.4 *)
val separator_tool_item :
?draw:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> separator_tool_item
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button_signals :
([> Gtk.tool_button] as 'a) obj ->
object
inherit GContainer.container_signals
val obj : 'a obj
method clicked : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button_skel :
([> Gtk.tool_button] as 'a) obj ->
object
inherit tool_item_skel
val obj : 'a obj
method icon_widget : GObj.widget
method set_icon_widget : GObj.widget -> unit
method label : string
method set_label : string -> unit
method label_widget : GObj.widget
method set_label_widget : GObj.widget -> unit
method stock_id : GtkStock.id
method set_stock_id : GtkStock.id -> unit
method use_underline : bool
method set_use_underline : bool -> unit
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button :
([> Gtk.tool_button] as 'a) obj ->
object
inherit tool_button_skel
val obj : 'a obj
method connect : tool_button_signals
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
val tool_button :
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> tool_button
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
class toggle_tool_button_signals :
([> Gtk.toggle_tool_button] as 'a) obj ->
object
inherit tool_button_signals
val obj : 'a obj
method toggled : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
class toggle_tool_button :
([> Gtk.toggle_tool_button] as 'a) obj ->
object
inherit tool_button_skel
val obj : 'a obj
method connect : toggle_tool_button_signals
method set_active : bool -> unit
method get_active : bool
end
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
val toggle_tool_button :
?active:bool ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> toggle_tool_button
* @gtkdoc gtk GtkRadioToolButton
@since GTK 2.4
@since GTK 2.4 *)
class radio_tool_button :
([> Gtk.radio_tool_button] as 'a) obj ->
object
inherit toggle_tool_button
val obj : 'a obj
method group : Gtk.radio_tool_button group
method set_group : Gtk.radio_tool_button group -> unit
end
* @gtkdoc gtk GtkRadioToolButton
@since GTK 2.4
@since GTK 2.4 *)
val radio_tool_button :
?group:radio_tool_button ->
?active:bool ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> radio_tool_button
* @gtkdoc gtk GtkMenuToolButton
@since GTK 2.6
@since GTK 2.6 *)
class menu_tool_button :
([> Gtk.menu_tool_button] as 'a) obj ->
object
inherit tool_button
val obj : 'a obj
method menu : Gtk.menu Gtk.obj
method set_menu : Gtk.menu Gtk.obj -> unit
method set_arrow_tooltip : GData.tooltips -> string -> string -> unit
end
* @gtkdoc gtk GtkMenuToolButton
@since GTK 2.6
@since GTK 2.6 *)
val menu_tool_button :
?menu:<as_menu:Gtk.menu Gtk.obj;..> ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> menu_tool_button
* @gtkdoc gtk GtkLinkButton
@since GTK 2.10
@since GTK 2.10 *)
class link_button :
([> Gtk.link_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method uri : string
method set_uri : string -> unit
end
* A button for URL
@gtkdoc gtk GtkLinkButton
@since GTK 2.10
@gtkdoc gtk GtkLinkButton
@since GTK 2.10 *)
val link_button :
?label:string ->
string ->
?packing:(widget -> unit) -> ?show:bool -> unit -> link_button
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/external/ocamlgtk/src/gButton.mli | ocaml | ************************************************************************
Lablgtk
This program is free software; you can redistribute it
comes with the library.
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
************************************************************************
* A widget that creates a signal when clicked on
* @gtkdoc gtk GtkButton
* @gtkdoc gtk GtkButton
* @gtkdoc gtk GtkButton
* @gtkdoc gtk GtkToggleButton
* @gtkdoc gtk GtkToggleButton
* A choice from multiple check buttons
@gtkdoc gtk GtkRadioButton
* @gtkdoc gtk GtkRadioButton | and/or modify it under the terms of the GNU Library General
Public License as published by the Free Software Foundation
version 2 , with the exception described in file COPYING which
GNU Library General Public License for more details .
You should have received a copy of the GNU Library 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
$ I d : gButton.mli 1515 2010 - 06 - 08 08:50:23Z garrigue $
open Gtk
open GObj
open GContainer
* { 3 GtkButton }
class button_skel : 'a obj ->
object
inherit GContainer.bin
constraint 'a = [> button]
val obj : 'a obj
method clicked : unit -> unit
method set_relief : Tags.relief_style -> unit
method relief : Tags.relief_style
method set_label : string -> unit
method label : string
method set_use_stock : bool -> unit
method use_stock : bool
method set_use_underline : bool -> unit
method use_underline : bool
method grab_default : unit -> unit
method event : event_ops
method set_focus_on_click : bool -> unit
method focus_on_click : bool
* @since GTK 2.6
* @since GTK 2.6
* @since GTK 2.6
* @since GTK 2.10
method set_image_position : GtkEnums.position_type -> unit
* @since GTK 2.10
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
end
class button_signals : 'b obj ->
object ('a)
inherit GContainer.container_signals
constraint 'b = [> button]
val obj : 'b obj
method clicked : callback:(unit -> unit) -> GtkSignal.id
method enter : callback:(unit -> unit) -> GtkSignal.id
method leave : callback:(unit -> unit) -> GtkSignal.id
method pressed : callback:(unit -> unit) -> GtkSignal.id
method released : callback:(unit -> unit) -> GtkSignal.id
end
* A widget that creates a signal when clicked on
@gtkdoc gtk GtkButton
@gtkdoc gtk GtkButton *)
class button : Gtk.button obj ->
object
inherit button_skel
val obj : Gtk.button obj
method connect : button_signals
end
val button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?packing:(widget -> unit) -> ?show:bool -> unit -> button
* { 4 GtkToggleButton & GtkRadioButton }
class toggle_button_signals : 'b obj ->
object ('a)
inherit button_signals
constraint 'b = [> toggle_button]
val obj : 'b obj
method toggled : callback:(unit -> unit) -> GtkSignal.id
end
* Create buttons which retain their state
@gtkdoc gtk GtkToggleButton
@gtkdoc gtk GtkToggleButton *)
class toggle_button :
'a obj ->
object
inherit button_skel
constraint 'a = [> Gtk.toggle_button]
val obj : 'a obj
method active : bool
method connect : toggle_button_signals
method set_active : bool -> unit
method set_draw_indicator : bool -> unit
end
val toggle_button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toggle_button
* @gtkdoc gtk
val check_button :
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toggle_button
class radio_button :
Gtk.radio_button obj ->
object
inherit toggle_button
val obj : Gtk.radio_button obj
method group : Gtk.radio_button group
method set_group : Gtk.radio_button group -> unit
end
val radio_button :
?group:Gtk.radio_button group ->
?label:string ->
?use_mnemonic:bool ->
?stock:GtkStock.id ->
?relief:Tags.relief_style ->
?active:bool ->
?draw_indicator:bool ->
?packing:(widget -> unit) -> ?show:bool -> unit -> radio_button
* { 4 GtkColorButton & GtkFontButton }
* @gtkdoc gtk GtkColorButton
@since GTK 2.4
@since GTK 2.4 *)
class color_button_signals :
([> Gtk.color_button] as 'a) Gtk.obj ->
object
inherit button_signals
val obj : 'a Gtk.obj
method color_set : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkColorButton
@since GTK 2.4
@since GTK 2.4 *)
class color_button :
([> Gtk.color_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method alpha : int
method set_alpha : int -> unit
method color : Gdk.color
method set_color : Gdk.color -> unit
method title : string
method set_title : string -> unit
method use_alpha : bool
method set_use_alpha : bool -> unit
method connect : color_button_signals
end
* A button to launch a color selection dialog
@gtkdoc gtk GtkColorButton
@since GTK 2.4
@gtkdoc gtk GtkColorButton
@since GTK 2.4 *)
val color_button :
?color:Gdk.color ->
?title:string ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> color_button
* @gtkdoc gtk GtkFontButton
@since GTK 2.4
@since GTK 2.4 *)
class font_button_signals :
([> Gtk.font_button] as 'a) Gtk.obj ->
object
inherit button_signals
val obj : 'a Gtk.obj
method font_set : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkFontButton
@since GTK 2.4
@since GTK 2.4 *)
class font_button :
([> Gtk.font_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method font_name : string
method set_font_name : string -> unit
method show_size : bool
method set_show_size : bool -> unit
method show_style : bool
method set_show_style : bool -> unit
method title : string
method set_title : string -> unit
method use_font : bool
method set_use_font : bool -> unit
method use_size : bool
method set_use_size : bool -> unit
method connect : font_button_signals
end
* A button to launch a font selection dialog
@gtkdoc gtk GtkFontButton
@since GTK 2.4
@gtkdoc gtk GtkFontButton
@since GTK 2.4 *)
val font_button :
?font_name:string ->
?title:string ->
?packing:(GObj.widget -> unit) -> ?show:bool -> unit -> font_button
* { 3 GtkToolbar }
class type tool_item_o = object
method as_tool_item : Gtk.tool_item obj
end
* @gtkdoc gtk GtkToolbar
class toolbar_signals :
([> Gtk.toolbar] as 'a) obj ->
object
inherit GContainer.container_signals
method orientation_changed :
callback:(GtkEnums.orientation -> unit) -> GtkSignal.id
method style_changed :
callback:(GtkEnums.toolbar_style -> unit) -> GtkSignal.id
* @since GTK 2.4
method move_focus :
* @since GTK 2.4
method popup_context_menu :
* @since GTK 2.4
end
* Create bars of buttons and other widgets
@gtkdoc gtk GtkToolbar
@gtkdoc gtk GtkToolbar *)
class toolbar :
Gtk.toolbar obj ->
object
inherit GContainer.container
val obj : Gtk.toolbar obj
method connect : toolbar_signals
method insert_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> button
method insert_radio_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> radio_button
method insert_space : ?pos:int -> unit -> unit
method insert_toggle_button :
?text:string ->
?tooltip:string ->
?tooltip_private:string ->
?icon:widget ->
?pos:int -> ?callback:(unit -> unit) -> unit -> toggle_button
method insert_widget :
?tooltip:string ->
?tooltip_private:string -> ?pos:int -> widget -> unit
method orientation : Tags.orientation
method set_orientation : Tags.orientation -> unit
method style : Tags.toolbar_style
method set_style : Tags.toolbar_style -> unit
method unset_style : unit -> unit
method icon_size : Tags.icon_size
method set_icon_size : Tags.icon_size -> unit
method unset_icon_size : unit -> unit
method get_tooltips : bool
method set_tooltips : bool -> unit
* Extended API , available in GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
* @since GTK 2.4
method insert : ?pos:int -> #tool_item_o -> unit
* @since GTK 2.4
@param pos default value is [ -1 ] i.e. end of the toolbar
@param pos default value is [-1] i.e. end of the toolbar *)
end
* @gtkdoc gtk GtkToolbar
val toolbar :
?orientation:Tags.orientation ->
?style:Tags.toolbar_style ->
?tooltips:bool ->
?border_width:int ->
?width:int ->
?height:int ->
?packing:(widget -> unit) -> ?show:bool -> unit -> toolbar
* { 4 ToolItems for the new toolbar API }
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
class tool_item_skel :
([> Gtk.tool_item] as 'a) obj ->
object
inherit GContainer.bin
val obj : 'a obj
method as_tool_item : Gtk.tool_item obj
method is_important : bool
method set_is_important : bool -> unit
method visible_horizontal : bool
method set_visible_horizontal : bool -> unit
method visible_vertical : bool
method set_visible_vertical : bool -> unit
method set_homogeneous : bool -> unit
method get_homogeneous : bool
method set_expand : bool -> unit
method get_expand : bool
method set_tooltip : GData.tooltips -> string -> string -> unit
method set_use_drag_window : bool -> unit
method get_use_drag_window : bool
end
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
class tool_item :
([> Gtk.tool_item] as 'a) obj ->
object
inherit tool_item_skel
val obj : 'a obj
method connect : GContainer.container_signals
end
* @gtkdoc gtk GtkToolItem
@since GTK 2.4
@since GTK 2.4 *)
val tool_item :
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> tool_item
* @gtkdoc gtk GtkSeparatorToolItem
@since GTK 2.4
@since GTK 2.4 *)
class separator_tool_item :
([> Gtk.separator_tool_item] as 'a) obj ->
object
inherit tool_item
val obj : 'a obj
method draw : bool
method set_draw : bool -> unit
end
* @gtkdoc gtk GtkSeparatorToolItem
@since GTK 2.4
@since GTK 2.4 *)
val separator_tool_item :
?draw:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> separator_tool_item
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button_signals :
([> Gtk.tool_button] as 'a) obj ->
object
inherit GContainer.container_signals
val obj : 'a obj
method clicked : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button_skel :
([> Gtk.tool_button] as 'a) obj ->
object
inherit tool_item_skel
val obj : 'a obj
method icon_widget : GObj.widget
method set_icon_widget : GObj.widget -> unit
method label : string
method set_label : string -> unit
method label_widget : GObj.widget
method set_label_widget : GObj.widget -> unit
method stock_id : GtkStock.id
method set_stock_id : GtkStock.id -> unit
method use_underline : bool
method set_use_underline : bool -> unit
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
class tool_button :
([> Gtk.tool_button] as 'a) obj ->
object
inherit tool_button_skel
val obj : 'a obj
method connect : tool_button_signals
end
* @gtkdoc gtk GtkToolButton
@since GTK 2.4
@since GTK 2.4 *)
val tool_button :
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> tool_button
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
class toggle_tool_button_signals :
([> Gtk.toggle_tool_button] as 'a) obj ->
object
inherit tool_button_signals
val obj : 'a obj
method toggled : callback:(unit -> unit) -> GtkSignal.id
end
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
class toggle_tool_button :
([> Gtk.toggle_tool_button] as 'a) obj ->
object
inherit tool_button_skel
val obj : 'a obj
method connect : toggle_tool_button_signals
method set_active : bool -> unit
method get_active : bool
end
* @gtkdoc gtk GtkToggleToolButton
@since GTK 2.4
@since GTK 2.4 *)
val toggle_tool_button :
?active:bool ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> toggle_tool_button
* @gtkdoc gtk GtkRadioToolButton
@since GTK 2.4
@since GTK 2.4 *)
class radio_tool_button :
([> Gtk.radio_tool_button] as 'a) obj ->
object
inherit toggle_tool_button
val obj : 'a obj
method group : Gtk.radio_tool_button group
method set_group : Gtk.radio_tool_button group -> unit
end
* @gtkdoc gtk GtkRadioToolButton
@since GTK 2.4
@since GTK 2.4 *)
val radio_tool_button :
?group:radio_tool_button ->
?active:bool ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> radio_tool_button
* @gtkdoc gtk GtkMenuToolButton
@since GTK 2.6
@since GTK 2.6 *)
class menu_tool_button :
([> Gtk.menu_tool_button] as 'a) obj ->
object
inherit tool_button
val obj : 'a obj
method menu : Gtk.menu Gtk.obj
method set_menu : Gtk.menu Gtk.obj -> unit
method set_arrow_tooltip : GData.tooltips -> string -> string -> unit
end
* @gtkdoc gtk GtkMenuToolButton
@since GTK 2.6
@since GTK 2.6 *)
val menu_tool_button :
?menu:<as_menu:Gtk.menu Gtk.obj;..> ->
?label:string ->
?stock:GtkStock.id ->
?use_underline:bool ->
?homogeneous:bool ->
?expand:bool ->
?packing:(tool_item_o -> unit) ->
?show:bool -> unit -> menu_tool_button
* @gtkdoc gtk GtkLinkButton
@since GTK 2.10
@since GTK 2.10 *)
class link_button :
([> Gtk.link_button] as 'a) Gtk.obj ->
object
inherit button_skel
val obj : 'a Gtk.obj
method uri : string
method set_uri : string -> unit
end
* A button for URL
@gtkdoc gtk GtkLinkButton
@since GTK 2.10
@gtkdoc gtk GtkLinkButton
@since GTK 2.10 *)
val link_button :
?label:string ->
string ->
?packing:(widget -> unit) -> ?show:bool -> unit -> link_button
|
0d663eec6288d6272e0e221708a2d6c733edd10c910b4abb954f5fc7347eb3a0 | eashanhatti/peridot | Declaration.hs | module Elaboration.Declaration where
import Syntax.Surface
import Syntax.Core qualified as C
import Syntax.Semantic qualified as N
import Syntax.Common hiding(Declaration(..), Universe(..), NameType)
import Elaboration.Effect
import Control.Effect.Reader
import Control.Carrier.Error.Either
import Control.Effect.State
import Control.Carrier.NonDet.Church hiding(Empty)
import Data.Map qualified as Map
import Data.Set qualified as Set
import {-# SOURCE #-} Elaboration.Term qualified as EE
import Normalization hiding(eval, readback, zonk)
import Normalization qualified as Norm
import Control.Monad
import Control.Monad.Extra
import Data.Foldable(toList, foldl')
import Data.Traversable
import GHC.Stack
import Data.Sequence
import Search(Substitution, concatSubsts')
import Prelude hiding(traverse, map, zip, concat, filter, mapWithIndex)
import Debug.Trace
import Extras
import Data.Bifunctor
import Data.Maybe
check :: HasCallStack => Query sig m => Id -> m C.Term
check did = memo (CheckDecl did) $ withDecl did $ withPos' $ \decl -> do
(cSig, univ) <- declType (unPDDeclId decl)
case decl of
PDDecl (DeclAst (ObjTerm name _ def) did) -> do
cDef <- eval cSig >>= EE.check def
pure cDef
PDDecl (DeclAst (MetaTerm name _ def) did) -> do
cDef <- eval cSig >>= EE.check def
pure cDef
PDDecl (DeclAst (Axiom name _) did) ->
pure (C.Rigid (C.MetaConstIntro did))
PDDecl (DeclAst (Prove _) did) -> do
vSig <- eval cSig
bs <- unBindings <$> ask
axioms <- unAxioms <$> ask
let
gDids =
flip filterMap (fromList . toList $ bs) \case
BGlobal gDid | Set.member gDid axioms -> Just gDid
_ -> Nothing
gTys <-
traverse
(\gDid -> do
(ty, _) <- declType gDid
eval ty)
gDids
defs <- allDefs
(tree, substs) <-
local
(\ctx -> ctx { unEnv = N.Env (N.unLocals . unEnv $ ctx) defs })
(proveDet gTys vSig)
modify (\st -> st { unSearchTrees = tree <| unSearchTrees st })
case substs of
Nothing -> do
report (FailedProve cSig vSig gTys)
pure (C.Rigid C.ElabError)
Just substs -> do
lvs <- unLogvarNames <$> get
forM substs \(tuvs, eqs) ->
local
(\ctx -> ctx
{ Norm.unUVEqs = eqs <> Norm.unUVEqs ctx
, Norm.unTypeUVs = tuvs <> Norm.unTypeUVs ctx })
(flip Map.traverseWithKey tuvs \gl1 sol ->
flip Map.traverseWithKey lvs \gl2 name -> do
b <- uvsEq gl1 gl2
when b do
cSol <- Norm.zonk (unTerm sol)
sols <- unLogSols <$> get
vSols <- traverse eval (sols ! name)
b ' < - not . or < $ > traverse ( convertible ( unTerm sol ) ) vSols
let b' = True
when b'
(modify (\st -> st
{ unLogSols = Map.adjust (cSol <|) name (unLogSols st)})))
if isAmbiguous substs then do
report (AmbiguousProve cSig substs)
pure (C.Rigid C.ElabError)
else do
r <- runError @() $ concatSubsts' substs
case r of
Right (ts, eqs) -> do
putTypeUVSols ts
putUVEqs eqs
pure (C.Rigid (C.MetaConstIntro did))
where
isAmbiguous :: Seq Substitution -> Bool
isAmbiguous substs =
let
substs' =
mapWithIndex (,) .
filter (not . Set.null) .
fmap
(Set.filter \case
LVGlobal _ -> False
UVGlobal _ -> True) .
fmap Map.keysSet .
fmap fst $
substs
in
not .
all (uncurry Set.disjoint) $
[(x, y) | (i1, x) <- substs', (i2, y) <- substs', i1 /= i2]
PDDecl (DeclAst (Fresh name _) did@(Id n)) -> do
modify (\st -> st
{ unLogvars = Set.insert did (unLogvars st)
, unLogSols = Map.insert (unName name) mempty (unLogSols st) })
pure (C.UniVar (UVGlobal n) (Just cSig))
PDDecl (DeclAst (Output path text) _) -> do
cText <- EE.check text (N.Rigid N.TextType)
vText <- eval cText
modify (\st -> st { unOutputs = (path, vText) <| unOutputs st })
pure (C.Rigid (C.Dummy "output"))
withPos' ::
HasCallStack => Elab sig m =>
(Predeclaration -> m a) ->
(Predeclaration -> m a)
withPos' act (PDDecl (SourcePos ast pos)) = withPos pos (act (PDDecl ast))
withPos' act pd = act pd
declType :: HasCallStack => Query sig m => Id -> m (C.Term, N.Universe)
declType did = memo (DeclType did) $ withDecl did $ withPos' $ \decl -> asType
case decl of
PDDecl (DeclAst (ObjTerm name sig def) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.ObjFunType Unification)
(EE.checkObjType sig)
PDDecl (DeclAst (MetaTerm name sig def) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Axiom (NameAst name) sig) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Prove sig) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Fresh name sig) (Id n)) -> do
modify (\st -> st
{ unLogvarNames = Map.insert (UVGlobal n) (unName name) (unLogvarNames st) })
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Output _ _) _) -> pure (C.Rigid (C.Dummy "outputtype"), N.Meta)
withImVars ::
forall sig m. Elab sig m =>
[Name] ->
(C.Term -> C.Term -> C.Term) ->
m (C.Term, N.Universe) ->
m (C.Term, N.Universe)
withImVars names con act = go names id where
go :: Elab sig m => [Name] -> (C.Term -> C.Term) -> m (C.Term, N.Universe)
go [] f = do
(cTerm, univ) <- act
pure (f cTerm, univ)
go (name:names) f = do
ty <- freshTypeUV N.MetaTypeType
cTy <- readback ty
bindLocal name ty (go names (con cTy . f))
imVars :: TermAst -> Set.Set Name
imVars (SourcePos ast _) = imVars ast
imVars (TermAst term) = case term of
MetaPi _ _ inTy outTy -> imVars inTy <> imVars outTy
MetaLam _ body -> imVars body
ObjPi _ _ inTy outTy -> imVars inTy <> imVars outTy
ObjLam _ body -> imVars body
App lam args ->
imVars lam <>
(concat . fmap snd . fmap (second imVars) $ args)
Var Im name -> Set.singleton name
LiftObj ty -> imVars ty
QuoteObj code -> imVars code
SpliceObj quote -> imVars quote
ImplProp p q -> imVars p <> imVars q
ConjProp p q -> imVars p <> imVars q
DisjProp p q -> imVars p <> imVars q
ForallProp _ ty p -> imVars ty <> imVars p
Case scr body1 body2 -> imVars scr <> imVars body1 <> imVars body2
Equal x y -> imVars x <> imVars y
Sig tys ->
concat . fmap snd . fmap (second imVars) $ tys
Struct defs -> concat . fmap snd . fmap (second imVars) $ defs
Select str _ -> imVars str
Patch str defs ->
imVars str <>
(concat . fmap snd . fmap (second imVars) $ defs)
Declare name ty cont -> imVars name <> imVars ty <> imVars cont
Define name def cont -> imVars name <> imVars def <> imVars cont
NameType _ ty -> imVars ty
TextAppend t1 t2 -> imVars t1 <> imVars t2
_ -> mempty
| null | https://raw.githubusercontent.com/eashanhatti/peridot/0f63a32f4ee0ed0049d80a5daefa748cf27c2b17/src/Elaboration/Declaration.hs | haskell | # SOURCE # | module Elaboration.Declaration where
import Syntax.Surface
import Syntax.Core qualified as C
import Syntax.Semantic qualified as N
import Syntax.Common hiding(Declaration(..), Universe(..), NameType)
import Elaboration.Effect
import Control.Effect.Reader
import Control.Carrier.Error.Either
import Control.Effect.State
import Control.Carrier.NonDet.Church hiding(Empty)
import Data.Map qualified as Map
import Data.Set qualified as Set
import Normalization hiding(eval, readback, zonk)
import Normalization qualified as Norm
import Control.Monad
import Control.Monad.Extra
import Data.Foldable(toList, foldl')
import Data.Traversable
import GHC.Stack
import Data.Sequence
import Search(Substitution, concatSubsts')
import Prelude hiding(traverse, map, zip, concat, filter, mapWithIndex)
import Debug.Trace
import Extras
import Data.Bifunctor
import Data.Maybe
check :: HasCallStack => Query sig m => Id -> m C.Term
check did = memo (CheckDecl did) $ withDecl did $ withPos' $ \decl -> do
(cSig, univ) <- declType (unPDDeclId decl)
case decl of
PDDecl (DeclAst (ObjTerm name _ def) did) -> do
cDef <- eval cSig >>= EE.check def
pure cDef
PDDecl (DeclAst (MetaTerm name _ def) did) -> do
cDef <- eval cSig >>= EE.check def
pure cDef
PDDecl (DeclAst (Axiom name _) did) ->
pure (C.Rigid (C.MetaConstIntro did))
PDDecl (DeclAst (Prove _) did) -> do
vSig <- eval cSig
bs <- unBindings <$> ask
axioms <- unAxioms <$> ask
let
gDids =
flip filterMap (fromList . toList $ bs) \case
BGlobal gDid | Set.member gDid axioms -> Just gDid
_ -> Nothing
gTys <-
traverse
(\gDid -> do
(ty, _) <- declType gDid
eval ty)
gDids
defs <- allDefs
(tree, substs) <-
local
(\ctx -> ctx { unEnv = N.Env (N.unLocals . unEnv $ ctx) defs })
(proveDet gTys vSig)
modify (\st -> st { unSearchTrees = tree <| unSearchTrees st })
case substs of
Nothing -> do
report (FailedProve cSig vSig gTys)
pure (C.Rigid C.ElabError)
Just substs -> do
lvs <- unLogvarNames <$> get
forM substs \(tuvs, eqs) ->
local
(\ctx -> ctx
{ Norm.unUVEqs = eqs <> Norm.unUVEqs ctx
, Norm.unTypeUVs = tuvs <> Norm.unTypeUVs ctx })
(flip Map.traverseWithKey tuvs \gl1 sol ->
flip Map.traverseWithKey lvs \gl2 name -> do
b <- uvsEq gl1 gl2
when b do
cSol <- Norm.zonk (unTerm sol)
sols <- unLogSols <$> get
vSols <- traverse eval (sols ! name)
b ' < - not . or < $ > traverse ( convertible ( unTerm sol ) ) vSols
let b' = True
when b'
(modify (\st -> st
{ unLogSols = Map.adjust (cSol <|) name (unLogSols st)})))
if isAmbiguous substs then do
report (AmbiguousProve cSig substs)
pure (C.Rigid C.ElabError)
else do
r <- runError @() $ concatSubsts' substs
case r of
Right (ts, eqs) -> do
putTypeUVSols ts
putUVEqs eqs
pure (C.Rigid (C.MetaConstIntro did))
where
isAmbiguous :: Seq Substitution -> Bool
isAmbiguous substs =
let
substs' =
mapWithIndex (,) .
filter (not . Set.null) .
fmap
(Set.filter \case
LVGlobal _ -> False
UVGlobal _ -> True) .
fmap Map.keysSet .
fmap fst $
substs
in
not .
all (uncurry Set.disjoint) $
[(x, y) | (i1, x) <- substs', (i2, y) <- substs', i1 /= i2]
PDDecl (DeclAst (Fresh name _) did@(Id n)) -> do
modify (\st -> st
{ unLogvars = Set.insert did (unLogvars st)
, unLogSols = Map.insert (unName name) mempty (unLogSols st) })
pure (C.UniVar (UVGlobal n) (Just cSig))
PDDecl (DeclAst (Output path text) _) -> do
cText <- EE.check text (N.Rigid N.TextType)
vText <- eval cText
modify (\st -> st { unOutputs = (path, vText) <| unOutputs st })
pure (C.Rigid (C.Dummy "output"))
withPos' ::
HasCallStack => Elab sig m =>
(Predeclaration -> m a) ->
(Predeclaration -> m a)
withPos' act (PDDecl (SourcePos ast pos)) = withPos pos (act (PDDecl ast))
withPos' act pd = act pd
declType :: HasCallStack => Query sig m => Id -> m (C.Term, N.Universe)
declType did = memo (DeclType did) $ withDecl did $ withPos' $ \decl -> asType
case decl of
PDDecl (DeclAst (ObjTerm name sig def) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.ObjFunType Unification)
(EE.checkObjType sig)
PDDecl (DeclAst (MetaTerm name sig def) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Axiom (NameAst name) sig) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Prove sig) _) ->
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Fresh name sig) (Id n)) -> do
modify (\st -> st
{ unLogvarNames = Map.insert (UVGlobal n) (unName name) (unLogvarNames st) })
withImVars
(Set.toList . imVars $ sig)
(C.MetaFunType Unification)
(EE.checkMetaType sig)
PDDecl (DeclAst (Output _ _) _) -> pure (C.Rigid (C.Dummy "outputtype"), N.Meta)
withImVars ::
forall sig m. Elab sig m =>
[Name] ->
(C.Term -> C.Term -> C.Term) ->
m (C.Term, N.Universe) ->
m (C.Term, N.Universe)
withImVars names con act = go names id where
go :: Elab sig m => [Name] -> (C.Term -> C.Term) -> m (C.Term, N.Universe)
go [] f = do
(cTerm, univ) <- act
pure (f cTerm, univ)
go (name:names) f = do
ty <- freshTypeUV N.MetaTypeType
cTy <- readback ty
bindLocal name ty (go names (con cTy . f))
imVars :: TermAst -> Set.Set Name
imVars (SourcePos ast _) = imVars ast
imVars (TermAst term) = case term of
MetaPi _ _ inTy outTy -> imVars inTy <> imVars outTy
MetaLam _ body -> imVars body
ObjPi _ _ inTy outTy -> imVars inTy <> imVars outTy
ObjLam _ body -> imVars body
App lam args ->
imVars lam <>
(concat . fmap snd . fmap (second imVars) $ args)
Var Im name -> Set.singleton name
LiftObj ty -> imVars ty
QuoteObj code -> imVars code
SpliceObj quote -> imVars quote
ImplProp p q -> imVars p <> imVars q
ConjProp p q -> imVars p <> imVars q
DisjProp p q -> imVars p <> imVars q
ForallProp _ ty p -> imVars ty <> imVars p
Case scr body1 body2 -> imVars scr <> imVars body1 <> imVars body2
Equal x y -> imVars x <> imVars y
Sig tys ->
concat . fmap snd . fmap (second imVars) $ tys
Struct defs -> concat . fmap snd . fmap (second imVars) $ defs
Select str _ -> imVars str
Patch str defs ->
imVars str <>
(concat . fmap snd . fmap (second imVars) $ defs)
Declare name ty cont -> imVars name <> imVars ty <> imVars cont
Define name def cont -> imVars name <> imVars def <> imVars cont
NameType _ ty -> imVars ty
TextAppend t1 t2 -> imVars t1 <> imVars t2
_ -> mempty
|
2a28691dd8fe15fc69e146da4bc680bcd24078d1ade422be6f1eb86b247e6bee | Appliscale/xprof | xprof_core_records_tests.erl | -module(xprof_core_records_tests).
-export([test_fun/1]).
-include_lib("eunit/include/eunit.hrl").
-define(M, xprof_core_records).
-record(r1, {f1}).
-record(r2, {f2 = default}).
smoke_test_() ->
{setup,
fun() ->
{ok, Pid} = ?M:start_link(),
Pid
end,
fun(Pid) ->
unlink(Pid),
exit(Pid, kill)
end,
[?_assertEqual([], ?M:get_record_defs()),
?_assertEqual([r1, r2], ?M:load_records(?MODULE)),
?_assertMatch([{attribute, _, record,
{r1,[{record_field, _, {atom, _,f1}}]}},
{attribute, _, record,
{r2,[{record_field, _, {atom, _,f2}, {atom, _, default}}]}}],
lists:sort(?M:get_record_defs())),
?_assertEqual(ok, ?M:forget_records(r2)),
?_assertMatch([{attribute, _, record,
{r1,[{record_field, _, {atom, _,f1}}]}}],
lists:sort(?M:get_record_defs())),
?_assertEqual(ok, ?M:forget_records('_')),
?_assertEqual([], ?M:get_record_defs())
]}.
%% only to silence compilation warning about unused records
test_fun(#r1{}) ->
#r2{}.
| null | https://raw.githubusercontent.com/Appliscale/xprof/198e5451db429cdb7bf6b4640ec932c425b635ae/apps/xprof_core/test/xprof_core_records_tests.erl | erlang | only to silence compilation warning about unused records | -module(xprof_core_records_tests).
-export([test_fun/1]).
-include_lib("eunit/include/eunit.hrl").
-define(M, xprof_core_records).
-record(r1, {f1}).
-record(r2, {f2 = default}).
smoke_test_() ->
{setup,
fun() ->
{ok, Pid} = ?M:start_link(),
Pid
end,
fun(Pid) ->
unlink(Pid),
exit(Pid, kill)
end,
[?_assertEqual([], ?M:get_record_defs()),
?_assertEqual([r1, r2], ?M:load_records(?MODULE)),
?_assertMatch([{attribute, _, record,
{r1,[{record_field, _, {atom, _,f1}}]}},
{attribute, _, record,
{r2,[{record_field, _, {atom, _,f2}, {atom, _, default}}]}}],
lists:sort(?M:get_record_defs())),
?_assertEqual(ok, ?M:forget_records(r2)),
?_assertMatch([{attribute, _, record,
{r1,[{record_field, _, {atom, _,f1}}]}}],
lists:sort(?M:get_record_defs())),
?_assertEqual(ok, ?M:forget_records('_')),
?_assertEqual([], ?M:get_record_defs())
]}.
test_fun(#r1{}) ->
#r2{}.
|
0cf630f6ad37e8c936053b30de080983b081f31e0c2823fa2e2e226d7214c446 | fission-codes/fission | Associator.hs | module Fission.Web.Server.App.Domain.Associator
( module Fission.Web.Server.App.Domain.Associator.Class
, associateWithFallback
) where
import Database.Persist.Types
import Fission.Prelude
import Fission.URL.Types
import qualified Fission.Web.Server.App.Domain.Initializer as AppDomain
import Fission.Web.Server.Models
-- Re-export
import Fission.Web.Server.App.Domain.Associator.Class
associateWithFallback ::
( MonadIO m
, Associator m
, AppDomain.Initializer m
)
=> UserId
-> AppId
-> Maybe Subdomain -- ^ Optional subdomain, falls back to autogenerated
-> UTCTime
-> m (Either Errors' Subdomain)
associateWithFallback userId appId Nothing now = do
subdomain <- liftIO (generate arbitrary)
associateWithFallback userId appId (Just subdomain) now
associateWithFallback userId appId sub@(Just subdomain) now = do
defaultDomainName <- AppDomain.initial
associate userId appId Active defaultDomainName sub now
<&> fmap \_ -> subdomain
| null | https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-web-server/library/Fission/Web/Server/App/Domain/Associator.hs | haskell | Re-export
^ Optional subdomain, falls back to autogenerated | module Fission.Web.Server.App.Domain.Associator
( module Fission.Web.Server.App.Domain.Associator.Class
, associateWithFallback
) where
import Database.Persist.Types
import Fission.Prelude
import Fission.URL.Types
import qualified Fission.Web.Server.App.Domain.Initializer as AppDomain
import Fission.Web.Server.Models
import Fission.Web.Server.App.Domain.Associator.Class
associateWithFallback ::
( MonadIO m
, Associator m
, AppDomain.Initializer m
)
=> UserId
-> AppId
-> UTCTime
-> m (Either Errors' Subdomain)
associateWithFallback userId appId Nothing now = do
subdomain <- liftIO (generate arbitrary)
associateWithFallback userId appId (Just subdomain) now
associateWithFallback userId appId sub@(Just subdomain) now = do
defaultDomainName <- AppDomain.initial
associate userId appId Active defaultDomainName sub now
<&> fmap \_ -> subdomain
|
4db6e38d5572a4f064afb27bda42c2dd8e71b5ab67ec9dd821f31ce07a3383e5 | jaspervdj/advent-of-code | 09.hs | {-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.List as L
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import qualified System.IO as IO
import Text.Read (readMaybe)
type Distances = Map.Map (String, String) Int
readDistances :: IO.Handle -> IO Distances
readDistances h =
fmap Map.unions (IO.hGetContents h >>= mapM readDistance . lines)
where
readDistance line = case words line of
[x, "to", y, "=", d] | Just n <- readMaybe d -> pure $
Map.fromList [((x, y), n), ((y, x), n)]
_ -> fail $ "Couldn't parse line: " ++ show line
distance :: Distances -> [String] -> Int
distance distances = go 0
where
go !acc (x : y : zs) =
go (acc + fromMaybe 0 (Map.lookup (x, y) distances)) (y : zs)
go !acc _ = acc
main :: IO ()
main = do
distances <- readDistances IO.stdin
let cities = Set.toList . Set.fromList . map fst $ Map.keys distances
print $ minimum $ map (distance distances) (L.permutations cities)
print $ maximum $ map (distance distances) (L.permutations cities)
| null | https://raw.githubusercontent.com/jaspervdj/advent-of-code/bdc9628d1495d4e7fdbd9cea2739b929f733e751/2015/09.hs | haskell | # LANGUAGE BangPatterns # | module Main where
import qualified Data.List as L
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import qualified Data.Set as Set
import qualified System.IO as IO
import Text.Read (readMaybe)
type Distances = Map.Map (String, String) Int
readDistances :: IO.Handle -> IO Distances
readDistances h =
fmap Map.unions (IO.hGetContents h >>= mapM readDistance . lines)
where
readDistance line = case words line of
[x, "to", y, "=", d] | Just n <- readMaybe d -> pure $
Map.fromList [((x, y), n), ((y, x), n)]
_ -> fail $ "Couldn't parse line: " ++ show line
distance :: Distances -> [String] -> Int
distance distances = go 0
where
go !acc (x : y : zs) =
go (acc + fromMaybe 0 (Map.lookup (x, y) distances)) (y : zs)
go !acc _ = acc
main :: IO ()
main = do
distances <- readDistances IO.stdin
let cities = Set.toList . Set.fromList . map fst $ Map.keys distances
print $ minimum $ map (distance distances) (L.permutations cities)
print $ maximum $ map (distance distances) (L.permutations cities)
|
a5f1d608db744c8aed252ccb05f20c07b0c86f735fce31048135decd22c16e0d | ocaml-ppx/ppx | filename.mli | include module type of struct include Ppx_caml.Filename end
val split_extension : string -> string * string
val split_extension_after_dot : string -> string * string
val extension : string -> string
type program_name_kind =
| In_path
| Relative_to_current_dir
| Absolute
val analyze_program_name : string -> program_name_kind
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/stdppx/filename.mli | ocaml | include module type of struct include Ppx_caml.Filename end
val split_extension : string -> string * string
val split_extension_after_dot : string -> string * string
val extension : string -> string
type program_name_kind =
| In_path
| Relative_to_current_dir
| Absolute
val analyze_program_name : string -> program_name_kind
| |
e98d773921f32f5fd1dbe3a39f173a0944c63c3206a93da1db7da13995f6e051 | utz82/pstk | hello-84.scm | ;; example to show use of a different tclsh
(cond-expand
(chicken-4 (use pstk))
(chicken-5 (import pstk)))
(tk-start "tclsh8.4")
(tk/pack
(tk 'create-widget 'button 'text: "Hello"
'command: (lambda () (display "Hello world") (newline)))
'padx: 20 'pady: 20)
(tk-event-loop)
| null | https://raw.githubusercontent.com/utz82/pstk/27e907097529a3d61bb63e87e4e1cd1ca9abc3af/doc/examples/hello-84.scm | scheme | example to show use of a different tclsh |
(cond-expand
(chicken-4 (use pstk))
(chicken-5 (import pstk)))
(tk-start "tclsh8.4")
(tk/pack
(tk 'create-widget 'button 'text: "Hello"
'command: (lambda () (display "Hello world") (newline)))
'padx: 20 'pady: 20)
(tk-event-loop)
|
c0d0d63de888c20bafea6f0128e973e688311c908f68b53b86a5837c1f265603 | racket/honu | api.rkt | #lang racket/base
Public API for interfacing with the honu macro system
(require honu-parse
(for-syntax honu-parse))
(provide define-honu-syntax
define-literal
(for-syntax racket-syntax
honu-expression
honu-syntax
honu-body
parse-all))
| null | https://raw.githubusercontent.com/racket/honu/b36b9aeda8be22bf7fda177e831f42ac1a1de79b/honu/core/api.rkt | racket | #lang racket/base
Public API for interfacing with the honu macro system
(require honu-parse
(for-syntax honu-parse))
(provide define-honu-syntax
define-literal
(for-syntax racket-syntax
honu-expression
honu-syntax
honu-body
parse-all))
| |
1974897f1d66a485af4c048e10e46b0cd296ab9d9030a3e28d11c0c9e02632a0 | antono/guix-debian | pciutils.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
;;;
;;; 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 pciutils)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module ((guix licenses)
#:renamer (symbol-prefix-proc 'license:))
#:use-module (guix build-system gnu)
#:use-module (gnu packages compression)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages which))
(define-public pciutils
(package
(name "pciutils")
(version "3.2.0")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version
".tar.bz2"))
(sha256
(base32
"0d9as9jzjjg5c1nwf58z1y1i7rf9fqxmww1civckhcvcn0xr85mq"))))
(build-system gnu-build-system)
(arguments
'(#:phases (alist-replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
;; There's no 'configure' script, just a raw makefile.
(substitute* "Makefile"
(("^PREFIX=.*$")
(string-append "PREFIX := " (assoc-ref outputs "out")
"\n"))
(("^MANDIR:=.*$")
;; By default the thing tries to automatically
;; determine whether to use $prefix/man or
;; $prefix/share/man, and wrongly so.
(string-append "MANDIR := " (assoc-ref outputs "out")
"/share/man\n"))
(("^SHARED=.*$")
;; Build libpciutils.so.
"SHARED := yes\n")
(("^ZLIB=.*$")
;; Ask for zlib support.
"ZLIB := yes\n")))
(alist-replace
'install
(lambda* (#:key outputs #:allow-other-keys)
Install the commands , library , and .pc files .
(zero? (system* "make" "install" "install-lib")))
%standard-phases))
Make sure programs have an RPATH so they can find libpciutils.so .
#:make-flags (list (string-append "LDFLAGS=-Wl,-rpath="
(assoc-ref %outputs "out") "/lib"))
;; No test suite.
#:tests? #f))
(native-inputs
`(("which" ,which)
("pkg-config" ,pkg-config)))
(inputs
TODO : Add dependency on .
`(("zlib" ,zlib)))
(home-page "/")
(synopsis "Programs for inspecting and manipulating PCI devices")
(description
"The PCI Utilities are a collection of programs for inspecting and
manipulating configuration of PCI devices, all based on a common portable
library libpci which offers access to the PCI configuration space on a variety
of operating systems. This includes the 'lspci' and 'setpci' commands.")
(license license:gpl2+)))
| null | https://raw.githubusercontent.com/antono/guix-debian/85ef443788f0788a62010a942973d4f7714d10b4/gnu/packages/pciutils.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.
There's no 'configure' script, just a raw makefile.
By default the thing tries to automatically
determine whether to use $prefix/man or
$prefix/share/man, and wrongly so.
Build libpciutils.so.
Ask for zlib support.
No test suite. | Copyright © 2014 < >
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 pciutils)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module ((guix licenses)
#:renamer (symbol-prefix-proc 'license:))
#:use-module (guix build-system gnu)
#:use-module (gnu packages compression)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages which))
(define-public pciutils
(package
(name "pciutils")
(version "3.2.0")
(source (origin
(method url-fetch)
(uri (string-append
"mirror-"
version
".tar.bz2"))
(sha256
(base32
"0d9as9jzjjg5c1nwf58z1y1i7rf9fqxmww1civckhcvcn0xr85mq"))))
(build-system gnu-build-system)
(arguments
'(#:phases (alist-replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(substitute* "Makefile"
(("^PREFIX=.*$")
(string-append "PREFIX := " (assoc-ref outputs "out")
"\n"))
(("^MANDIR:=.*$")
(string-append "MANDIR := " (assoc-ref outputs "out")
"/share/man\n"))
(("^SHARED=.*$")
"SHARED := yes\n")
(("^ZLIB=.*$")
"ZLIB := yes\n")))
(alist-replace
'install
(lambda* (#:key outputs #:allow-other-keys)
Install the commands , library , and .pc files .
(zero? (system* "make" "install" "install-lib")))
%standard-phases))
Make sure programs have an RPATH so they can find libpciutils.so .
#:make-flags (list (string-append "LDFLAGS=-Wl,-rpath="
(assoc-ref %outputs "out") "/lib"))
#:tests? #f))
(native-inputs
`(("which" ,which)
("pkg-config" ,pkg-config)))
(inputs
TODO : Add dependency on .
`(("zlib" ,zlib)))
(home-page "/")
(synopsis "Programs for inspecting and manipulating PCI devices")
(description
"The PCI Utilities are a collection of programs for inspecting and
manipulating configuration of PCI devices, all based on a common portable
library libpci which offers access to the PCI configuration space on a variety
of operating systems. This includes the 'lspci' and 'setpci' commands.")
(license license:gpl2+)))
|
1cf8c996036fff39054c201da75e5f71296b59b665696a0e83fdab6d8c35c30a | chris-taylor/aima-haskell | Grass.hs | module AI.Probability.Example.Grass
( grass
, AI.Probability.Bayes.enumerationAsk
, AI.Probability.Bayes.eliminationAsk
, AI.Probability.Bayes.rejectionSample
, AI.Probability.Bayes.likelihoodWeighting
) where
import AI.Probability.Bayes
|The " grass " example from AIMA . You can query the network using any of the
ask functions . For example , to query the distribution of /Rain/ given
-- that /GrassWet/ is true, you would do
--
-- >>> enumerationAsk alarm [("GrassWet",True)] "Rain"
True 35.8 %
False 64.2 %
--
-- The same bug as in the alarm example also occurs here.
grass :: BayesNet String
grass = fromList [ ("Rain", [], [0.2])
, ("Sprinkler", ["Rain"], [0.01, 0.4])
, ("GrassWet", ["Sprinkler","Rain"], [0.99, 0.9, 0.8, 0]) ] | null | https://raw.githubusercontent.com/chris-taylor/aima-haskell/538dcfe82a57a623e45174e911ce68974d8aa839/src/AI/Probability/Example/Grass.hs | haskell | that /GrassWet/ is true, you would do
>>> enumerationAsk alarm [("GrassWet",True)] "Rain"
The same bug as in the alarm example also occurs here.
| module AI.Probability.Example.Grass
( grass
, AI.Probability.Bayes.enumerationAsk
, AI.Probability.Bayes.eliminationAsk
, AI.Probability.Bayes.rejectionSample
, AI.Probability.Bayes.likelihoodWeighting
) where
import AI.Probability.Bayes
|The " grass " example from AIMA . You can query the network using any of the
ask functions . For example , to query the distribution of /Rain/ given
True 35.8 %
False 64.2 %
grass :: BayesNet String
grass = fromList [ ("Rain", [], [0.2])
, ("Sprinkler", ["Rain"], [0.01, 0.4])
, ("GrassWet", ["Sprinkler","Rain"], [0.99, 0.9, 0.8, 0]) ] |
c7e7da96789da4abfaad2b230f93582978fb141c7a0adbb00f20e15db21ff638 | erlangonrails/devdb | win32_dns.erl | %%%----------------------------------------------------------------------
%%% File : win32_dns.erl
Author : nt
Purpose : Get name servers in a Windows machine
Created : 5 Mar 2009 by nt
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne
%%%
%%% 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
%%%
%%%----------------------------------------------------------------------
-module(win32_dns).
-export([get_nameservers/0]).
-include("ejabberd.hrl").
-define(IF_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters\\Interfaces").
-define(TOP_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters").
get_nameservers() ->
{_, Config} = pick_config(),
IPTs = get_value(["NameServer"], Config),
lists:filter(fun(IPTuple) -> is_good_ns(IPTuple) end, IPTs).
is_good_ns(Addr) ->
element(1,
inet_res:nnslookup("a.root-servers.net", in, any, [{Addr,53}],
timer:seconds(5)
)
) =:= ok.
reg() ->
{ok, R} = win32reg:open([read]),
R.
interfaces(R) ->
ok = win32reg:change_key(R, ?IF_KEY),
{ok, I} = win32reg:sub_keys(R),
I.
config_keys(R, Key) ->
ok = win32reg:change_key(R, Key),
[ {K,
case win32reg:value(R, K) of
{ok, V} -> try_translate(K, V);
_ -> undefined
end
} || K <- ["Domain", "DhcpDomain",
"NameServer", "DhcpNameServer", "SearchList"]].
try_translate(K, V) ->
try translate(K, V) of
Res ->
Res
catch
A:B ->
?ERROR_MSG("Error '~p' translating Win32 registry~n"
"K: ~p~nV: ~p~nError: ~p", [A, K, V, B]),
undefined
end.
translate(NS, V) when NS =:= "NameServer"; NS =:= "DhcpNameServer" ->
%% The IPs may be separated by commas ',' or by spaces " "
%% The parts of an IP are separated by dots '.'
IPsStrings = [string:tokens(IP, ".") || IP <- string:tokens(V, " ,")],
[ list_to_tuple([list_to_integer(String) || String <- IpStrings])
|| IpStrings <- IPsStrings];
translate(_, V) -> V.
interface_configs(R) ->
[{If, config_keys(R, ?IF_KEY ++ "\\" ++ If)}
|| If <- interfaces(R)].
sort_configs(Configs) ->
lists:sort(fun ({_, A}, {_, B}) ->
ANS = proplists:get_value("NameServer", A),
BNS = proplists:get_value("NameServer", B),
if ANS =/= undefined, BNS =:= undefined -> false;
true -> count_undef(A) < count_undef(B)
end
end,
Configs).
count_undef(L) when is_list(L) ->
lists:foldl(fun ({_K, undefined}, Acc) -> Acc +1;
({_K, []}, Acc) -> Acc +1;
(_, Acc) -> Acc
end, 0, L).
all_configs() ->
R = reg(),
TopConfig = config_keys(R, ?TOP_KEY),
Configs = [{top, TopConfig}
| interface_configs(R)],
win32reg:close(R),
{TopConfig, Configs}.
pick_config() ->
{TopConfig, Configs} = all_configs(),
NSConfigs = [{If, C} || {If, C} <- Configs,
get_value(["DhcpNameServer","NameServer"], C)
=/= undefined],
case get_value(["DhcpNameServer","NameServer"],
TopConfig) of
%% No top level nameserver to pick interface with
undefined ->
hd(sort_configs(NSConfigs));
%% Top level has a nameserver - use this to select an interface.
NS ->
Cs = [ {If, C}
|| {If, C} <- Configs,
lists:member(NS,
[get_value(["NameServer"], C),
get_value(["DhcpNameServer"], C)])],
hd(sort_configs(Cs))
end.
get_value([], _Config) -> undefined;
get_value([K|Keys], Config) ->
case proplists:get_value(K, Config) of
undefined -> get_value(Keys, Config);
V -> V
end.
| null | https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/ejabberd-2.1.4/src/win32_dns.erl | erlang | ----------------------------------------------------------------------
File : win32_dns.erl
This program is free software; you can redistribute it and/or
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.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
The IPs may be separated by commas ',' or by spaces " "
The parts of an IP are separated by dots '.'
No top level nameserver to pick interface with
Top level has a nameserver - use this to select an interface. | Author : nt
Purpose : Get name servers in a Windows machine
Created : 5 Mar 2009 by nt
ejabberd , Copyright ( C ) 2002 - 2010 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(win32_dns).
-export([get_nameservers/0]).
-include("ejabberd.hrl").
-define(IF_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters\\Interfaces").
-define(TOP_KEY, "\\hklm\\system\\CurrentControlSet\\Services\\TcpIp\\Parameters").
get_nameservers() ->
{_, Config} = pick_config(),
IPTs = get_value(["NameServer"], Config),
lists:filter(fun(IPTuple) -> is_good_ns(IPTuple) end, IPTs).
is_good_ns(Addr) ->
element(1,
inet_res:nnslookup("a.root-servers.net", in, any, [{Addr,53}],
timer:seconds(5)
)
) =:= ok.
reg() ->
{ok, R} = win32reg:open([read]),
R.
interfaces(R) ->
ok = win32reg:change_key(R, ?IF_KEY),
{ok, I} = win32reg:sub_keys(R),
I.
config_keys(R, Key) ->
ok = win32reg:change_key(R, Key),
[ {K,
case win32reg:value(R, K) of
{ok, V} -> try_translate(K, V);
_ -> undefined
end
} || K <- ["Domain", "DhcpDomain",
"NameServer", "DhcpNameServer", "SearchList"]].
try_translate(K, V) ->
try translate(K, V) of
Res ->
Res
catch
A:B ->
?ERROR_MSG("Error '~p' translating Win32 registry~n"
"K: ~p~nV: ~p~nError: ~p", [A, K, V, B]),
undefined
end.
translate(NS, V) when NS =:= "NameServer"; NS =:= "DhcpNameServer" ->
IPsStrings = [string:tokens(IP, ".") || IP <- string:tokens(V, " ,")],
[ list_to_tuple([list_to_integer(String) || String <- IpStrings])
|| IpStrings <- IPsStrings];
translate(_, V) -> V.
interface_configs(R) ->
[{If, config_keys(R, ?IF_KEY ++ "\\" ++ If)}
|| If <- interfaces(R)].
sort_configs(Configs) ->
lists:sort(fun ({_, A}, {_, B}) ->
ANS = proplists:get_value("NameServer", A),
BNS = proplists:get_value("NameServer", B),
if ANS =/= undefined, BNS =:= undefined -> false;
true -> count_undef(A) < count_undef(B)
end
end,
Configs).
count_undef(L) when is_list(L) ->
lists:foldl(fun ({_K, undefined}, Acc) -> Acc +1;
({_K, []}, Acc) -> Acc +1;
(_, Acc) -> Acc
end, 0, L).
all_configs() ->
R = reg(),
TopConfig = config_keys(R, ?TOP_KEY),
Configs = [{top, TopConfig}
| interface_configs(R)],
win32reg:close(R),
{TopConfig, Configs}.
pick_config() ->
{TopConfig, Configs} = all_configs(),
NSConfigs = [{If, C} || {If, C} <- Configs,
get_value(["DhcpNameServer","NameServer"], C)
=/= undefined],
case get_value(["DhcpNameServer","NameServer"],
TopConfig) of
undefined ->
hd(sort_configs(NSConfigs));
NS ->
Cs = [ {If, C}
|| {If, C} <- Configs,
lists:member(NS,
[get_value(["NameServer"], C),
get_value(["DhcpNameServer"], C)])],
hd(sort_configs(Cs))
end.
get_value([], _Config) -> undefined;
get_value([K|Keys], Config) ->
case proplists:get_value(K, Config) of
undefined -> get_value(Keys, Config);
V -> V
end.
|
913f0b0211e32b0da65921f955a762ca99df163dc267bf053d038a05daf880ad | TrustInSoft/tis-interpreter | metrics_base.ml | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
vname , vaddrof
;;
Formatting html with
let html_tag_functions =
let mark_open_tag t = Format.sprintf "<%s>" t
and mark_close_tag t =
try
let index = String.index t ' ' in
Format.sprintf "</%s>" (String.sub t 0 index)
with
| Not_found -> Format.sprintf "</%s>" t
and print_open_tag _ = ()
and print_close_tag _ = ()
in
{ Format.mark_open_tag = mark_open_tag;
Format.mark_close_tag = mark_close_tag;
Format.print_open_tag = print_open_tag;
Format.print_close_tag = print_close_tag;
}
;;
Utility function to have underlines the same length as the title .
Underlines follow reStructuredText header conventions .
Underlines follow reStructuredText header conventions.
*)
let mk_hdr level ppf hdr_strg =
let c = match level with
| 1 -> '='
| 2 -> '-'
| 3 -> '~'
| _ -> assert false
in
let len = String.length hdr_strg in
let underline = String.make len c in
Format.fprintf ppf "@[<v 0>%s@ %s@]" hdr_strg underline ;
;;
(** Defining base metrics and operations on those *)
module BasicMetrics = struct
* Record type to compute cyclomatic complexity
type t = {
cfile_name : string;
cfunc_name : string;
cslocs: int;
cifs: int;
cloops: int;
ccalls: int;
cgotos: int;
cassigns: int;
cexits: int;
cfuncs: int;
cptrs: int;
cdecision_points: int;
cglob_vars: int;
ccyclo: int;
}
;;
let empty_metrics =
{ cfile_name = "";
cfunc_name = "";
cslocs = 0;
cifs = 0;
cloops = 0;
ccalls = 0;
cgotos = 0;
cassigns = 0;
cexits = 0;
cfuncs = 0;
cptrs = 0;
cdecision_points = 0;
cglob_vars = 0;
ccyclo = 0;
}
;;
let apply_then_set f metrics = metrics := f !metrics ;;
let incr_slocs metrics = { metrics with cslocs = succ metrics.cslocs ;} ;;
let incr_assigns metrics =
{ metrics with cassigns = succ metrics.cassigns ;}
;;
let incr_calls metrics = { metrics with ccalls = succ metrics.ccalls ;} ;;
let incr_exits metrics = { metrics with cexits = succ metrics.cexits ;} ;;
let incr_funcs metrics = { metrics with cfuncs = succ metrics.cfuncs ;} ;;
let incr_gotos metrics = { metrics with cgotos = succ metrics.cgotos ;} ;;
let incr_ifs metrics = { metrics with cifs = succ metrics.cifs ;} ;;
let incr_loops metrics = { metrics with cloops = succ metrics.cloops ;} ;;
let incr_ptrs metrics = { metrics with cptrs = succ metrics.cptrs ;} ;;
let incr_dpoints metrics =
{ metrics with cdecision_points = succ metrics.cdecision_points ;}
;;
let incr_glob_vars metrics = { metrics with cglob_vars = succ metrics.cglob_vars ;} ;;
let set_cyclo metrics cyclo = { metrics with ccyclo = cyclo ;} ;;
Compute cyclomatic complexity of a given metrics record
let compute_cyclo metrics =
metrics.cdecision_points - metrics.cexits + 2
;;
let labels =
[ "Sloc"; "Decision point"; "Global variables"; "If"; "Loop"; "Goto";
"Assignment"; "Exit point"; "Function"; "Function call";
"Pointer dereferencing";
"Cyclomatic complexity";
]
;;
let str_values metrics =
List.map string_of_int
[ metrics.cslocs; metrics.cdecision_points; metrics.cglob_vars; metrics.cifs;
metrics.cloops; metrics.cgotos; metrics.cassigns;
metrics.cexits; metrics.cfuncs; metrics.ccalls;
metrics.cptrs; metrics.ccyclo;
]
;;
let to_list metrics =
List.map2 (fun x y -> [ x; y; ]) labels (str_values metrics)
;;
(* Pretty print metrics as text eg. in stdout *)
let pp_base_metrics fmt metrics =
let heading =
if metrics.cfile_name = "" && metrics.cfunc_name = "" then
(* It is a global metrics *)
"Global metrics"
else Format.sprintf "Stats for function <%s/%s>"
(Filepath.pretty metrics.cfile_name) metrics.cfunc_name
in
Format.fprintf fmt "@[<v 0>%a @ %a@]"
(mk_hdr 1) heading
((fun l1 ppf l2 ->
List.iter2 (fun x y -> Format.fprintf ppf "%s = %s@ " x y)
l1 l2) labels)
(str_values metrics)
;;
(* Dummy utility functions for pretty printing simple types *)
let pp_strg fmt s = Format.fprintf fmt "%s" s
and pp_int fmt n = Format.fprintf fmt "%d" n
;;
type cell_type =
| Classic
| Entry
;;
let cell_type_to_string = function
| Entry -> "entry"
| Classic -> "classic"
;;
let pp_cell_type_html fmt cell_type =
Format.fprintf fmt "class=\"%s\"" (cell_type_to_string cell_type)
;;
(* Pretty print a HTML cell given a pretty printing function [pp_fun]
and a value [pp_arg]
*)
let pp_cell cell_type pp_fun fmt pp_arg =
Format.fprintf fmt "@{<td %a>%a@}"
pp_cell_type_html cell_type
pp_fun pp_arg
;;
let pp_cell_default = pp_cell Classic;;
let pp_base_metrics_as_html_row fmt metrics =
Format.fprintf fmt "\
@[<v 0>\
@{<tr>@[<v 2>@ \
@[<v 0>%a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@ @]@]\
@}@ @]"
(pp_cell Entry pp_strg) metrics.cfunc_name
(pp_cell_default pp_int) metrics.cifs
(pp_cell_default pp_int) metrics.cassigns
(pp_cell_default pp_int) metrics.cloops
(pp_cell_default pp_int) metrics.ccalls
(pp_cell_default pp_int) metrics.cgotos
(pp_cell_default pp_int) metrics.cptrs
(pp_cell_default pp_int) metrics.cexits
(pp_cell_default pp_int) metrics.ccyclo
;;
end (* End of BasicMetrics *)
* { 3 Filename utilities }
exception No_suffix;;
let get_suffix filename =
try
let slen = String.length filename in
let last_idx = pred slen in
let last_dot_idx = String.rindex_from filename last_idx '.' in
if last_dot_idx < last_idx then
String.sub filename (succ last_dot_idx) (slen - last_dot_idx - 1)
else ""
with
| Not_found -> raise No_suffix
;;
type output_type =
| Html
| Text
;;
let get_file_type filename =
try
match get_suffix filename with
| "html" | "htm" -> Html
| "txt" | "text" -> Text
| s ->
Metrics_parameters.fatal
"Unknown file extension %s. Cannot produce output.@." s
with
| No_suffix ->
Metrics_parameters.fatal
"File %s has no suffix. Cannot produce output.@." filename
module VarinfoByName = struct
type t = Cil_types.varinfo
let compare v1 v2 = Pervasives.compare v1.vname v2.vname
end
* Map and sets of varinfos sorted by name ( and not by ids )
module VInfoMap = FCMap.Make (VarinfoByName)
module VInfoSet = FCSet.Make (VarinfoByName)
(** Other pretty-printing and formatting utilities *)
let pretty_set fmt s =
Format.fprintf fmt "@[";
VInfoMap.iter
(fun f n ->
Format.fprintf fmt "%s %s(%d call%s);@ "
f.Cil_types.vname
(if f.vaddrof then "(address taken) " else "")
n (if n > 1 then "s" else ""))
s;
Format.fprintf fmt "@]"
let pretty_extern_vars fmt s =
Pretty_utils.pp_iter ~pre:"@[" ~suf:"@]" ~sep:";@ "
VInfoSet.iter Printer.pp_varinfo fmt s
let is_in_libc (loc:location) =
Filepath.is_relative ~base:Config.datadir (fst loc).Lexing.pos_fname
(* Utilities for CIL ASTs *)
let file_of_vinfodef fvinfo =
let kf = Globals.Functions.get fvinfo in
let decl_loc1, _decl_loc2 =
match kf.fundec with
| Definition (_, loc) -> loc
| Declaration (_, _, _, loc) -> loc
in decl_loc1.Lexing.pos_fname
;;
let file_of_fundef (fun_dec: Cil_types.fundec) =
file_of_vinfodef fun_dec.svar
;;
Utilities for Cabs ASTs
let extract_fundef_name sname =
match sname with
| _spec, (the_name, _, _, _) -> the_name
;;
let get_filename fdef =
match fdef with
| Cabs.FUNDEF(_, _, _, (loc1, _), _loc2) -> loc1.Lexing.pos_fname
| _ -> assert false
;;
let consider_function vinfo =
not (!Db.Value.mem_builtin vinfo.vname
|| Ast_info.is_frama_c_builtin vinfo.vname
|| Cil.is_unused_builtin vinfo
) && (Metrics_parameters.Libc.get () || not (is_in_libc vinfo.vdecl))
let consider_variable vinfo =
not (Cil.hasAttribute "FRAMA_C_MODEL" vinfo.vattr)
let float_to_string f =
let s = Format.sprintf "%F" f in
let len = String.length s in
let plen = pred len in
if s.[plen] = '.' then String.sub s 0 plen else Format.sprintf "%.2f" f
(** Other pretty-printing and formatting utilities *)
let is_entry_point vinfo times_called =
times_called = 0 && not vinfo.vaddrof && consider_function vinfo
;;
let number_entry_points fs =
VInfoMap.fold
(fun fvinfo n acc -> if is_entry_point fvinfo n then succ acc else acc)
fs 0
;;
let pretty_entry_points fmt fs =
let print fmt =
VInfoMap.iter
(fun fvinfo n ->
if is_entry_point fvinfo n
then Format.fprintf fmt "%s;@ " fvinfo.vname)
in
Format.fprintf fmt "@[<hov 1>%a@]" print fs;
;;
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/metrics/metrics_base.ml | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* Defining base metrics and operations on those
Pretty print metrics as text eg. in stdout
It is a global metrics
Dummy utility functions for pretty printing simple types
Pretty print a HTML cell given a pretty printing function [pp_fun]
and a value [pp_arg]
End of BasicMetrics
* Other pretty-printing and formatting utilities
Utilities for CIL ASTs
* Other pretty-printing and formatting utilities
Local Variables:
compile-command: "make -C ../../.."
End:
| Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
vname , vaddrof
;;
Formatting html with
let html_tag_functions =
let mark_open_tag t = Format.sprintf "<%s>" t
and mark_close_tag t =
try
let index = String.index t ' ' in
Format.sprintf "</%s>" (String.sub t 0 index)
with
| Not_found -> Format.sprintf "</%s>" t
and print_open_tag _ = ()
and print_close_tag _ = ()
in
{ Format.mark_open_tag = mark_open_tag;
Format.mark_close_tag = mark_close_tag;
Format.print_open_tag = print_open_tag;
Format.print_close_tag = print_close_tag;
}
;;
Utility function to have underlines the same length as the title .
Underlines follow reStructuredText header conventions .
Underlines follow reStructuredText header conventions.
*)
let mk_hdr level ppf hdr_strg =
let c = match level with
| 1 -> '='
| 2 -> '-'
| 3 -> '~'
| _ -> assert false
in
let len = String.length hdr_strg in
let underline = String.make len c in
Format.fprintf ppf "@[<v 0>%s@ %s@]" hdr_strg underline ;
;;
module BasicMetrics = struct
* Record type to compute cyclomatic complexity
type t = {
cfile_name : string;
cfunc_name : string;
cslocs: int;
cifs: int;
cloops: int;
ccalls: int;
cgotos: int;
cassigns: int;
cexits: int;
cfuncs: int;
cptrs: int;
cdecision_points: int;
cglob_vars: int;
ccyclo: int;
}
;;
let empty_metrics =
{ cfile_name = "";
cfunc_name = "";
cslocs = 0;
cifs = 0;
cloops = 0;
ccalls = 0;
cgotos = 0;
cassigns = 0;
cexits = 0;
cfuncs = 0;
cptrs = 0;
cdecision_points = 0;
cglob_vars = 0;
ccyclo = 0;
}
;;
let apply_then_set f metrics = metrics := f !metrics ;;
let incr_slocs metrics = { metrics with cslocs = succ metrics.cslocs ;} ;;
let incr_assigns metrics =
{ metrics with cassigns = succ metrics.cassigns ;}
;;
let incr_calls metrics = { metrics with ccalls = succ metrics.ccalls ;} ;;
let incr_exits metrics = { metrics with cexits = succ metrics.cexits ;} ;;
let incr_funcs metrics = { metrics with cfuncs = succ metrics.cfuncs ;} ;;
let incr_gotos metrics = { metrics with cgotos = succ metrics.cgotos ;} ;;
let incr_ifs metrics = { metrics with cifs = succ metrics.cifs ;} ;;
let incr_loops metrics = { metrics with cloops = succ metrics.cloops ;} ;;
let incr_ptrs metrics = { metrics with cptrs = succ metrics.cptrs ;} ;;
let incr_dpoints metrics =
{ metrics with cdecision_points = succ metrics.cdecision_points ;}
;;
let incr_glob_vars metrics = { metrics with cglob_vars = succ metrics.cglob_vars ;} ;;
let set_cyclo metrics cyclo = { metrics with ccyclo = cyclo ;} ;;
Compute cyclomatic complexity of a given metrics record
let compute_cyclo metrics =
metrics.cdecision_points - metrics.cexits + 2
;;
let labels =
[ "Sloc"; "Decision point"; "Global variables"; "If"; "Loop"; "Goto";
"Assignment"; "Exit point"; "Function"; "Function call";
"Pointer dereferencing";
"Cyclomatic complexity";
]
;;
let str_values metrics =
List.map string_of_int
[ metrics.cslocs; metrics.cdecision_points; metrics.cglob_vars; metrics.cifs;
metrics.cloops; metrics.cgotos; metrics.cassigns;
metrics.cexits; metrics.cfuncs; metrics.ccalls;
metrics.cptrs; metrics.ccyclo;
]
;;
let to_list metrics =
List.map2 (fun x y -> [ x; y; ]) labels (str_values metrics)
;;
let pp_base_metrics fmt metrics =
let heading =
if metrics.cfile_name = "" && metrics.cfunc_name = "" then
"Global metrics"
else Format.sprintf "Stats for function <%s/%s>"
(Filepath.pretty metrics.cfile_name) metrics.cfunc_name
in
Format.fprintf fmt "@[<v 0>%a @ %a@]"
(mk_hdr 1) heading
((fun l1 ppf l2 ->
List.iter2 (fun x y -> Format.fprintf ppf "%s = %s@ " x y)
l1 l2) labels)
(str_values metrics)
;;
let pp_strg fmt s = Format.fprintf fmt "%s" s
and pp_int fmt n = Format.fprintf fmt "%d" n
;;
type cell_type =
| Classic
| Entry
;;
let cell_type_to_string = function
| Entry -> "entry"
| Classic -> "classic"
;;
let pp_cell_type_html fmt cell_type =
Format.fprintf fmt "class=\"%s\"" (cell_type_to_string cell_type)
;;
let pp_cell cell_type pp_fun fmt pp_arg =
Format.fprintf fmt "@{<td %a>%a@}"
pp_cell_type_html cell_type
pp_fun pp_arg
;;
let pp_cell_default = pp_cell Classic;;
let pp_base_metrics_as_html_row fmt metrics =
Format.fprintf fmt "\
@[<v 0>\
@{<tr>@[<v 2>@ \
@[<v 0>%a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@ %a@ @]@]\
@}@ @]"
(pp_cell Entry pp_strg) metrics.cfunc_name
(pp_cell_default pp_int) metrics.cifs
(pp_cell_default pp_int) metrics.cassigns
(pp_cell_default pp_int) metrics.cloops
(pp_cell_default pp_int) metrics.ccalls
(pp_cell_default pp_int) metrics.cgotos
(pp_cell_default pp_int) metrics.cptrs
(pp_cell_default pp_int) metrics.cexits
(pp_cell_default pp_int) metrics.ccyclo
;;
* { 3 Filename utilities }
exception No_suffix;;
let get_suffix filename =
try
let slen = String.length filename in
let last_idx = pred slen in
let last_dot_idx = String.rindex_from filename last_idx '.' in
if last_dot_idx < last_idx then
String.sub filename (succ last_dot_idx) (slen - last_dot_idx - 1)
else ""
with
| Not_found -> raise No_suffix
;;
type output_type =
| Html
| Text
;;
let get_file_type filename =
try
match get_suffix filename with
| "html" | "htm" -> Html
| "txt" | "text" -> Text
| s ->
Metrics_parameters.fatal
"Unknown file extension %s. Cannot produce output.@." s
with
| No_suffix ->
Metrics_parameters.fatal
"File %s has no suffix. Cannot produce output.@." filename
module VarinfoByName = struct
type t = Cil_types.varinfo
let compare v1 v2 = Pervasives.compare v1.vname v2.vname
end
* Map and sets of varinfos sorted by name ( and not by ids )
module VInfoMap = FCMap.Make (VarinfoByName)
module VInfoSet = FCSet.Make (VarinfoByName)
let pretty_set fmt s =
Format.fprintf fmt "@[";
VInfoMap.iter
(fun f n ->
Format.fprintf fmt "%s %s(%d call%s);@ "
f.Cil_types.vname
(if f.vaddrof then "(address taken) " else "")
n (if n > 1 then "s" else ""))
s;
Format.fprintf fmt "@]"
let pretty_extern_vars fmt s =
Pretty_utils.pp_iter ~pre:"@[" ~suf:"@]" ~sep:";@ "
VInfoSet.iter Printer.pp_varinfo fmt s
let is_in_libc (loc:location) =
Filepath.is_relative ~base:Config.datadir (fst loc).Lexing.pos_fname
let file_of_vinfodef fvinfo =
let kf = Globals.Functions.get fvinfo in
let decl_loc1, _decl_loc2 =
match kf.fundec with
| Definition (_, loc) -> loc
| Declaration (_, _, _, loc) -> loc
in decl_loc1.Lexing.pos_fname
;;
let file_of_fundef (fun_dec: Cil_types.fundec) =
file_of_vinfodef fun_dec.svar
;;
Utilities for Cabs ASTs
let extract_fundef_name sname =
match sname with
| _spec, (the_name, _, _, _) -> the_name
;;
let get_filename fdef =
match fdef with
| Cabs.FUNDEF(_, _, _, (loc1, _), _loc2) -> loc1.Lexing.pos_fname
| _ -> assert false
;;
let consider_function vinfo =
not (!Db.Value.mem_builtin vinfo.vname
|| Ast_info.is_frama_c_builtin vinfo.vname
|| Cil.is_unused_builtin vinfo
) && (Metrics_parameters.Libc.get () || not (is_in_libc vinfo.vdecl))
let consider_variable vinfo =
not (Cil.hasAttribute "FRAMA_C_MODEL" vinfo.vattr)
let float_to_string f =
let s = Format.sprintf "%F" f in
let len = String.length s in
let plen = pred len in
if s.[plen] = '.' then String.sub s 0 plen else Format.sprintf "%.2f" f
let is_entry_point vinfo times_called =
times_called = 0 && not vinfo.vaddrof && consider_function vinfo
;;
let number_entry_points fs =
VInfoMap.fold
(fun fvinfo n acc -> if is_entry_point fvinfo n then succ acc else acc)
fs 0
;;
let pretty_entry_points fmt fs =
let print fmt =
VInfoMap.iter
(fun fvinfo n ->
if is_entry_point fvinfo n
then Format.fprintf fmt "%s;@ " fvinfo.vname)
in
Format.fprintf fmt "@[<hov 1>%a@]" print fs;
;;
|
abb991e5316b65b6ab255c62ed9ecd1a921709ec5f797380c214d0debe9fb229 | scalaris-team/scalaris | yaws_revproxy.erl | %%%-------------------------------------------------------------------
%%% File : yaws_revproxy.erl
%%% Author : <>
%%% Description : reverse proxy
%%%
Created : 3 Dec 2003 by < >
%%%-------------------------------------------------------------------
-module(yaws_revproxy).
-include("../include/yaws.hrl").
-include("../include/yaws_api.hrl").
-include("yaws_debug.hrl").
-export([out/1]).
%% reverse proxy implementation.
the revproxy internal state
-record(revproxy, {srvsock, %% the socket opened on the backend server
the socket type : ssl | nossl
cliconn_status, %% "Connection:" header value:
srvconn_status, %% "keep-alive' or "close"
state, %% revproxy state:
%% sendheaders | sendcontent | sendchunk |
%% recvheaders | recvcontent | recvchunk |
%% terminate
prefix, %% The prefix to strip and add
url, %% the url we're proxying to
r_meth, %% what req method are we processing
r_host, %% and value of Host: for the cli request
resp, %% response received from the server
headers, %% and associated headers
srvdata, %% the server data
is_chunked, %% true if the response is chunked
intercept_mod %% revproxy request/response intercept module
}).
%% TODO: Activate proxy keep-alive with a new option ?
-define(proxy_keepalive, false).
Initialize the connection to the backend server . If an error occurred , return
an error 404 .
out(#arg{req=Req, headers=Hdrs, state=#proxy_cfg{url=URL}=State}=Arg) ->
case connect(URL) of
{ok, Sock, Type} ->
?Debug("Connection established on ~p: Socket=~p, Type=~p~n",
[URL, Sock, Type]),
RPState = #revproxy{srvsock = Sock,
type = Type,
state = sendheaders,
prefix = State#proxy_cfg.prefix,
url = URL,
r_meth = Req#http_request.method,
r_host = Hdrs#headers.host,
intercept_mod = State#proxy_cfg.intercept_mod},
out(Arg#arg{state=RPState});
_ERR ->
?Debug("Connection failed: ~p~n", [_ERR]),
out404(Arg)
end;
%% Send the client request to the server then check if the request content is
%% chunked or not
out(#arg{state=#revproxy{}=RPState}=Arg)
when RPState#revproxy.state == sendheaders ->
?Debug("Send request headers to backend server: ~n"
" - ~s~n", [?format_record(Arg#arg.req, http_request)]),
Req = rewrite_request(RPState, Arg#arg.req),
Hdrs0 = Arg#arg.headers,
Hdrs = rewrite_client_headers(RPState, Hdrs0),
{NewReq, NewHdrs} = case RPState#revproxy.intercept_mod of
undefined ->
{Req, Hdrs};
InterceptMod ->
case catch InterceptMod:rewrite_request(
Req, Hdrs) of
{ok, NewReq0, NewHdrs0} ->
{NewReq0, NewHdrs0};
InterceptError ->
error_logger:error_msg(
"revproxy intercept module ~p:"
"rewrite_request failed: ~p~n",
[InterceptMod, InterceptError]),
exit({error, intercept_mod})
end
end,
ReqStr = yaws_api:reformat_request(NewReq),
HdrsStr = yaws:headers_to_str(NewHdrs),
case send(RPState, [ReqStr, "\r\n", HdrsStr, "\r\n"]) of
ok ->
case yaws:to_lower(Hdrs#headers.transfer_encoding) of
"chunked" ->
?Debug("Request content is chunked~n", []),
out(Arg#arg{state=RPState#revproxy{state=sendchunk}});
_ ->
out(Arg#arg{state=RPState#revproxy{state=sendcontent}})
end;
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
%% Send the request content to the server. Here the content is not chunked. But
%% it can be split because of 'partial_post_size' value.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == sendcontent ->
case Arg#arg.clidata of
{partial, Bin} ->
?Debug("Send partial content to backend server: ~p bytes~n",
[size(Bin)]),
case send(RPState, Bin) of
ok ->
{get_more, undefined, RPState};
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
Bin when is_binary(Bin), Bin /= <<>> ->
?Debug("Send content to backend server: ~p bytes~n", [size(Bin)]),
case send(RPState, Bin) of
ok ->
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
_ ->
?Debug("no content found~n", []),
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1})
end;
%% Send the request content to the server. Here the content is chunked, so we
%% must rebuild the chunk before sending it. Chunks can have different size than
%% the original request because of 'partial_post_size' value.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == sendchunk ->
case Arg#arg.clidata of
{partial, Bin} ->
?Debug("Send chunked content to backend server: ~p bytes~n",
[size(Bin)]),
Res = send(RPState,
[yaws:integer_to_hex(size(Bin)),"\r\n",Bin,"\r\n"]),
case Res of
ok ->
{get_more, undefined, RPState};
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
<<>> ->
?Debug("Send last chunk to backend server~n", []),
case send(RPState, "0\r\n\r\n") of
ok ->
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end
end;
%% The request and its content were sent. Now, we try to read the response
%% headers. Then we check if the response content is chunked or not.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvheaders ->
Res = yaws:http_get_headers(RPState#revproxy.srvsock,
RPState#revproxy.type),
case Res of
{error, {too_many_headers, _Resp}} ->
?Debug("Response headers too large from backend server~n", []),
close(RPState),
outXXX(500, Arg);
{Resp0, RespHdrs0} when is_record(Resp0, http_response) ->
?Debug("Response headers received from backend server:~n"
" - ~s~n - ~s~n", [?format_record(Resp0, http_response),
?format_record(RespHdrs0, headers)]),
{Resp, RespHdrs} =
case RPState#revproxy.intercept_mod of
undefined ->
{Resp0, RespHdrs0};
InterceptMod ->
case catch InterceptMod:rewrite_response(
Resp0, RespHdrs0) of
{ok, NewResp, NewRespHdrs} ->
{NewResp, NewRespHdrs};
InterceptError ->
error_logger:error_msg(
"revproxy intercept module ~p:"
"rewrite_response failure: ~p~n",
[InterceptMod, InterceptError]),
exit({error, intercept_mod})
end
end,
{CliConn, SrvConn} = get_connection_status(
(Arg#arg.req)#http_request.version,
Arg#arg.headers, RespHdrs
),
RPState1 = RPState#revproxy{cliconn_status = CliConn,
srvconn_status = SrvConn,
resp = Resp,
headers = RespHdrs},
if
RPState1#revproxy.r_meth =:= 'HEAD' ->
RPState2 = RPState1#revproxy{state=terminate},
out(Arg#arg{state=RPState2});
Resp#http_response.status =:= 100 orelse
Resp#http_response.status =:= 204 orelse
Resp#http_response.status =:= 205 orelse
Resp#http_response.status =:= 304 orelse
Resp#http_response.status =:= 406 ->
RPState2 = RPState1#revproxy{state=terminate},
out(Arg#arg{state=RPState2});
true ->
RPState2 =
case {yaws:to_lower(RespHdrs#headers.transfer_encoding),
RespHdrs#headers.content_length} of
{"chunked", _} ->
RPState1#revproxy{state=recvchunk};
{_, undefined} ->
RPState1#revproxy{
cliconn_status="close",
srvconn_status="close",
state=recvcontent};
_ ->
RPState1#revproxy{state=recvcontent}
end,
out(Arg#arg{state=RPState2})
end;
{_R, _H} ->
%% bad_request
?Debug("Bad response received from backend server: ~p~n", [_R]),
close(RPState),
outXXX(500, Arg);
closed ->
?Debug("TCP error: ~p~n", [closed]),
outXXX(500, Arg)
end;
%% The response content is not chunked.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvcontent ->
Len = case (RPState#revproxy.headers)#headers.content_length of
undefined -> undefined;
CLen -> list_to_integer(CLen)
end,
SC=get(sc),
if
is_integer(Len) andalso Len =< SC#sconf.partial_post_size ->
case read(RPState, Len) of
{ok, Data} ->
?Debug("Response content received from the backend server: "
"~p bytes~n", [size(Data)]),
RPState1 = RPState#revproxy{state = terminate,
is_chunked = false,
srvdata = {content, Data}},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
is_integer(Len) ->
Here partial_post_size is always an integer
BlockSize = SC#sconf.partial_post_size,
BlockCount = Len div BlockSize,
LastBlock = Len rem BlockSize,
SrvData = {block, BlockCount, BlockSize, LastBlock},
RPState1 = RPState#revproxy{state = terminate,
is_chunked = true,
srvdata = SrvData},
out(Arg#arg{state=RPState1});
true ->
SrvData = {block, undefined, undefined, undefined},
RPState1 = RPState#revproxy{state = terminate,
is_chunked = true,
srvdata = SrvData},
out(Arg#arg{state=RPState1})
end;
The response content is chunked . Read the first chunk here and spawn a
%% process to read others.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvchunk ->
case read_chunk(RPState) of
{ok, Data} ->
?Debug("First chunk received from the backend server : "
"~p bytes~n", [size(Data)]),
RPState1 = RPState#revproxy{state = terminate,
is_chunked = (Data /= <<>>),
srvdata = {stream, Data}},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
%% Now, we return the result and we let yaws_server deals with it. If it is
%% possible, we try to cache the connection.
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == terminate ->
case RPState#revproxy.srvconn_status of
"close" when RPState#revproxy.is_chunked == false -> close(RPState);
"close" -> ok;
_ -> cache_connection(RPState)
end,
AllHdrs = [{header, H} || H <- yaws_api:reformat_header(
rewrite_server_headers(RPState)
)],
?Debug("~p~n", [AllHdrs]),
Res = [
{status, (RPState#revproxy.resp)#http_response.status},
{allheaders, AllHdrs}
],
case RPState#revproxy.srvdata of
{content, <<>>} ->
Res;
{content, Data} ->
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{content, MimeType, Data}];
{stream, <<>>} ->
Chunked response with only the last empty chunk : do not spawn a
%% process to manage chunks
yaws_api:stream_chunk_end(self()),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent, MimeType, <<>>}];
{stream, Chunk} ->
Self = self(),
GC = get(gc),
spawn(fun() -> put(gc, GC), recv_next_chunk(Self, Arg) end),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent, MimeType, Chunk}];
{block, BlockCnt, BlockSz, LastBlock} ->
GC = get(gc),
Pid = spawn(fun() ->
put(gc, GC),
receive
{ok, YawsPid} ->
recv_blocks(YawsPid, Arg, BlockCnt,
BlockSz, LastBlock);
{discard, YawsPid} ->
recv_blocks(YawsPid, Arg, 0, BlockSz, 0)
end
end),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent_from_pid, MimeType, Pid}];
_ ->
Res
end;
Catch unexpected state by sending an error 500
out(#arg{state=RPState}=Arg) ->
?Debug("Unexpected revproxy state:~n - ~s~n",
[?format_record(RPState, revproxy)]),
case RPState#revproxy.srvsock of
undefined -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg).
%%==========================================================================
out404(Arg) ->
SC=get(sc),
(SC#sconf.errormod_404):out404(Arg,get(gc),SC).
outXXX(Code, _Arg) ->
Content = ["<html><h1>", integer_to_list(Code), $\ ,
yaws_api:code_to_phrase(Code), "</h1></html>"],
[
{status, Code},
{header, {connection, "close"}},
{content, "text/html", Content}
].
%%==========================================================================
%% This function is used to read a chunk and to stream it to the client.
recv_next_chunk(YawsPid, #arg{state=RPState}=Arg) ->
case read_chunk(RPState) of
{ok, <<>>} ->
?Debug("Last chunk received from the backend server~n", []),
yaws_api:stream_chunk_end(YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
_ -> ok %% Cached by the main process
end;
{ok, Data} ->
?Debug("Next chunk received from the backend server : "
"~p bytes~n", [size(Data)]),
yaws_api:stream_chunk_deliver(YawsPid, Data),
recv_next_chunk(YawsPid, Arg);
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_chunk_end(YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end.
%%==========================================================================
%% This function reads blocks from the server and streams them to the client.
recv_blocks(YawsPid, #arg{state=RPState}=Arg,
undefined, undefined, undefined) ->
case read(RPState) of
{ok, <<>>} ->
no data , wait 100 msec to avoid time - consuming loop and retry
timer:sleep(100),
recv_blocks(YawsPid, Arg, undefined, undefined, undefined);
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Arg#arg.clisock, Data),
recv_blocks(YawsPid, Arg, undefined, undefined, undefined);
{error, closed} ->
yaws_api:stream_process_end(closed, YawsPid);
{error, _Reason} ->
?Debug("TCP error: ~p~n", [_Reason]),
yaws_api:stream_process_end(closed, YawsPid),
close(RPState)
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, 0, _, 0) ->
yaws_api:stream_process_end(Arg#arg.clisock, YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
_ -> ok %% Cached by the main process
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, 0, _, LastBlock) ->
Sock = Arg#arg.clisock,
case read(RPState, LastBlock) of
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Sock, Data),
yaws_api:stream_process_end(Sock, YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
_ -> ok %% Cached by the main process
end;
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_process_end(closed, YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, BlockCnt, BlockSz, LastBlock) ->
case read(RPState, BlockSz) of
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Arg#arg.clisock, Data),
recv_blocks(YawsPid, Arg, BlockCnt-1, BlockSz, LastBlock);
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_process_end(closed, YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end.
%%==========================================================================
%% TODO: find a better way to cache connections to backend servers. Here we can
have 1 connection per gserv process for each backend server .
get_cached_connection(URL) ->
Key = lists:flatten(yaws_api:reformat_url(URL)),
case erase(Key) of
undefined ->
undefined;
{Sock, nossl} ->
case gen_tcp:recv(Sock, 0, 1) of
{error, closed} ->
?Debug("Invalid cached connection~n", []),
undefined;
_ ->
?Debug("Found cached connection to ~s~n", [Key]),
{ok, Sock, nossl}
end;
{Sock, ssl} ->
case ssl:recv(Sock, 0, 1) of
{error, closed} ->
?Debug("Invalid cached connection~n", []),
undefined;
_ ->
?Debug("Found cached connection to ~s~n", [Key]),
{ok, Sock, ssl}
end
end.
cache_connection(RPState) ->
Key = lists:flatten(yaws_api:reformat_url(RPState#revproxy.url)),
?Debug("Cache connection to ~s~n", [Key]),
InitDB0 = get(init_db),
InitDB1 = lists:keystore(
Key, 1, InitDB0,
{Key, {RPState#revproxy.srvsock, RPState#revproxy.type}}
),
put(init_db, InitDB1),
ok.
%%==========================================================================
connect(URL) ->
case get_cached_connection(URL) of
{ok, Sock, Type} -> {ok, Sock, Type};
undefined -> do_connect(URL)
end.
do_connect(URL) ->
Opts = [
binary,
{packet, raw},
{active, false},
{reuseaddr, true}
],
case URL#url.scheme of
http ->
Port = case URL#url.port of
undefined -> 80;
P -> P
end,
case yaws:tcp_connect(URL#url.host, Port, Opts) of
{ok, S} -> {ok, S, nossl};
Err -> Err
end;
https ->
Port = case URL#url.port of
undefined -> 443;
P -> P
end,
case yaws:ssl_connect(URL#url.host, Port, Opts) of
{ok, S} -> {ok, S, ssl};
Err -> Err
end;
_ ->
{error, unsupported_protocol}
end.
send(#revproxy{srvsock=Sock, type=ssl}, Data) ->
ssl:send(Sock, Data);
send(#revproxy{srvsock=Sock, type=nossl}, Data) ->
gen_tcp:send(Sock, Data).
read(#revproxy{srvsock=Sock, type=Type}) ->
yaws:setopts(Sock, [{packet, raw}, binary], Type),
yaws:do_recv(Sock, 0, Type).
read(RPState, Len) ->
yaws:setopts(RPState#revproxy.srvsock, [{packet, raw}, binary],
RPState#revproxy.type),
read(RPState, Len, []).
read(_, 0, Data) ->
{ok, iolist_to_binary(lists:reverse(Data))};
read(RPState = #revproxy{srvsock=Sock, type=Type}, Len, Data) ->
case yaws:do_recv(Sock, Len, Type) of
{ok, Bin} -> read(RPState, Len-size(Bin), [Bin|Data]);
{error, Reason} -> {error, Reason}
end.
read_chunk(#revproxy{srvsock=Sock, type=Type}) ->
try
yaws:setopts(Sock, [binary, {packet, line}], Type),
%% Ignore chunk extentions
{Len, _Exts} = yaws:get_chunk_header(Sock, Type),
yaws:setopts(Sock, [binary, {packet, raw}], Type),
if
Len == 0 ->
%% Ignore chunk trailer
yaws:get_chunk_trailer(Sock, Type),
{ok, <<>>};
true ->
B = yaws:get_chunk(Sock, Len, 0, Type),
ok = yaws:eat_crnl(Sock, Type),
{ok, iolist_to_binary(B)}
end
catch
_:Reason ->
{error, Reason}
end.
close(#revproxy{srvsock=Sock, type=ssl}) ->
ssl:close(Sock);
close(#revproxy{srvsock=Sock, type=nossl}) ->
gen_tcp:close(Sock).
get_connection_status(Version, ReqHdrs, RespHdrs) ->
CliConn = case Version of
{0,9} ->
"close";
{1, 0} ->
case ReqHdrs#headers.connection of
undefined -> "close";
C1 -> yaws:to_lower(C1)
end;
{1, 1} ->
case ReqHdrs#headers.connection of
undefined -> "keep-alive";
C1 -> yaws:to_lower(C1)
end
end,
?Debug("Client Connection header: ~p~n", [CliConn]),
%% below, ignore dialyzer warning:
%% "The pattern 'true' can never match the type 'false'"
SrvConn = case ?proxy_keepalive of
true ->
case RespHdrs#headers.connection of
undefined -> CliConn;
C2 -> yaws:to_lower(C2)
end;
false ->
"close"
end,
?Debug("Server Connection header: ~p~n", [SrvConn]),
{CliConn, SrvConn}.
%%==========================================================================
rewrite_request(RPState, Req) ->
?Debug("Request path to rewrite: ~p~n", [Req#http_request.path]),
{abs_path, Path} = Req#http_request.path,
NewPath = strip_prefix(Path, RPState#revproxy.prefix),
?Debug("New Request path: ~p~n", [NewPath]),
Req#http_request{path = {abs_path, NewPath}}.
rewrite_client_headers(RPState, Hdrs) ->
?Debug("Host header to rewrite: ~p~n", [Hdrs#headers.host]),
Host = case Hdrs#headers.host of
undefined ->
undefined;
_ ->
ProxyUrl = RPState#revproxy.url,
[ProxyUrl#url.host,
case ProxyUrl#url.port of
undefined -> [];
P -> [$:|integer_to_list(P)]
end]
end,
?Debug("New Host header: ~p~n", [Host]),
Hdrs#headers{host = Host}.
rewrite_server_headers(RPState) ->
Hdrs = RPState#revproxy.headers,
?Debug("Location header to rewrite: ~p~n", [Hdrs#headers.location]),
Loc = case Hdrs#headers.location of
undefined ->
undefined;
L ->
?Debug("parse_url(~p)~n", [L]),
LocUrl = (catch yaws_api:parse_url(L)),
ProxyUrl = RPState#revproxy.url,
if
LocUrl#url.scheme == ProxyUrl#url.scheme andalso
LocUrl#url.host == ProxyUrl#url.host andalso
LocUrl#url.port == ProxyUrl#url.port ->
rewrite_loc_url(RPState, LocUrl);
element(1, L) == 'EXIT' ->
rewrite_loc_rel(RPState, L);
true ->
L
end
end,
?Debug("New Location header: ~p~n", [Loc]),
%% FIXME: And we also should do cookies here ...
Hdrs#headers{location = Loc, connection = RPState#revproxy.cliconn_status}.
Rewrite a properly formatted location redir
rewrite_loc_url(RPState, LocUrl) ->
SC=get(sc),
Scheme = yaws:redirect_scheme(SC),
RedirHost = yaws:redirect_host(SC, RPState#revproxy.r_host),
[Scheme, RedirHost, slash_append(RPState#revproxy.prefix, LocUrl#url.path)].
%% This is the case for broken webservers that reply with
%% Location: /path
%% or even worse, Location: path
rewrite_loc_rel(RPState, Loc) ->
SC=get(sc),
Scheme = yaws:redirect_scheme(SC),
RedirHost = yaws:redirect_host(SC, RPState#revproxy.r_host),
[Scheme, RedirHost, Loc].
strip_prefix("", "") ->
"/";
strip_prefix(P, "") ->
P;
strip_prefix(P, "/") ->
P;
strip_prefix([H|T1], [H|T2]) ->
strip_prefix(T1, T2).
slash_append("/", [$/|T]) ->
[$/|T];
slash_append("/", T) ->
[$/|T];
slash_append([], [$/|T]) ->
[$/|T];
slash_append([], T) ->
[$/|T];
slash_append([H|T], X) ->
[H | slash_append(T, X)].
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/contrib/yaws/src/yaws_revproxy.erl | erlang | -------------------------------------------------------------------
File : yaws_revproxy.erl
Author : <>
Description : reverse proxy
-------------------------------------------------------------------
reverse proxy implementation.
the socket opened on the backend server
"Connection:" header value:
"keep-alive' or "close"
revproxy state:
sendheaders | sendcontent | sendchunk |
recvheaders | recvcontent | recvchunk |
terminate
The prefix to strip and add
the url we're proxying to
what req method are we processing
and value of Host: for the cli request
response received from the server
and associated headers
the server data
true if the response is chunked
revproxy request/response intercept module
TODO: Activate proxy keep-alive with a new option ?
Send the client request to the server then check if the request content is
chunked or not
Send the request content to the server. Here the content is not chunked. But
it can be split because of 'partial_post_size' value.
Send the request content to the server. Here the content is chunked, so we
must rebuild the chunk before sending it. Chunks can have different size than
the original request because of 'partial_post_size' value.
The request and its content were sent. Now, we try to read the response
headers. Then we check if the response content is chunked or not.
bad_request
The response content is not chunked.
process to read others.
Now, we return the result and we let yaws_server deals with it. If it is
possible, we try to cache the connection.
process to manage chunks
==========================================================================
==========================================================================
This function is used to read a chunk and to stream it to the client.
Cached by the main process
==========================================================================
This function reads blocks from the server and streams them to the client.
Cached by the main process
Cached by the main process
==========================================================================
TODO: find a better way to cache connections to backend servers. Here we can
==========================================================================
Ignore chunk extentions
Ignore chunk trailer
below, ignore dialyzer warning:
"The pattern 'true' can never match the type 'false'"
==========================================================================
FIXME: And we also should do cookies here ...
This is the case for broken webservers that reply with
Location: /path
or even worse, Location: path | Created : 3 Dec 2003 by < >
-module(yaws_revproxy).
-include("../include/yaws.hrl").
-include("../include/yaws_api.hrl").
-include("yaws_debug.hrl").
-export([out/1]).
the revproxy internal state
the socket type : ssl | nossl
}).
-define(proxy_keepalive, false).
Initialize the connection to the backend server . If an error occurred , return
an error 404 .
out(#arg{req=Req, headers=Hdrs, state=#proxy_cfg{url=URL}=State}=Arg) ->
case connect(URL) of
{ok, Sock, Type} ->
?Debug("Connection established on ~p: Socket=~p, Type=~p~n",
[URL, Sock, Type]),
RPState = #revproxy{srvsock = Sock,
type = Type,
state = sendheaders,
prefix = State#proxy_cfg.prefix,
url = URL,
r_meth = Req#http_request.method,
r_host = Hdrs#headers.host,
intercept_mod = State#proxy_cfg.intercept_mod},
out(Arg#arg{state=RPState});
_ERR ->
?Debug("Connection failed: ~p~n", [_ERR]),
out404(Arg)
end;
out(#arg{state=#revproxy{}=RPState}=Arg)
when RPState#revproxy.state == sendheaders ->
?Debug("Send request headers to backend server: ~n"
" - ~s~n", [?format_record(Arg#arg.req, http_request)]),
Req = rewrite_request(RPState, Arg#arg.req),
Hdrs0 = Arg#arg.headers,
Hdrs = rewrite_client_headers(RPState, Hdrs0),
{NewReq, NewHdrs} = case RPState#revproxy.intercept_mod of
undefined ->
{Req, Hdrs};
InterceptMod ->
case catch InterceptMod:rewrite_request(
Req, Hdrs) of
{ok, NewReq0, NewHdrs0} ->
{NewReq0, NewHdrs0};
InterceptError ->
error_logger:error_msg(
"revproxy intercept module ~p:"
"rewrite_request failed: ~p~n",
[InterceptMod, InterceptError]),
exit({error, intercept_mod})
end
end,
ReqStr = yaws_api:reformat_request(NewReq),
HdrsStr = yaws:headers_to_str(NewHdrs),
case send(RPState, [ReqStr, "\r\n", HdrsStr, "\r\n"]) of
ok ->
case yaws:to_lower(Hdrs#headers.transfer_encoding) of
"chunked" ->
?Debug("Request content is chunked~n", []),
out(Arg#arg{state=RPState#revproxy{state=sendchunk}});
_ ->
out(Arg#arg{state=RPState#revproxy{state=sendcontent}})
end;
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == sendcontent ->
case Arg#arg.clidata of
{partial, Bin} ->
?Debug("Send partial content to backend server: ~p bytes~n",
[size(Bin)]),
case send(RPState, Bin) of
ok ->
{get_more, undefined, RPState};
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
Bin when is_binary(Bin), Bin /= <<>> ->
?Debug("Send content to backend server: ~p bytes~n", [size(Bin)]),
case send(RPState, Bin) of
ok ->
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
_ ->
?Debug("no content found~n", []),
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1})
end;
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == sendchunk ->
case Arg#arg.clidata of
{partial, Bin} ->
?Debug("Send chunked content to backend server: ~p bytes~n",
[size(Bin)]),
Res = send(RPState,
[yaws:integer_to_hex(size(Bin)),"\r\n",Bin,"\r\n"]),
case Res of
ok ->
{get_more, undefined, RPState};
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
<<>> ->
?Debug("Send last chunk to backend server~n", []),
case send(RPState, "0\r\n\r\n") of
ok ->
RPState1 = RPState#revproxy{state=recvheaders},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end
end;
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvheaders ->
Res = yaws:http_get_headers(RPState#revproxy.srvsock,
RPState#revproxy.type),
case Res of
{error, {too_many_headers, _Resp}} ->
?Debug("Response headers too large from backend server~n", []),
close(RPState),
outXXX(500, Arg);
{Resp0, RespHdrs0} when is_record(Resp0, http_response) ->
?Debug("Response headers received from backend server:~n"
" - ~s~n - ~s~n", [?format_record(Resp0, http_response),
?format_record(RespHdrs0, headers)]),
{Resp, RespHdrs} =
case RPState#revproxy.intercept_mod of
undefined ->
{Resp0, RespHdrs0};
InterceptMod ->
case catch InterceptMod:rewrite_response(
Resp0, RespHdrs0) of
{ok, NewResp, NewRespHdrs} ->
{NewResp, NewRespHdrs};
InterceptError ->
error_logger:error_msg(
"revproxy intercept module ~p:"
"rewrite_response failure: ~p~n",
[InterceptMod, InterceptError]),
exit({error, intercept_mod})
end
end,
{CliConn, SrvConn} = get_connection_status(
(Arg#arg.req)#http_request.version,
Arg#arg.headers, RespHdrs
),
RPState1 = RPState#revproxy{cliconn_status = CliConn,
srvconn_status = SrvConn,
resp = Resp,
headers = RespHdrs},
if
RPState1#revproxy.r_meth =:= 'HEAD' ->
RPState2 = RPState1#revproxy{state=terminate},
out(Arg#arg{state=RPState2});
Resp#http_response.status =:= 100 orelse
Resp#http_response.status =:= 204 orelse
Resp#http_response.status =:= 205 orelse
Resp#http_response.status =:= 304 orelse
Resp#http_response.status =:= 406 ->
RPState2 = RPState1#revproxy{state=terminate},
out(Arg#arg{state=RPState2});
true ->
RPState2 =
case {yaws:to_lower(RespHdrs#headers.transfer_encoding),
RespHdrs#headers.content_length} of
{"chunked", _} ->
RPState1#revproxy{state=recvchunk};
{_, undefined} ->
RPState1#revproxy{
cliconn_status="close",
srvconn_status="close",
state=recvcontent};
_ ->
RPState1#revproxy{state=recvcontent}
end,
out(Arg#arg{state=RPState2})
end;
{_R, _H} ->
?Debug("Bad response received from backend server: ~p~n", [_R]),
close(RPState),
outXXX(500, Arg);
closed ->
?Debug("TCP error: ~p~n", [closed]),
outXXX(500, Arg)
end;
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvcontent ->
Len = case (RPState#revproxy.headers)#headers.content_length of
undefined -> undefined;
CLen -> list_to_integer(CLen)
end,
SC=get(sc),
if
is_integer(Len) andalso Len =< SC#sconf.partial_post_size ->
case read(RPState, Len) of
{ok, Data} ->
?Debug("Response content received from the backend server: "
"~p bytes~n", [size(Data)]),
RPState1 = RPState#revproxy{state = terminate,
is_chunked = false,
srvdata = {content, Data}},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
is_integer(Len) ->
Here partial_post_size is always an integer
BlockSize = SC#sconf.partial_post_size,
BlockCount = Len div BlockSize,
LastBlock = Len rem BlockSize,
SrvData = {block, BlockCount, BlockSize, LastBlock},
RPState1 = RPState#revproxy{state = terminate,
is_chunked = true,
srvdata = SrvData},
out(Arg#arg{state=RPState1});
true ->
SrvData = {block, undefined, undefined, undefined},
RPState1 = RPState#revproxy{state = terminate,
is_chunked = true,
srvdata = SrvData},
out(Arg#arg{state=RPState1})
end;
The response content is chunked . Read the first chunk here and spawn a
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == recvchunk ->
case read_chunk(RPState) of
{ok, Data} ->
?Debug("First chunk received from the backend server : "
"~p bytes~n", [size(Data)]),
RPState1 = RPState#revproxy{state = terminate,
is_chunked = (Data /= <<>>),
srvdata = {stream, Data}},
out(Arg#arg{state=RPState1});
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
case Reason of
closed -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg)
end;
out(#arg{state=RPState}=Arg) when RPState#revproxy.state == terminate ->
case RPState#revproxy.srvconn_status of
"close" when RPState#revproxy.is_chunked == false -> close(RPState);
"close" -> ok;
_ -> cache_connection(RPState)
end,
AllHdrs = [{header, H} || H <- yaws_api:reformat_header(
rewrite_server_headers(RPState)
)],
?Debug("~p~n", [AllHdrs]),
Res = [
{status, (RPState#revproxy.resp)#http_response.status},
{allheaders, AllHdrs}
],
case RPState#revproxy.srvdata of
{content, <<>>} ->
Res;
{content, Data} ->
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{content, MimeType, Data}];
{stream, <<>>} ->
Chunked response with only the last empty chunk : do not spawn a
yaws_api:stream_chunk_end(self()),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent, MimeType, <<>>}];
{stream, Chunk} ->
Self = self(),
GC = get(gc),
spawn(fun() -> put(gc, GC), recv_next_chunk(Self, Arg) end),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent, MimeType, Chunk}];
{block, BlockCnt, BlockSz, LastBlock} ->
GC = get(gc),
Pid = spawn(fun() ->
put(gc, GC),
receive
{ok, YawsPid} ->
recv_blocks(YawsPid, Arg, BlockCnt,
BlockSz, LastBlock);
{discard, YawsPid} ->
recv_blocks(YawsPid, Arg, 0, BlockSz, 0)
end
end),
MimeType = (RPState#revproxy.headers)#headers.content_type,
Res ++ [{streamcontent_from_pid, MimeType, Pid}];
_ ->
Res
end;
Catch unexpected state by sending an error 500
out(#arg{state=RPState}=Arg) ->
?Debug("Unexpected revproxy state:~n - ~s~n",
[?format_record(RPState, revproxy)]),
case RPState#revproxy.srvsock of
undefined -> ok;
_ -> close(RPState)
end,
outXXX(500, Arg).
out404(Arg) ->
SC=get(sc),
(SC#sconf.errormod_404):out404(Arg,get(gc),SC).
outXXX(Code, _Arg) ->
Content = ["<html><h1>", integer_to_list(Code), $\ ,
yaws_api:code_to_phrase(Code), "</h1></html>"],
[
{status, Code},
{header, {connection, "close"}},
{content, "text/html", Content}
].
recv_next_chunk(YawsPid, #arg{state=RPState}=Arg) ->
case read_chunk(RPState) of
{ok, <<>>} ->
?Debug("Last chunk received from the backend server~n", []),
yaws_api:stream_chunk_end(YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
end;
{ok, Data} ->
?Debug("Next chunk received from the backend server : "
"~p bytes~n", [size(Data)]),
yaws_api:stream_chunk_deliver(YawsPid, Data),
recv_next_chunk(YawsPid, Arg);
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_chunk_end(YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end.
recv_blocks(YawsPid, #arg{state=RPState}=Arg,
undefined, undefined, undefined) ->
case read(RPState) of
{ok, <<>>} ->
no data , wait 100 msec to avoid time - consuming loop and retry
timer:sleep(100),
recv_blocks(YawsPid, Arg, undefined, undefined, undefined);
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Arg#arg.clisock, Data),
recv_blocks(YawsPid, Arg, undefined, undefined, undefined);
{error, closed} ->
yaws_api:stream_process_end(closed, YawsPid);
{error, _Reason} ->
?Debug("TCP error: ~p~n", [_Reason]),
yaws_api:stream_process_end(closed, YawsPid),
close(RPState)
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, 0, _, 0) ->
yaws_api:stream_process_end(Arg#arg.clisock, YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, 0, _, LastBlock) ->
Sock = Arg#arg.clisock,
case read(RPState, LastBlock) of
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Sock, Data),
yaws_api:stream_process_end(Sock, YawsPid),
case RPState#revproxy.srvconn_status of
"close" -> close(RPState);
end;
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_process_end(closed, YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end;
recv_blocks(YawsPid, #arg{state=RPState}=Arg, BlockCnt, BlockSz, LastBlock) ->
case read(RPState, BlockSz) of
{ok, Data} ->
?Debug("Response content received from the backend server : "
"~p bytes~n", [size(Data)]),
ok = yaws_api:stream_process_deliver(Arg#arg.clisock, Data),
recv_blocks(YawsPid, Arg, BlockCnt-1, BlockSz, LastBlock);
{error, Reason} ->
?Debug("TCP error: ~p~n", [Reason]),
yaws_api:stream_process_end(closed, YawsPid),
case Reason of
closed -> ok;
_ -> close(RPState)
end
end.
have 1 connection per gserv process for each backend server .
get_cached_connection(URL) ->
Key = lists:flatten(yaws_api:reformat_url(URL)),
case erase(Key) of
undefined ->
undefined;
{Sock, nossl} ->
case gen_tcp:recv(Sock, 0, 1) of
{error, closed} ->
?Debug("Invalid cached connection~n", []),
undefined;
_ ->
?Debug("Found cached connection to ~s~n", [Key]),
{ok, Sock, nossl}
end;
{Sock, ssl} ->
case ssl:recv(Sock, 0, 1) of
{error, closed} ->
?Debug("Invalid cached connection~n", []),
undefined;
_ ->
?Debug("Found cached connection to ~s~n", [Key]),
{ok, Sock, ssl}
end
end.
cache_connection(RPState) ->
Key = lists:flatten(yaws_api:reformat_url(RPState#revproxy.url)),
?Debug("Cache connection to ~s~n", [Key]),
InitDB0 = get(init_db),
InitDB1 = lists:keystore(
Key, 1, InitDB0,
{Key, {RPState#revproxy.srvsock, RPState#revproxy.type}}
),
put(init_db, InitDB1),
ok.
connect(URL) ->
case get_cached_connection(URL) of
{ok, Sock, Type} -> {ok, Sock, Type};
undefined -> do_connect(URL)
end.
do_connect(URL) ->
Opts = [
binary,
{packet, raw},
{active, false},
{reuseaddr, true}
],
case URL#url.scheme of
http ->
Port = case URL#url.port of
undefined -> 80;
P -> P
end,
case yaws:tcp_connect(URL#url.host, Port, Opts) of
{ok, S} -> {ok, S, nossl};
Err -> Err
end;
https ->
Port = case URL#url.port of
undefined -> 443;
P -> P
end,
case yaws:ssl_connect(URL#url.host, Port, Opts) of
{ok, S} -> {ok, S, ssl};
Err -> Err
end;
_ ->
{error, unsupported_protocol}
end.
send(#revproxy{srvsock=Sock, type=ssl}, Data) ->
ssl:send(Sock, Data);
send(#revproxy{srvsock=Sock, type=nossl}, Data) ->
gen_tcp:send(Sock, Data).
read(#revproxy{srvsock=Sock, type=Type}) ->
yaws:setopts(Sock, [{packet, raw}, binary], Type),
yaws:do_recv(Sock, 0, Type).
read(RPState, Len) ->
yaws:setopts(RPState#revproxy.srvsock, [{packet, raw}, binary],
RPState#revproxy.type),
read(RPState, Len, []).
read(_, 0, Data) ->
{ok, iolist_to_binary(lists:reverse(Data))};
read(RPState = #revproxy{srvsock=Sock, type=Type}, Len, Data) ->
case yaws:do_recv(Sock, Len, Type) of
{ok, Bin} -> read(RPState, Len-size(Bin), [Bin|Data]);
{error, Reason} -> {error, Reason}
end.
read_chunk(#revproxy{srvsock=Sock, type=Type}) ->
try
yaws:setopts(Sock, [binary, {packet, line}], Type),
{Len, _Exts} = yaws:get_chunk_header(Sock, Type),
yaws:setopts(Sock, [binary, {packet, raw}], Type),
if
Len == 0 ->
yaws:get_chunk_trailer(Sock, Type),
{ok, <<>>};
true ->
B = yaws:get_chunk(Sock, Len, 0, Type),
ok = yaws:eat_crnl(Sock, Type),
{ok, iolist_to_binary(B)}
end
catch
_:Reason ->
{error, Reason}
end.
close(#revproxy{srvsock=Sock, type=ssl}) ->
ssl:close(Sock);
close(#revproxy{srvsock=Sock, type=nossl}) ->
gen_tcp:close(Sock).
get_connection_status(Version, ReqHdrs, RespHdrs) ->
CliConn = case Version of
{0,9} ->
"close";
{1, 0} ->
case ReqHdrs#headers.connection of
undefined -> "close";
C1 -> yaws:to_lower(C1)
end;
{1, 1} ->
case ReqHdrs#headers.connection of
undefined -> "keep-alive";
C1 -> yaws:to_lower(C1)
end
end,
?Debug("Client Connection header: ~p~n", [CliConn]),
SrvConn = case ?proxy_keepalive of
true ->
case RespHdrs#headers.connection of
undefined -> CliConn;
C2 -> yaws:to_lower(C2)
end;
false ->
"close"
end,
?Debug("Server Connection header: ~p~n", [SrvConn]),
{CliConn, SrvConn}.
rewrite_request(RPState, Req) ->
?Debug("Request path to rewrite: ~p~n", [Req#http_request.path]),
{abs_path, Path} = Req#http_request.path,
NewPath = strip_prefix(Path, RPState#revproxy.prefix),
?Debug("New Request path: ~p~n", [NewPath]),
Req#http_request{path = {abs_path, NewPath}}.
rewrite_client_headers(RPState, Hdrs) ->
?Debug("Host header to rewrite: ~p~n", [Hdrs#headers.host]),
Host = case Hdrs#headers.host of
undefined ->
undefined;
_ ->
ProxyUrl = RPState#revproxy.url,
[ProxyUrl#url.host,
case ProxyUrl#url.port of
undefined -> [];
P -> [$:|integer_to_list(P)]
end]
end,
?Debug("New Host header: ~p~n", [Host]),
Hdrs#headers{host = Host}.
rewrite_server_headers(RPState) ->
Hdrs = RPState#revproxy.headers,
?Debug("Location header to rewrite: ~p~n", [Hdrs#headers.location]),
Loc = case Hdrs#headers.location of
undefined ->
undefined;
L ->
?Debug("parse_url(~p)~n", [L]),
LocUrl = (catch yaws_api:parse_url(L)),
ProxyUrl = RPState#revproxy.url,
if
LocUrl#url.scheme == ProxyUrl#url.scheme andalso
LocUrl#url.host == ProxyUrl#url.host andalso
LocUrl#url.port == ProxyUrl#url.port ->
rewrite_loc_url(RPState, LocUrl);
element(1, L) == 'EXIT' ->
rewrite_loc_rel(RPState, L);
true ->
L
end
end,
?Debug("New Location header: ~p~n", [Loc]),
Hdrs#headers{location = Loc, connection = RPState#revproxy.cliconn_status}.
Rewrite a properly formatted location redir
rewrite_loc_url(RPState, LocUrl) ->
SC=get(sc),
Scheme = yaws:redirect_scheme(SC),
RedirHost = yaws:redirect_host(SC, RPState#revproxy.r_host),
[Scheme, RedirHost, slash_append(RPState#revproxy.prefix, LocUrl#url.path)].
rewrite_loc_rel(RPState, Loc) ->
SC=get(sc),
Scheme = yaws:redirect_scheme(SC),
RedirHost = yaws:redirect_host(SC, RPState#revproxy.r_host),
[Scheme, RedirHost, Loc].
strip_prefix("", "") ->
"/";
strip_prefix(P, "") ->
P;
strip_prefix(P, "/") ->
P;
strip_prefix([H|T1], [H|T2]) ->
strip_prefix(T1, T2).
slash_append("/", [$/|T]) ->
[$/|T];
slash_append("/", T) ->
[$/|T];
slash_append([], [$/|T]) ->
[$/|T];
slash_append([], T) ->
[$/|T];
slash_append([H|T], X) ->
[H | slash_append(T, X)].
|
27fa15047b04abd7b642234149573b0927ab2c0bab5ceaf47792cbf0aa30ecff | danielecapo/sfont | properties.rkt | #lang racket
(require racket/generic
"private/gui/draw-property.rkt")
(provide (all-defined-out)
(all-from-out "private/gui/draw-property.rkt"))
;;; property prop:has-matrix
;;; Used for objects that have transformation matrix (like components)
(define-values (prop:has-matrix has-matrix? has-matrix-ref)
(make-struct-type-property 'has-matrix))
Any - >
produce the TransformationMatrix of the object ( if the ( has - matrix ? o ) is true )
(define (get-matrix o)
(if (has-matrix? o)
((has-matrix-ref o) o)
(error "Object has no matrix")))
i d Object(T ) TransfromationMatrix - > Object(T )
; produce an object of type id with the new transformation matrix
(define-syntax-rule (set-matrix id o m)
(if (has-matrix? o)
(struct-copy id o [matrix m])
(error "Object has no matrix")))
;;; property prop:has-position
;;; Used for objects that have a position
(define-values (prop:has-position has-position? has-position-ref)
(make-struct-type-property 'has-position))
Any - >
produce the position Vec(tor ) of the object
(define (get-position o)
(if (has-position? o)
((has-position-ref o) o)
(error "Object has no position")))
i d Object(T ) Object(T )
; produce an object of type id with the new position
(define-syntax-rule (set-position id o m)
(if (has-position? o)
(struct-copy id o [pos m])
(error "Object has no position"))) | null | https://raw.githubusercontent.com/danielecapo/sfont/c854f9734f15f4c7cd4b98e041b8c961faa3eef2/sfont/properties.rkt | racket | property prop:has-matrix
Used for objects that have transformation matrix (like components)
produce an object of type id with the new transformation matrix
property prop:has-position
Used for objects that have a position
produce an object of type id with the new position | #lang racket
(require racket/generic
"private/gui/draw-property.rkt")
(provide (all-defined-out)
(all-from-out "private/gui/draw-property.rkt"))
(define-values (prop:has-matrix has-matrix? has-matrix-ref)
(make-struct-type-property 'has-matrix))
Any - >
produce the TransformationMatrix of the object ( if the ( has - matrix ? o ) is true )
(define (get-matrix o)
(if (has-matrix? o)
((has-matrix-ref o) o)
(error "Object has no matrix")))
i d Object(T ) TransfromationMatrix - > Object(T )
(define-syntax-rule (set-matrix id o m)
(if (has-matrix? o)
(struct-copy id o [matrix m])
(error "Object has no matrix")))
(define-values (prop:has-position has-position? has-position-ref)
(make-struct-type-property 'has-position))
Any - >
produce the position Vec(tor ) of the object
(define (get-position o)
(if (has-position? o)
((has-position-ref o) o)
(error "Object has no position")))
i d Object(T ) Object(T )
(define-syntax-rule (set-position id o m)
(if (has-position? o)
(struct-copy id o [pos m])
(error "Object has no position"))) |
be39e0681c48f5d6399b55cb581969c6f94458be7327cc5d9a2b73b060a0ee95 | sjl/newseasons | users.clj | (ns newseasons.models.users
(:use newseasons.settings)
(:use newseasons.models.keys)
(:use newseasons.utils)
(:use [newseasons.models.shows :only (show-get)])
(:require [noir.util.crypt :as crypt])
(:use [aleph.redis :only (redis-client)]))
(def r (redis-client {:host "localhost" :password redis-pass}))
; "Schema" --------------------------------------------------------------------
;
; Users are stored as Redis hashes, with their watched shows as a separate set.
;
; user:<email address> = {
; email: the email address for ease of use
; pass: the user's hashed password
; }
; user:<email address>:shows = #{show-id, ...}
;
; The show watching data is also denormalized based on show.
;
; shows:<id>:watchers - #{email, ...}
; Code ------------------------------------------------------------------------
(defn user-get [email]
(let [user (apply hash-map @(r [:hgetall (key-user email)]))]
(when (not (empty? user))
(merge {:email (user "email") :pass (user "pass")}
{:shows (sort-maps-by (map show-get
@(r [:smembers (key-user-shows email)]))
:title)}))))
(defn user-set-email! [email new-email]
@(r [:hset (key-user email) "email" new-email]))
(defn user-set-pass! [email new-pass]
@(r [:hset (key-user email) "pass" (crypt/encrypt new-pass)]))
(defn user-add-show! [email show-id]
@(r [:sadd (key-user-shows email) show-id])
@(r [:sadd (key-show-watchers show-id) email]))
(defn user-rem-show! [email show-id]
@(r [:srem (key-user-shows email) show-id])
@(r [:srem (key-show-watchers show-id) email]))
(defn user-delete! [email]
@(r [:del (key-user email)])
@(r [:del (key-user-shows email)])
(let [shows @(r [:smembers "shows:to-check"])]
(dorun (map (fn [show-id]
@(r [:srem (key-show-watchers show-id) email]))
shows))))
| null | https://raw.githubusercontent.com/sjl/newseasons/9f3bce450b413ee065abcf1b6b5b7dbdd8728481/src/newseasons/models/users.clj | clojure | "Schema" --------------------------------------------------------------------
Users are stored as Redis hashes, with their watched shows as a separate set.
user:<email address> = {
email: the email address for ease of use
pass: the user's hashed password
}
user:<email address>:shows = #{show-id, ...}
The show watching data is also denormalized based on show.
shows:<id>:watchers - #{email, ...}
Code ------------------------------------------------------------------------ | (ns newseasons.models.users
(:use newseasons.settings)
(:use newseasons.models.keys)
(:use newseasons.utils)
(:use [newseasons.models.shows :only (show-get)])
(:require [noir.util.crypt :as crypt])
(:use [aleph.redis :only (redis-client)]))
(def r (redis-client {:host "localhost" :password redis-pass}))
(defn user-get [email]
(let [user (apply hash-map @(r [:hgetall (key-user email)]))]
(when (not (empty? user))
(merge {:email (user "email") :pass (user "pass")}
{:shows (sort-maps-by (map show-get
@(r [:smembers (key-user-shows email)]))
:title)}))))
(defn user-set-email! [email new-email]
@(r [:hset (key-user email) "email" new-email]))
(defn user-set-pass! [email new-pass]
@(r [:hset (key-user email) "pass" (crypt/encrypt new-pass)]))
(defn user-add-show! [email show-id]
@(r [:sadd (key-user-shows email) show-id])
@(r [:sadd (key-show-watchers show-id) email]))
(defn user-rem-show! [email show-id]
@(r [:srem (key-user-shows email) show-id])
@(r [:srem (key-show-watchers show-id) email]))
(defn user-delete! [email]
@(r [:del (key-user email)])
@(r [:del (key-user-shows email)])
(let [shows @(r [:smembers "shows:to-check"])]
(dorun (map (fn [show-id]
@(r [:srem (key-show-watchers show-id) email]))
shows))))
|
9ae705119caab05a29ac6a9518b233b482c48a5f6c8024f7cd4766580bd76412 | input-output-hk/quickcheck-dynamic | CanGenerate.hs | module Test.QuickCheck.DynamicLogic.CanGenerate (canGenerate) where
import System.IO.Unsafe
import Test.QuickCheck
| prob g p@
-- returns @False@ if we are sure @Prob(g generates x satisfying p) >= prob@
otherwise @True@ ( and we know such an x can be generated ) .
canGenerate :: Double -> Gen a -> (a -> Bool) -> Bool
canGenerate prob g p = unsafePerformIO $ tryToGenerate 1
where
tryToGenerate luck
| luck < eps = return False
| otherwise = do
x <- generate g
if p x
then return True
else tryToGenerate (luck * (1 - prob))
Our confidence level is 1 - eps
eps = 1.0e-9
| null | https://raw.githubusercontent.com/input-output-hk/quickcheck-dynamic/aef136ede729a25762aecf95979951c07add817a/quickcheck-dynamic/src/Test/QuickCheck/DynamicLogic/CanGenerate.hs | haskell | returns @False@ if we are sure @Prob(g generates x satisfying p) >= prob@ | module Test.QuickCheck.DynamicLogic.CanGenerate (canGenerate) where
import System.IO.Unsafe
import Test.QuickCheck
| prob g p@
otherwise @True@ ( and we know such an x can be generated ) .
canGenerate :: Double -> Gen a -> (a -> Bool) -> Bool
canGenerate prob g p = unsafePerformIO $ tryToGenerate 1
where
tryToGenerate luck
| luck < eps = return False
| otherwise = do
x <- generate g
if p x
then return True
else tryToGenerate (luck * (1 - prob))
Our confidence level is 1 - eps
eps = 1.0e-9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.