_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
|
---|---|---|---|---|---|---|---|---|
c4c9c6207e2e7327064a6695cd7d815eb4f4c4f6137f486daf945371a3ea75b2 | tty/async_search | facet_sup.erl | %%%-------------------------------------------------------------------
@author < >
Copyright ( c ) 2011
%%% Permission is hereby granted, free of charge, to any person obtaining
%%% a copy of this software and associated documentation files (the
" Software " ) , to deal in the Software without restriction , including
%%% without limitation the rights to use, copy, modify, merge, publish,
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
%%% the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
%%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
%%% MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
%%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION
%%% OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
%%% WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
%%% @end
%%%-------------------------------------------------------------------
-module(facet_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the supervisor
%%
( ) - > { ok , Pid } | ignore | { error , Error }
%% @end
%%--------------------------------------------------------------------
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Whenever a supervisor is started using supervisor:start_link/[2,3],
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
%%
) - > { ok , { SupFlags , [ ChildSpec ] } } |
%% ignore |
%% {error, Reason}
%% @end
%%--------------------------------------------------------------------
init([]) ->
RestartStrategy = simple_one_for_one,
MaxRestarts = 0,
MaxSecondsBetweenRestarts = 1,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = temporary,
Shutdown = brutal_kill,
Type = worker,
FacetSer = {facet_ser, {facet_ser, start_link, []},
Restart, Shutdown, Type, [facet_ser]},
{ok, {SupFlags, [FacetSer]}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/tty/async_search/deaf29fc504c6d24acd5a11577628c54c4615558/src/facet_sup.erl | erlang | -------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@end
-------------------------------------------------------------------
API
Supervisor callbacks
===================================================================
API functions
===================================================================
--------------------------------------------------------------------
@doc
Starts the supervisor
@end
--------------------------------------------------------------------
===================================================================
Supervisor callbacks
===================================================================
--------------------------------------------------------------------
@doc
Whenever a supervisor is started using supervisor:start_link/[2,3],
this function is called by the new process to find out about
restart strategy, maximum restart frequency and child
specifications.
ignore |
{error, Reason}
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | @author < >
Copyright ( c ) 2011
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION
-module(facet_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SERVER, ?MODULE).
( ) - > { ok , Pid } | ignore | { error , Error }
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
@private
) - > { ok , { SupFlags , [ ChildSpec ] } } |
init([]) ->
RestartStrategy = simple_one_for_one,
MaxRestarts = 0,
MaxSecondsBetweenRestarts = 1,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = temporary,
Shutdown = brutal_kill,
Type = worker,
FacetSer = {facet_ser, {facet_ser, start_link, []},
Restart, Shutdown, Type, [facet_ser]},
{ok, {SupFlags, [FacetSer]}}.
Internal functions
|
6a1391135adff250cd0545228e0f2b0872db469c7c3303680aa00d735d4b1061 | cemerick/austin | repls.clj | (ns cemerick.austin.repls
(:require [cemerick.austin :refer (exec-env)]
[clojure.tools.nrepl.middleware.interruptible-eval :as nrepl-eval]
[cemerick.piggieback :as pb]
cljs.repl))
(def browser-repl-env
"An atom into which you can `reset!` the Austin REPL environment to which you
want your browser-connected REPLs to connect. (This is strictly a convenience,
you can easily achieve the same thing by other means without touching this
atom.) A typical usage pattern might be:
In your nREPL (or other REPL implementation) session:
(def repl-env (reset! cemerick.austin.repls/browser-repl-env
(cemerick.austin/repl-env)))
(cemerick.austin.repls/cljs-repl repl-env)
And, somewhere in your webapp (demonstrating using hiccup markup, but whatever
you use to generate HTML will work):
[:html
; ... etc ...
[:body [:script (cemerick.austin.repls/browser-connected-repl-js)]]]
`browser-connected-repl-js` uses the REPL environment in this atom to construct
a JavaScript string that will connect the browser runtime to that REPL environment
on load.
When you want your app to connect to a different REPL environment, just
`reset!` `cemerick.austin.repls/browser-repl-env` again."
(atom nil))
(defn browser-connected-repl-js
"Uses the REPL environment in `browser-repl-env` to construct
a JavaScript string that will connect the browser runtime to that REPL environment
on load. See `browser-repl-env` docs for more."
[]
(when-let [repl-url (:repl-url @browser-repl-env)]
(format ";goog.require('clojure.browser.repl');clojure.browser.repl.connect.call(null, '%s');"
repl-url)))
(defn cljs-repl
"Same as `cljs.repl/repl`, except will use the appropriate REPL entry point
(Piggieback's `cljs-repl` or `cljs.repl/repl`) based on the the current
environment (i.e. whether nREPL is being used or not, respectively)."
[repl-env & options]
(if (thread-bound? #'nrepl-eval/*msg*)
(apply pb/cljs-repl :repl-env repl-env options)
(apply cljs.repl/repl repl-env options)))
(defn exec
"Starts a ClojureScript REPL using Austin's `exec-env` REPL environment
using `cljs-repl` in this namespace (and so can be used whether you're using
nREPL or not). All arguments are passed on to `exec-env` without
modification."
[& exec-env-args]
(cljs-repl (apply exec-env exec-env-args)))
| null | https://raw.githubusercontent.com/cemerick/austin/424bca352286bed3f3324177651ca2b914851407/src/clj/cemerick/austin/repls.clj | clojure | ... etc ... | (ns cemerick.austin.repls
(:require [cemerick.austin :refer (exec-env)]
[clojure.tools.nrepl.middleware.interruptible-eval :as nrepl-eval]
[cemerick.piggieback :as pb]
cljs.repl))
(def browser-repl-env
"An atom into which you can `reset!` the Austin REPL environment to which you
want your browser-connected REPLs to connect. (This is strictly a convenience,
you can easily achieve the same thing by other means without touching this
atom.) A typical usage pattern might be:
In your nREPL (or other REPL implementation) session:
(def repl-env (reset! cemerick.austin.repls/browser-repl-env
(cemerick.austin/repl-env)))
(cemerick.austin.repls/cljs-repl repl-env)
And, somewhere in your webapp (demonstrating using hiccup markup, but whatever
you use to generate HTML will work):
[:html
[:body [:script (cemerick.austin.repls/browser-connected-repl-js)]]]
`browser-connected-repl-js` uses the REPL environment in this atom to construct
a JavaScript string that will connect the browser runtime to that REPL environment
on load.
When you want your app to connect to a different REPL environment, just
`reset!` `cemerick.austin.repls/browser-repl-env` again."
(atom nil))
(defn browser-connected-repl-js
"Uses the REPL environment in `browser-repl-env` to construct
a JavaScript string that will connect the browser runtime to that REPL environment
on load. See `browser-repl-env` docs for more."
[]
(when-let [repl-url (:repl-url @browser-repl-env)]
(format ";goog.require('clojure.browser.repl');clojure.browser.repl.connect.call(null, '%s');"
repl-url)))
(defn cljs-repl
"Same as `cljs.repl/repl`, except will use the appropriate REPL entry point
(Piggieback's `cljs-repl` or `cljs.repl/repl`) based on the the current
environment (i.e. whether nREPL is being used or not, respectively)."
[repl-env & options]
(if (thread-bound? #'nrepl-eval/*msg*)
(apply pb/cljs-repl :repl-env repl-env options)
(apply cljs.repl/repl repl-env options)))
(defn exec
"Starts a ClojureScript REPL using Austin's `exec-env` REPL environment
using `cljs-repl` in this namespace (and so can be used whether you're using
nREPL or not). All arguments are passed on to `exec-env` without
modification."
[& exec-env-args]
(cljs-repl (apply exec-env exec-env-args)))
|
396cf7110b0a3ff1cd2e1fee22aa2b3b95bf94cf0753571a67bf35aea87ee0ed | gpetiot/Frama-C-StaDy | infer.mli | Computes and returns a hashtable such that :
- var1 = > inferred size for var1
- var2 = > inferred size for var2
- ...
- var n = > inferred size for varn
- var1 => inferred size for var1
- var2 => inferred size for var2
- ...
- var n => inferred size for varn *)
val lengths_from_requires :
Kernel_function.t -> Cil_types.term list Cil_datatype.Varinfo.Hashtbl.t
| null | https://raw.githubusercontent.com/gpetiot/Frama-C-StaDy/48d8677c0c145d730d7f94e37b7b3e3a80fd1a27/infer.mli | ocaml | Computes and returns a hashtable such that :
- var1 = > inferred size for var1
- var2 = > inferred size for var2
- ...
- var n = > inferred size for varn
- var1 => inferred size for var1
- var2 => inferred size for var2
- ...
- var n => inferred size for varn *)
val lengths_from_requires :
Kernel_function.t -> Cil_types.term list Cil_datatype.Varinfo.Hashtbl.t
|
|
c224ee18f666346f91a15d2735a9591c1314b67cd905d2db9a34f6b525801e9a | dgiot/dgiot | dgiot_meter.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc dgiot_meter Protocol
-module(dgiot_meter).
-include("dgiot_meter.hrl").
-include_lib("dgiot/include/logger.hrl").
-export([parse_frame/3, to_frame/1]).
-export([search_meter/1, search_meter/4, get_ValueData/2]).
-export([
create_dtu/3,
create_dtu/4,
create_meter/5,
create_meter4G/3,
create_meter4G/6,
get_sub_device/1,
send_task/4,
send_mqtt/4
]).
-define(APP, ?MODULE).
%%新设备
create_dtu(mqtt, DtuAddr, ProductId, DTUIP) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"ACL">> := Acl}} ->
Requests = #{
<<"devaddr">> => DtuAddr,
<<"name">> => <<"DTU_", DtuAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => Acl,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"DTU", DtuAddr/binary>>,
<<"devModel">> => <<"DTU_">>
},
dgiot_device:create_device(Requests);
_ ->
pass
end.
create_dtu(DtuAddr, ChannelId, DTUIP) ->
case dgiot_data:get({dtu, ChannelId}) of
{ProductId, Acl, _Properties} ->
Requests = #{
<<"devaddr">> => DtuAddr,
<<"name">> => <<"DTU_", DtuAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => Acl,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"DTU", DtuAddr/binary>>,
<<"devModel">> => <<"DTU_">>
},
dgiot_device:create_device(Requests);
_ ->
pass
end.
create_meter(MeterAddr, ChannelId, DTUIP, DtuId, DtuAddr) ->
case dgiot_data:get({meter, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => MeterAddr,
<<"name">> => <<"Meter_", MeterAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"route">> => #{DtuAddr => MeterAddr},
<<"parentId">> => #{
<<"className">> => <<"Device">>,
<<"objectId">> => DtuId,
<<"__type">> => <<"Pointer">>
},
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Meter", MeterAddr/binary>>,
<<"devModel">> => <<"Meter">>
},
dgiot_device:create_device(Requests),
Topic = <<"$dg/device/", ProductId/binary, "/", MeterAddr/binary, "/profile">>,
dgiot_mqtt:subscribe(Topic),
{DtuProductId, _, _} = dgiot_data:get({dtu, ChannelId}),
dgiot_task:save_pnque(DtuProductId, DtuAddr, ProductId, MeterAddr);
_ ->
pass
end.
create_meter4G(MeterAddr, MDa, ChannelId, DTUIP, DtuId, DtuAddr) ->
case dgiot_data:get({meter, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => MeterAddr,
<<"name">> => <<"Meter_", MDa/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"route">> => #{DtuAddr => MDa},
<<"parentId">> => #{
<<"className">> => <<"Device">>,
<<"objectId">> => DtuId,
<<"__type">> => <<"Pointer">>
},
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Meter_", MDa/binary>>,
<<"devModel">> => <<"Meter">>
},
dgiot_device:create_device(Requests),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, MeterAddr),
dgiot_data:insert({metertda, DeviceId}, {dgiot_utils:to_binary(MDa), DtuAddr}),
Topic = <<"$dg/device/", ProductId/binary, "/", MeterAddr/binary, "/properties/report">>,
dgiot_mqtt:subscribe(Topic),
{DtuProductId, _, _} = dgiot_data:get({dtu, ChannelId}),
dgiot_task:save_pnque(DtuProductId, DtuAddr, ProductId, MeterAddr);
_ ->
pass
end.
create_meter4G(DevAddr, ChannelId, DTUIP) ->
case dgiot_data:get({dtu, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => DevAddr,
<<"name">> => <<"Concentrator_", DevAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Concentrator", DevAddr/binary>>,
<<"devModel">> => <<"Concentrator">>
},
dgiot_device:create_device(Requests),
dgiot_task:save_pnque(ProductId, DevAddr, ProductId, DevAddr);
_ ->
pass
end.
get_sub_device(DtuAddr) ->
Query = #{<<"keys">> => [<<"devaddr">>, <<"product">>, <<"route">>],
<<"where">> => #{<<"route.", DtuAddr/binary>> => #{<<"$regex">> => <<".+">>}},
<<"order">> => <<"devaddr">>, <<"limit">> => 256},
case dgiot_parse:query_object(<<"Device">>, Query) of
{ok, #{<<"results">> := []}} -> [];
{ok, #{<<"results">> := List}} -> List;
_ -> []
end.
parse_frame(?DLT645, Buff, Opts) ->
{Rest, Frames} = dlt645_decoder:parse_frame(Buff, Opts),
{Rest, lists:foldl(fun(X, Acc) ->
Acc ++ [maps:without([<<"diff">>, <<"send_di">>], X)]
end, [], Frames)};
parse_frame(?DLT376, Buff, Opts) ->
{Rest, Frames} = dlt376_decoder:parse_frame(Buff, Opts),
{Rest, lists:foldl(fun(X, Acc) ->
Acc ++ [maps:without([<<"diff">>, <<"send_di">>], X)]
end, [], Frames)}.
% DLT376发送抄数指令
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT376,
<<"dataSource">> := #{
<<"afn">> := Afn,
<<"da">> := Da,
<<"dt">> := Dt
}
} = Frame) ->
<<Afn2:8>> = dgiot_utils:hex_to_binary(Afn),
dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(Addr)),
<<"data">> => <<>>,
<<"da">> => Da,
<<"dt">> => Dt,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => Afn2
});
% DLT645 组装电表抄表指令
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT645,
<<"dataSource">> := #{
<<"di">> := Di
}
} = Frame) ->
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
});
% DLT645 组装电表控制指令
to_frame(#{
<<"devaddr">> := Addr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"devpass">> := DevPass,
<<"apiname">> := get_meter_ctrl
} = Frame) ->
case CtrlFlag of
true ->
PassGrade = <<"02">>,
Di = <<(dgiot_utils:hex_to_binary(DevPass))/binary, (dgiot_utils:hex_to_binary(PassGrade))/binary>>,
Data = <<"111111111C00010101010133">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(Di),
<<"data">> => dgiot_utils:hex_to_binary(Data),
<<"command">> => ?DLT645_MS_FORCE_EVENT
});
false ->
PassGrade = <<"02">>,
Di = <<(dgiot_utils:hex_to_binary(DevPass))/binary, (dgiot_utils:hex_to_binary(PassGrade))/binary>>,
Data = <<"111111111A00010101010133">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"data">> => dgiot_utils:hex_to_binary(Data),
<<"di">> => dlt645_proctol:reverse(Di),
<<"command">> => ?DLT645_MS_FORCE_EVENT
})
end;
% DLT376 远程电表控制(透明转发)
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"devpass">> := DevPass,
<<"protocol">> := ?DLT376,
<<"apiname">> := get_meter_ctrl
} = Frame) ->
Di = <<"00000100">>,
Data = <<16#02, 16#6B, 16#64, 16#64, 16#1C, 16#00>>,
Data2 = <<16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00>>,
CtrlPayload = to_frame(Frame#{
<<"protocol">> => ?DLT645,
<<"devaddr">> => DevAddr,
<<"ctrlflag">> => CtrlFlag,
<<"devpass">> => DevPass,
<<"apiname">> => get_meter_ctrl
}),
DataNew = <<Data/binary, CtrlPayload/binary, Data2/binary>>,
? LOG(info , " 230 to_frame , DataNew ~p ~ n ~ n ~ n",[dgiot_utils : binary_to_hex(DataNew ) ] ) ,
RetPlayload = dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(DevAddr)),
<<"data">> => dgiot_utils:binary_to_hex(DataNew),
<<"di">> => Di,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => ?DLT376_MS_CONVERT_SEND_AFN
}),
? LOG(info , " 231 to_frame , ~p ~ n ~ n ~ n",[dgiot_utils : binary_to_hex(RetPlayload ) ] ) ,
RetPlayload;
DLT645 组装电表获取上次拉闸合闸的时间
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"apiname">> := get_meter_ctrl_status
} = Frame) ->
case CtrlFlag of
true ->
Di = <<"1E000101">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(DevAddr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
});
false ->
Di = <<"1D000101">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(DevAddr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
})
end;
% DLT376 组装电表获取上次拉闸合闸的时间(透明转发)
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT376,
<<"apiname">> := get_meter_ctrl_status
} = Frame) ->
Di = <<"00000100">>,
Data = <<16#02, 16#6B, 16#64, 16#64, 16#10, 16#00>>,
Data2 = <<16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00>>,
CtrlPayload = to_frame(Frame#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"apiname">> := get_meter_ctrl_status
}),
DataNew = <<Data/binary, CtrlPayload/binary, Data2/binary>>,
? LOG(info , " 260 to_frame , DataNew ~p,~n ~ n ~ n",[dgiot_utils : binary_to_hex(CtrlPayload ) ] ) ,
RetPlayload = dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(DevAddr)),
<<"data">> => dgiot_utils:binary_to_hex(DataNew),
<<"di">> => Di,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => ?DLT376_MS_CONVERT_SEND_AFN
}),
RetPlayload;
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT645,
<<"dataSource">> := #{
<<"di">> := Di
}
} = Frame) ->
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"command">> => ?DLT645_MS_READ_DATA
});
to_frame(Frame) ->
io:format("~s ~p Error Frame = ~p.~n", [?FILE, ?LINE, Frame]).
search_meter(tcp, _Ref, TCPState, 0) ->
Payload = dlt645_decoder:to_frame(#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(<<16#AA, 16#AA, 16#AA, 16#AA, 16#AA, 16#AA>>),
<<"command">> => ?DLT645_MS_READ_DATA,
组合有功
}),
? LOG(info , " Payload ~p " , [ dgiot_utils : binary_to_hex(Payload ) ] ) ,
dgiot_tcp_server:send(TCPState, Payload),
read_meter;
search_meter(tcp, Ref, TCPState, 1) ->
case Ref of
undefined ->
pass;
_ ->
erlang:cancel_timer(Ref)
end,
case search_meter(1) of
<<"finish">> ->
{undefined, read_meter, <<>>};
<<"skip">> ->
{erlang:send_after(1500, self(), search_meter), search_meter, <<>>};
Payload ->
dgiot_tcp_server:send(TCPState, Payload),
{erlang:send_after(1500, self(), search_meter), search_meter, Payload}
end.
search_meter(1) ->
Flag =
case get({search_meter, self()}) of
undefined ->
put({search_meter, self()}, 254),
255;
16#AA ->
put({search_meter, self()}, 16#A9),
<<"skip">>;
Len when Len < 0 ->
<<"finish">>;
Len ->
put({search_meter, self()}, Len - 1),
Len
end,
case Flag of
<<"finish">> ->
<<"finish">>;
<<"skip">> ->
<<"skip">>;
_ ->
dlt645_decoder:to_frame(#{
<<"msgtype">> => ?DLT645,
<<"addr">> => <<Flag:8, 16#AA, 16#AA, 16#AA, 16#AA, 16#AA>>,
<<"command">> => ?DLT645_MS_READ_DATA,
组合有功
end;
search_meter(_) ->
<<"finish">>.
di
get_ValueData(Value, ProductId) ->
maps:fold(fun(K, V, Acc) ->
case dgiot_data:get({protocol, K, ProductId}) of
not_find ->
Acc#{K => V};
Identifier ->
Acc#{Identifier => V}
end
end, #{}, Value).
send_task(ProductId, DevAddr, DtuId, Value) ->
发送给task进行数据存储
Taskchannel = dgiot_product_channel:get_taskchannel(ProductId),
dgiot_client:send(Taskchannel, DtuId, Topic, Value),
Topic.
send_mqtt(ProductId, DevAddr, Di, Value) ->
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
Topic = <<"thing/", ProductId/binary, "/", DevAddr/binary, "/status">>,
DValue = #{dgiot_utils:to_hex(Di) => Value},
dgiot_mqtt:publish(DeviceId, Topic, jsx:encode(DValue)),
Topic.
| null | https://raw.githubusercontent.com/dgiot/dgiot/e25a9682fb10c1e686b0a81ea9a2db330ce5143d/apps/dgiot_meter/src/dgiot_meter.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
@doc dgiot_meter Protocol
新设备
DLT376发送抄数指令
DLT645 组装电表抄表指令
DLT645 组装电表控制指令
DLT376 远程电表控制(透明转发)
DLT376 组装电表获取上次拉闸合闸的时间(透明转发) | Copyright ( c ) 2020 DGIOT Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(dgiot_meter).
-include("dgiot_meter.hrl").
-include_lib("dgiot/include/logger.hrl").
-export([parse_frame/3, to_frame/1]).
-export([search_meter/1, search_meter/4, get_ValueData/2]).
-export([
create_dtu/3,
create_dtu/4,
create_meter/5,
create_meter4G/3,
create_meter4G/6,
get_sub_device/1,
send_task/4,
send_mqtt/4
]).
-define(APP, ?MODULE).
create_dtu(mqtt, DtuAddr, ProductId, DTUIP) ->
case dgiot_product:lookup_prod(ProductId) of
{ok, #{<<"ACL">> := Acl}} ->
Requests = #{
<<"devaddr">> => DtuAddr,
<<"name">> => <<"DTU_", DtuAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => Acl,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"DTU", DtuAddr/binary>>,
<<"devModel">> => <<"DTU_">>
},
dgiot_device:create_device(Requests);
_ ->
pass
end.
create_dtu(DtuAddr, ChannelId, DTUIP) ->
case dgiot_data:get({dtu, ChannelId}) of
{ProductId, Acl, _Properties} ->
Requests = #{
<<"devaddr">> => DtuAddr,
<<"name">> => <<"DTU_", DtuAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => Acl,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"DTU", DtuAddr/binary>>,
<<"devModel">> => <<"DTU_">>
},
dgiot_device:create_device(Requests);
_ ->
pass
end.
create_meter(MeterAddr, ChannelId, DTUIP, DtuId, DtuAddr) ->
case dgiot_data:get({meter, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => MeterAddr,
<<"name">> => <<"Meter_", MeterAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"route">> => #{DtuAddr => MeterAddr},
<<"parentId">> => #{
<<"className">> => <<"Device">>,
<<"objectId">> => DtuId,
<<"__type">> => <<"Pointer">>
},
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Meter", MeterAddr/binary>>,
<<"devModel">> => <<"Meter">>
},
dgiot_device:create_device(Requests),
Topic = <<"$dg/device/", ProductId/binary, "/", MeterAddr/binary, "/profile">>,
dgiot_mqtt:subscribe(Topic),
{DtuProductId, _, _} = dgiot_data:get({dtu, ChannelId}),
dgiot_task:save_pnque(DtuProductId, DtuAddr, ProductId, MeterAddr);
_ ->
pass
end.
create_meter4G(MeterAddr, MDa, ChannelId, DTUIP, DtuId, DtuAddr) ->
case dgiot_data:get({meter, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => MeterAddr,
<<"name">> => <<"Meter_", MDa/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"route">> => #{DtuAddr => MDa},
<<"parentId">> => #{
<<"className">> => <<"Device">>,
<<"objectId">> => DtuId,
<<"__type">> => <<"Pointer">>
},
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Meter_", MDa/binary>>,
<<"devModel">> => <<"Meter">>
},
dgiot_device:create_device(Requests),
DeviceId = dgiot_parse_id:get_deviceid(ProductId, MeterAddr),
dgiot_data:insert({metertda, DeviceId}, {dgiot_utils:to_binary(MDa), DtuAddr}),
Topic = <<"$dg/device/", ProductId/binary, "/", MeterAddr/binary, "/properties/report">>,
dgiot_mqtt:subscribe(Topic),
{DtuProductId, _, _} = dgiot_data:get({dtu, ChannelId}),
dgiot_task:save_pnque(DtuProductId, DtuAddr, ProductId, MeterAddr);
_ ->
pass
end.
create_meter4G(DevAddr, ChannelId, DTUIP) ->
case dgiot_data:get({dtu, ChannelId}) of
{ProductId, ACL, _Properties} ->
Requests = #{
<<"devaddr">> => DevAddr,
<<"name">> => <<"Concentrator_", DevAddr/binary>>,
<<"ip">> => DTUIP,
<<"isEnable">> => true,
<<"product">> => ProductId,
<<"ACL">> => ACL,
<<"status">> => <<"ONLINE">>,
<<"brand">> => <<"Concentrator", DevAddr/binary>>,
<<"devModel">> => <<"Concentrator">>
},
dgiot_device:create_device(Requests),
dgiot_task:save_pnque(ProductId, DevAddr, ProductId, DevAddr);
_ ->
pass
end.
get_sub_device(DtuAddr) ->
Query = #{<<"keys">> => [<<"devaddr">>, <<"product">>, <<"route">>],
<<"where">> => #{<<"route.", DtuAddr/binary>> => #{<<"$regex">> => <<".+">>}},
<<"order">> => <<"devaddr">>, <<"limit">> => 256},
case dgiot_parse:query_object(<<"Device">>, Query) of
{ok, #{<<"results">> := []}} -> [];
{ok, #{<<"results">> := List}} -> List;
_ -> []
end.
parse_frame(?DLT645, Buff, Opts) ->
{Rest, Frames} = dlt645_decoder:parse_frame(Buff, Opts),
{Rest, lists:foldl(fun(X, Acc) ->
Acc ++ [maps:without([<<"diff">>, <<"send_di">>], X)]
end, [], Frames)};
parse_frame(?DLT376, Buff, Opts) ->
{Rest, Frames} = dlt376_decoder:parse_frame(Buff, Opts),
{Rest, lists:foldl(fun(X, Acc) ->
Acc ++ [maps:without([<<"diff">>, <<"send_di">>], X)]
end, [], Frames)}.
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT376,
<<"dataSource">> := #{
<<"afn">> := Afn,
<<"da">> := Da,
<<"dt">> := Dt
}
} = Frame) ->
<<Afn2:8>> = dgiot_utils:hex_to_binary(Afn),
dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(Addr)),
<<"data">> => <<>>,
<<"da">> => Da,
<<"dt">> => Dt,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => Afn2
});
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT645,
<<"dataSource">> := #{
<<"di">> := Di
}
} = Frame) ->
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
});
to_frame(#{
<<"devaddr">> := Addr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"devpass">> := DevPass,
<<"apiname">> := get_meter_ctrl
} = Frame) ->
case CtrlFlag of
true ->
PassGrade = <<"02">>,
Di = <<(dgiot_utils:hex_to_binary(DevPass))/binary, (dgiot_utils:hex_to_binary(PassGrade))/binary>>,
Data = <<"111111111C00010101010133">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(Di),
<<"data">> => dgiot_utils:hex_to_binary(Data),
<<"command">> => ?DLT645_MS_FORCE_EVENT
});
false ->
PassGrade = <<"02">>,
Di = <<(dgiot_utils:hex_to_binary(DevPass))/binary, (dgiot_utils:hex_to_binary(PassGrade))/binary>>,
Data = <<"111111111A00010101010133">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"data">> => dgiot_utils:hex_to_binary(Data),
<<"di">> => dlt645_proctol:reverse(Di),
<<"command">> => ?DLT645_MS_FORCE_EVENT
})
end;
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"devpass">> := DevPass,
<<"protocol">> := ?DLT376,
<<"apiname">> := get_meter_ctrl
} = Frame) ->
Di = <<"00000100">>,
Data = <<16#02, 16#6B, 16#64, 16#64, 16#1C, 16#00>>,
Data2 = <<16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00>>,
CtrlPayload = to_frame(Frame#{
<<"protocol">> => ?DLT645,
<<"devaddr">> => DevAddr,
<<"ctrlflag">> => CtrlFlag,
<<"devpass">> => DevPass,
<<"apiname">> => get_meter_ctrl
}),
DataNew = <<Data/binary, CtrlPayload/binary, Data2/binary>>,
? LOG(info , " 230 to_frame , DataNew ~p ~ n ~ n ~ n",[dgiot_utils : binary_to_hex(DataNew ) ] ) ,
RetPlayload = dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(DevAddr)),
<<"data">> => dgiot_utils:binary_to_hex(DataNew),
<<"di">> => Di,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => ?DLT376_MS_CONVERT_SEND_AFN
}),
? LOG(info , " 231 to_frame , ~p ~ n ~ n ~ n",[dgiot_utils : binary_to_hex(RetPlayload ) ] ) ,
RetPlayload;
DLT645 组装电表获取上次拉闸合闸的时间
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"apiname">> := get_meter_ctrl_status
} = Frame) ->
case CtrlFlag of
true ->
Di = <<"1E000101">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(DevAddr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
});
false ->
Di = <<"1D000101">>,
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(DevAddr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"data">> => <<>>,
<<"command">> => ?DLT645_MS_READ_DATA
})
end;
to_frame(#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT376,
<<"apiname">> := get_meter_ctrl_status
} = Frame) ->
Di = <<"00000100">>,
Data = <<16#02, 16#6B, 16#64, 16#64, 16#10, 16#00>>,
Data2 = <<16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00, 16#00>>,
CtrlPayload = to_frame(Frame#{
<<"devaddr">> := DevAddr,
<<"ctrlflag">> := CtrlFlag,
<<"protocol">> := ?DLT645,
<<"apiname">> := get_meter_ctrl_status
}),
DataNew = <<Data/binary, CtrlPayload/binary, Data2/binary>>,
? LOG(info , " 260 to_frame , DataNew ~p,~n ~ n ~ n",[dgiot_utils : binary_to_hex(CtrlPayload ) ] ) ,
RetPlayload = dlt376_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT376,
<<"addr">> => dlt376_proctol:decode_of_addr(dgiot_utils:hex_to_binary(DevAddr)),
<<"data">> => dgiot_utils:binary_to_hex(DataNew),
<<"di">> => Di,
<<"command">> => ?DLT376_MS_READ_DATA,
<<"afn">> => ?DLT376_MS_CONVERT_SEND_AFN
}),
RetPlayload;
to_frame(#{
<<"devaddr">> := Addr,
<<"protocol">> := ?DLT645,
<<"dataSource">> := #{
<<"di">> := Di
}
} = Frame) ->
dlt645_decoder:to_frame(Frame#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Addr)),
<<"di">> => dlt645_proctol:reverse(dgiot_utils:hex_to_binary(Di)),
<<"command">> => ?DLT645_MS_READ_DATA
});
to_frame(Frame) ->
io:format("~s ~p Error Frame = ~p.~n", [?FILE, ?LINE, Frame]).
search_meter(tcp, _Ref, TCPState, 0) ->
Payload = dlt645_decoder:to_frame(#{
<<"msgtype">> => ?DLT645,
<<"addr">> => dlt645_proctol:reverse(<<16#AA, 16#AA, 16#AA, 16#AA, 16#AA, 16#AA>>),
<<"command">> => ?DLT645_MS_READ_DATA,
组合有功
}),
? LOG(info , " Payload ~p " , [ dgiot_utils : binary_to_hex(Payload ) ] ) ,
dgiot_tcp_server:send(TCPState, Payload),
read_meter;
search_meter(tcp, Ref, TCPState, 1) ->
case Ref of
undefined ->
pass;
_ ->
erlang:cancel_timer(Ref)
end,
case search_meter(1) of
<<"finish">> ->
{undefined, read_meter, <<>>};
<<"skip">> ->
{erlang:send_after(1500, self(), search_meter), search_meter, <<>>};
Payload ->
dgiot_tcp_server:send(TCPState, Payload),
{erlang:send_after(1500, self(), search_meter), search_meter, Payload}
end.
search_meter(1) ->
Flag =
case get({search_meter, self()}) of
undefined ->
put({search_meter, self()}, 254),
255;
16#AA ->
put({search_meter, self()}, 16#A9),
<<"skip">>;
Len when Len < 0 ->
<<"finish">>;
Len ->
put({search_meter, self()}, Len - 1),
Len
end,
case Flag of
<<"finish">> ->
<<"finish">>;
<<"skip">> ->
<<"skip">>;
_ ->
dlt645_decoder:to_frame(#{
<<"msgtype">> => ?DLT645,
<<"addr">> => <<Flag:8, 16#AA, 16#AA, 16#AA, 16#AA, 16#AA>>,
<<"command">> => ?DLT645_MS_READ_DATA,
组合有功
end;
search_meter(_) ->
<<"finish">>.
di
get_ValueData(Value, ProductId) ->
maps:fold(fun(K, V, Acc) ->
case dgiot_data:get({protocol, K, ProductId}) of
not_find ->
Acc#{K => V};
Identifier ->
Acc#{Identifier => V}
end
end, #{}, Value).
send_task(ProductId, DevAddr, DtuId, Value) ->
发送给task进行数据存储
Taskchannel = dgiot_product_channel:get_taskchannel(ProductId),
dgiot_client:send(Taskchannel, DtuId, Topic, Value),
Topic.
send_mqtt(ProductId, DevAddr, Di, Value) ->
DeviceId = dgiot_parse_id:get_deviceid(ProductId, DevAddr),
Topic = <<"thing/", ProductId/binary, "/", DevAddr/binary, "/status">>,
DValue = #{dgiot_utils:to_hex(Di) => Value},
dgiot_mqtt:publish(DeviceId, Topic, jsx:encode(DValue)),
Topic.
|
08b8e2693a8daa0f15d2f73d36bf6e8e8bf1d3673dec15f0ad1676eae10659e5 | eutro/mc-clojure-lib | fabric_core.clj | (in-ns 'eutros.clojurelib.lib.core)
(import net.fabricmc.loader.api.FabricLoader
net.fabricmc.loader.api.MappingResolver
net.fabricmc.api.EnvType
java.util.regex.Matcher
java.util.regex.Pattern)
(def IS_FORGE false)
(def IS_FABRIC true)
(def IS_CLIENT (identical? (.getEnvironmentType (FabricLoader/getInstance))
EnvType/CLIENT))
(def MAPPINGS (if (.isDevelopmentEnvironment (FabricLoader/getInstance))
:obf/yrn :obf/itm))
(def ^:private ^MappingResolver mapping-resolver (.getMappingResolver (FabricLoader/getInstance)))
(.debug LOGGER
(str "Loading on FABRIC\n"
(if IS_CLIENT "CLIENT" "DEDICATED SERVER") " distribution\n"
(.toUpperCase (name MAPPINGS)) " mappings"))
(defn mapped [form]
(let [itm-name (get (meta form)
:obf/itm
form)]
(symbol (if (= MAPPINGS :obf/itm)
itm-name
(case (-> (.matcher #"\.?(\w+_\d+)$" (str itm-name))
(doto .find)
(.group 1)
first)
\m (.mapMethodName mapping-resolver
"intermediary"
(str (get (meta form) :obf/owner))
(str itm-name)
(str (get (meta form) :obf/desc)))
\f (.mapFieldName mapping-resolver
"intermediary"
(str (get (meta form) :obf/owner))
(str itm-name)
(str (get (meta form) :obf/desc)))
\c (.mapClassName mapping-resolver
"intermediary" (str itm-name)))))))
| null | https://raw.githubusercontent.com/eutro/mc-clojure-lib/2e0e8b018ca474a63d46f92c34085d0f095bf5c0/src/main/resources/eutros/clojurelib/fabric/fabric_core.clj | clojure | (in-ns 'eutros.clojurelib.lib.core)
(import net.fabricmc.loader.api.FabricLoader
net.fabricmc.loader.api.MappingResolver
net.fabricmc.api.EnvType
java.util.regex.Matcher
java.util.regex.Pattern)
(def IS_FORGE false)
(def IS_FABRIC true)
(def IS_CLIENT (identical? (.getEnvironmentType (FabricLoader/getInstance))
EnvType/CLIENT))
(def MAPPINGS (if (.isDevelopmentEnvironment (FabricLoader/getInstance))
:obf/yrn :obf/itm))
(def ^:private ^MappingResolver mapping-resolver (.getMappingResolver (FabricLoader/getInstance)))
(.debug LOGGER
(str "Loading on FABRIC\n"
(if IS_CLIENT "CLIENT" "DEDICATED SERVER") " distribution\n"
(.toUpperCase (name MAPPINGS)) " mappings"))
(defn mapped [form]
(let [itm-name (get (meta form)
:obf/itm
form)]
(symbol (if (= MAPPINGS :obf/itm)
itm-name
(case (-> (.matcher #"\.?(\w+_\d+)$" (str itm-name))
(doto .find)
(.group 1)
first)
\m (.mapMethodName mapping-resolver
"intermediary"
(str (get (meta form) :obf/owner))
(str itm-name)
(str (get (meta form) :obf/desc)))
\f (.mapFieldName mapping-resolver
"intermediary"
(str (get (meta form) :obf/owner))
(str itm-name)
(str (get (meta form) :obf/desc)))
\c (.mapClassName mapping-resolver
"intermediary" (str itm-name)))))))
|
|
88ef33f2b6592ef206efb1872ab9e2b36635a883ae91252da3968e6d1fe9d214 | racket/slideshow | aspect.rkt | #lang racket/base
(provide aspect?)
(define (aspect? v)
(or (not v)
(eq? v 'widescreen)
(eq? v 'fullscreen)))
| null | https://raw.githubusercontent.com/racket/slideshow/4588507e83e9aa859c6841e655b98417d46987e6/slideshow-lib/slideshow/private/aspect.rkt | racket | #lang racket/base
(provide aspect?)
(define (aspect? v)
(or (not v)
(eq? v 'widescreen)
(eq? v 'fullscreen)))
|
|
b244ee04961a2ff71aea89917df9333673b3a1a8b9ed06791858afb67271a13e | DKurilo/hackerrank | solution.hs | # LANGUAGE UnicodeSyntax #
module Main where
import Prelude.Unicode
import Control.Monad.Unicode
import Control.Monad
import qualified Data.ByteString.Char8 as BSC
import Debug.Trace
import System.IO
data Fate = CENTRAL | RIGHT | LEFT | DEAD
deriving (Show)
combine ∷ [Int] → Int
combine = foldl (\n d → n * 10 + d) 0
prime ∷ Int → Bool
prime 1 = False
prime 2 = True
prime n =
and ∘ map (\p → n `mod` p ≠ 0) ∘ takeWhile (((≥)∘floor∘sqrt∘fromIntegral) n) $ primes
primes ∷ [Int]
primes = sieve [2..]
sieve ∷ [Int] → [Int]
sieve (p:xs) = p:sieve [x | x ← xs, x `mod` p > 0]
findFate ∷ [Int] → Fate
findFate ns
| right ∧ left = CENTRAL
| right = RIGHT
| left = LEFT
| otherwise = DEAD
where right = check id ns
left = check reverse ns
check prep ns =
foldl (\p i → let ns' = prep ∘ take i ∘ prep $ ns
d = head ns'
n = combine ns' in
p ∧ d ≠ 0 ∧ prime n)
True [1..length ns]
main ∷ IO()
main = do
let getInt bx = case BSC.readInt bx of
Just (x,_) → x
_ → 0
t ← getInt <$> BSC.getLine
forM_ [1..t] $ \_ → BSC.pack ∘ show ∘ findFate ∘ map getInt ∘ BSC.groupBy (\a b → False)
<$> BSC.getLine ≫= BSC.putStrLn
| null | https://raw.githubusercontent.com/DKurilo/hackerrank/37063170567b397b25a2b7123bc9c1299d34814a/captain-prime/solution.hs | haskell | # LANGUAGE UnicodeSyntax #
module Main where
import Prelude.Unicode
import Control.Monad.Unicode
import Control.Monad
import qualified Data.ByteString.Char8 as BSC
import Debug.Trace
import System.IO
data Fate = CENTRAL | RIGHT | LEFT | DEAD
deriving (Show)
combine ∷ [Int] → Int
combine = foldl (\n d → n * 10 + d) 0
prime ∷ Int → Bool
prime 1 = False
prime 2 = True
prime n =
and ∘ map (\p → n `mod` p ≠ 0) ∘ takeWhile (((≥)∘floor∘sqrt∘fromIntegral) n) $ primes
primes ∷ [Int]
primes = sieve [2..]
sieve ∷ [Int] → [Int]
sieve (p:xs) = p:sieve [x | x ← xs, x `mod` p > 0]
findFate ∷ [Int] → Fate
findFate ns
| right ∧ left = CENTRAL
| right = RIGHT
| left = LEFT
| otherwise = DEAD
where right = check id ns
left = check reverse ns
check prep ns =
foldl (\p i → let ns' = prep ∘ take i ∘ prep $ ns
d = head ns'
n = combine ns' in
p ∧ d ≠ 0 ∧ prime n)
True [1..length ns]
main ∷ IO()
main = do
let getInt bx = case BSC.readInt bx of
Just (x,_) → x
_ → 0
t ← getInt <$> BSC.getLine
forM_ [1..t] $ \_ → BSC.pack ∘ show ∘ findFate ∘ map getInt ∘ BSC.groupBy (\a b → False)
<$> BSC.getLine ≫= BSC.putStrLn
|
|
baca66d7567636f932b97f267c3cc90fd962ae8e1b8d281c5d9ec330fec2ba03 | borodust/notalone | main.lisp | (cl:in-package :notalone)
(define-sound orbital-colossus "sounds/Orbital_Colossus.ogg")
(register-resource-package :notalone (asdf:system-relative-pathname :notalone "assets/"))
(defgame notalone ()
((world :initform (make-instance 'world))
(game-state))
(:viewport-width *viewport-width*)
(:viewport-height *viewport-height*)
(:viewport-title "NOTALONE")
(:prepare-resources nil))
(defmethod post-initialize :after ((this notalone))
(with-slots (game-state) this
(setf game-state (make-instance 'resource-preparation))
(flet ((%look-at (x y)
(look-at game-state x y)))
(bind-cursor #'%look-at))
(labels ((%bind-button (button)
(bind-button button :pressed
(lambda ()
(press-key game-state button)))
(bind-button button :released
(lambda ()
(release-key game-state button)))))
(%bind-button :w)
(%bind-button :a)
(%bind-button :s)
(%bind-button :d)
(%bind-button :enter))
(bind-button :mouse-left :pressed (lambda () (shoot game-state)))
(bind-button :escape :pressed #'gamekit:stop)
(prepare-resources 'zombie 'brains-1 'brains-2 'brains-3 'groan 'crackly-groan
'shotgun-fire 'shotgun
'orbital-colossus)))
(defmethod notice-resources ((this notalone) &rest resource-names)
(declare (ignore resource-names))
(with-slots (game-state world) this
(labels ((restart-game ()
(setf world (make-instance 'world))
(start-game))
(end-game ()
(setf game-state (make-instance 'game-end :world world :restart #'restart-game)))
(start-game ()
(setf game-state (make-instance 'game :end #'end-game :world world))))
(setf game-state (make-instance 'game-start :start #'start-game)))))
(defun unbind-buttons ()
(loop for button in '(:w :a :s :d :mouse-left)
do (bind-button button :pressed nil)
do (bind-button button :released nil)))
(defmethod draw ((this notalone))
(with-slots (game-state) this
(render game-state)))
(defmethod act ((this notalone))
(with-slots (game-state) this
(act game-state)))
(defun play-game (&optional blocking)
(gamekit:start 'notalone :blocking blocking))
| null | https://raw.githubusercontent.com/borodust/notalone/f914ec7b63618f917a976f49ff9fcd57b72a1b1d/main.lisp | lisp | (cl:in-package :notalone)
(define-sound orbital-colossus "sounds/Orbital_Colossus.ogg")
(register-resource-package :notalone (asdf:system-relative-pathname :notalone "assets/"))
(defgame notalone ()
((world :initform (make-instance 'world))
(game-state))
(:viewport-width *viewport-width*)
(:viewport-height *viewport-height*)
(:viewport-title "NOTALONE")
(:prepare-resources nil))
(defmethod post-initialize :after ((this notalone))
(with-slots (game-state) this
(setf game-state (make-instance 'resource-preparation))
(flet ((%look-at (x y)
(look-at game-state x y)))
(bind-cursor #'%look-at))
(labels ((%bind-button (button)
(bind-button button :pressed
(lambda ()
(press-key game-state button)))
(bind-button button :released
(lambda ()
(release-key game-state button)))))
(%bind-button :w)
(%bind-button :a)
(%bind-button :s)
(%bind-button :d)
(%bind-button :enter))
(bind-button :mouse-left :pressed (lambda () (shoot game-state)))
(bind-button :escape :pressed #'gamekit:stop)
(prepare-resources 'zombie 'brains-1 'brains-2 'brains-3 'groan 'crackly-groan
'shotgun-fire 'shotgun
'orbital-colossus)))
(defmethod notice-resources ((this notalone) &rest resource-names)
(declare (ignore resource-names))
(with-slots (game-state world) this
(labels ((restart-game ()
(setf world (make-instance 'world))
(start-game))
(end-game ()
(setf game-state (make-instance 'game-end :world world :restart #'restart-game)))
(start-game ()
(setf game-state (make-instance 'game :end #'end-game :world world))))
(setf game-state (make-instance 'game-start :start #'start-game)))))
(defun unbind-buttons ()
(loop for button in '(:w :a :s :d :mouse-left)
do (bind-button button :pressed nil)
do (bind-button button :released nil)))
(defmethod draw ((this notalone))
(with-slots (game-state) this
(render game-state)))
(defmethod act ((this notalone))
(with-slots (game-state) this
(act game-state)))
(defun play-game (&optional blocking)
(gamekit:start 'notalone :blocking blocking))
|
|
d4a4d1ea3f264b4b76a76e52da099506b851b062d660c7db21cecc813c289fbb | tmfg/mmtis-national-access-point | email.clj | (ns ote.email
"Email sending utilities."
(:require [clojure.set :as set]
[postal.core :as postal]
[ote.nap.cookie :as nap-cookie]
[ote.nap.users :as nap-users]
[taoensso.timbre :as log]
[ote.localization :as localization]
[com.stuartsierra.component :as component]))
(defprotocol Send
(send! [this message]
"Send a single email.
Message can have the following keys.
Sender and recipient:
:from, :to, :cc, :bcc
Message subject and content:
:subject, :body"))
(defn- send-email
"Send a singular email using Postal."
[server msg]
(if (-> server :host some?)
(let [response (-> (postal/send-message server msg)
(set/rename-keys {:error :status}))]
(log/info (str "Sending email to <" (:to msg) "> with subject '" (:subject msg) "' resulted in " response)))
(log/warn "not sending email because configured smtp host is empty")))
(defrecord Email [email-opts]
component/Lifecycle
(start [this] this)
(stop [this] this)
Send
(send! [{{:keys [server msg]} :email-opts} message]
(send-email server
(merge msg message))))
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/d05e7d1b06a9078964b9fe58d546e87ca6078cfc/ote/src/clj/ote/email.clj | clojure | (ns ote.email
"Email sending utilities."
(:require [clojure.set :as set]
[postal.core :as postal]
[ote.nap.cookie :as nap-cookie]
[ote.nap.users :as nap-users]
[taoensso.timbre :as log]
[ote.localization :as localization]
[com.stuartsierra.component :as component]))
(defprotocol Send
(send! [this message]
"Send a single email.
Message can have the following keys.
Sender and recipient:
:from, :to, :cc, :bcc
Message subject and content:
:subject, :body"))
(defn- send-email
"Send a singular email using Postal."
[server msg]
(if (-> server :host some?)
(let [response (-> (postal/send-message server msg)
(set/rename-keys {:error :status}))]
(log/info (str "Sending email to <" (:to msg) "> with subject '" (:subject msg) "' resulted in " response)))
(log/warn "not sending email because configured smtp host is empty")))
(defrecord Email [email-opts]
component/Lifecycle
(start [this] this)
(stop [this] this)
Send
(send! [{{:keys [server msg]} :email-opts} message]
(send-email server
(merge msg message))))
|
|
b95fa0ac798c96955b67683e4fd7a3da36b6c9e84cfcd4d7b412e878ea4509a4 | takikawa/racket-ppa | info.rkt | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("profile-lib" "profile-doc"))) (define implies (quote ("profile-lib" "profile-doc"))) (define pkg-desc "Libraries for statistical performance profiling") (define pkg-authors (quote (eli))) (define license (quote (Apache-2.0 OR MIT)))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/profile/info.rkt | racket | (module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("profile-lib" "profile-doc"))) (define implies (quote ("profile-lib" "profile-doc"))) (define pkg-desc "Libraries for statistical performance profiling") (define pkg-authors (quote (eli))) (define license (quote (Apache-2.0 OR MIT)))))
|
|
cccab269347ab14fc6d68e64c99dbb8c0fff7c8ad4214ed50a8bd5091e4cab0e | mransan/ocaml-protoc | test18_ml.ml | module T = Test18_types
module Pb = Test18_pb
module Pp = Test18_pp
let decode_ref_data () =
T.
{
string_to_string = [ "one", "two"; "three", "four" ];
string_to_int = [ "one", 1l; "three", 3l ];
int_to_int = [ 1, 2; 3, 4 ];
int_to_message_value =
[ 1l, { mv_field = "one" }; 2l, { mv_field = "two" } ];
int_to_enum_value = [ 1l, Ev_1; 2l, Ev_2 ];
int_to_oneof_value = [ 1l, Ov_field1 "one"; 2l, Ov_field2 2l ];
}
let mode = Test_util.parse_args ()
let sort_by_string_key l =
let cmp : string -> string -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let sort_by_int_key l =
let cmp : int -> int -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let sort_by_int32_key l =
let cmp : int32 -> int32 -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let decode_maps decoder =
let maps = Pb.decode_maps decoder in
let {
T.string_to_string;
T.string_to_int;
T.int_to_int;
T.int_to_message_value;
T.int_to_enum_value;
T.int_to_oneof_value;
} =
maps
in
{
T.string_to_string = sort_by_string_key string_to_string;
T.string_to_int = sort_by_string_key string_to_int;
T.int_to_int = sort_by_int_key int_to_int;
T.int_to_message_value = sort_by_int32_key int_to_message_value;
T.int_to_enum_value = sort_by_int32_key int_to_enum_value;
T.int_to_oneof_value = sort_by_int32_key int_to_oneof_value;
}
let () =
match mode with
| Test_util.Decode ->
Test_util.decode "test18.c2ml.data" decode_maps Pp.pp_maps
(decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test18.ml2c.data" Pb.encode_maps (decode_ref_data ())
| null | https://raw.githubusercontent.com/mransan/ocaml-protoc/e43b509b9c4a06e419edba92a0d3f8e26b0a89ba/src/tests/integration-tests/test18_ml.ml | ocaml | module T = Test18_types
module Pb = Test18_pb
module Pp = Test18_pp
let decode_ref_data () =
T.
{
string_to_string = [ "one", "two"; "three", "four" ];
string_to_int = [ "one", 1l; "three", 3l ];
int_to_int = [ 1, 2; 3, 4 ];
int_to_message_value =
[ 1l, { mv_field = "one" }; 2l, { mv_field = "two" } ];
int_to_enum_value = [ 1l, Ev_1; 2l, Ev_2 ];
int_to_oneof_value = [ 1l, Ov_field1 "one"; 2l, Ov_field2 2l ];
}
let mode = Test_util.parse_args ()
let sort_by_string_key l =
let cmp : string -> string -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let sort_by_int_key l =
let cmp : int -> int -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let sort_by_int32_key l =
let cmp : int32 -> int32 -> int = compare in
let cmp (lhs, _) (rhs, _) = cmp lhs rhs in
List.stable_sort cmp l
let decode_maps decoder =
let maps = Pb.decode_maps decoder in
let {
T.string_to_string;
T.string_to_int;
T.int_to_int;
T.int_to_message_value;
T.int_to_enum_value;
T.int_to_oneof_value;
} =
maps
in
{
T.string_to_string = sort_by_string_key string_to_string;
T.string_to_int = sort_by_string_key string_to_int;
T.int_to_int = sort_by_int_key int_to_int;
T.int_to_message_value = sort_by_int32_key int_to_message_value;
T.int_to_enum_value = sort_by_int32_key int_to_enum_value;
T.int_to_oneof_value = sort_by_int32_key int_to_oneof_value;
}
let () =
match mode with
| Test_util.Decode ->
Test_util.decode "test18.c2ml.data" decode_maps Pp.pp_maps
(decode_ref_data ())
| Test_util.Encode ->
Test_util.encode "test18.ml2c.data" Pb.encode_maps (decode_ref_data ())
|
|
662e68b8ee5e884615f6f73ccc6d0fc257a5c8fc286a1ed948d206cd314447aa | incoherentsoftware/defect-process | SpeedRail.hs | module Level.Room.SpeedRail
( SpeedRail(..)
, mkSpeedRail
, speedRailSurface
, updateSpeedRail
, drawSpeedRail
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Foldable (for_)
import Configs
import Configs.All.Settings
import Configs.All.Settings.Debug
import Collision.Hitbox
import FileCache
import Level.Room.SpeedRail.JSON
import Util
import Window.Graphics
import World.Surface
import World.ZIndex
debugHbxColor = Color 255 0 220 255 :: Color
data SpeedRail = SpeedRail
{ _dir :: Direction
, _hitbox :: Hitbox
, _sprite :: Sprite
}
mkSpeedRail :: (FileCache m, GraphicsRead m, MonadIO m) => SpeedRailJSON -> m SpeedRail
mkSpeedRail json = do
spr <- loadPackSprite $ PackResourceFilePath "data/levels/level-items.pack" "speed-rail.spr"
return $ SpeedRail
{ _dir = _direction (json :: SpeedRailJSON)
, _hitbox = _fromJSON $ _hitbox (json :: SpeedRailJSON)
, _sprite = spr
}
speedRailSurface :: SpeedRail -> Surface
speedRailSurface speedRail = Surface
{ _type = SpeedRailSurface $ _dir speedRail
, _hitbox = _hitbox (speedRail :: SpeedRail)
} :: Surface
updateSpeedRail :: SpeedRail -> SpeedRail
updateSpeedRail speedRail = speedRail {_sprite = updateSprite (_sprite speedRail)}
-- assumes total speed rail width is evenly divided by the speed rail sprite width
drawSpeedRail :: (ConfigsRead m, GraphicsReadWrite m, MonadIO m) => SpeedRail -> m ()
drawSpeedRail speedRail =
let
hbx = _hitbox (speedRail :: SpeedRail)
totalWidth = round $ hitboxWidth hbx
spr = _sprite speedRail
sprWidthF = spriteImageWidth spr
sprWidth = round sprWidthF
dir = _dir speedRail
in do
whenM (readSettingsConfig _debug _drawItemHitboxes) $
drawHitbox debugHbxColor levelItemZIndex hbx
for_ [1..totalWidth `div` sprWidth] $ \i ->
let
x = hitboxLeft hbx + (realToFrac i - 1) * sprWidthF
x'
| dir == LeftDir = x + sprWidthF
| otherwise = x
pos = Pos2 x' (hitboxBot hbx)
in drawSprite pos dir levelItemZIndex spr
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Level/Room/SpeedRail.hs | haskell | assumes total speed rail width is evenly divided by the speed rail sprite width | module Level.Room.SpeedRail
( SpeedRail(..)
, mkSpeedRail
, speedRailSurface
, updateSpeedRail
, drawSpeedRail
) where
import Control.Monad.IO.Class (MonadIO)
import Data.Foldable (for_)
import Configs
import Configs.All.Settings
import Configs.All.Settings.Debug
import Collision.Hitbox
import FileCache
import Level.Room.SpeedRail.JSON
import Util
import Window.Graphics
import World.Surface
import World.ZIndex
debugHbxColor = Color 255 0 220 255 :: Color
data SpeedRail = SpeedRail
{ _dir :: Direction
, _hitbox :: Hitbox
, _sprite :: Sprite
}
mkSpeedRail :: (FileCache m, GraphicsRead m, MonadIO m) => SpeedRailJSON -> m SpeedRail
mkSpeedRail json = do
spr <- loadPackSprite $ PackResourceFilePath "data/levels/level-items.pack" "speed-rail.spr"
return $ SpeedRail
{ _dir = _direction (json :: SpeedRailJSON)
, _hitbox = _fromJSON $ _hitbox (json :: SpeedRailJSON)
, _sprite = spr
}
speedRailSurface :: SpeedRail -> Surface
speedRailSurface speedRail = Surface
{ _type = SpeedRailSurface $ _dir speedRail
, _hitbox = _hitbox (speedRail :: SpeedRail)
} :: Surface
updateSpeedRail :: SpeedRail -> SpeedRail
updateSpeedRail speedRail = speedRail {_sprite = updateSprite (_sprite speedRail)}
drawSpeedRail :: (ConfigsRead m, GraphicsReadWrite m, MonadIO m) => SpeedRail -> m ()
drawSpeedRail speedRail =
let
hbx = _hitbox (speedRail :: SpeedRail)
totalWidth = round $ hitboxWidth hbx
spr = _sprite speedRail
sprWidthF = spriteImageWidth spr
sprWidth = round sprWidthF
dir = _dir speedRail
in do
whenM (readSettingsConfig _debug _drawItemHitboxes) $
drawHitbox debugHbxColor levelItemZIndex hbx
for_ [1..totalWidth `div` sprWidth] $ \i ->
let
x = hitboxLeft hbx + (realToFrac i - 1) * sprWidthF
x'
| dir == LeftDir = x + sprWidthF
| otherwise = x
pos = Pos2 x' (hitboxBot hbx)
in drawSprite pos dir levelItemZIndex spr
|
a0637b612436de90c7b6a9010d39db11380c8274348ec5ebe633feeb382cb9b4 | kit-ty-kate/labrys | pattern.ml | Copyright ( c ) 2013 - 2017 The Labrys developers .
(* See the LICENSE file at the top-level directory. *)
type ty = TypedEnv.nty
type loc = Location.t
type name = Ident.Name.t
type constr_name = Ident.Constr.t
type index = int
type branch = int
type pattern' =
| Wildcard
| Constr of (loc * constr_name * pattern list)
| Or of (pattern * pattern)
| As of (pattern * name)
and pattern = (ty * pattern')
type tree =
| Switch of ((loc * constr_name * ty * tree) list * tree option)
| Swap of (index * tree)
| Alias of (name * tree)
| Jump of branch
type matrix = (pattern list * branch) list
let p_as name (ps, a) =
(List.map (fun p -> (fst p, As (p, name))) ps, a)
let specialize ~eq ~ty_size =
let rec aux (p, a) = match p with
| [] -> assert false (* NOTE: This is forbidden by the syntax *)
| (_, Constr (_, c, qs))::ps when eq c -> [(qs @ ps, a)]
| (_, Constr _)::_ -> []
| (_, Wildcard) as p::ps -> [(List.replicate ty_size p @ ps, a)]
| (_, Or (q1, q2))::ps -> aux (q1::ps, a) @ aux (q2::ps, a)
| (_, As (p, name))::ps -> List.map (p_as name) (aux (p::ps, a))
in
fun m -> List.flatten (List.map aux m)
let decompose =
let rec aux (p, a) = match p with
| [] -> assert false (* NOTE: This is forbidden by the syntax *)
| (_, Constr _)::_ -> []
| (_, Wildcard)::ps -> [(ps, a)]
| (_, Or (q1, q2))::ps -> aux (q1::ps, a) @ aux (q2::ps, a)
| (_, As (p, name))::ps -> List.map (p_as name) (aux (p::ps, a))
in
fun m -> List.flatten (List.map aux m)
let jump a =
let exception JumpFailed of index in
let rec aux i = function
| [(_, Wildcard)] | [] -> Jump a
| (_, Constr _)::_ -> raise (JumpFailed i)
| (_, Wildcard)::xs -> Swap (i, aux (succ i) xs)
| (_, Or _)::_ -> assert false (* NOTE: Case removed in destruct_ors *)
| (_, As (p, name))::xs -> Alias (name, aux i (p::xs))
in
fun row -> try Ok (aux 1 row) with JumpFailed i -> Error i
let rec extract_constr = function
| (_, Wildcard) -> []
| (ty, Constr (loc, c, ps)) -> [(loc, c, ty, List.length ps)]
| (_, Or (p1, p2)) -> extract_constr p1 @ extract_constr p2
| (_, As (p, _)) -> extract_constr p
let rec get_head_constrs = function
| [] -> []
| ([], _)::_ -> assert false (* NOTE: Cannot happen *)
| ((p::_), _)::m -> extract_constr p @ get_head_constrs m
let get_head_constrs m =
let constrs = get_head_constrs m in
let rm_duplicates constrs ((_, c, _, _) as x) =
if List.exists (fun (_, c', _, _) -> Ident.Constr.equal c c') constrs then
constrs
else
constrs @ [x]
in
List.fold_left rm_duplicates [] constrs
let destruct_ors =
let rec aux acc a = function
| [] -> [(acc, a)]
| (_, (Wildcard | Constr _)) as p::ps -> aux (acc @ [p]) a ps
| (_, Or (p1, p2))::ps -> aux acc a (p1::ps) @ aux acc a (p2::ps)
| (_, As (p, name))::ps ->
let acc = destr_as name (aux acc a [p]) in
List.flatten (List.map (fun acc -> aux acc a ps) acc)
and destr_as name acc =
let rec aux = function
| ([], _) -> assert false (* NOTE: Cannot happen *)
| ([p], _) -> [(fst p, As (p, name))]
| (p::ps, a) -> p :: aux (ps, a)
in
List.map aux acc
in
fun (row, a) m -> match aux [] a row with
| [] -> assert false (* NOTE: Cannot happen *)
| (row, a)::_ as m' -> (row, a, m' @ m)
let rec compile = function
| [] -> assert false (* NOTE: This is forbidden by the syntax *)
| row::m ->
let (row, a, m) = destruct_ors row m in
begin match jump a row with
| Ok t -> t
| Error 1 -> switch m
| Error i -> Swap (i, compile (Utils.swap_list (pred i) m))
end
and switch m =
let heads = get_head_constrs m in
let default = match decompose m with
| [] -> None
| m -> Some (compile m)
in
let aux (loc, c, ty, ty_size) =
let eq = Ident.Constr.equal c in
let tree = compile (specialize ~eq ~ty_size m) in
(loc, c, ty, tree)
in
Switch (List.map aux heads, default)
| null | https://raw.githubusercontent.com/kit-ty-kate/labrys/4a3e0c5dd45343b4de2e22051095b49d05772608/src/typing/pattern.ml | ocaml | See the LICENSE file at the top-level directory.
NOTE: This is forbidden by the syntax
NOTE: This is forbidden by the syntax
NOTE: Case removed in destruct_ors
NOTE: Cannot happen
NOTE: Cannot happen
NOTE: Cannot happen
NOTE: This is forbidden by the syntax | Copyright ( c ) 2013 - 2017 The Labrys developers .
type ty = TypedEnv.nty
type loc = Location.t
type name = Ident.Name.t
type constr_name = Ident.Constr.t
type index = int
type branch = int
type pattern' =
| Wildcard
| Constr of (loc * constr_name * pattern list)
| Or of (pattern * pattern)
| As of (pattern * name)
and pattern = (ty * pattern')
type tree =
| Switch of ((loc * constr_name * ty * tree) list * tree option)
| Swap of (index * tree)
| Alias of (name * tree)
| Jump of branch
type matrix = (pattern list * branch) list
let p_as name (ps, a) =
(List.map (fun p -> (fst p, As (p, name))) ps, a)
let specialize ~eq ~ty_size =
let rec aux (p, a) = match p with
| (_, Constr (_, c, qs))::ps when eq c -> [(qs @ ps, a)]
| (_, Constr _)::_ -> []
| (_, Wildcard) as p::ps -> [(List.replicate ty_size p @ ps, a)]
| (_, Or (q1, q2))::ps -> aux (q1::ps, a) @ aux (q2::ps, a)
| (_, As (p, name))::ps -> List.map (p_as name) (aux (p::ps, a))
in
fun m -> List.flatten (List.map aux m)
let decompose =
let rec aux (p, a) = match p with
| (_, Constr _)::_ -> []
| (_, Wildcard)::ps -> [(ps, a)]
| (_, Or (q1, q2))::ps -> aux (q1::ps, a) @ aux (q2::ps, a)
| (_, As (p, name))::ps -> List.map (p_as name) (aux (p::ps, a))
in
fun m -> List.flatten (List.map aux m)
let jump a =
let exception JumpFailed of index in
let rec aux i = function
| [(_, Wildcard)] | [] -> Jump a
| (_, Constr _)::_ -> raise (JumpFailed i)
| (_, Wildcard)::xs -> Swap (i, aux (succ i) xs)
| (_, As (p, name))::xs -> Alias (name, aux i (p::xs))
in
fun row -> try Ok (aux 1 row) with JumpFailed i -> Error i
let rec extract_constr = function
| (_, Wildcard) -> []
| (ty, Constr (loc, c, ps)) -> [(loc, c, ty, List.length ps)]
| (_, Or (p1, p2)) -> extract_constr p1 @ extract_constr p2
| (_, As (p, _)) -> extract_constr p
let rec get_head_constrs = function
| [] -> []
| ((p::_), _)::m -> extract_constr p @ get_head_constrs m
let get_head_constrs m =
let constrs = get_head_constrs m in
let rm_duplicates constrs ((_, c, _, _) as x) =
if List.exists (fun (_, c', _, _) -> Ident.Constr.equal c c') constrs then
constrs
else
constrs @ [x]
in
List.fold_left rm_duplicates [] constrs
let destruct_ors =
let rec aux acc a = function
| [] -> [(acc, a)]
| (_, (Wildcard | Constr _)) as p::ps -> aux (acc @ [p]) a ps
| (_, Or (p1, p2))::ps -> aux acc a (p1::ps) @ aux acc a (p2::ps)
| (_, As (p, name))::ps ->
let acc = destr_as name (aux acc a [p]) in
List.flatten (List.map (fun acc -> aux acc a ps) acc)
and destr_as name acc =
let rec aux = function
| ([p], _) -> [(fst p, As (p, name))]
| (p::ps, a) -> p :: aux (ps, a)
in
List.map aux acc
in
fun (row, a) m -> match aux [] a row with
| (row, a)::_ as m' -> (row, a, m' @ m)
let rec compile = function
| row::m ->
let (row, a, m) = destruct_ors row m in
begin match jump a row with
| Ok t -> t
| Error 1 -> switch m
| Error i -> Swap (i, compile (Utils.swap_list (pred i) m))
end
and switch m =
let heads = get_head_constrs m in
let default = match decompose m with
| [] -> None
| m -> Some (compile m)
in
let aux (loc, c, ty, ty_size) =
let eq = Ident.Constr.equal c in
let tree = compile (specialize ~eq ~ty_size m) in
(loc, c, ty, tree)
in
Switch (List.map aux heads, default)
|
29ca5e81b4e2395bdcf565bd864def4afb14fbfe5be497c4f78729ef6598d0eb | generateme/inferme | particles.clj | ;;
(ns particles
(:require [inferme.core :as im]
[fastmath.random :as r]
[fastmath.stats :as stats]
[inferme.plot :as plot]))
(def T 1000)
(def my-data (-> (r/distribution :normal {:mu 3.14})
(r/->seq T)))
(defn toy-model
[data]
(im/make-model
[mu (:normal {:sd 10.0})
sigma (:gamma {:scale 1.0 :shape 1.0})]
(im/model-result [(im/observe (im/distr :normal {:mu mu :sd sigma}) data)])))
(def thetas (repeatedly 5 (partial im/random-priors (toy-model my-data) true)))
thetas
= > ( { : mu 4.054065086000591 , : sigma 0.22571464728078117 }
{ : mu 1.2929671048412783 , : sigma 1.2628673250997287 }
{ : mu -3.166100638586244 , : sigma 0.020847483157448405 }
{ : mu 6.117304193607003 , : sigma 2.4512726002325786 }
{ : mu 0.368333623969723 , : sigma 0.04464271965407036 } )
(map (comp :LP (partial im/call (toy-model (take 3 my-data)))) thetas)
;; => (-24.32084504686292
;; -11.502669047839152
;; -140943.38208640966
;; -13.420018533365576
;; -6164.348150041295)
(def res (im/infer :metropolis-within-gibbs (toy-model my-data)))
(:acceptance-ratio res)
(:out-of-prior res)
(plot/histogram (im/trace res :mu))
(plot/histogram (im/trace res :sigma))
(plot/histogram (im/trace res :LP))
(im/stats res :mu)
(im/stats res :sigma)
(def my-data [1.88253582, 3.52487957, 3.5693534])
(def theta [-11.56023514, 0.66673981])
(apply - ((juxt :LP :LL) (im/call (toy-model (take 3 my-data)) theta)))
(def mu (im/distr :normal {:sd 10.0}))
(def sigma (im/distr :gamma {:scale 1.0 :shape 1.0}))
(im/score mu (theta 0));; => -3.8897188086591727
(im/score sigma (theta 1)) ;; => -0.66673981
| null | https://raw.githubusercontent.com/generateme/inferme/3670839bee3873cfee812907937e8229431a15b2/notebooks/particles.clj | clojure |
=> (-24.32084504686292
-11.502669047839152
-140943.38208640966
-13.420018533365576
-6164.348150041295)
=> -3.8897188086591727
=> -0.66673981 |
(ns particles
(:require [inferme.core :as im]
[fastmath.random :as r]
[fastmath.stats :as stats]
[inferme.plot :as plot]))
(def T 1000)
(def my-data (-> (r/distribution :normal {:mu 3.14})
(r/->seq T)))
(defn toy-model
[data]
(im/make-model
[mu (:normal {:sd 10.0})
sigma (:gamma {:scale 1.0 :shape 1.0})]
(im/model-result [(im/observe (im/distr :normal {:mu mu :sd sigma}) data)])))
(def thetas (repeatedly 5 (partial im/random-priors (toy-model my-data) true)))
thetas
= > ( { : mu 4.054065086000591 , : sigma 0.22571464728078117 }
{ : mu 1.2929671048412783 , : sigma 1.2628673250997287 }
{ : mu -3.166100638586244 , : sigma 0.020847483157448405 }
{ : mu 6.117304193607003 , : sigma 2.4512726002325786 }
{ : mu 0.368333623969723 , : sigma 0.04464271965407036 } )
(map (comp :LP (partial im/call (toy-model (take 3 my-data)))) thetas)
(def res (im/infer :metropolis-within-gibbs (toy-model my-data)))
(:acceptance-ratio res)
(:out-of-prior res)
(plot/histogram (im/trace res :mu))
(plot/histogram (im/trace res :sigma))
(plot/histogram (im/trace res :LP))
(im/stats res :mu)
(im/stats res :sigma)
(def my-data [1.88253582, 3.52487957, 3.5693534])
(def theta [-11.56023514, 0.66673981])
(apply - ((juxt :LP :LL) (im/call (toy-model (take 3 my-data)) theta)))
(def mu (im/distr :normal {:sd 10.0}))
(def sigma (im/distr :gamma {:scale 1.0 :shape 1.0}))
|
b27365c5457f31d02d97113d4ee48e180c2273cee9791171412631f66c9b9efa | sydow/ireal | IReal.hs | -- | This module provides the type 'IReal', the values of which are real numbers and intervals, with
-- potentially unbounded precision arithmetic and elementary functions.
--
-- 'IReal' is an instance of the standard numeric classes, so we can interact in ghci as follows:
--
> > > exp 0.5 + pi * sqrt ( 2 + sin 1 ) ? 50
6.94439823755032768935865535478209938180612180886848
--
-- The right operand to the operator '?' indicates the number of decimals to display in the result.
-- Using '?' is the default way to print values; the 'Show' instance is not recommended to use, since
-- the redundant rounding policy implies that we cannot guarantee to generate equal string representations
-- for equal values.
--
-- For simple expressions like the above,
one can request a thousand decimals with more or less instantaneous result ; also ten thousand decimals is easy
( less than a second on a typical laptop ) .
--
-- Here is an example with interval arguments:
--
> > > exp ( 0.5 + - 0.001 ) + pi * sqrt ( 2 + sin ( 1 + - 0.003 ) ) ? 30
6.94[| 1236147625 .. 7554488225 | ]
--
-- The result is displayed in a non-standard but hopefully easily interpreted notation.
We will not get the requested 30 decimals here ; interval upper and lower bounds are displayed
with at most 10 distinguishing digits . The result of an interval computation is conservative ;
-- it includes all possible values of the expression for inputs in the given intervals. As always in
-- interval arithmetic, results may be unduly pessimistic because of the dependency problem.
--
As a third example , consider
--
> > > log ( 2 + - 1e-50 ) ? 30
0.693147180559945309417232121458
--
The result is obviously an interval , not a number , but displayed with 30 decimals it looks just like a real number . Conversely ,
-- a real number is an infinite object and we can only ever compute an approximation to it. So a finitely printed 'IReal' value
can always be thought of as denoting an interval ; there is an error margin of one unit in the last displayed digit .
These remarks give a first intuition for why it may be fruitful to merge real numbers and intervals into one type .
--
' IReal ' is also an instance of ' Eq ' and ' ' ; these are , however , non - total for computability reasons ;
-- evaluation of e.g. @sin pi == 0@ at type 'IReal' will not terminate.
--
-- At the github site <> one can find a QuickCheck testsuite (in directory tests), a paper with documentation (in directory doc) and a number of
-- small applications (in directory applications).
module Data.Number.IReal (
-- * The type of real numbers and intervals
IReal,
toDouble,
-- * Printing 'IReal's
(?),
(??),
showIReal,
-- * Total comparison operators
(<!),
(>!),
(=?=),
atDecimals,
-- * Intervals
-- ** Constructing interval values
(+-),
(-+-),
hull,
intersection,
-- ** Selectors
lower,
upper,
mid,
rad,
containedIn,
-- * Balanced folds
foldb,
foldb1,
bsum,
foldb',
isumN',
isum',
-- * Automatic Differentiation
Dif(..),
deriv,
derivs,
con,
var,
unDif,
val,
-- * QuickCheck support
-- ** Generators
uniformNum,
uniformIval,
exprGen,
-- ** Properties
propIsRealNum,
propIsRealIval,
-- * Auxiliary functions and type classes
force,
dec2bits,
lg2,
Powers(..),
Scalable(..),
VarPrec(..)
) where
import Data.Number.IReal.IReal
import Data.Number.IReal.Powers
import Data.Number.IReal.IntegerInterval
import Data.Number.IReal.Scalable
import Data.Number.IReal.UnsafeMemo
import Data.Number.IReal.IRealOperations
import Data.Number.IReal.Generators
import Data.Number.IReal.Auxiliary
import Data.Number.IReal.FoldB
import Data.Number.IReal.FAD
| null | https://raw.githubusercontent.com/sydow/ireal/c06438544c711169baac7960540202379f9294b1/Data/Number/IReal.hs | haskell | | This module provides the type 'IReal', the values of which are real numbers and intervals, with
potentially unbounded precision arithmetic and elementary functions.
'IReal' is an instance of the standard numeric classes, so we can interact in ghci as follows:
The right operand to the operator '?' indicates the number of decimals to display in the result.
Using '?' is the default way to print values; the 'Show' instance is not recommended to use, since
the redundant rounding policy implies that we cannot guarantee to generate equal string representations
for equal values.
For simple expressions like the above,
Here is an example with interval arguments:
The result is displayed in a non-standard but hopefully easily interpreted notation.
it includes all possible values of the expression for inputs in the given intervals. As always in
interval arithmetic, results may be unduly pessimistic because of the dependency problem.
a real number is an infinite object and we can only ever compute an approximation to it. So a finitely printed 'IReal' value
evaluation of e.g. @sin pi == 0@ at type 'IReal' will not terminate.
At the github site <> one can find a QuickCheck testsuite (in directory tests), a paper with documentation (in directory doc) and a number of
small applications (in directory applications).
* The type of real numbers and intervals
* Printing 'IReal's
* Total comparison operators
* Intervals
** Constructing interval values
** Selectors
* Balanced folds
* Automatic Differentiation
* QuickCheck support
** Generators
** Properties
* Auxiliary functions and type classes | > > > exp 0.5 + pi * sqrt ( 2 + sin 1 ) ? 50
6.94439823755032768935865535478209938180612180886848
one can request a thousand decimals with more or less instantaneous result ; also ten thousand decimals is easy
( less than a second on a typical laptop ) .
> > > exp ( 0.5 + - 0.001 ) + pi * sqrt ( 2 + sin ( 1 + - 0.003 ) ) ? 30
6.94[| 1236147625 .. 7554488225 | ]
We will not get the requested 30 decimals here ; interval upper and lower bounds are displayed
with at most 10 distinguishing digits . The result of an interval computation is conservative ;
As a third example , consider
> > > log ( 2 + - 1e-50 ) ? 30
0.693147180559945309417232121458
The result is obviously an interval , not a number , but displayed with 30 decimals it looks just like a real number . Conversely ,
can always be thought of as denoting an interval ; there is an error margin of one unit in the last displayed digit .
These remarks give a first intuition for why it may be fruitful to merge real numbers and intervals into one type .
' IReal ' is also an instance of ' Eq ' and ' ' ; these are , however , non - total for computability reasons ;
module Data.Number.IReal (
IReal,
toDouble,
(?),
(??),
showIReal,
(<!),
(>!),
(=?=),
atDecimals,
(+-),
(-+-),
hull,
intersection,
lower,
upper,
mid,
rad,
containedIn,
foldb,
foldb1,
bsum,
foldb',
isumN',
isum',
Dif(..),
deriv,
derivs,
con,
var,
unDif,
val,
uniformNum,
uniformIval,
exprGen,
propIsRealNum,
propIsRealIval,
force,
dec2bits,
lg2,
Powers(..),
Scalable(..),
VarPrec(..)
) where
import Data.Number.IReal.IReal
import Data.Number.IReal.Powers
import Data.Number.IReal.IntegerInterval
import Data.Number.IReal.Scalable
import Data.Number.IReal.UnsafeMemo
import Data.Number.IReal.IRealOperations
import Data.Number.IReal.Generators
import Data.Number.IReal.Auxiliary
import Data.Number.IReal.FoldB
import Data.Number.IReal.FAD
|
42cb5eb5dc13a14e7302e3a7b2885dd6f5b80d9eab5f8f227a5fd0ba89c3e3d3 | polyfy/polylith | create_component.clj | (ns polylith.clj.core.help.create-component
(:require [polylith.clj.core.help.shared :as s]))
(defn help-text [cm]
(str " Creates a component.\n"
"\n"
" poly create component name:" (s/key "NAME" cm) " [interface:" (s/key "INTERFACE" cm) "]\n"
" " (s/key "NAME" cm) " = The name of the component to create.\n"
"\n"
" " (s/key "INTERFACE" cm) " = The name of the interface (namespace) or " (s/key "NAME" cm) " if not given.\n"
"\n"
" Example:\n"
" poly create c name:user\n"
" poly create component name:user\n"
" poly create component name:admin interface:user"))
(defn print-help [color-mode]
(println (help-text color-mode)))
| null | https://raw.githubusercontent.com/polyfy/polylith/31c1fe4e71fa250544b7b549ff9734a074c809a4/components/help/src/polylith/clj/core/help/create_component.clj | clojure | (ns polylith.clj.core.help.create-component
(:require [polylith.clj.core.help.shared :as s]))
(defn help-text [cm]
(str " Creates a component.\n"
"\n"
" poly create component name:" (s/key "NAME" cm) " [interface:" (s/key "INTERFACE" cm) "]\n"
" " (s/key "NAME" cm) " = The name of the component to create.\n"
"\n"
" " (s/key "INTERFACE" cm) " = The name of the interface (namespace) or " (s/key "NAME" cm) " if not given.\n"
"\n"
" Example:\n"
" poly create c name:user\n"
" poly create component name:user\n"
" poly create component name:admin interface:user"))
(defn print-help [color-mode]
(println (help-text color-mode)))
|
|
c762fd67c722fc33f7a0ac0e6217ad3baf73a00b1b73f334678e124c36237009 | xclerc/ocamljava | cyclicBarrier.mli |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* 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 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java 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 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
(** Reusable barriers. *)
type t = java'util'concurrent'CyclicBarrier java_instance
(** The type of cyclic barriers, that are barriers possibly re-used once
all waiting threads have restarted. *)
val make : java_int -> t
* [ make n ] returns a barrier waiting for [ n ] threads ; see
{ java java.util.concurrent . CyclicBarrier#CyclicBarrier(int ) } .
@raise Java_exception if [ n ] is negative
{java java.util.concurrent.CyclicBarrier#CyclicBarrier(int)}.
@raise Java_exception if [n] is negative *)
val await : t -> java_int
* Waits until all threads have reached the barrier ; see
{ java java.util.concurrent . CyclicBarrier#await ( ) } .
@raise Java_exception if the barrier is broken
@raise Java_exception if the thread is interrupted
{java java.util.concurrent.CyclicBarrier#await()}.
@raise Java_exception if the barrier is broken
@raise Java_exception if the thread is interrupted *)
val await_time : t -> java_long -> TimeUnit.t -> java_int
* [ await_time b t u ] is similar to [ await b ] , except that the current
thread will at most wait for [ t ] ( time value whose unit is [ u ] ) ; see
{ java java.util.concurrent . , java.util.concurrent . TimeUnit ) } .
@Raises Java_exception if the barrier is broken .
@Raises Java_exception if the thread is interrupted .
@Raises Java_exception if time has elapsed without gathering all
threads
thread will at most wait for [t] (time value whose unit is [u]); see
{java java.util.concurrent.CyclicBarrier#await(long, java.util.concurrent.TimeUnit)}.
@Raises Java_exception if the barrier is broken.
@Raises Java_exception if the thread is interrupted.
@Raises Java_exception if time has elapsed without gathering all
threads *)
val get_number_waiting : t -> java_int
(** Returns the number of threads currently waiting on the barrier; see
{java java.util.concurrent.CyclicBarrier#getNumberWaiting()}. *)
val get_parties : t -> java_int
(** Returns the number of threads to be waited on the barrier; see
{java java.util.concurrent.CyclicBarrier#getParties()}. *)
val is_broken : t -> bool
(** Tests whether the barrier is broken. A barrier is broken if {!reset}
when threads are waiting on it; see
{java java.util.concurrent.CyclicBarrier#isBroken()}. *)
val reset : t -> unit
* Resets the barrier to its original state . The barrier will be broken
if there are threads currently waiting on it ; see
{ java java.util.concurrent . CyclicBarrier#reset ( ) } .
if there are threads currently waiting on it; see
{java java.util.concurrent.CyclicBarrier#reset()}. *)
* { 6 Null value }
val null : t
(** The [null] value. *)
external is_null : t -> bool =
"java is_null"
(** [is_null obj] returns [true] iff [obj] is equal to [null]. *)
external is_not_null : t -> bool =
"java is_not_null"
(** [is_not_null obj] returns [false] iff [obj] is equal to [null]. *)
* { 6 Miscellaneous }
val wrap : t -> t option
(** [wrap obj] wraps the reference [obj] into an option type:
- [Some x] if [obj] is not [null];
- [None] if [obj] is [null]. *)
val unwrap : t option -> t
(** [unwrap obj] unwraps the option [obj] into a bare reference:
- [Some x] is mapped to [x];
- [None] is mapped to [null]. *)
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/sync/cyclicBarrier.mli | ocaml | * Reusable barriers.
* The type of cyclic barriers, that are barriers possibly re-used once
all waiting threads have restarted.
* Returns the number of threads currently waiting on the barrier; see
{java java.util.concurrent.CyclicBarrier#getNumberWaiting()}.
* Returns the number of threads to be waited on the barrier; see
{java java.util.concurrent.CyclicBarrier#getParties()}.
* Tests whether the barrier is broken. A barrier is broken if {!reset}
when threads are waiting on it; see
{java java.util.concurrent.CyclicBarrier#isBroken()}.
* The [null] value.
* [is_null obj] returns [true] iff [obj] is equal to [null].
* [is_not_null obj] returns [false] iff [obj] is equal to [null].
* [wrap obj] wraps the reference [obj] into an option type:
- [Some x] if [obj] is not [null];
- [None] if [obj] is [null].
* [unwrap obj] unwraps the option [obj] into a bare reference:
- [Some x] is mapped to [x];
- [None] is mapped to [null]. |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* 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 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java 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 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
type t = java'util'concurrent'CyclicBarrier java_instance
val make : java_int -> t
* [ make n ] returns a barrier waiting for [ n ] threads ; see
{ java java.util.concurrent . CyclicBarrier#CyclicBarrier(int ) } .
@raise Java_exception if [ n ] is negative
{java java.util.concurrent.CyclicBarrier#CyclicBarrier(int)}.
@raise Java_exception if [n] is negative *)
val await : t -> java_int
* Waits until all threads have reached the barrier ; see
{ java java.util.concurrent . CyclicBarrier#await ( ) } .
@raise Java_exception if the barrier is broken
@raise Java_exception if the thread is interrupted
{java java.util.concurrent.CyclicBarrier#await()}.
@raise Java_exception if the barrier is broken
@raise Java_exception if the thread is interrupted *)
val await_time : t -> java_long -> TimeUnit.t -> java_int
* [ await_time b t u ] is similar to [ await b ] , except that the current
thread will at most wait for [ t ] ( time value whose unit is [ u ] ) ; see
{ java java.util.concurrent . , java.util.concurrent . TimeUnit ) } .
@Raises Java_exception if the barrier is broken .
@Raises Java_exception if the thread is interrupted .
@Raises Java_exception if time has elapsed without gathering all
threads
thread will at most wait for [t] (time value whose unit is [u]); see
{java java.util.concurrent.CyclicBarrier#await(long, java.util.concurrent.TimeUnit)}.
@Raises Java_exception if the barrier is broken.
@Raises Java_exception if the thread is interrupted.
@Raises Java_exception if time has elapsed without gathering all
threads *)
val get_number_waiting : t -> java_int
val get_parties : t -> java_int
val is_broken : t -> bool
val reset : t -> unit
* Resets the barrier to its original state . The barrier will be broken
if there are threads currently waiting on it ; see
{ java java.util.concurrent . CyclicBarrier#reset ( ) } .
if there are threads currently waiting on it; see
{java java.util.concurrent.CyclicBarrier#reset()}. *)
* { 6 Null value }
val null : t
external is_null : t -> bool =
"java is_null"
external is_not_null : t -> bool =
"java is_not_null"
* { 6 Miscellaneous }
val wrap : t -> t option
val unwrap : t option -> t
|
327ddea20cd065331932d269ce448399d2485363d8e81057740d5bc6899576d6 | fortytools/holumbus | W3WIndexer.hs | # OPTIONS #
-- ------------------------------------------------------------
module Main
where
import Codec.Compression.BZip ( compress, decompress )
import Control.Monad.Reader
import Data.Binary
import Data.Char
import Data.Function.Selector
import Data.Maybe
import IndexConfig
import IndexTypes
import PageInfo
import URIConfig
import Holumbus.Crawler
import Holumbus.Crawler.CacheCore
import Holumbus.Crawler.IndexerCore
import Holumbus.Crawler.PdfToText
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Text.XML.HXT.Core
import Text.XML.HXT.Cache
import Text.XML.HXT.Curl
-- ------------------------------------------------------------
data AppAction
= BuildIx | BuildCache | MergeIx
deriving (Eq, Show)
data AppOpts
= AO
{ ao_progname :: String
, ao_index :: String
, ao_ixout :: String
, ao_ixsearch :: String
, ao_xml :: String
, ao_help :: Bool
, ao_action :: AppAction
, ao_defrag :: Bool
, ao_partix :: Bool
, ao_resume :: Maybe String
, ao_msg :: String
, ao_crawlDoc :: (Int, Int, Int)
, ao_crawlSav :: Int
, ao_crawlSfn :: String
, ao_crawlLog :: (Priority, Priority)
, ao_crawlPar :: SysConfig
, ao_crawlFct :: W3WIndexerConfig -> W3WIndexerConfig
, ao_crawlCch :: CacheCrawlerConfig -> CacheCrawlerConfig
, ao_uriConfig :: UriConfig
}
-- ------------------------------------------------------------
initAppOpts :: AppOpts
initAppOpts
= AO
{ ao_progname = "w3wIndexer"
, ao_index = ""
, ao_ixout = ""
, ao_ixsearch = ""
, ao_xml = ""
, ao_help = False
, ao_action = BuildIx
, ao_defrag = False
, ao_partix = False
, ao_resume = Nothing
, ao_msg = ""
max docs , par docs , threads : no parallel threads , but 1024 docs are indexed before results are inserted
, ao_crawlSav = 5000 -- save intervall
, ao_crawlSfn = "./tmp/ix-" -- save path
log cache and hxt
set cache dir , cache remains valid 1 day , 404 pages are cached
>>>
withCompression (compress, decompress) -- compress cache files
>>>
withStrictDeserialize yes -- strict input of cache files
>>>
withAcceptedMimeTypes [ text_html
, application_xhtml
, application_pdf
]
>>>
withCurl [ (curl_location, v_1) -- automatically follow redirects
but limit # of redirects to 3
]
>>>
withRedirect no
>>>
withInputOption curl_max_filesize (show (1024 * 1024 * 3 `div` 2 ::Int))
this limit excludes automtically generated pages , sometimes > 1.5
>>>
withParseHTML no
>>>
withParseByMimeType yes
>>>
withMimeTypeHandler application_pdf extractPdfText
configure URI rewriting
>>>
disableRobotsTxt -- for w3w robots.txt is not needed
)
configure URI rewriting
>>>
disableRobotsTxt -- for w3w robots.txt is not needed
)
, ao_uriConfig = UCFullIndex
}
where
editPackageURIs
= chgS theProcessRefs (>>> arr editTilde)
withCache' :: Int -> XIOSysState -> XIOSysState
withCache' sec = withCache "./cache" sec yes
-- ------------------------------------------------------------
type HIO = ReaderT AppOpts IO
main :: IO ()
main
= do pn <- getProgName
args <- getArgs
runReaderT main2 (evalOptions pn args)
-- ------------------------------------------------------------
main2 :: HIO ()
main2
= do (h, pn) <- asks (ao_help &&& ao_progname)
if h
then do msg <- asks ao_msg
liftIO $ do hPutStrLn stderr (msg ++ "\n" ++ usageInfo pn w3wOptDescr)
if null msg
then exitSuccess
else exitFailure
else do asks (snd . ao_crawlLog) >>= setLogLevel ""
a <- asks ao_action
case a of
BuildCache -> mainCache
BuildIx -> mainIndex
MergeIx -> mainMerge
liftIO $ exitSuccess
-- ------------------------------------------------------------
mainIndex :: HIO ()
mainIndex
= action
where
action
= do rs <- asks ao_resume
if isJust rs
then notice ["resume haddock document indexing"]
else return ()
indexPkg >>= writePartialRes
mainMerge :: HIO ()
mainMerge
= loadPartialIx >>= mergeAndWritePartialRes
where
loadPartialIx :: HIO [Int]
loadPartialIx
= local
(\ o -> o { ao_action = BuildIx })
(snd `fmap` indexPkg)
indexPkg :: HIO (W3WIndexerState, [Int])
indexPkg
= do notice ["indexing all w3w pages"]
getS (theResultAccu .&&&. theListOfDocsSaved) `fmap` w3wIndexer
mainCache :: HIO ()
mainCache
= do rs <- asks ao_resume
notice $ if isJust rs
then ["resume cache update"]
else ["cache w3w pages"]
w3wCacher >>= writeResults
-- ------------------------------------------------------------
w3wIndexer :: HIO W3WIndexerCrawlerState
w3wIndexer
= do o <- ask
liftIO $ stdIndexer
(config o)
(ao_resume o)
(w3wStart $ ao_uriConfig o)
emptyW3WState
where
config0 o
= indexCrawlerConfig
(ao_crawlPar o)
(w3wRefs $ ao_uriConfig o)
Nothing
(Just $ checkDocumentStatus >>> checkTransferStatus >>> preDocumentFilter)
(Just $ w3wGetTitle)
(Just $ w3wGetPageInfo)
(w3wIndexConfig)
config o
= ao_crawlFct o $
setCrawlerTraceLevel ct ht $
setCrawlerSaveConf si sp $
setCrawlerSaveAction partA $
setCrawlerMaxDocs md mp mt $
config0 $ o
where
xout = ao_xml o
(ct, ht) = ao_crawlLog o
si = ao_crawlSav o
sp = ao_crawlSfn o
(md, mp, mt) = ao_crawlDoc o
partA
| ao_partix o = writePartialIndex (not . null $ xout)
| otherwise = const $ return ()
-- ------------------------------------------------------------
checkTransferStatus :: IOSArrow XmlTree XmlTree
checkTransferStatus
= ( ( getAttrValue transferStatus
>>>
isA (== "200")
)
`guards` this
)
-- ------------------------------------------------------------
preDocumentFilter :: IOSArrow XmlTree XmlTree
preDocumentFilter
= choiceA
[ isHtmlContents :-> this -- do nothing
, isPdfContents :-> this -- extractPdfText is already done in readDocument
-- , isPdfContents :-> extractPdfText -- extract the text from a pdf
, this :-> replaceChildren none -- throw away any contents
]
extractPdfText :: IOSArrow XmlTree XmlTree
extractPdfText
= traceDoc "Indexer: extractPdfText: start"
>>>
processChildren ( deep getText >>> pdfToTextA >>> mkText )
>>>
traceDoc "Indexer: extractPdfText: result"
-- ------------------------------------------------------------
w3wCacher :: HIO CacheCrawlerState
w3wCacher
= do o <- ask
liftIO $ stdCacher
(ao_crawlDoc o)
(ao_crawlSav o, ao_crawlSfn o)
(ao_crawlLog o)
(ao_crawlPar o)
(ao_crawlCch o)
(ao_resume o)
(w3wStart $ ao_uriConfig o)
(w3wRefs $ ao_uriConfig o)
-- ------------------------------------------------------------
writePartialRes :: (W3WIndexerState, [Int]) -> HIO ()
writePartialRes (s, ps)
= do part <- asks ao_partix
if part
then mergeAndWritePartialRes ps
else writeRes s
where
writeRes s'
= writeSearchBin' s' >> writeResults s'
writeSearchBin' s'
= do out <- asks ao_ixsearch
writeSearchBin out s'
mergeAndWritePartialRes :: [Int] -> HIO ()
mergeAndWritePartialRes ps
= do pxs <- (\ fn -> map (mkTmpFile 10 fn) ps) `fmap` asks ao_crawlSfn
out <- asks ao_ixsearch
mergeAndWritePartialRes' id' pxs out
where
id' :: SmallDocuments PageInfo -> SmallDocuments PageInfo
id' = id
-- ------------------------------------------------------------
writeResults :: (XmlPickler a, Binary a) => a -> HIO ()
writeResults v
= do (xf, of') <- asks (ao_xml &&& (ao_ixout &&& ao_index))
writeXml xf v
writeBin (out of') v
where
out (bf, bi)
| null bf = bi
| otherwise = bf
-- ------------------------------------------------------------
notice :: MonadIO m => [String] -> m ()
notice = noticeC "w3w"
-- ------------------------------------------------------------
evalOptions :: String -> [String] -> AppOpts
evalOptions pn args
= foldl (.) (ef1 . ef2) opts $
initAppOpts { ao_progname = pn }
where
(opts, ns, es) = getOpt Permute w3wOptDescr args
ef1
| null es = id
| otherwise = \ x -> x { ao_help = True
, ao_msg = concat es
}
| otherwise = id
ef2
| null ns = id
| otherwise = \ x -> x { ao_help = True
, ao_msg = "wrong program arguments: " ++ unwords ns
}
-- ------------------------------------------------------------
w3wOptDescr :: [OptDescr (AppOpts -> AppOpts)]
w3wOptDescr
= [ Option "h?" ["help"]
( NoArg $
\ x -> x { ao_help = True }
)
"usage info"
, Option "" ["build-index"]
( NoArg $
\ x -> x { ao_crawlSfn = "./tmp/ix-" }
)
"build W3W index (default)"
, Option "" ["build-cache"]
( NoArg $
\ x -> x { ao_action = BuildCache }
)
"update the W3W cache"
, Option "" ["test-index"]
( NoArg $
\ x -> x { ao_uriConfig = UCTestIndex }
)
"build a small sub index of the fhw pages for testing"
, Option "" ["debug-index"]
( NoArg $
\ x -> x { ao_uriConfig = UCDebugIndex }
)
"build a small sub index of the fhw pages for testing"
, Option "i" ["index"]
( ReqArg
(\ f x -> x { ao_index = f })
"INDEX"
)
"index input file (binary format) to be operated on"
, Option "n" ["new-index"]
( ReqArg
(\ f x -> x { ao_ixout = f })
"NEW-INDEX"
)
"new index file (binary format) to be generatet, default is index file"
, Option "s" ["new-search"]
( ReqArg
(\ f x -> x { ao_ixsearch = f })
"SEARCH-INDEX"
)
"new search index files (binary format) ready to be used by W3W! search"
, Option "x" ["xml-output"]
( ReqArg
(\ f x -> x { ao_xml = f })
"XML-FILE"
)
"output of final crawler state in xml format, \"-\" for stdout"
, Option "r" ["resume"]
( ReqArg
(\ s x -> x { ao_resume = Just s})
"FILE"
)
"resume program with file containing saved intermediate state"
, Option "" ["maxdocs"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxDocs i $
ao_crawlDoc x }))
"NUMBER"
)
"maximum # of docs to be processed"
, Option "" ["maxthreads"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxThreads i $
ao_crawlDoc x }))
"NUMBER"
)
( "maximum # of parallel threads, 0: sequential, 1: " ++
"single thread with binary merge, else real parallel threads, default: 1" )
, Option "" ["maxpar"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxParDocs i $
ao_crawlDoc x }))
"NUMBER"
)
"maximum # of docs indexed at once before the results are inserted into index, default: 1024"
, Option "" ["valid"]
( ReqArg
(setOption parseTime (\ x t -> x { ao_crawlPar = setDocAge t $
ao_crawlPar x }))
"DURATION"
)
( "validate cache for pages older than given time, format: " ++
"10sec, 5min, 20hours, 3days, 5weeks, 1month, default is 1month" )
, Option "" ["partition"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_partix = True
, ao_crawlSav = i }))
"NUMBER"
)
( "partition the index into smaller chunks of given # of docs" ++
" and write the index part by part" )
, Option "" ["merge"]
( ReqArg
(\ s x -> x { ao_action = MergeIx
, ao_resume = Just s})
"FILE"
)
"merge chunks into final index, resume with latest crawler state"
, Option "" ["save"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlSav = i }))
"NUMBER"
)
"save intermediate results of index, default is 5000"
]
where
setOption parse f s x
= either (\ e -> x { ao_msg = e
, ao_help = True
}
) (f x) . parse $ s
-- ------------------------------------------------------------
parseInt :: String -> Either String Int
parseInt s
| match "[0-9]+" s = Right $ read s
| otherwise = Left $ "number expected in option arg"
parseTime :: String -> Either String Int
parseTime s
| match "[0-9]+(s(ec)?)?" s = Right $ t
| match "[0-9]+(m(in)?)?" s = Right $ t * 60
| match "[0-9]+(h(our(s)?)?)?" s = Right $ t * 60 * 60
| match "[0-9]+(d(ay(s)?)?)?" s = Right $ t * 60 * 60 * 24
| match "[0-9]+(w(eek(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 7
| match "[0-9]+(m(onth(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 30
| match "[0-9]+(y(ear(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 30 * 365
| otherwise = Left $ "error in duration format in option arg"
where
t = read . filter isDigit $ s
-- ------------------------------------------------------------
setMaxDocs :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxDocs md (_md, mp, mt) = (md, md `min` mp, mt)
setMaxParDocs :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxParDocs mp (md, _mp, mt) = (md, mp, mt)
setMaxThreads :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxThreads mt (md, mp, _mt) = (md, mp, mt)
setDocAge :: Int -> SysConfig -> SysConfig
setDocAge d = (>>> withCache' d)
-- ------------------------------------------------------------
| null | https://raw.githubusercontent.com/fortytools/holumbus/4b2f7b832feab2715a4d48be0b07dca018eaa8e8/W3W/src/W3WIndexer.hs | haskell | ------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
save intervall
save path
compress cache files
strict input of cache files
automatically follow redirects
for w3w robots.txt is not needed
for w3w robots.txt is not needed
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
do nothing
extractPdfText is already done in readDocument
, isPdfContents :-> extractPdfText -- extract the text from a pdf
throw away any contents
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------ | # OPTIONS #
module Main
where
import Codec.Compression.BZip ( compress, decompress )
import Control.Monad.Reader
import Data.Binary
import Data.Char
import Data.Function.Selector
import Data.Maybe
import IndexConfig
import IndexTypes
import PageInfo
import URIConfig
import Holumbus.Crawler
import Holumbus.Crawler.CacheCore
import Holumbus.Crawler.IndexerCore
import Holumbus.Crawler.PdfToText
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.IO
import Text.XML.HXT.Core
import Text.XML.HXT.Cache
import Text.XML.HXT.Curl
data AppAction
= BuildIx | BuildCache | MergeIx
deriving (Eq, Show)
data AppOpts
= AO
{ ao_progname :: String
, ao_index :: String
, ao_ixout :: String
, ao_ixsearch :: String
, ao_xml :: String
, ao_help :: Bool
, ao_action :: AppAction
, ao_defrag :: Bool
, ao_partix :: Bool
, ao_resume :: Maybe String
, ao_msg :: String
, ao_crawlDoc :: (Int, Int, Int)
, ao_crawlSav :: Int
, ao_crawlSfn :: String
, ao_crawlLog :: (Priority, Priority)
, ao_crawlPar :: SysConfig
, ao_crawlFct :: W3WIndexerConfig -> W3WIndexerConfig
, ao_crawlCch :: CacheCrawlerConfig -> CacheCrawlerConfig
, ao_uriConfig :: UriConfig
}
initAppOpts :: AppOpts
initAppOpts
= AO
{ ao_progname = "w3wIndexer"
, ao_index = ""
, ao_ixout = ""
, ao_ixsearch = ""
, ao_xml = ""
, ao_help = False
, ao_action = BuildIx
, ao_defrag = False
, ao_partix = False
, ao_resume = Nothing
, ao_msg = ""
max docs , par docs , threads : no parallel threads , but 1024 docs are indexed before results are inserted
log cache and hxt
set cache dir , cache remains valid 1 day , 404 pages are cached
>>>
>>>
>>>
withAcceptedMimeTypes [ text_html
, application_xhtml
, application_pdf
]
>>>
but limit # of redirects to 3
]
>>>
withRedirect no
>>>
withInputOption curl_max_filesize (show (1024 * 1024 * 3 `div` 2 ::Int))
this limit excludes automtically generated pages , sometimes > 1.5
>>>
withParseHTML no
>>>
withParseByMimeType yes
>>>
withMimeTypeHandler application_pdf extractPdfText
configure URI rewriting
>>>
)
configure URI rewriting
>>>
)
, ao_uriConfig = UCFullIndex
}
where
editPackageURIs
= chgS theProcessRefs (>>> arr editTilde)
withCache' :: Int -> XIOSysState -> XIOSysState
withCache' sec = withCache "./cache" sec yes
type HIO = ReaderT AppOpts IO
main :: IO ()
main
= do pn <- getProgName
args <- getArgs
runReaderT main2 (evalOptions pn args)
main2 :: HIO ()
main2
= do (h, pn) <- asks (ao_help &&& ao_progname)
if h
then do msg <- asks ao_msg
liftIO $ do hPutStrLn stderr (msg ++ "\n" ++ usageInfo pn w3wOptDescr)
if null msg
then exitSuccess
else exitFailure
else do asks (snd . ao_crawlLog) >>= setLogLevel ""
a <- asks ao_action
case a of
BuildCache -> mainCache
BuildIx -> mainIndex
MergeIx -> mainMerge
liftIO $ exitSuccess
mainIndex :: HIO ()
mainIndex
= action
where
action
= do rs <- asks ao_resume
if isJust rs
then notice ["resume haddock document indexing"]
else return ()
indexPkg >>= writePartialRes
mainMerge :: HIO ()
mainMerge
= loadPartialIx >>= mergeAndWritePartialRes
where
loadPartialIx :: HIO [Int]
loadPartialIx
= local
(\ o -> o { ao_action = BuildIx })
(snd `fmap` indexPkg)
indexPkg :: HIO (W3WIndexerState, [Int])
indexPkg
= do notice ["indexing all w3w pages"]
getS (theResultAccu .&&&. theListOfDocsSaved) `fmap` w3wIndexer
mainCache :: HIO ()
mainCache
= do rs <- asks ao_resume
notice $ if isJust rs
then ["resume cache update"]
else ["cache w3w pages"]
w3wCacher >>= writeResults
w3wIndexer :: HIO W3WIndexerCrawlerState
w3wIndexer
= do o <- ask
liftIO $ stdIndexer
(config o)
(ao_resume o)
(w3wStart $ ao_uriConfig o)
emptyW3WState
where
config0 o
= indexCrawlerConfig
(ao_crawlPar o)
(w3wRefs $ ao_uriConfig o)
Nothing
(Just $ checkDocumentStatus >>> checkTransferStatus >>> preDocumentFilter)
(Just $ w3wGetTitle)
(Just $ w3wGetPageInfo)
(w3wIndexConfig)
config o
= ao_crawlFct o $
setCrawlerTraceLevel ct ht $
setCrawlerSaveConf si sp $
setCrawlerSaveAction partA $
setCrawlerMaxDocs md mp mt $
config0 $ o
where
xout = ao_xml o
(ct, ht) = ao_crawlLog o
si = ao_crawlSav o
sp = ao_crawlSfn o
(md, mp, mt) = ao_crawlDoc o
partA
| ao_partix o = writePartialIndex (not . null $ xout)
| otherwise = const $ return ()
checkTransferStatus :: IOSArrow XmlTree XmlTree
checkTransferStatus
= ( ( getAttrValue transferStatus
>>>
isA (== "200")
)
`guards` this
)
preDocumentFilter :: IOSArrow XmlTree XmlTree
preDocumentFilter
= choiceA
]
extractPdfText :: IOSArrow XmlTree XmlTree
extractPdfText
= traceDoc "Indexer: extractPdfText: start"
>>>
processChildren ( deep getText >>> pdfToTextA >>> mkText )
>>>
traceDoc "Indexer: extractPdfText: result"
w3wCacher :: HIO CacheCrawlerState
w3wCacher
= do o <- ask
liftIO $ stdCacher
(ao_crawlDoc o)
(ao_crawlSav o, ao_crawlSfn o)
(ao_crawlLog o)
(ao_crawlPar o)
(ao_crawlCch o)
(ao_resume o)
(w3wStart $ ao_uriConfig o)
(w3wRefs $ ao_uriConfig o)
writePartialRes :: (W3WIndexerState, [Int]) -> HIO ()
writePartialRes (s, ps)
= do part <- asks ao_partix
if part
then mergeAndWritePartialRes ps
else writeRes s
where
writeRes s'
= writeSearchBin' s' >> writeResults s'
writeSearchBin' s'
= do out <- asks ao_ixsearch
writeSearchBin out s'
mergeAndWritePartialRes :: [Int] -> HIO ()
mergeAndWritePartialRes ps
= do pxs <- (\ fn -> map (mkTmpFile 10 fn) ps) `fmap` asks ao_crawlSfn
out <- asks ao_ixsearch
mergeAndWritePartialRes' id' pxs out
where
id' :: SmallDocuments PageInfo -> SmallDocuments PageInfo
id' = id
writeResults :: (XmlPickler a, Binary a) => a -> HIO ()
writeResults v
= do (xf, of') <- asks (ao_xml &&& (ao_ixout &&& ao_index))
writeXml xf v
writeBin (out of') v
where
out (bf, bi)
| null bf = bi
| otherwise = bf
notice :: MonadIO m => [String] -> m ()
notice = noticeC "w3w"
evalOptions :: String -> [String] -> AppOpts
evalOptions pn args
= foldl (.) (ef1 . ef2) opts $
initAppOpts { ao_progname = pn }
where
(opts, ns, es) = getOpt Permute w3wOptDescr args
ef1
| null es = id
| otherwise = \ x -> x { ao_help = True
, ao_msg = concat es
}
| otherwise = id
ef2
| null ns = id
| otherwise = \ x -> x { ao_help = True
, ao_msg = "wrong program arguments: " ++ unwords ns
}
w3wOptDescr :: [OptDescr (AppOpts -> AppOpts)]
w3wOptDescr
= [ Option "h?" ["help"]
( NoArg $
\ x -> x { ao_help = True }
)
"usage info"
, Option "" ["build-index"]
( NoArg $
\ x -> x { ao_crawlSfn = "./tmp/ix-" }
)
"build W3W index (default)"
, Option "" ["build-cache"]
( NoArg $
\ x -> x { ao_action = BuildCache }
)
"update the W3W cache"
, Option "" ["test-index"]
( NoArg $
\ x -> x { ao_uriConfig = UCTestIndex }
)
"build a small sub index of the fhw pages for testing"
, Option "" ["debug-index"]
( NoArg $
\ x -> x { ao_uriConfig = UCDebugIndex }
)
"build a small sub index of the fhw pages for testing"
, Option "i" ["index"]
( ReqArg
(\ f x -> x { ao_index = f })
"INDEX"
)
"index input file (binary format) to be operated on"
, Option "n" ["new-index"]
( ReqArg
(\ f x -> x { ao_ixout = f })
"NEW-INDEX"
)
"new index file (binary format) to be generatet, default is index file"
, Option "s" ["new-search"]
( ReqArg
(\ f x -> x { ao_ixsearch = f })
"SEARCH-INDEX"
)
"new search index files (binary format) ready to be used by W3W! search"
, Option "x" ["xml-output"]
( ReqArg
(\ f x -> x { ao_xml = f })
"XML-FILE"
)
"output of final crawler state in xml format, \"-\" for stdout"
, Option "r" ["resume"]
( ReqArg
(\ s x -> x { ao_resume = Just s})
"FILE"
)
"resume program with file containing saved intermediate state"
, Option "" ["maxdocs"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxDocs i $
ao_crawlDoc x }))
"NUMBER"
)
"maximum # of docs to be processed"
, Option "" ["maxthreads"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxThreads i $
ao_crawlDoc x }))
"NUMBER"
)
( "maximum # of parallel threads, 0: sequential, 1: " ++
"single thread with binary merge, else real parallel threads, default: 1" )
, Option "" ["maxpar"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlDoc = setMaxParDocs i $
ao_crawlDoc x }))
"NUMBER"
)
"maximum # of docs indexed at once before the results are inserted into index, default: 1024"
, Option "" ["valid"]
( ReqArg
(setOption parseTime (\ x t -> x { ao_crawlPar = setDocAge t $
ao_crawlPar x }))
"DURATION"
)
( "validate cache for pages older than given time, format: " ++
"10sec, 5min, 20hours, 3days, 5weeks, 1month, default is 1month" )
, Option "" ["partition"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_partix = True
, ao_crawlSav = i }))
"NUMBER"
)
( "partition the index into smaller chunks of given # of docs" ++
" and write the index part by part" )
, Option "" ["merge"]
( ReqArg
(\ s x -> x { ao_action = MergeIx
, ao_resume = Just s})
"FILE"
)
"merge chunks into final index, resume with latest crawler state"
, Option "" ["save"]
( ReqArg
(setOption parseInt (\ x i -> x { ao_crawlSav = i }))
"NUMBER"
)
"save intermediate results of index, default is 5000"
]
where
setOption parse f s x
= either (\ e -> x { ao_msg = e
, ao_help = True
}
) (f x) . parse $ s
parseInt :: String -> Either String Int
parseInt s
| match "[0-9]+" s = Right $ read s
| otherwise = Left $ "number expected in option arg"
parseTime :: String -> Either String Int
parseTime s
| match "[0-9]+(s(ec)?)?" s = Right $ t
| match "[0-9]+(m(in)?)?" s = Right $ t * 60
| match "[0-9]+(h(our(s)?)?)?" s = Right $ t * 60 * 60
| match "[0-9]+(d(ay(s)?)?)?" s = Right $ t * 60 * 60 * 24
| match "[0-9]+(w(eek(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 7
| match "[0-9]+(m(onth(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 30
| match "[0-9]+(y(ear(s)?)?)?" s = Right $ t * 60 * 60 * 24 * 30 * 365
| otherwise = Left $ "error in duration format in option arg"
where
t = read . filter isDigit $ s
setMaxDocs :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxDocs md (_md, mp, mt) = (md, md `min` mp, mt)
setMaxParDocs :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxParDocs mp (md, _mp, mt) = (md, mp, mt)
setMaxThreads :: Int -> (Int, Int, Int) -> (Int, Int, Int)
setMaxThreads mt (md, mp, _mt) = (md, mp, mt)
setDocAge :: Int -> SysConfig -> SysConfig
setDocAge d = (>>> withCache' d)
|
d9e99719e64c20740efbe1dffe07c28e702d8acb42c5fa4bd79754a6ee64fd9f | VictorNicollet/Ohm | main.ml | (* Include all tests... *)
module Run = Run
| null | https://raw.githubusercontent.com/VictorNicollet/Ohm/ca90c162f6c49927c893114491f29d44aaf71feb/test/main.ml | ocaml | Include all tests... |
module Run = Run
|
e1be7a49e2d0f8f90d3befd730a4fa10a333a28f6fbda74ba768242c138f622a | libguestfs/virt-v2v | parse_domain_from_vmx.ml | virt - v2v
* Copyright ( C ) 2017 - 2021 Red Hat Inc.
*
* 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. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2017-2021 Red Hat Inc.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
open Printf
open Scanf
open Std_utils
open Tools_utils
open Unix_utils
open Common_gettext.Gettext
open Types
open Utils
open Name_from_disk
type vmx_source =
local file or NFS
SSH URI
(* The single filename on the command line is intepreted either as
* a local file or a remote SSH URI (only if ‘-it ssh’).
*)
let vmx_source_of_arg input_transport arg =
match input_transport, arg with
| None, arg -> File arg
| Some `SSH, arg ->
let uri =
try Xml.parse_uri arg
with Invalid_argument _ ->
error (f_"remote vmx ‘%s’ could not be parsed as a URI") arg in
if uri.Xml.uri_scheme <> None && uri.Xml.uri_scheme <> Some "ssh" then
error (f_"vmx URI start with ‘ssh://...’");
if uri.Xml.uri_server = None then
error (f_"vmx URI remote server name omitted");
if uri.Xml.uri_path = None || uri.Xml.uri_path = Some "/" then
error (f_"vmx URI path component looks incorrect");
SSH uri
Return various fields from the URI . The checks in vmx_source_of_arg
* should ensure that none of these assertions fail .
* should ensure that none of these assertions fail.
*)
let port_of_uri { Xml.uri_port } =
match uri_port with i when i <= 0 -> None | i -> Some i
let server_of_uri { Xml.uri_server } =
match uri_server with None -> assert false | Some s -> s
let path_of_uri { Xml.uri_path } =
match uri_path with None -> assert false | Some p -> p
' ' a remote file into a temporary local file , returning the path
* of the temporary local file .
* of the temporary local file.
*)
let scp_from_remote_to_temporary uri tmpdir filename =
let localfile = tmpdir // filename in
let cmd =
sprintf "scp -T%s%s %s%s:%s %s"
(if verbose () then "" else " -q")
(match port_of_uri uri with
| None -> ""
| Some port -> sprintf " -P %d" port)
(match uri.Xml.uri_user with
| None -> ""
| Some user -> quote user ^ "@")
(quote (server_of_uri uri))
(quote (path_of_uri uri))
(quote localfile) in
if verbose () then
eprintf "%s\n%!" cmd;
if Sys.command cmd <> 0 then
error (f_"could not copy the VMX file from the remote server, \
see earlier error messages");
localfile
(* Test if [path] exists on the remote server. *)
let remote_file_exists uri path =
let cmd =
sprintf "ssh%s %s%s test -f %s"
(match port_of_uri uri with
| None -> ""
| Some port -> sprintf " -p %d" port)
(match uri.Xml.uri_user with
| None -> ""
| Some user -> quote user ^ "@")
(quote (server_of_uri uri))
(quote path) in
if verbose () then
eprintf "%s\n%!" cmd;
Sys.command cmd = 0
let rec find_disks vmx vmx_source =
(* Set the s_disk_id field to an incrementing number. *)
List.mapi
(fun i (source, filename) -> { source with s_disk_id = i }, filename)
(find_scsi_disks vmx vmx_source @
find_nvme_disks vmx vmx_source @
find_sata_disks vmx vmx_source @
find_ide_disks vmx vmx_source)
Find all SCSI hard disks .
*
* In the VMX file :
* scsi0.virtualDev = " pvscsi " # or may be " lsilogic " etc .
* scsi0:0.deviceType = " disk " | " plainDisk " | " rawDisk " | " scsi - hardDisk "
* | omitted
* scsi0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* scsi0.virtualDev = "pvscsi" # or may be "lsilogic" etc.
* scsi0:0.deviceType = "disk" | "plainDisk" | "rawDisk" | "scsi-hardDisk"
* | omitted
* scsi0:0.fileName = "guest.vmdk"
*)
and find_scsi_disks vmx vmx_source =
let get_scsi_controller_target ns =
sscanf ns "scsi%d:%d" (fun c t -> c, t)
in
let is_scsi_controller_target ns =
try ignore (get_scsi_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let scsi_device_types = [ Some "disk"; Some "plaindisk"; Some "rawdisk";
Some "scsi-harddisk"; None ] in
let scsi_controller = Source_SCSI in
find_hdds vmx vmx_source
get_scsi_controller_target is_scsi_controller_target
scsi_device_types scsi_controller
Find all hard disks .
*
* In the VMX file :
* nvme0.pcislotnumber = " 192 "
* nvme0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* nvme0.pcislotnumber = "192"
* nvme0:0.fileName = "guest.vmdk"
*)
and find_nvme_disks vmx vmx_source =
let get_nvme_controller_target ns =
sscanf ns "nvme%d:%d" (fun c t -> c, t)
in
let is_nvme_controller_target ns =
try ignore (get_nvme_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let nvme_device_types = [ None ] in
let nvme_controller = Source_NVME in
find_hdds vmx vmx_source
get_nvme_controller_target is_nvme_controller_target
nvme_device_types nvme_controller
Find all SATA hard disks .
*
* In the VMX file :
* = " 33 "
* sata0:3.fileName = " win2019_1.vmdk "
*
* The " deviceType " field must be absent ; that field is only used for various
* CD - ROM types .
*
* In the VMX file:
* sata0.pciSlotNumber = "33"
* sata0:3.fileName = "win2019_1.vmdk"
*
* The "deviceType" field must be absent; that field is only used for various
* CD-ROM types.
*)
and find_sata_disks vmx vmx_source =
let get_sata_controller_target ns =
sscanf ns "sata%d:%d" (fun c t -> c, t)
in
let is_sata_controller_target ns =
try ignore (get_sata_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let sata_device_types = [ None ] in
let sata_controller = Source_SATA in
find_hdds vmx vmx_source
get_sata_controller_target is_sata_controller_target
sata_device_types sata_controller
Find all IDE hard disks .
*
* In the VMX file :
* ide0:0.deviceType = " ata - hardDisk "
* ide0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* ide0:0.deviceType = "ata-hardDisk"
* ide0:0.fileName = "guest.vmdk"
*)
and find_ide_disks vmx vmx_source =
let get_ide_controller_target ns =
sscanf ns "ide%d:%d" (fun c t -> c, t)
in
let is_ide_controller_target ns =
try ignore (get_ide_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let ide_device_types = [ Some "ata-harddisk" ] in
let ide_controller = Source_IDE in
find_hdds vmx vmx_source
get_ide_controller_target is_ide_controller_target
ide_device_types ide_controller
and find_hdds vmx vmx_source
get_controller_target is_controller_target
device_types controller =
(* Find namespaces matching '(ide|scsi|nvme|sata)X:Y' with suitable
* deviceType.
*)
let hdds =
Parse_vmx.select_namespaces (
function
| [ns] ->
(* Check the namespace is '(ide|scsi|nvme|sata)X:Y' *)
if not (is_controller_target ns) then false
else (
(* Check the deviceType is one we are looking for. *)
let dt = Parse_vmx.get_string vmx [ns; "deviceType"] in
let dt = Option.map String.lowercase_ascii dt in
List.mem dt device_types
)
| _ -> false
) vmx in
(* Map the subset to a list of disks. *)
let hdds =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns; "filename"], Some filename ->
let c, t = get_controller_target ns in
let s = { s_disk_id = (-1); s_controller = Some controller } in
Some (c, t, s, filename)
| _ -> None
) hdds in
let hdds = List.filter_map identity hdds in
(* We don't have a way to return the controllers and targets, so
* just make sure the disks are sorted into order, since Parse_vmx
* won't return them in any particular order.
*)
let hdds = List.sort compare hdds in
List.map (fun (_, _, source, filename) -> source, filename) hdds
Find all removable disks .
*
* In the VMX file :
* ide1:0.deviceType = " cdrom - image "
* ide1:0.fileName = " boot.iso "
*
* XXX This only supports IDE CD - ROMs , but we could support SCSI CD - ROMs , SATA
* CD - ROMs , and floppies in future .
*
* In the VMX file:
* ide1:0.deviceType = "cdrom-image"
* ide1:0.fileName = "boot.iso"
*
* XXX This only supports IDE CD-ROMs, but we could support SCSI CD-ROMs, SATA
* CD-ROMs, and floppies in future.
*)
and find_removables vmx =
let get_ide_controller_target ns =
sscanf ns "ide%d:%d" (fun c t -> c, t)
in
let is_ide_controller_target ns =
try ignore (get_ide_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let device_types = [ "atapi-cdrom";
"cdrom-image"; "cdrom-raw" ] in
(* Find namespaces matching 'ideX:Y' with suitable deviceType. *)
let devs =
Parse_vmx.select_namespaces (
function
| [ns] ->
(* Check the namespace is 'ideX:Y' *)
if not (is_ide_controller_target ns) then false
else (
(* Check the deviceType is one we are looking for. *)
match Parse_vmx.get_string vmx [ns; "deviceType"] with
| Some str ->
let str = String.lowercase_ascii str in
List.mem str device_types
| None -> false
)
| _ -> false
) vmx in
(* Map the subset to a list of CD-ROMs. *)
let devs =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns], None ->
let c, t = get_ide_controller_target ns in
let s = { s_removable_type = CDROM;
s_removable_controller = Some Source_IDE;
s_removable_slot = Some (ide_slot c t) } in
Some s
| _ -> None
) devs in
let devs = List.filter_map identity devs in
(* Sort by slot. *)
let devs =
List.sort
(fun { s_removable_slot = s1 } { s_removable_slot = s2 } ->
compare s1 s2)
devs in
devs
and ide_slot c t =
(* Assuming the old master/slave arrangement. *)
c * 2 + t
Find all ethernet cards .
*
* In the VMX file :
* ethernet0.virtualDev = " vmxnet3 "
* ethernet0.networkName = " VM Network "
* ethernet0.generatedAddress = " 00:01:02:03:04:05 "
* ethernet0.connectionType = " bridged " # also : " custom " , " " or not present
*
* In the VMX file:
* ethernet0.virtualDev = "vmxnet3"
* ethernet0.networkName = "VM Network"
* ethernet0.generatedAddress = "00:01:02:03:04:05"
* ethernet0.connectionType = "bridged" # also: "custom", "nat" or not present
*)
and find_nics vmx =
let get_ethernet_port ns =
sscanf ns "ethernet%d" (fun p -> p)
in
let is_ethernet_port ns =
try ignore (get_ethernet_port ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
(* Find namespaces matching 'ethernetX'. *)
let nics =
Parse_vmx.select_namespaces (
function
| [ns] -> is_ethernet_port ns
| _ -> false
) vmx in
Map the subset to a list of NICs .
let nics =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns], None ->
let port = get_ethernet_port ns in
let mac = Parse_vmx.get_string vmx [ns; "generatedAddress"] in
let model = Parse_vmx.get_string vmx [ns; "virtualDev"] in
let model =
match model with
| Some m when String.lowercase_ascii m = "e1000" ->
Some Source_e1000
| Some model ->
Some (Source_other_nic (String.lowercase_ascii model))
| None -> None in
let vnet = Parse_vmx.get_string vmx [ns; "networkName"] in
let vnet =
match vnet with
| Some vnet -> vnet
| None -> ns (* "ethernetX" *) in
let vnet_type =
match Parse_vmx.get_string vmx [ns; "connectionType"] with
| Some b when String.lowercase_ascii b = "bridged" ->
Bridge
| Some _ | None -> Network in
Some (port,
{ s_mac = mac; s_nic_model = model;
s_vnet = vnet;
s_vnet_type = vnet_type })
| _ -> None
) nics in
let nics = List.filter_map identity nics in
(* Sort by port. *)
let nics = List.sort compare nics in
let nics = List.map (fun (_, source) -> source) nics in
nics
let parse_domain_from_vmx vmx_source =
let tmpdir =
let t = Mkdtemp.temp_dir "vmx." in
On_exit.rm_rf t;
t in
If the transport is SSH , fetch the file from remote , else
* parse it from local .
* parse it from local.
*)
let vmx =
match vmx_source with
| File filename -> Parse_vmx.parse_file filename
| SSH uri ->
let filename = scp_from_remote_to_temporary uri tmpdir "source.vmx" in
Parse_vmx.parse_file filename in
let name =
match Parse_vmx.get_string vmx ["displayName"] with
| Some s -> s
| None ->
warning (f_"no displayName key found in VMX file");
match vmx_source with
| File filename -> name_from_disk filename
| SSH uri -> name_from_disk (path_of_uri uri) in
let genid =
(* See: -devel/2018-07/msg02019.html *)
let genid_lo = Parse_vmx.get_int64 vmx ["vm"; "genid"]
and genid_hi = Parse_vmx.get_int64 vmx ["vm"; "genidX"] in
match genid_lo, genid_hi with
| None, None | Some _, None | None, Some _ ->
None
| Some lo, Some hi ->
(* See docs/vm-generation-id-across-hypervisors.txt *)
let sub = String.sub (sprintf "%016Lx%016Lx" lo hi) in
let uuid =
sub 8 8 ^ "-" ^
sub 4 4 ^ "-" ^
sub 0 4 ^ "-" ^
sub 30 2 ^ sub 28 2 ^ "-" ^
sub 26 2 ^ sub 24 2 ^ sub 22 2 ^ sub 20 2 ^ sub 18 2 ^ sub 16 2 in
Some uuid in
let memory_mb =
match Parse_vmx.get_int64 vmx ["memSize"] with
default is really 32 MB !
| Some i -> i in
let memory = memory_mb *^ 1024L *^ 1024L in
let vcpu =
match Parse_vmx.get_int vmx ["numvcpus"] with
| None -> 1
| Some i -> i in
let cpu_topology =
match Parse_vmx.get_int vmx ["cpuid"; "coresPerSocket"] with
| None -> None
| Some cores_per_socket ->
let sockets = vcpu / cores_per_socket in
if sockets <= 0 then (
warning (f_"invalid cpuid.coresPerSocket < number of vCPUs");
None
)
else
Some { s_cpu_sockets = sockets; s_cpu_cores = cores_per_socket;
s_cpu_threads = 1 } in
let firmware =
match Parse_vmx.get_string vmx ["firmware"] with
| None -> BIOS
| Some "efi" -> UEFI
(* Other values are not documented for this field ... *)
| Some fw ->
warning (f_"unknown firmware value '%s', assuming BIOS") fw;
BIOS in
let sound =
match Parse_vmx.get_string vmx ["sound"; "virtualDev"] with
| Some "sb16" -> Some { s_sound_model = SB16 }
| Some "es1371" -> Some { s_sound_model = ES1370 (* hmmm ... *) }
| Some "hdaudio" -> Some { s_sound_model = ICH6 (* intel-hda *) }
| Some model ->
warning (f_"unknown sound device '%s' ignored") model;
None
| None -> None in
let disks = find_disks vmx vmx_source in
let removables = find_removables vmx in
let nics = find_nics vmx in
let source = {
s_hypervisor = VMware;
s_name = name;
s_genid = genid;
s_memory = memory;
s_vcpu = vcpu;
s_cpu_vendor = None;
s_cpu_model = None;
s_cpu_topology = cpu_topology;
s_features = [];
s_firmware = firmware;
s_display = None;
s_sound = sound;
s_disks = List.map fst disks;
s_removables = removables;
s_nics = nics;
} in
source, List.map snd disks
| null | https://raw.githubusercontent.com/libguestfs/virt-v2v/d2b01e487ff4ef56d139a5e0f22efd9b2ed9b64c/input/parse_domain_from_vmx.ml | ocaml | The single filename on the command line is intepreted either as
* a local file or a remote SSH URI (only if ‘-it ssh’).
Test if [path] exists on the remote server.
Set the s_disk_id field to an incrementing number.
Find namespaces matching '(ide|scsi|nvme|sata)X:Y' with suitable
* deviceType.
Check the namespace is '(ide|scsi|nvme|sata)X:Y'
Check the deviceType is one we are looking for.
Map the subset to a list of disks.
We don't have a way to return the controllers and targets, so
* just make sure the disks are sorted into order, since Parse_vmx
* won't return them in any particular order.
Find namespaces matching 'ideX:Y' with suitable deviceType.
Check the namespace is 'ideX:Y'
Check the deviceType is one we are looking for.
Map the subset to a list of CD-ROMs.
Sort by slot.
Assuming the old master/slave arrangement.
Find namespaces matching 'ethernetX'.
"ethernetX"
Sort by port.
See: -devel/2018-07/msg02019.html
See docs/vm-generation-id-across-hypervisors.txt
Other values are not documented for this field ...
hmmm ...
intel-hda | virt - v2v
* Copyright ( C ) 2017 - 2021 Red Hat Inc.
*
* 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. ,
* 51 Franklin Street , Fifth Floor , Boston , USA .
* Copyright (C) 2017-2021 Red Hat Inc.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*)
open Printf
open Scanf
open Std_utils
open Tools_utils
open Unix_utils
open Common_gettext.Gettext
open Types
open Utils
open Name_from_disk
type vmx_source =
local file or NFS
SSH URI
let vmx_source_of_arg input_transport arg =
match input_transport, arg with
| None, arg -> File arg
| Some `SSH, arg ->
let uri =
try Xml.parse_uri arg
with Invalid_argument _ ->
error (f_"remote vmx ‘%s’ could not be parsed as a URI") arg in
if uri.Xml.uri_scheme <> None && uri.Xml.uri_scheme <> Some "ssh" then
error (f_"vmx URI start with ‘ssh://...’");
if uri.Xml.uri_server = None then
error (f_"vmx URI remote server name omitted");
if uri.Xml.uri_path = None || uri.Xml.uri_path = Some "/" then
error (f_"vmx URI path component looks incorrect");
SSH uri
Return various fields from the URI . The checks in vmx_source_of_arg
* should ensure that none of these assertions fail .
* should ensure that none of these assertions fail.
*)
let port_of_uri { Xml.uri_port } =
match uri_port with i when i <= 0 -> None | i -> Some i
let server_of_uri { Xml.uri_server } =
match uri_server with None -> assert false | Some s -> s
let path_of_uri { Xml.uri_path } =
match uri_path with None -> assert false | Some p -> p
' ' a remote file into a temporary local file , returning the path
* of the temporary local file .
* of the temporary local file.
*)
let scp_from_remote_to_temporary uri tmpdir filename =
let localfile = tmpdir // filename in
let cmd =
sprintf "scp -T%s%s %s%s:%s %s"
(if verbose () then "" else " -q")
(match port_of_uri uri with
| None -> ""
| Some port -> sprintf " -P %d" port)
(match uri.Xml.uri_user with
| None -> ""
| Some user -> quote user ^ "@")
(quote (server_of_uri uri))
(quote (path_of_uri uri))
(quote localfile) in
if verbose () then
eprintf "%s\n%!" cmd;
if Sys.command cmd <> 0 then
error (f_"could not copy the VMX file from the remote server, \
see earlier error messages");
localfile
let remote_file_exists uri path =
let cmd =
sprintf "ssh%s %s%s test -f %s"
(match port_of_uri uri with
| None -> ""
| Some port -> sprintf " -p %d" port)
(match uri.Xml.uri_user with
| None -> ""
| Some user -> quote user ^ "@")
(quote (server_of_uri uri))
(quote path) in
if verbose () then
eprintf "%s\n%!" cmd;
Sys.command cmd = 0
let rec find_disks vmx vmx_source =
List.mapi
(fun i (source, filename) -> { source with s_disk_id = i }, filename)
(find_scsi_disks vmx vmx_source @
find_nvme_disks vmx vmx_source @
find_sata_disks vmx vmx_source @
find_ide_disks vmx vmx_source)
Find all SCSI hard disks .
*
* In the VMX file :
* scsi0.virtualDev = " pvscsi " # or may be " lsilogic " etc .
* scsi0:0.deviceType = " disk " | " plainDisk " | " rawDisk " | " scsi - hardDisk "
* | omitted
* scsi0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* scsi0.virtualDev = "pvscsi" # or may be "lsilogic" etc.
* scsi0:0.deviceType = "disk" | "plainDisk" | "rawDisk" | "scsi-hardDisk"
* | omitted
* scsi0:0.fileName = "guest.vmdk"
*)
and find_scsi_disks vmx vmx_source =
let get_scsi_controller_target ns =
sscanf ns "scsi%d:%d" (fun c t -> c, t)
in
let is_scsi_controller_target ns =
try ignore (get_scsi_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let scsi_device_types = [ Some "disk"; Some "plaindisk"; Some "rawdisk";
Some "scsi-harddisk"; None ] in
let scsi_controller = Source_SCSI in
find_hdds vmx vmx_source
get_scsi_controller_target is_scsi_controller_target
scsi_device_types scsi_controller
Find all hard disks .
*
* In the VMX file :
* nvme0.pcislotnumber = " 192 "
* nvme0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* nvme0.pcislotnumber = "192"
* nvme0:0.fileName = "guest.vmdk"
*)
and find_nvme_disks vmx vmx_source =
let get_nvme_controller_target ns =
sscanf ns "nvme%d:%d" (fun c t -> c, t)
in
let is_nvme_controller_target ns =
try ignore (get_nvme_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let nvme_device_types = [ None ] in
let nvme_controller = Source_NVME in
find_hdds vmx vmx_source
get_nvme_controller_target is_nvme_controller_target
nvme_device_types nvme_controller
Find all SATA hard disks .
*
* In the VMX file :
* = " 33 "
* sata0:3.fileName = " win2019_1.vmdk "
*
* The " deviceType " field must be absent ; that field is only used for various
* CD - ROM types .
*
* In the VMX file:
* sata0.pciSlotNumber = "33"
* sata0:3.fileName = "win2019_1.vmdk"
*
* The "deviceType" field must be absent; that field is only used for various
* CD-ROM types.
*)
and find_sata_disks vmx vmx_source =
let get_sata_controller_target ns =
sscanf ns "sata%d:%d" (fun c t -> c, t)
in
let is_sata_controller_target ns =
try ignore (get_sata_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let sata_device_types = [ None ] in
let sata_controller = Source_SATA in
find_hdds vmx vmx_source
get_sata_controller_target is_sata_controller_target
sata_device_types sata_controller
Find all IDE hard disks .
*
* In the VMX file :
* ide0:0.deviceType = " ata - hardDisk "
* ide0:0.fileName = " guest.vmdk "
*
* In the VMX file:
* ide0:0.deviceType = "ata-hardDisk"
* ide0:0.fileName = "guest.vmdk"
*)
and find_ide_disks vmx vmx_source =
let get_ide_controller_target ns =
sscanf ns "ide%d:%d" (fun c t -> c, t)
in
let is_ide_controller_target ns =
try ignore (get_ide_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let ide_device_types = [ Some "ata-harddisk" ] in
let ide_controller = Source_IDE in
find_hdds vmx vmx_source
get_ide_controller_target is_ide_controller_target
ide_device_types ide_controller
and find_hdds vmx vmx_source
get_controller_target is_controller_target
device_types controller =
let hdds =
Parse_vmx.select_namespaces (
function
| [ns] ->
if not (is_controller_target ns) then false
else (
let dt = Parse_vmx.get_string vmx [ns; "deviceType"] in
let dt = Option.map String.lowercase_ascii dt in
List.mem dt device_types
)
| _ -> false
) vmx in
let hdds =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns; "filename"], Some filename ->
let c, t = get_controller_target ns in
let s = { s_disk_id = (-1); s_controller = Some controller } in
Some (c, t, s, filename)
| _ -> None
) hdds in
let hdds = List.filter_map identity hdds in
let hdds = List.sort compare hdds in
List.map (fun (_, _, source, filename) -> source, filename) hdds
Find all removable disks .
*
* In the VMX file :
* ide1:0.deviceType = " cdrom - image "
* ide1:0.fileName = " boot.iso "
*
* XXX This only supports IDE CD - ROMs , but we could support SCSI CD - ROMs , SATA
* CD - ROMs , and floppies in future .
*
* In the VMX file:
* ide1:0.deviceType = "cdrom-image"
* ide1:0.fileName = "boot.iso"
*
* XXX This only supports IDE CD-ROMs, but we could support SCSI CD-ROMs, SATA
* CD-ROMs, and floppies in future.
*)
and find_removables vmx =
let get_ide_controller_target ns =
sscanf ns "ide%d:%d" (fun c t -> c, t)
in
let is_ide_controller_target ns =
try ignore (get_ide_controller_target ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let device_types = [ "atapi-cdrom";
"cdrom-image"; "cdrom-raw" ] in
let devs =
Parse_vmx.select_namespaces (
function
| [ns] ->
if not (is_ide_controller_target ns) then false
else (
match Parse_vmx.get_string vmx [ns; "deviceType"] with
| Some str ->
let str = String.lowercase_ascii str in
List.mem str device_types
| None -> false
)
| _ -> false
) vmx in
let devs =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns], None ->
let c, t = get_ide_controller_target ns in
let s = { s_removable_type = CDROM;
s_removable_controller = Some Source_IDE;
s_removable_slot = Some (ide_slot c t) } in
Some s
| _ -> None
) devs in
let devs = List.filter_map identity devs in
let devs =
List.sort
(fun { s_removable_slot = s1 } { s_removable_slot = s2 } ->
compare s1 s2)
devs in
devs
and ide_slot c t =
c * 2 + t
Find all ethernet cards .
*
* In the VMX file :
* ethernet0.virtualDev = " vmxnet3 "
* ethernet0.networkName = " VM Network "
* ethernet0.generatedAddress = " 00:01:02:03:04:05 "
* ethernet0.connectionType = " bridged " # also : " custom " , " " or not present
*
* In the VMX file:
* ethernet0.virtualDev = "vmxnet3"
* ethernet0.networkName = "VM Network"
* ethernet0.generatedAddress = "00:01:02:03:04:05"
* ethernet0.connectionType = "bridged" # also: "custom", "nat" or not present
*)
and find_nics vmx =
let get_ethernet_port ns =
sscanf ns "ethernet%d" (fun p -> p)
in
let is_ethernet_port ns =
try ignore (get_ethernet_port ns); true
with Scanf.Scan_failure _ | End_of_file | Failure _ -> false
in
let nics =
Parse_vmx.select_namespaces (
function
| [ns] -> is_ethernet_port ns
| _ -> false
) vmx in
Map the subset to a list of NICs .
let nics =
Parse_vmx.map (
fun path v ->
match path, v with
| [ns], None ->
let port = get_ethernet_port ns in
let mac = Parse_vmx.get_string vmx [ns; "generatedAddress"] in
let model = Parse_vmx.get_string vmx [ns; "virtualDev"] in
let model =
match model with
| Some m when String.lowercase_ascii m = "e1000" ->
Some Source_e1000
| Some model ->
Some (Source_other_nic (String.lowercase_ascii model))
| None -> None in
let vnet = Parse_vmx.get_string vmx [ns; "networkName"] in
let vnet =
match vnet with
| Some vnet -> vnet
let vnet_type =
match Parse_vmx.get_string vmx [ns; "connectionType"] with
| Some b when String.lowercase_ascii b = "bridged" ->
Bridge
| Some _ | None -> Network in
Some (port,
{ s_mac = mac; s_nic_model = model;
s_vnet = vnet;
s_vnet_type = vnet_type })
| _ -> None
) nics in
let nics = List.filter_map identity nics in
let nics = List.sort compare nics in
let nics = List.map (fun (_, source) -> source) nics in
nics
let parse_domain_from_vmx vmx_source =
let tmpdir =
let t = Mkdtemp.temp_dir "vmx." in
On_exit.rm_rf t;
t in
If the transport is SSH , fetch the file from remote , else
* parse it from local .
* parse it from local.
*)
let vmx =
match vmx_source with
| File filename -> Parse_vmx.parse_file filename
| SSH uri ->
let filename = scp_from_remote_to_temporary uri tmpdir "source.vmx" in
Parse_vmx.parse_file filename in
let name =
match Parse_vmx.get_string vmx ["displayName"] with
| Some s -> s
| None ->
warning (f_"no displayName key found in VMX file");
match vmx_source with
| File filename -> name_from_disk filename
| SSH uri -> name_from_disk (path_of_uri uri) in
let genid =
let genid_lo = Parse_vmx.get_int64 vmx ["vm"; "genid"]
and genid_hi = Parse_vmx.get_int64 vmx ["vm"; "genidX"] in
match genid_lo, genid_hi with
| None, None | Some _, None | None, Some _ ->
None
| Some lo, Some hi ->
let sub = String.sub (sprintf "%016Lx%016Lx" lo hi) in
let uuid =
sub 8 8 ^ "-" ^
sub 4 4 ^ "-" ^
sub 0 4 ^ "-" ^
sub 30 2 ^ sub 28 2 ^ "-" ^
sub 26 2 ^ sub 24 2 ^ sub 22 2 ^ sub 20 2 ^ sub 18 2 ^ sub 16 2 in
Some uuid in
let memory_mb =
match Parse_vmx.get_int64 vmx ["memSize"] with
default is really 32 MB !
| Some i -> i in
let memory = memory_mb *^ 1024L *^ 1024L in
let vcpu =
match Parse_vmx.get_int vmx ["numvcpus"] with
| None -> 1
| Some i -> i in
let cpu_topology =
match Parse_vmx.get_int vmx ["cpuid"; "coresPerSocket"] with
| None -> None
| Some cores_per_socket ->
let sockets = vcpu / cores_per_socket in
if sockets <= 0 then (
warning (f_"invalid cpuid.coresPerSocket < number of vCPUs");
None
)
else
Some { s_cpu_sockets = sockets; s_cpu_cores = cores_per_socket;
s_cpu_threads = 1 } in
let firmware =
match Parse_vmx.get_string vmx ["firmware"] with
| None -> BIOS
| Some "efi" -> UEFI
| Some fw ->
warning (f_"unknown firmware value '%s', assuming BIOS") fw;
BIOS in
let sound =
match Parse_vmx.get_string vmx ["sound"; "virtualDev"] with
| Some "sb16" -> Some { s_sound_model = SB16 }
| Some model ->
warning (f_"unknown sound device '%s' ignored") model;
None
| None -> None in
let disks = find_disks vmx vmx_source in
let removables = find_removables vmx in
let nics = find_nics vmx in
let source = {
s_hypervisor = VMware;
s_name = name;
s_genid = genid;
s_memory = memory;
s_vcpu = vcpu;
s_cpu_vendor = None;
s_cpu_model = None;
s_cpu_topology = cpu_topology;
s_features = [];
s_firmware = firmware;
s_display = None;
s_sound = sound;
s_disks = List.map fst disks;
s_removables = removables;
s_nics = nics;
} in
source, List.map snd disks
|
87a641ff9cc6c9f723349144a290377b39d7af2d06e489e4ad1886ba5eff9c4a | ericfinster/minitt | Skel.hs | module Core.Skel where
Haskell module generated by the BNF converter
import Core.Abs
import Core.ErrM
type Result = Err String
failure :: Show a => a -> Result
failure x = Bad $ "Undefined case: " ++ show x
transIdent :: Ident -> Result
transIdent x = case x of
Ident str -> failure x
transCaseTk :: CaseTk -> Result
transCaseTk x = case x of
CaseTk str -> failure x
transDataTk :: DataTk -> Result
transDataTk x = case x of
DataTk str -> failure x
transExp :: Exp -> Result
transExp x = case x of
ELam patt exp -> failure x
ESet -> failure x
EPi patt exp0 exp -> failure x
ESig patt exp0 exp -> failure x
EOne -> failure x
Eunit -> failure x
EPair exp0 exp -> failure x
ECon id exp -> failure x
EData datatk summands -> failure x
ECase casetk branchs -> failure x
EFst exp -> failure x
ESnd exp -> failure x
EApp exp0 exp -> failure x
EVar id -> failure x
EVoid -> failure x
EDec decl exp -> failure x
EPN -> failure x
transDecl :: Decl -> Result
transDecl x = case x of
Def patt exp0 exp -> failure x
Drec patt exp0 exp -> failure x
transPatt :: Patt -> Result
transPatt x = case x of
PPair patt0 patt -> failure x
Punit -> failure x
PVar id -> failure x
transSummand :: Summand -> Result
transSummand x = case x of
Summand id exp -> failure x
transBranch :: Branch -> Result
transBranch x = case x of
Branch id exp -> failure x
| null | https://raw.githubusercontent.com/ericfinster/minitt/19ac0bfa4d1742efb06627f6a9590f601d6f9ecb/src/main/haskell/Core/Skel.hs | haskell | module Core.Skel where
Haskell module generated by the BNF converter
import Core.Abs
import Core.ErrM
type Result = Err String
failure :: Show a => a -> Result
failure x = Bad $ "Undefined case: " ++ show x
transIdent :: Ident -> Result
transIdent x = case x of
Ident str -> failure x
transCaseTk :: CaseTk -> Result
transCaseTk x = case x of
CaseTk str -> failure x
transDataTk :: DataTk -> Result
transDataTk x = case x of
DataTk str -> failure x
transExp :: Exp -> Result
transExp x = case x of
ELam patt exp -> failure x
ESet -> failure x
EPi patt exp0 exp -> failure x
ESig patt exp0 exp -> failure x
EOne -> failure x
Eunit -> failure x
EPair exp0 exp -> failure x
ECon id exp -> failure x
EData datatk summands -> failure x
ECase casetk branchs -> failure x
EFst exp -> failure x
ESnd exp -> failure x
EApp exp0 exp -> failure x
EVar id -> failure x
EVoid -> failure x
EDec decl exp -> failure x
EPN -> failure x
transDecl :: Decl -> Result
transDecl x = case x of
Def patt exp0 exp -> failure x
Drec patt exp0 exp -> failure x
transPatt :: Patt -> Result
transPatt x = case x of
PPair patt0 patt -> failure x
Punit -> failure x
PVar id -> failure x
transSummand :: Summand -> Result
transSummand x = case x of
Summand id exp -> failure x
transBranch :: Branch -> Result
transBranch x = case x of
Branch id exp -> failure x
|
|
c95d4b58b449f9384d7799bd9f6d1cfdd4712646ce7ef40096d5f5881310b033 | wireapp/wire-server | NewTeamMember_team.hs | # LANGUAGE OverloadedLists #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , 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 Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Test.Wire.API.Golden.Generated.NewTeamMember_team where
import Data.Id (Id (Id))
import Data.Json.Util (readUTCTimeMillis)
import qualified Data.UUID as UUID (fromString)
import GHC.Exts (IsList (fromList))
import Imports (Maybe (Just, Nothing), fromJust)
import Wire.API.Team.Member (NewTeamMember, mkNewTeamMember)
import Wire.API.Team.Permission
( Perm
( AddTeamMember,
CreateConversation,
DeleteTeam,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedDeleteConversation,
DoNotUseDeprecatedModifyConvName,
GetBilling,
GetMemberPermissions,
GetTeamConversations,
RemoveTeamMember,
SetBilling,
SetMemberPermissions,
SetTeamData
),
Permissions (Permissions, _copy, _self),
)
testObject_NewTeamMember_team_1 :: NewTeamMember
testObject_NewTeamMember_team_1 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0007-0000-000200000002")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000100000004")),
fromJust (readUTCTimeMillis "1864-05-04T12:59:54.182Z")
)
)
testObject_NewTeamMember_team_2 :: NewTeamMember
testObject_NewTeamMember_team_2 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000004-0000-0000-0000-000200000003")))
( Permissions
{ _self =
fromList
[ CreateConversation,
DoNotUseDeprecatedDeleteConversation,
AddTeamMember,
RemoveTeamMember,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedModifyConvName
],
_copy = fromList [DoNotUseDeprecatedDeleteConversation, DoNotUseDeprecatedAddRemoveConvMember]
}
)
( Just
( Id (fromJust (UUID.fromString "00000003-0000-0000-0000-000500000008")),
fromJust (readUTCTimeMillis "1864-05-16T00:49:15.576Z")
)
)
testObject_NewTeamMember_team_3 :: NewTeamMember
testObject_NewTeamMember_team_3 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0008-0000-000700000005")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, RemoveTeamMember, GetBilling, DeleteTeam],
_copy = fromList [CreateConversation, DoNotUseDeprecatedDeleteConversation, GetBilling]
}
)
( Just
( Id (fromJust (UUID.fromString "00000005-0000-0004-0000-000500000002")),
fromJust (readUTCTimeMillis "1864-05-08T07:57:50.660Z")
)
)
testObject_NewTeamMember_team_4 :: NewTeamMember
testObject_NewTeamMember_team_4 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0001-0000-000700000005")))
( Permissions
{ _self = fromList [CreateConversation, AddTeamMember, SetTeamData],
_copy = fromList [CreateConversation, SetTeamData]
}
)
Nothing
testObject_NewTeamMember_team_5 :: NewTeamMember
testObject_NewTeamMember_team_5 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000002")))
(Permissions {_self = fromList [AddTeamMember, SetBilling, GetTeamConversations], _copy = fromList [AddTeamMember]})
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000600000006")),
fromJust (readUTCTimeMillis "1864-05-12T23:29:05.832Z")
)
)
testObject_NewTeamMember_team_6 :: NewTeamMember
testObject_NewTeamMember_team_6 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0006-0000-000400000003")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, GetBilling, SetTeamData, SetMemberPermissions],
_copy = fromList [CreateConversation, GetBilling]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0001-0000-000800000003")),
fromJust (readUTCTimeMillis "1864-05-16T01:49:44.477Z")
)
)
testObject_NewTeamMember_team_7 :: NewTeamMember
testObject_NewTeamMember_team_7 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000007-0000-0004-0000-000500000005")))
( Permissions
{ _self =
fromList
[AddTeamMember, RemoveTeamMember, DoNotUseDeprecatedModifyConvName, GetTeamConversations, DeleteTeam],
_copy = fromList [AddTeamMember]
}
)
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0005-0000-000000000007")),
fromJust (readUTCTimeMillis "1864-05-08T14:17:14.531Z")
)
)
testObject_NewTeamMember_team_8 :: NewTeamMember
testObject_NewTeamMember_team_8 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0003-0000-000200000003")))
( Permissions
{ _self = fromList [DoNotUseDeprecatedModifyConvName],
_copy = fromList [DoNotUseDeprecatedModifyConvName]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0000-0000-000200000002")),
fromJust (readUTCTimeMillis "1864-05-16T06:33:31.445Z")
)
)
testObject_NewTeamMember_team_9 :: NewTeamMember
testObject_NewTeamMember_team_9 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0008-0000-000300000004")))
(Permissions {_self = fromList [SetBilling], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000002-0000-0001-0000-000700000000")),
fromJust (readUTCTimeMillis "1864-05-08T10:27:23.240Z")
)
)
testObject_NewTeamMember_team_10 :: NewTeamMember
testObject_NewTeamMember_team_10 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0003-0000-000600000003")))
(Permissions {_self = fromList [GetBilling], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000004-0000-0006-0000-000600000008")),
fromJust (readUTCTimeMillis "1864-05-15T10:49:54.418Z")
)
)
testObject_NewTeamMember_team_11 :: NewTeamMember
testObject_NewTeamMember_team_11 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000006-0000-0005-0000-000000000002")))
( Permissions
{ _self = fromList [CreateConversation, DoNotUseDeprecatedModifyConvName, SetTeamData],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000002-0000-0003-0000-000800000002")),
fromJust (readUTCTimeMillis "1864-05-14T12:23:51.061Z")
)
)
testObject_NewTeamMember_team_12 :: NewTeamMember
testObject_NewTeamMember_team_12 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0004-0000-000000000007")))
(Permissions {_self = fromList [SetBilling, SetTeamData, GetTeamConversations], _copy = fromList []})
Nothing
testObject_NewTeamMember_team_13 :: NewTeamMember
testObject_NewTeamMember_team_13 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0004-0000-000600000001")))
( Permissions
{ _self = fromList [AddTeamMember, DoNotUseDeprecatedAddRemoveConvMember, SetTeamData, GetTeamConversations],
_copy = fromList [AddTeamMember, DoNotUseDeprecatedAddRemoveConvMember, GetTeamConversations]
}
)
Nothing
testObject_NewTeamMember_team_14 :: NewTeamMember
testObject_NewTeamMember_team_14 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000500000004")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, DoNotUseDeprecatedModifyConvName, GetBilling],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0008-0000-000000000003")),
fromJust (readUTCTimeMillis "1864-05-16T00:23:45.641Z")
)
)
testObject_NewTeamMember_team_15 :: NewTeamMember
testObject_NewTeamMember_team_15 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0008-0000-000800000007")))
( Permissions
{ _self = fromList [RemoveTeamMember, GetMemberPermissions, DeleteTeam],
_copy = fromList [RemoveTeamMember, GetMemberPermissions]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0004-0000-000300000006")),
fromJust (readUTCTimeMillis "1864-05-02T08:10:15.332Z")
)
)
testObject_NewTeamMember_team_16 :: NewTeamMember
testObject_NewTeamMember_team_16 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0006-0000-000300000005")))
( Permissions
{ _self = fromList [CreateConversation, RemoveTeamMember, GetBilling, GetTeamConversations, DeleteTeam],
_copy = fromList []
}
)
Nothing
testObject_NewTeamMember_team_17 :: NewTeamMember
testObject_NewTeamMember_team_17 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0008-0000-000400000005")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000004-0000-0008-0000-000800000007")),
fromJust (readUTCTimeMillis "1864-05-07T21:53:30.897Z")
)
)
testObject_NewTeamMember_team_18 :: NewTeamMember
testObject_NewTeamMember_team_18 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000006-0000-0003-0000-000000000001")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000500000002")),
fromJust (readUTCTimeMillis "1864-05-11T12:32:01.417Z")
)
)
testObject_NewTeamMember_team_19 :: NewTeamMember
testObject_NewTeamMember_team_19 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000004-0000-0005-0000-000100000008")))
( Permissions
{ _self = fromList [DoNotUseDeprecatedDeleteConversation, RemoveTeamMember, SetBilling, SetMemberPermissions],
_copy = fromList [DoNotUseDeprecatedDeleteConversation, SetBilling]
}
)
Nothing
testObject_NewTeamMember_team_20 :: NewTeamMember
testObject_NewTeamMember_team_20 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000000000004")))
( Permissions
{ _self =
fromList
[ AddTeamMember,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedModifyConvName,
SetBilling,
GetMemberPermissions,
GetTeamConversations
],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000400000008")),
fromJust (readUTCTimeMillis "1864-05-05T07:36:25.213Z")
)
)
| null | https://raw.githubusercontent.com/wireapp/wire-server/c428355b7683b7b7722ea544eba314fc843ad8fa/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/NewTeamMember_team.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
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 Affero General Public License for more
details.
with this program. If not, see </>. | # LANGUAGE OverloadedLists #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Test.Wire.API.Golden.Generated.NewTeamMember_team where
import Data.Id (Id (Id))
import Data.Json.Util (readUTCTimeMillis)
import qualified Data.UUID as UUID (fromString)
import GHC.Exts (IsList (fromList))
import Imports (Maybe (Just, Nothing), fromJust)
import Wire.API.Team.Member (NewTeamMember, mkNewTeamMember)
import Wire.API.Team.Permission
( Perm
( AddTeamMember,
CreateConversation,
DeleteTeam,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedDeleteConversation,
DoNotUseDeprecatedModifyConvName,
GetBilling,
GetMemberPermissions,
GetTeamConversations,
RemoveTeamMember,
SetBilling,
SetMemberPermissions,
SetTeamData
),
Permissions (Permissions, _copy, _self),
)
testObject_NewTeamMember_team_1 :: NewTeamMember
testObject_NewTeamMember_team_1 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0007-0000-000200000002")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000100000004")),
fromJust (readUTCTimeMillis "1864-05-04T12:59:54.182Z")
)
)
testObject_NewTeamMember_team_2 :: NewTeamMember
testObject_NewTeamMember_team_2 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000004-0000-0000-0000-000200000003")))
( Permissions
{ _self =
fromList
[ CreateConversation,
DoNotUseDeprecatedDeleteConversation,
AddTeamMember,
RemoveTeamMember,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedModifyConvName
],
_copy = fromList [DoNotUseDeprecatedDeleteConversation, DoNotUseDeprecatedAddRemoveConvMember]
}
)
( Just
( Id (fromJust (UUID.fromString "00000003-0000-0000-0000-000500000008")),
fromJust (readUTCTimeMillis "1864-05-16T00:49:15.576Z")
)
)
testObject_NewTeamMember_team_3 :: NewTeamMember
testObject_NewTeamMember_team_3 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0008-0000-000700000005")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, RemoveTeamMember, GetBilling, DeleteTeam],
_copy = fromList [CreateConversation, DoNotUseDeprecatedDeleteConversation, GetBilling]
}
)
( Just
( Id (fromJust (UUID.fromString "00000005-0000-0004-0000-000500000002")),
fromJust (readUTCTimeMillis "1864-05-08T07:57:50.660Z")
)
)
testObject_NewTeamMember_team_4 :: NewTeamMember
testObject_NewTeamMember_team_4 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0001-0000-000700000005")))
( Permissions
{ _self = fromList [CreateConversation, AddTeamMember, SetTeamData],
_copy = fromList [CreateConversation, SetTeamData]
}
)
Nothing
testObject_NewTeamMember_team_5 :: NewTeamMember
testObject_NewTeamMember_team_5 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000002")))
(Permissions {_self = fromList [AddTeamMember, SetBilling, GetTeamConversations], _copy = fromList [AddTeamMember]})
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000600000006")),
fromJust (readUTCTimeMillis "1864-05-12T23:29:05.832Z")
)
)
testObject_NewTeamMember_team_6 :: NewTeamMember
testObject_NewTeamMember_team_6 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0006-0000-000400000003")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, GetBilling, SetTeamData, SetMemberPermissions],
_copy = fromList [CreateConversation, GetBilling]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0001-0000-000800000003")),
fromJust (readUTCTimeMillis "1864-05-16T01:49:44.477Z")
)
)
testObject_NewTeamMember_team_7 :: NewTeamMember
testObject_NewTeamMember_team_7 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000007-0000-0004-0000-000500000005")))
( Permissions
{ _self =
fromList
[AddTeamMember, RemoveTeamMember, DoNotUseDeprecatedModifyConvName, GetTeamConversations, DeleteTeam],
_copy = fromList [AddTeamMember]
}
)
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0005-0000-000000000007")),
fromJust (readUTCTimeMillis "1864-05-08T14:17:14.531Z")
)
)
testObject_NewTeamMember_team_8 :: NewTeamMember
testObject_NewTeamMember_team_8 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0003-0000-000200000003")))
( Permissions
{ _self = fromList [DoNotUseDeprecatedModifyConvName],
_copy = fromList [DoNotUseDeprecatedModifyConvName]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0000-0000-000200000002")),
fromJust (readUTCTimeMillis "1864-05-16T06:33:31.445Z")
)
)
testObject_NewTeamMember_team_9 :: NewTeamMember
testObject_NewTeamMember_team_9 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0008-0000-000300000004")))
(Permissions {_self = fromList [SetBilling], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000002-0000-0001-0000-000700000000")),
fromJust (readUTCTimeMillis "1864-05-08T10:27:23.240Z")
)
)
testObject_NewTeamMember_team_10 :: NewTeamMember
testObject_NewTeamMember_team_10 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0003-0000-000600000003")))
(Permissions {_self = fromList [GetBilling], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000004-0000-0006-0000-000600000008")),
fromJust (readUTCTimeMillis "1864-05-15T10:49:54.418Z")
)
)
testObject_NewTeamMember_team_11 :: NewTeamMember
testObject_NewTeamMember_team_11 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000006-0000-0005-0000-000000000002")))
( Permissions
{ _self = fromList [CreateConversation, DoNotUseDeprecatedModifyConvName, SetTeamData],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000002-0000-0003-0000-000800000002")),
fromJust (readUTCTimeMillis "1864-05-14T12:23:51.061Z")
)
)
testObject_NewTeamMember_team_12 :: NewTeamMember
testObject_NewTeamMember_team_12 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0004-0000-000000000007")))
(Permissions {_self = fromList [SetBilling, SetTeamData, GetTeamConversations], _copy = fromList []})
Nothing
testObject_NewTeamMember_team_13 :: NewTeamMember
testObject_NewTeamMember_team_13 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000002-0000-0004-0000-000600000001")))
( Permissions
{ _self = fromList [AddTeamMember, DoNotUseDeprecatedAddRemoveConvMember, SetTeamData, GetTeamConversations],
_copy = fromList [AddTeamMember, DoNotUseDeprecatedAddRemoveConvMember, GetTeamConversations]
}
)
Nothing
testObject_NewTeamMember_team_14 :: NewTeamMember
testObject_NewTeamMember_team_14 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000500000004")))
( Permissions
{ _self =
fromList
[CreateConversation, DoNotUseDeprecatedDeleteConversation, DoNotUseDeprecatedModifyConvName, GetBilling],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0008-0000-000000000003")),
fromJust (readUTCTimeMillis "1864-05-16T00:23:45.641Z")
)
)
testObject_NewTeamMember_team_15 :: NewTeamMember
testObject_NewTeamMember_team_15 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0008-0000-000800000007")))
( Permissions
{ _self = fromList [RemoveTeamMember, GetMemberPermissions, DeleteTeam],
_copy = fromList [RemoveTeamMember, GetMemberPermissions]
}
)
( Just
( Id (fromJust (UUID.fromString "00000006-0000-0004-0000-000300000006")),
fromJust (readUTCTimeMillis "1864-05-02T08:10:15.332Z")
)
)
testObject_NewTeamMember_team_16 :: NewTeamMember
testObject_NewTeamMember_team_16 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0006-0000-000300000005")))
( Permissions
{ _self = fromList [CreateConversation, RemoveTeamMember, GetBilling, GetTeamConversations, DeleteTeam],
_copy = fromList []
}
)
Nothing
testObject_NewTeamMember_team_17 :: NewTeamMember
testObject_NewTeamMember_team_17 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000000-0000-0008-0000-000400000005")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000004-0000-0008-0000-000800000007")),
fromJust (readUTCTimeMillis "1864-05-07T21:53:30.897Z")
)
)
testObject_NewTeamMember_team_18 :: NewTeamMember
testObject_NewTeamMember_team_18 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000006-0000-0003-0000-000000000001")))
(Permissions {_self = fromList [], _copy = fromList []})
( Just
( Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000500000002")),
fromJust (readUTCTimeMillis "1864-05-11T12:32:01.417Z")
)
)
testObject_NewTeamMember_team_19 :: NewTeamMember
testObject_NewTeamMember_team_19 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000004-0000-0005-0000-000100000008")))
( Permissions
{ _self = fromList [DoNotUseDeprecatedDeleteConversation, RemoveTeamMember, SetBilling, SetMemberPermissions],
_copy = fromList [DoNotUseDeprecatedDeleteConversation, SetBilling]
}
)
Nothing
testObject_NewTeamMember_team_20 :: NewTeamMember
testObject_NewTeamMember_team_20 =
mkNewTeamMember
(Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000000000004")))
( Permissions
{ _self =
fromList
[ AddTeamMember,
DoNotUseDeprecatedAddRemoveConvMember,
DoNotUseDeprecatedModifyConvName,
SetBilling,
GetMemberPermissions,
GetTeamConversations
],
_copy = fromList []
}
)
( Just
( Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000400000008")),
fromJust (readUTCTimeMillis "1864-05-05T07:36:25.213Z")
)
)
|
5d597535b726dd680c6513442c4eb4b54656a40e3249038e27c9dbb6ed5c9df8 | mgritter/aoc-lh | Main.hs | module Main (main) where
import LoadLines
import Data.Maybe
import Data.List (foldl')
import Data.List.Split
data Stack =
Empty |
Box String Stack
{-@ measure empty @-}
empty :: Stack -> Bool
empty Empty = True
empty _ = False
{-@ top :: {s:Stack | not empty s} -> String @-}
top :: Stack -> String
top (Box x _) = x
{-@ pop :: {s:Stack | not empty s} -> Stack @-}
pop :: Stack -> Stack
pop (Box _ y) = y
{-@ push :: String -> Stack -> Stack @-}
push :: String -> Stack -> Stack
push item stack = Box item stack
@ data Cargo = Stacks { numStacks : : ,
stacks : : { s:[Stack ] | len s = numStacks } }
@
stacks :: {s:[Stack] | len s = numStacks} }
@-}
data Cargo =
Stacks { numStacks :: Int
, stacks :: [Stack] }
@ type InRange c = { i : Int | 1 < = i & & i < = numStacks c } @
-- FIXME: how can we prove that stacks !! i is the only thing that changed
-- in c2 compared with c?
{-@ replaceStack :: c:Cargo -> pos:InRange c
-> s:Stack -> {c2:Cargo | numStacks c2 = numStacks c} @-}
replaceStack :: Cargo -> Int -> Stack -> Cargo
replaceStack c position newstack =
let oldstacks = stacks c in
Stacks { numStacks = numStacks c,
stacks = (take (position - 1) oldstacks) ++ [newstack] ++ (drop position oldstacks ) }
@ pickUp : : c : Cargo - > pos : Int - > Maybe ( String , Cargo ) @
pickUp :: Cargo -> Int -> Maybe (String, Cargo)
pickUp c position | position > numStacks c = Nothing
pickUp c position | position <= 0 = Nothing
pickUp c position = let s = (stacks c) !! (position - 1) in
if empty s then Nothing
else Just (top s, replaceStack c position (pop s))
{-@ place :: c:Cargo -> pos:Int -> String -> Maybe Cargo @-}
place :: Cargo -> Int -> String -> Maybe Cargo
place c position label | position > numStacks c = Nothing
place c position label | position <= 0 = Nothing
place c position label = let s = (stacks c) !! (position - 1) in
Just $ replaceStack c position (push label s)
{-@ topBoxes :: Cargo -> String @-}
topBoxes :: Cargo -> String
topBoxes c = concat $ map topOrNull (stacks c)
where topOrNull s = if empty s then "" else top s
@ data Operation = Move { numBoxes : : { n : Int | n > = 1 } ,
fromStack : : { n : Int | n > = 1 } ,
toStack : : { n : Int | n > = 1 } } @
fromStack :: {n:Int | n >= 1},
toStack :: {n:Int | n >= 1} } @-}
data Operation =
Move { numBoxes :: Int
, fromStack :: Int
, toStack :: Int }
parseOperation :: String -> Maybe Operation
parseOperation s = let tokens = splitOneOf " " s in
if length tokens /= 6 then Nothing else
let nb = (read (tokens !! 1))
fs = (read (tokens !! 3))
ts = (read (tokens !! 5)) in
if nb >= 1 && fs >= 1 && ts >= 1 then
Just $ Move nb fs ts
else
Nothing
applySingle :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applySingle Nothing _ = Nothing
applySingle _ Nothing = Nothing
applySingle (Just c) (Just op) = case (pickUp c (fromStack op)) of
Nothing -> Nothing
Just (item, c') -> (place c' (toStack op) item)
applyOperation :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applyOperation Nothing _ = Nothing
applyOperation _ Nothing = Nothing
applyOperation (Just c) (Just op) = foldl' applySingle (Just c) (replicate (numBoxes op) (Just op))
-- Boxes are returned top-first: [A,B,C]
{-@ pickUpN :: c:Cargo -> pos:Int -> {num:Int | num >= 0} ->
Maybe ({boxes:[String] | len boxes = num}, Cargo) / [num] @-}
pickUpN :: Cargo -> Int -> Int -> Maybe ([String], Cargo)
pickUpN c position _ | position > numStacks c = Nothing
pickUpN c position _ | position <= 0 = Nothing
pickUpN c position 0 = Just ([], c)
pickUpN c position num =
let s = (stacks c) !! (position - 1) in
if empty s then Nothing
else let remainder = pickUpN (replaceStack c position (pop s)) position (num-1) in
case remainder of
Nothing -> Nothing
Just (boxes,finalc) -> Just ((top s):boxes, finalc)
-- Boxes are given top-first: [A,B,C]
{-@ placeN :: c:Cargo -> pos:Int -> [String] ->
Maybe {c2:Cargo | numStacks c2 = numStacks c} @-}
placeN :: Cargo -> Int -> [String] -> Maybe Cargo
placeN c position labels | position > numStacks c = Nothing
placeN c position labels | position <= 0 = Nothing
placeN c position [] = Just c
placeN c position (top:rest) = let result = placeN c position rest in
case result of
Nothing -> Nothing
Just c' -> let s = (stacks c') !! (position - 1) in
Just $ replaceStack c' position (push top s)
applyOperation2 :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applyOperation2 Nothing _ = Nothing
applyOperation2 _ Nothing = Nothing
applyOperation2 (Just c) (Just op) =
case pickUpN c (fromStack op) (numBoxes op) of
Nothing -> Nothing
Just (boxes,c') ->
placeN c' (toStack op) boxes
[ D ]
[ N ] [ C ]
[ Z ] [ M ] [ P ]
1 2 3
[D]
[N] [C]
[Z] [M] [P]
1 2 3
-}
part1Example = Stacks 3 [
Box "N" (Box "Z" Empty),
Box "D" (Box "C" (Box "M" Empty)),
Box "P" Empty ]
[ V ] [ C ] [ M ]
[ V ] [ J ] [ N ] [ H ] [ V ]
[ R ] [ F ] [ N ] [ W ] [ Z ] [ N ]
[ H ] [ R ] [ D ] [ Q ] [ M ] [ L ] [ B ]
[ B ] [ C ] [ H ] [ V ] [ R ] [ C ] [ G ] [ R ]
[ G ] [ G ] [ F ] [ S ] [ D ] [ H ] [ B ] [ R ] [ S ]
[ D ] [ N ] [ S ] [ D ] [ H ] [ G ] [ J ] [ J ] [ G ]
[ W ] [ J ] [ L ] [ J ] [ S ] [ P ] [ F ] [ S ] [ L ]
1 2 3 4 5 6 7 8 9
[V] [C] [M]
[V] [J] [N] [H] [V]
[R] [F] [N] [W] [Z] [N]
[H] [R] [D] [Q] [M] [L] [B]
[B] [C] [H] [V] [R] [C] [G] [R]
[G] [G] [F] [S] [D] [H] [B] [R] [S]
[D] [N] [S] [D] [H] [G] [J] [J] [G]
[W] [J] [L] [J] [S] [P] [F] [S] [L]
1 2 3 4 5 6 7 8 9
-}
stringToStack :: String -> Stack
stringToStack [] = Empty
stringToStack (b:rest) = Box [b] (stringToStack rest)
realInput = Stacks 9 [
stringToStack "VRHBGDW",
stringToStack "FRCGNJ",
stringToStack "JNDHFSL",
stringToStack "VSDJ",
stringToStack "VNWQRDHS",
stringToStack "MCHGP",
stringToStack "CHZLGBJF",
stringToStack "RJS",
stringToStack "MVNBRSGL" ]
startStack = realInput
part1 :: [String] -> IO ()
part1 input = do
putStrLn "Part 1"
let operations = map parseOperation input in
case foldl' applyOperation (Just startStack) operations of
Nothing -> putStrLn "Error!"
Just c -> print $ topBoxes c
part2 :: [String] -> IO ()
part2 input = do
putStrLn "Part 2"
let operations = map parseOperation input in
case foldl' applyOperation2 (Just startStack) operations of
Nothing -> putStrLn "Error!"
Just c -> print $ topBoxes c
main :: IO ()
main = runOnLines part1 part2
| null | https://raw.githubusercontent.com/mgritter/aoc-lh/cab617c29a52cb334e248f8cb417d96ccc4907ad/2022/day5/Main.hs | haskell | @ measure empty @
@ top :: {s:Stack | not empty s} -> String @
@ pop :: {s:Stack | not empty s} -> Stack @
@ push :: String -> Stack -> Stack @
FIXME: how can we prove that stacks !! i is the only thing that changed
in c2 compared with c?
@ replaceStack :: c:Cargo -> pos:InRange c
-> s:Stack -> {c2:Cargo | numStacks c2 = numStacks c} @
@ place :: c:Cargo -> pos:Int -> String -> Maybe Cargo @
@ topBoxes :: Cargo -> String @
Boxes are returned top-first: [A,B,C]
@ pickUpN :: c:Cargo -> pos:Int -> {num:Int | num >= 0} ->
Maybe ({boxes:[String] | len boxes = num}, Cargo) / [num] @
Boxes are given top-first: [A,B,C]
@ placeN :: c:Cargo -> pos:Int -> [String] ->
Maybe {c2:Cargo | numStacks c2 = numStacks c} @ | module Main (main) where
import LoadLines
import Data.Maybe
import Data.List (foldl')
import Data.List.Split
data Stack =
Empty |
Box String Stack
empty :: Stack -> Bool
empty Empty = True
empty _ = False
top :: Stack -> String
top (Box x _) = x
pop :: Stack -> Stack
pop (Box _ y) = y
push :: String -> Stack -> Stack
push item stack = Box item stack
@ data Cargo = Stacks { numStacks : : ,
stacks : : { s:[Stack ] | len s = numStacks } }
@
stacks :: {s:[Stack] | len s = numStacks} }
@-}
data Cargo =
Stacks { numStacks :: Int
, stacks :: [Stack] }
@ type InRange c = { i : Int | 1 < = i & & i < = numStacks c } @
replaceStack :: Cargo -> Int -> Stack -> Cargo
replaceStack c position newstack =
let oldstacks = stacks c in
Stacks { numStacks = numStacks c,
stacks = (take (position - 1) oldstacks) ++ [newstack] ++ (drop position oldstacks ) }
@ pickUp : : c : Cargo - > pos : Int - > Maybe ( String , Cargo ) @
pickUp :: Cargo -> Int -> Maybe (String, Cargo)
pickUp c position | position > numStacks c = Nothing
pickUp c position | position <= 0 = Nothing
pickUp c position = let s = (stacks c) !! (position - 1) in
if empty s then Nothing
else Just (top s, replaceStack c position (pop s))
place :: Cargo -> Int -> String -> Maybe Cargo
place c position label | position > numStacks c = Nothing
place c position label | position <= 0 = Nothing
place c position label = let s = (stacks c) !! (position - 1) in
Just $ replaceStack c position (push label s)
topBoxes :: Cargo -> String
topBoxes c = concat $ map topOrNull (stacks c)
where topOrNull s = if empty s then "" else top s
@ data Operation = Move { numBoxes : : { n : Int | n > = 1 } ,
fromStack : : { n : Int | n > = 1 } ,
toStack : : { n : Int | n > = 1 } } @
fromStack :: {n:Int | n >= 1},
toStack :: {n:Int | n >= 1} } @-}
data Operation =
Move { numBoxes :: Int
, fromStack :: Int
, toStack :: Int }
parseOperation :: String -> Maybe Operation
parseOperation s = let tokens = splitOneOf " " s in
if length tokens /= 6 then Nothing else
let nb = (read (tokens !! 1))
fs = (read (tokens !! 3))
ts = (read (tokens !! 5)) in
if nb >= 1 && fs >= 1 && ts >= 1 then
Just $ Move nb fs ts
else
Nothing
applySingle :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applySingle Nothing _ = Nothing
applySingle _ Nothing = Nothing
applySingle (Just c) (Just op) = case (pickUp c (fromStack op)) of
Nothing -> Nothing
Just (item, c') -> (place c' (toStack op) item)
applyOperation :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applyOperation Nothing _ = Nothing
applyOperation _ Nothing = Nothing
applyOperation (Just c) (Just op) = foldl' applySingle (Just c) (replicate (numBoxes op) (Just op))
pickUpN :: Cargo -> Int -> Int -> Maybe ([String], Cargo)
pickUpN c position _ | position > numStacks c = Nothing
pickUpN c position _ | position <= 0 = Nothing
pickUpN c position 0 = Just ([], c)
pickUpN c position num =
let s = (stacks c) !! (position - 1) in
if empty s then Nothing
else let remainder = pickUpN (replaceStack c position (pop s)) position (num-1) in
case remainder of
Nothing -> Nothing
Just (boxes,finalc) -> Just ((top s):boxes, finalc)
placeN :: Cargo -> Int -> [String] -> Maybe Cargo
placeN c position labels | position > numStacks c = Nothing
placeN c position labels | position <= 0 = Nothing
placeN c position [] = Just c
placeN c position (top:rest) = let result = placeN c position rest in
case result of
Nothing -> Nothing
Just c' -> let s = (stacks c') !! (position - 1) in
Just $ replaceStack c' position (push top s)
applyOperation2 :: Maybe Cargo -> Maybe Operation -> Maybe Cargo
applyOperation2 Nothing _ = Nothing
applyOperation2 _ Nothing = Nothing
applyOperation2 (Just c) (Just op) =
case pickUpN c (fromStack op) (numBoxes op) of
Nothing -> Nothing
Just (boxes,c') ->
placeN c' (toStack op) boxes
[ D ]
[ N ] [ C ]
[ Z ] [ M ] [ P ]
1 2 3
[D]
[N] [C]
[Z] [M] [P]
1 2 3
-}
part1Example = Stacks 3 [
Box "N" (Box "Z" Empty),
Box "D" (Box "C" (Box "M" Empty)),
Box "P" Empty ]
[ V ] [ C ] [ M ]
[ V ] [ J ] [ N ] [ H ] [ V ]
[ R ] [ F ] [ N ] [ W ] [ Z ] [ N ]
[ H ] [ R ] [ D ] [ Q ] [ M ] [ L ] [ B ]
[ B ] [ C ] [ H ] [ V ] [ R ] [ C ] [ G ] [ R ]
[ G ] [ G ] [ F ] [ S ] [ D ] [ H ] [ B ] [ R ] [ S ]
[ D ] [ N ] [ S ] [ D ] [ H ] [ G ] [ J ] [ J ] [ G ]
[ W ] [ J ] [ L ] [ J ] [ S ] [ P ] [ F ] [ S ] [ L ]
1 2 3 4 5 6 7 8 9
[V] [C] [M]
[V] [J] [N] [H] [V]
[R] [F] [N] [W] [Z] [N]
[H] [R] [D] [Q] [M] [L] [B]
[B] [C] [H] [V] [R] [C] [G] [R]
[G] [G] [F] [S] [D] [H] [B] [R] [S]
[D] [N] [S] [D] [H] [G] [J] [J] [G]
[W] [J] [L] [J] [S] [P] [F] [S] [L]
1 2 3 4 5 6 7 8 9
-}
stringToStack :: String -> Stack
stringToStack [] = Empty
stringToStack (b:rest) = Box [b] (stringToStack rest)
realInput = Stacks 9 [
stringToStack "VRHBGDW",
stringToStack "FRCGNJ",
stringToStack "JNDHFSL",
stringToStack "VSDJ",
stringToStack "VNWQRDHS",
stringToStack "MCHGP",
stringToStack "CHZLGBJF",
stringToStack "RJS",
stringToStack "MVNBRSGL" ]
startStack = realInput
part1 :: [String] -> IO ()
part1 input = do
putStrLn "Part 1"
let operations = map parseOperation input in
case foldl' applyOperation (Just startStack) operations of
Nothing -> putStrLn "Error!"
Just c -> print $ topBoxes c
part2 :: [String] -> IO ()
part2 input = do
putStrLn "Part 2"
let operations = map parseOperation input in
case foldl' applyOperation2 (Just startStack) operations of
Nothing -> putStrLn "Error!"
Just c -> print $ topBoxes c
main :: IO ()
main = runOnLines part1 part2
|
0cfc92c974340d4bbd7e3d439ca46cdcce384d4cd9b767b6389439dfa1231c96 | kupl/FixML | sub4.ml | type nat = ZERO | SUCC of nat
let rec natadd nat1 nat2 =
match nat1 with
ZERO -> nat2
|SUCC nat -> natadd nat (SUCC nat2);;
let rec natmul nat1 nat2 =
match nat1 with
ZERO -> ZERO
|SUCC nat -> natmul nat (natadd nat2 nat2);;
| null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/nat/nat1/submissions/sub4.ml | ocaml | type nat = ZERO | SUCC of nat
let rec natadd nat1 nat2 =
match nat1 with
ZERO -> nat2
|SUCC nat -> natadd nat (SUCC nat2);;
let rec natmul nat1 nat2 =
match nat1 with
ZERO -> ZERO
|SUCC nat -> natmul nat (natadd nat2 nat2);;
|
|
ca2348068ca4bb814776003638eb120d12328cb235c77a2e90ae2579e590bf22 | sdiehl/elliptic-curve | SECP160R2.hs | module Data.Curve.Weierstrass.SECP160R2
( module Data.Curve.Weierstrass
, Point(..)
-- * SECP160R2 curve
, module Data.Curve.Weierstrass.SECP160R2
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
-------------------------------------------------------------------------------
-- Types
-------------------------------------------------------------------------------
-- | SECP160R2 curve.
data SECP160R2
-- | Field of points of SECP160R2 curve.
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffeffffac73
-- | Field of coefficients of SECP160R2 curve.
type Fr = Prime R
type R = 0x100000000000000000000351ee786a818f3a1a16b
SECP160R2 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP160R2 Fq Fr => WCurve c SECP160R2 Fq Fr where
a_ = const _a
{-# INLINABLE a_ #-}
b_ = const _b
# INLINABLE b _ #
h_ = const _h
{-# INLINABLE h_ #-}
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
-- | Affine SECP160R2 curve point.
type PA = WAPoint SECP160R2 Fq Fr
Affine SECP160R2 curve is a Weierstrass affine curve .
instance WACurve SECP160R2 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
-- | Jacobian SECP160R2 point.
type PJ = WJPoint SECP160R2 Fq Fr
Jacobian SECP160R2 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP160R2 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
-- | Projective SECP160R2 point.
type PP = WPPoint SECP160R2 Fq Fr
Projective SECP160R2 curve is a Weierstrass projective curve .
instance WPCurve SECP160R2 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
-------------------------------------------------------------------------------
-- Parameters
-------------------------------------------------------------------------------
-- | Coefficient @A@ of SECP160R2 curve.
_a :: Fq
_a = 0xfffffffffffffffffffffffffffffffeffffac70
# INLINABLE _ a #
| Coefficient @B@ of SECP160R2 curve .
_b :: Fq
_b = 0xb4e134d3fb59eb8bab57274904664d5af50388ba
{-# INLINABLE _b #-}
-- | Cofactor of SECP160R2 curve.
_h :: Natural
_h = 0x1
# INLINABLE _ h #
-- | Characteristic of SECP160R2 curve.
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffeffffac73
{-# INLINABLE _q #-}
-- | Order of SECP160R2 curve.
_r :: Natural
_r = 0x100000000000000000000351ee786a818f3a1a16b
{-# INLINABLE _r #-}
-- | Coordinate @X@ of SECP160R2 curve.
_x :: Fq
_x = 0x52dcb034293a117e1f4ff11b30f7199d3144ce6d
{-# INLINABLE _x #-}
-- | Coordinate @Y@ of SECP160R2 curve.
_y :: Fq
_y = 0xfeaffef2e331f296e071fa0df9982cfea7d43f2e
{-# INLINABLE _y #-}
-- | Generator of affine SECP160R2 curve.
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP160R2 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
-- | Generator of projective SECP160R2 curve.
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
| null | https://raw.githubusercontent.com/sdiehl/elliptic-curve/445e196a550e36e0f25bd4d9d6a38676b4cf2be8/src/Data/Curve/Weierstrass/SECP160R2.hs | haskell | * SECP160R2 curve
-----------------------------------------------------------------------------
Types
-----------------------------------------------------------------------------
| SECP160R2 curve.
| Field of points of SECP160R2 curve.
| Field of coefficients of SECP160R2 curve.
# INLINABLE a_ #
# INLINABLE h_ #
| Affine SECP160R2 curve point.
| Jacobian SECP160R2 point.
| Projective SECP160R2 point.
-----------------------------------------------------------------------------
Parameters
-----------------------------------------------------------------------------
| Coefficient @A@ of SECP160R2 curve.
# INLINABLE _b #
| Cofactor of SECP160R2 curve.
| Characteristic of SECP160R2 curve.
# INLINABLE _q #
| Order of SECP160R2 curve.
# INLINABLE _r #
| Coordinate @X@ of SECP160R2 curve.
# INLINABLE _x #
| Coordinate @Y@ of SECP160R2 curve.
# INLINABLE _y #
| Generator of affine SECP160R2 curve.
| Generator of projective SECP160R2 curve. | module Data.Curve.Weierstrass.SECP160R2
( module Data.Curve.Weierstrass
, Point(..)
, module Data.Curve.Weierstrass.SECP160R2
) where
import Protolude
import Data.Field.Galois
import GHC.Natural (Natural)
import Data.Curve.Weierstrass
data SECP160R2
type Fq = Prime Q
type Q = 0xfffffffffffffffffffffffffffffffeffffac73
type Fr = Prime R
type R = 0x100000000000000000000351ee786a818f3a1a16b
SECP160R2 curve is a Weierstrass curve .
instance Curve 'Weierstrass c SECP160R2 Fq Fr => WCurve c SECP160R2 Fq Fr where
a_ = const _a
b_ = const _b
# INLINABLE b _ #
h_ = const _h
q_ = const _q
# INLINABLE q _ #
r_ = const _r
# INLINABLE r _ #
type PA = WAPoint SECP160R2 Fq Fr
Affine SECP160R2 curve is a Weierstrass affine curve .
instance WACurve SECP160R2 Fq Fr where
gA_ = gA
# INLINABLE gA _ #
type PJ = WJPoint SECP160R2 Fq Fr
Jacobian SECP160R2 curve is a Weierstrass Jacobian curve .
instance WJCurve SECP160R2 Fq Fr where
gJ_ = gJ
# INLINABLE gJ _ #
type PP = WPPoint SECP160R2 Fq Fr
Projective SECP160R2 curve is a Weierstrass projective curve .
instance WPCurve SECP160R2 Fq Fr where
gP_ = gP
# INLINABLE gP _ #
_a :: Fq
_a = 0xfffffffffffffffffffffffffffffffeffffac70
# INLINABLE _ a #
| Coefficient @B@ of SECP160R2 curve .
_b :: Fq
_b = 0xb4e134d3fb59eb8bab57274904664d5af50388ba
_h :: Natural
_h = 0x1
# INLINABLE _ h #
_q :: Natural
_q = 0xfffffffffffffffffffffffffffffffeffffac73
_r :: Natural
_r = 0x100000000000000000000351ee786a818f3a1a16b
_x :: Fq
_x = 0x52dcb034293a117e1f4ff11b30f7199d3144ce6d
_y :: Fq
_y = 0xfeaffef2e331f296e071fa0df9982cfea7d43f2e
gA :: PA
gA = A _x _y
# INLINABLE gA #
| Generator of Jacobian SECP160R2 curve .
gJ :: PJ
gJ = J _x _y 1
# INLINABLE gJ #
gP :: PP
gP = P _x _y 1
# INLINABLE gP #
|
24dd2892453d79bf22a73778b8f8f3765ccac09860ed404d98d0f914c5a3393a | McParen/croatoan | border_set.lisp | (in-package :de.anvi.ncurses)
;;; border_set
;;; create curses borders or lines using complex characters and renditions
;;; -island.net/ncurses/man/curs_border_set.3x.html
;;; C prototypes
;; int border_set(const cchar_t *ls, const cchar_t *rs, const cchar_t *ts, const cchar_t *bs, const cchar_t *tl, const cchar_t *tr, const cchar_t *bl, const cchar_t *br);
;; int wborder_set(WINDOW *win, const cchar_t *ls, const cchar_t *rs, const cchar_t *ts, const cchar_t *bs, const cchar_t *tl, const cchar_t *tr, const cchar_t *bl, const cchar_t *br);
;; int box_set(WINDOW *win, const cchar_t *verch, const cchar_t *horch);
;; int hline_set(const cchar_t *wch, int n);
int whline_set(WINDOW * win , const cchar_t * wch , int n ) ;
;; int mvhline_set(int y, int x, const cchar_t *wch, int n);
;; int mvwhline_set(WINDOW *win, int y, int x, const cchar_t *wch, int n);
;; int vline_set(const cchar_t *wch, int n);
;; int wvline_set(WINDOW *win, const cchar_t *wch, int n);
;; int mvvline_set(int y, int x, const cchar_t *wch, int n);
;; int mvwvline_set(WINDOW *win, int y, int x, const cchar_t *wch, int n);
;;; Low-level CFFI wrappers
(cffi:defcfun ("border_set" border-set) :int
(ls (:pointer (:struct cchar_t)))
(rs (:pointer (:struct cchar_t)))
(ts (:pointer (:struct cchar_t)))
(bs (:pointer (:struct cchar_t)))
(tl (:pointer (:struct cchar_t)))
(tr (:pointer (:struct cchar_t)))
(bl (:pointer (:struct cchar_t)))
(br (:pointer (:struct cchar_t))))
(cffi:defcfun ("wborder_set" wborder-set) :int
(win window)
(ls (:pointer (:struct cchar_t)))
(rs (:pointer (:struct cchar_t)))
(ts (:pointer (:struct cchar_t)))
(bs (:pointer (:struct cchar_t)))
(tl (:pointer (:struct cchar_t)))
(tr (:pointer (:struct cchar_t)))
(bl (:pointer (:struct cchar_t)))
(br (:pointer (:struct cchar_t))))
(cffi:defcfun ("box_set" box-set) :int
(win window)
(verch (:pointer (:struct cchar_t)))
(horch (:pointer (:struct cchar_t))))
(cffi:defcfun ("hline_set" hline-set) :int (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("whline_set" whline-set) :int (win window) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvhline_set" mvhline-set) :int (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvwhline_set" mvwhline-set) :int (win window) (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("vline_set" vline-set) :int (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("wvline_set" wvline-set) :int (win window) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvvline_set" mvvline-set) :int (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvwvline_set" mvwvline-set) :int (win window) (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
| null | https://raw.githubusercontent.com/McParen/croatoan/46a5aba653389d15ae16dc0a581fd67a33378b62/ncurses/border_set.lisp | lisp | border_set
create curses borders or lines using complex characters and renditions
-island.net/ncurses/man/curs_border_set.3x.html
C prototypes
int border_set(const cchar_t *ls, const cchar_t *rs, const cchar_t *ts, const cchar_t *bs, const cchar_t *tl, const cchar_t *tr, const cchar_t *bl, const cchar_t *br);
int wborder_set(WINDOW *win, const cchar_t *ls, const cchar_t *rs, const cchar_t *ts, const cchar_t *bs, const cchar_t *tl, const cchar_t *tr, const cchar_t *bl, const cchar_t *br);
int box_set(WINDOW *win, const cchar_t *verch, const cchar_t *horch);
int hline_set(const cchar_t *wch, int n);
int mvhline_set(int y, int x, const cchar_t *wch, int n);
int mvwhline_set(WINDOW *win, int y, int x, const cchar_t *wch, int n);
int vline_set(const cchar_t *wch, int n);
int wvline_set(WINDOW *win, const cchar_t *wch, int n);
int mvvline_set(int y, int x, const cchar_t *wch, int n);
int mvwvline_set(WINDOW *win, int y, int x, const cchar_t *wch, int n);
Low-level CFFI wrappers | (in-package :de.anvi.ncurses)
(cffi:defcfun ("border_set" border-set) :int
(ls (:pointer (:struct cchar_t)))
(rs (:pointer (:struct cchar_t)))
(ts (:pointer (:struct cchar_t)))
(bs (:pointer (:struct cchar_t)))
(tl (:pointer (:struct cchar_t)))
(tr (:pointer (:struct cchar_t)))
(bl (:pointer (:struct cchar_t)))
(br (:pointer (:struct cchar_t))))
(cffi:defcfun ("wborder_set" wborder-set) :int
(win window)
(ls (:pointer (:struct cchar_t)))
(rs (:pointer (:struct cchar_t)))
(ts (:pointer (:struct cchar_t)))
(bs (:pointer (:struct cchar_t)))
(tl (:pointer (:struct cchar_t)))
(tr (:pointer (:struct cchar_t)))
(bl (:pointer (:struct cchar_t)))
(br (:pointer (:struct cchar_t))))
(cffi:defcfun ("box_set" box-set) :int
(win window)
(verch (:pointer (:struct cchar_t)))
(horch (:pointer (:struct cchar_t))))
(cffi:defcfun ("hline_set" hline-set) :int (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("whline_set" whline-set) :int (win window) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvhline_set" mvhline-set) :int (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvwhline_set" mvwhline-set) :int (win window) (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("vline_set" vline-set) :int (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("wvline_set" wvline-set) :int (win window) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvvline_set" mvvline-set) :int (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
(cffi:defcfun ("mvwvline_set" mvwvline-set) :int (win window) (y :int) (x :int) (wch (:pointer (:struct cchar_t))) (n :int))
|
8e05a041fed290094f6fbe7532dce5f5b27c4467a3ffac2f02131985b87f13ce | originrose/cortex | gaussian.clj | (ns cortex.gaussian
"Namespace for working with gaussian distributions."
(:require [clojure.core.matrix :as m])
(:import [java.security SecureRandom]))
(def ^:dynamic ^SecureRandom *RAND-GENERATOR* (SecureRandom.))
(defn rand-normal ^double []
(.nextDouble *RAND-GENERATOR*))
(defn rand-gaussian ^double []
(.nextGaussian *RAND-GENERATOR*))
(defn calc-mean-variance
[data]
(let [num-elems (double (m/ecount data))
elem-sum (double (m/esum data))]
(if (= num-elems 0.0)
{:mean 0
:variance 0}
(let [mean (/ elem-sum num-elems)
variance (/ (double (m/ereduce (fn [^double sum val]
(let [temp-val (- mean (double val))]
(+ sum (* temp-val temp-val))))
0.0
data))
num-elems)]
{:mean mean
:variance variance}))))
(defn ensure-gaussian!
[data ^double mean ^double variance]
(let [actual-stats (calc-mean-variance data)
actual-variance (double (:variance actual-stats))
actual-mean (double (:mean actual-stats))
variance-fix (Math/sqrt (double (if (> actual-variance 0.0)
(/ variance actual-variance)
1.0)))
adjusted-mean (* actual-mean variance-fix)
mean-fix (- mean adjusted-mean)]
(doall (m/emap! (fn [^double data-var]
(+ (* variance-fix data-var)
mean-fix))
data))))
| null | https://raw.githubusercontent.com/originrose/cortex/94b1430538e6187f3dfd1697c36ff2c62b475901/src/cortex/gaussian.clj | clojure | (ns cortex.gaussian
"Namespace for working with gaussian distributions."
(:require [clojure.core.matrix :as m])
(:import [java.security SecureRandom]))
(def ^:dynamic ^SecureRandom *RAND-GENERATOR* (SecureRandom.))
(defn rand-normal ^double []
(.nextDouble *RAND-GENERATOR*))
(defn rand-gaussian ^double []
(.nextGaussian *RAND-GENERATOR*))
(defn calc-mean-variance
[data]
(let [num-elems (double (m/ecount data))
elem-sum (double (m/esum data))]
(if (= num-elems 0.0)
{:mean 0
:variance 0}
(let [mean (/ elem-sum num-elems)
variance (/ (double (m/ereduce (fn [^double sum val]
(let [temp-val (- mean (double val))]
(+ sum (* temp-val temp-val))))
0.0
data))
num-elems)]
{:mean mean
:variance variance}))))
(defn ensure-gaussian!
[data ^double mean ^double variance]
(let [actual-stats (calc-mean-variance data)
actual-variance (double (:variance actual-stats))
actual-mean (double (:mean actual-stats))
variance-fix (Math/sqrt (double (if (> actual-variance 0.0)
(/ variance actual-variance)
1.0)))
adjusted-mean (* actual-mean variance-fix)
mean-fix (- mean adjusted-mean)]
(doall (m/emap! (fn [^double data-var]
(+ (* variance-fix data-var)
mean-fix))
data))))
|
|
e020ee8e65b7c6a619f098718e3ef8833549183301f7911fa643c75b2b8d48c0 | ragkousism/Guix-on-Hurd | jemalloc.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2015 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages jemalloc)
#:use-module ((guix licenses) #:select (bsd-2))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (gnu packages base)
#:use-module (gnu packages gcc)
#:use-module (guix build-system gnu))
(define-public jemalloc
(package
(name "jemalloc")
(version "4.2.0")
(source (origin
(method url-fetch)
(uri (string-append
"/"
name "-" version ".tar.bz2"))
(sha256
(base32
"1jvasihaizawz44j02bri47bd905flns03nkigipys81p6pds5mj"))))
(build-system gnu-build-system)
(home-page "/")
(synopsis "General-purpose scalable concurrent malloc implementation")
(description
"This library providing a malloc(3) implementation that emphasizes
fragmentation avoidance and scalable concurrency support.")
(license bsd-2)))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/jemalloc.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 © 2015 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages jemalloc)
#:use-module ((guix licenses) #:select (bsd-2))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (gnu packages base)
#:use-module (gnu packages gcc)
#:use-module (guix build-system gnu))
(define-public jemalloc
(package
(name "jemalloc")
(version "4.2.0")
(source (origin
(method url-fetch)
(uri (string-append
"/"
name "-" version ".tar.bz2"))
(sha256
(base32
"1jvasihaizawz44j02bri47bd905flns03nkigipys81p6pds5mj"))))
(build-system gnu-build-system)
(home-page "/")
(synopsis "General-purpose scalable concurrent malloc implementation")
(description
"This library providing a malloc(3) implementation that emphasizes
fragmentation avoidance and scalable concurrency support.")
(license bsd-2)))
|
c2739f38c06ebdda5659c5ce95b3f31da34e6d3edd95e5789c22ddcc347e11de | ndmitchell/supero | Main.hs |
module Main where
main = main_small `seq` putChar 'x'
main_small x = map (+ (1::Int)) (map (+2) x)
| null | https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/examples/deforestation2/Main.hs | haskell |
module Main where
main = main_small `seq` putChar 'x'
main_small x = map (+ (1::Int)) (map (+2) x)
|
|
bce086fd766544fb6dbd6f93a9535e99dc963c2eb9984a21c608202594f82128 | cndreisbach/clojure-web-dev-workshop | user.clj | (ns user
(:require [alembic.still :refer [distill]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[clojure.repl :refer :all]
[clojure.tools.namespace.repl :refer [refresh refresh-all]]
[ring.mock.request :refer [request]]
[we-owe.system :as system]
[we-owe.debts :as debts]))
(def system nil)
(def debts [{:from "Clinton" :to "Pete" :amount 3.50}
{:from "Clinton" :to "Diego" :amount 2.00}
{:from "Pete" :to "Clinton" :amount 1.25}
{:from "Jill" :to "Pete" :amount 10.00}])
(defn init
"Constructs the current dev system."
[]
(alter-var-root #'system
(constantly (system/system))))
(defn start
"Starts the current development system."
[]
(alter-var-root #'system system/start))
(defn stop
"Shuts down and destroys the current development system."
[]
(alter-var-root #'system
(fn [s] (when s (system/stop s)))))
(defn go
"Initializes the current development system and starts it running."
[]
(init)
(start)
(swap!
(:db system)
assoc :debts debts)
)
(defn reset []
(stop)
(refresh :after 'user/go))
(comment
(reset)
)
| null | https://raw.githubusercontent.com/cndreisbach/clojure-web-dev-workshop/95d9fdf94b39f8a1e408b8bf75a81b92899ee7d9/code/07-frp/dev/user.clj | clojure | (ns user
(:require [alembic.still :refer [distill]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[clojure.repl :refer :all]
[clojure.tools.namespace.repl :refer [refresh refresh-all]]
[ring.mock.request :refer [request]]
[we-owe.system :as system]
[we-owe.debts :as debts]))
(def system nil)
(def debts [{:from "Clinton" :to "Pete" :amount 3.50}
{:from "Clinton" :to "Diego" :amount 2.00}
{:from "Pete" :to "Clinton" :amount 1.25}
{:from "Jill" :to "Pete" :amount 10.00}])
(defn init
"Constructs the current dev system."
[]
(alter-var-root #'system
(constantly (system/system))))
(defn start
"Starts the current development system."
[]
(alter-var-root #'system system/start))
(defn stop
"Shuts down and destroys the current development system."
[]
(alter-var-root #'system
(fn [s] (when s (system/stop s)))))
(defn go
"Initializes the current development system and starts it running."
[]
(init)
(start)
(swap!
(:db system)
assoc :debts debts)
)
(defn reset []
(stop)
(refresh :after 'user/go))
(comment
(reset)
)
|
|
bfa2f03aed17d577b9f6686d169e919b03721a77e086d76386a69ac47e2cccf0 | cram2/cram | package.lisp | ;;;
Copyright ( c ) 2017 , < >
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
* Neither the name of the Institute for Artificial Intelligence/
;;; Universitaet Bremen 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
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
;;; POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(defpackage cram-boxy-plans
(:nicknames #:boxy-plans)
(:use #:common-lisp #:cram-prolog #:cram-designator-specification)
(:export))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_boxy/cram_boxy_plans/src/package.lisp | lisp |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
Universitaet Bremen nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
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. | Copyright ( c ) 2017 , < >
* Neither the name of the Institute for Artificial Intelligence/
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR
LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN
(in-package :cl-user)
(defpackage cram-boxy-plans
(:nicknames #:boxy-plans)
(:use #:common-lisp #:cram-prolog #:cram-designator-specification)
(:export))
|
ca0ddac972b9075b01072611ded4fcb81d849e3a5e4d80e1d94b54bf79ac5392 | inhabitedtype/ocaml-aws | sendCommand.ml | open Types
open Aws
type input = SendCommandRequest.t
type output = SendCommandResult.t
type error = Errors_internal.t
let service = "ssm"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-11-06" ]; "Action", [ "SendCommand" ] ]
(Util.drop_empty
(Uri.query_of_encoded (Query.render (SendCommandRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "SendCommandResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp SendCommandResult.parse)
(let open Error in
BadResponse { body; message = "Could not find well formed SendCommandResult." })
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing SendCommandResult - missing field in body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/sendCommand.ml | ocaml | open Types
open Aws
type input = SendCommandRequest.t
type output = SendCommandResult.t
type error = Errors_internal.t
let service = "ssm"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-11-06" ]; "Action", [ "SendCommand" ] ]
(Util.drop_empty
(Uri.query_of_encoded (Query.render (SendCommandRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "SendCommandResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp SendCommandResult.parse)
(let open Error in
BadResponse { body; message = "Could not find well formed SendCommandResult." })
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing SendCommandResult - missing field in body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
|
|
4514cfa0f7669603a51b876e81c5927faa0e6b0ded5e6e6f954ecef06f74aeae | metabase/metabase | version_info.clj | (ns release.version-info
"Code for generating, uploading, and validating version-info.json."
(:require
[cheshire.core :as json]
[clj-http.client :as http]
[metabuild-common.core :as u]
[release.common :as c]
[release.common.github :as github]))
(defn- version-info-filename []
(case (c/edition)
:oss "version-info.json"
:ee "version-info-ee.json"
nil))
(defn- version-info-url
"The base name of the version-info.json file, which includes an -ee suffix for :ee edition."
[]
(format "static.metabase.com/%s" (version-info-filename)))
(defn- tmp-version-info-filename
"The name of the temp file to create for generating the current version info file."
[]
(format "/tmp/%s" (version-info-filename)))
(defn- current-version-info
"Fetch the current version of the version info file via HTTP."
[]
(u/step "Fetch existing version info file"
(let [{:keys [status body], :as response} (http/get (str "http://" (version-info-url)))]
(when (>= status 400)
(throw (ex-info (format "Error fetching version info: status code %d" status)
(try
{:body (json/parse-string body true)}
(catch Throwable _
{:body body})))))
(json/parse-string body true))))
(defn- info-for-new-version
"The info map for the version we're currently releasing to add to the version info file."
[]
{:version (str "v" (c/version))
:released (str (java.time.LocalDate/now))
:patch (c/patch-version?)
TODO -- these need to be curated a bit before publishing ...
:highlights (mapv :title (github/milestone-issues))})
(defn- generate-version-info! []
(let [filename (version-info-filename)
tmpname (tmp-version-info-filename)]
(u/step (format "Generate %s" filename)
(u/step (format "Delete and create %s" tmpname)
(u/delete-file-if-exists! tmpname)
(let [{:keys [latest], :as info} (current-version-info)]
(spit tmpname (-> info
;; move the current `:latest` to the beginning of `:older`
(update :older (fn [older]
(distinct (cons latest older))))
(assoc :latest (info-for-new-version))
json/generate-string)))))))
(defn- upload-version-info! []
(u/step "Upload version info"
(u/s3-copy! (format "s3" (version-info-url)) (format "s3" (version-info-url)))
(u/s3-copy! (u/assert-file-exists (tmp-version-info-filename)) (format "s3" (version-info-url)))))
(defn- validate-version-info []
(u/step (format "Validate version info at %s" (version-info-url))
(let [info (current-version-info)
latest-version (-> info :latest :version)]
(u/announce "Latest version from %s is %s" (version-info-url) latest-version)
(when-not (= latest-version (str "v" (c/version)))
(throw (ex-info (format "Latest version is %s; expected %s" latest-version (str "v" (c/version)))
{:version-info info})))
(u/announce (format "%s is valid." (version-info-filename))))))
(defn- update-version-info!* []
(generate-version-info!)
(upload-version-info!)
(validate-version-info)
(u/announce (format "%s updated." (version-info-filename))))
(defn update-version-info! []
(u/step (format "Update %s" (version-info-filename))
(cond
(c/pre-release-version?)
(u/announce "Pre-release version, not updating version-info.json")
(not (c/latest-version?))
(u/announce "Not the latest version, not updating version-info.json")
:else
(update-version-info!*))))
| null | https://raw.githubusercontent.com/metabase/metabase/5e9b52a32dfeab754d218c758d08fffbacb7c0e7/bin/build/src/release/version_info.clj | clojure | move the current `:latest` to the beginning of `:older` | (ns release.version-info
"Code for generating, uploading, and validating version-info.json."
(:require
[cheshire.core :as json]
[clj-http.client :as http]
[metabuild-common.core :as u]
[release.common :as c]
[release.common.github :as github]))
(defn- version-info-filename []
(case (c/edition)
:oss "version-info.json"
:ee "version-info-ee.json"
nil))
(defn- version-info-url
"The base name of the version-info.json file, which includes an -ee suffix for :ee edition."
[]
(format "static.metabase.com/%s" (version-info-filename)))
(defn- tmp-version-info-filename
"The name of the temp file to create for generating the current version info file."
[]
(format "/tmp/%s" (version-info-filename)))
(defn- current-version-info
"Fetch the current version of the version info file via HTTP."
[]
(u/step "Fetch existing version info file"
(let [{:keys [status body], :as response} (http/get (str "http://" (version-info-url)))]
(when (>= status 400)
(throw (ex-info (format "Error fetching version info: status code %d" status)
(try
{:body (json/parse-string body true)}
(catch Throwable _
{:body body})))))
(json/parse-string body true))))
(defn- info-for-new-version
"The info map for the version we're currently releasing to add to the version info file."
[]
{:version (str "v" (c/version))
:released (str (java.time.LocalDate/now))
:patch (c/patch-version?)
TODO -- these need to be curated a bit before publishing ...
:highlights (mapv :title (github/milestone-issues))})
(defn- generate-version-info! []
(let [filename (version-info-filename)
tmpname (tmp-version-info-filename)]
(u/step (format "Generate %s" filename)
(u/step (format "Delete and create %s" tmpname)
(u/delete-file-if-exists! tmpname)
(let [{:keys [latest], :as info} (current-version-info)]
(spit tmpname (-> info
(update :older (fn [older]
(distinct (cons latest older))))
(assoc :latest (info-for-new-version))
json/generate-string)))))))
(defn- upload-version-info! []
(u/step "Upload version info"
(u/s3-copy! (format "s3" (version-info-url)) (format "s3" (version-info-url)))
(u/s3-copy! (u/assert-file-exists (tmp-version-info-filename)) (format "s3" (version-info-url)))))
(defn- validate-version-info []
(u/step (format "Validate version info at %s" (version-info-url))
(let [info (current-version-info)
latest-version (-> info :latest :version)]
(u/announce "Latest version from %s is %s" (version-info-url) latest-version)
(when-not (= latest-version (str "v" (c/version)))
(throw (ex-info (format "Latest version is %s; expected %s" latest-version (str "v" (c/version)))
{:version-info info})))
(u/announce (format "%s is valid." (version-info-filename))))))
(defn- update-version-info!* []
(generate-version-info!)
(upload-version-info!)
(validate-version-info)
(u/announce (format "%s updated." (version-info-filename))))
(defn update-version-info! []
(u/step (format "Update %s" (version-info-filename))
(cond
(c/pre-release-version?)
(u/announce "Pre-release version, not updating version-info.json")
(not (c/latest-version?))
(u/announce "Not the latest version, not updating version-info.json")
:else
(update-version-info!*))))
|
6b8af4b06af510407066fd6f2175bf254409f4b1f1b4079a201fd2fb6312afd8 | 1Jajen1/Brokkr | Chunk.hs | # LANGUAGE RecordWildCards #
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE MultiWayIf #-}
module IO.Chunk (
Chunk(..)
, ChunkSection(..)
, Biomes(..)
, BlockStates(..)
, countBlocks
, numSections
) where
import Registry.Biome
import Block.Internal.BlockState
import Block.Internal.Conversion
import Chunk.Heightmap
import Chunk.Position
import Control.DeepSeq
import Data.Coerce
import Data.Int
import Data.List (sortOn)
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Primitive as Prim
import GHC.Generics
import GHC.TypeLits
import Util.Binary
import Util.NBT
import Util.NBT.Internal
import Util.Vector.Packed (PackedVector, DynamicNat(..))
import qualified Util.Vector.Packed as P
import Util.PalettedVector
snapshot of a chunk on disk
-- Used to serialize and deserialize chunks to disk
data Chunk = Chunk {
position :: {-# UNPACK #-} !ChunkPosition
, lowestYSection :: {-# UNPACK #-} !Int
, sections :: {-# UNPACK #-} !(V.Vector ChunkSection)
, heightmaps :: {-# UNPACK #-} !Heightmaps
}
deriving stock (Show, Generic)
deriving anyclass NFData
deriving (FromBinary) via BinaryNBT Chunk
type NibbleVector = PackedVector ('Static 4096) ('Static 4)
data ChunkSection = ChunkSection {
y :: {-# UNPACK #-} !Int
, blockLight :: !(Maybe NibbleVector)
, skyLight :: !(Maybe NibbleVector)
, blocks :: !BlockStates
, biomes :: !Biomes
, blockCount :: {-# UNPACK #-} !Int
}
deriving stock (Show, Generic)
deriving anyclass NFData
type BlockPaletteMaxBitsize = 1 + Log2 (HighestBlockStateId - 1)
type BiomePaletteMaxBitsze = 6
type SectionSize = 4096
type BiomeSectionSize = 64
newtype BlockStates = BlockStates (PalettedVector SectionSize BlockPaletteMaxBitsize)
deriving stock Show
deriving newtype (NFData, ToBinary)
newtype Biomes = Biomes (PalettedVector BiomeSectionSize BiomePaletteMaxBitsze)
deriving stock Show
deriving newtype (NFData, ToBinary)
--
instance FromNBT Chunk where
parseNBT = withCompound $ \obj -> do
!xPos <- fromIntegral @Int32 <$> obj .: "xPos"
!zPos <- fromIntegral @Int32 <$> obj .: "zPos"
let !position = ChunkPos xPos zPos
!lowestYSection <- fromIntegral @Int32 <$> obj .: "yPos"
TODO This may contain gaps ( can it ? )
!sectionsUnordered <- obj .: "sections"
let !sections = V.fromListN (V.length sectionsUnordered) . sortOn y $ V.toList sectionsUnordered
!heightmaps <- obj .: "Heightmaps"
pure Chunk{..}
# INLINE parseNBT #
# SCC parseNBT #
instance FromNBT ChunkSection where
parseNBT = withCompound $ \obj -> do
!y <- fromIntegral @Int8 <$> obj .: "Y"
!blockLight <- obj .:? "BlockLight" -- TODO Make sure the Maybe is fully forced
!skyLight <- obj .:? "SkyLight"
!blocks <- obj .: "block_states"
let !blockCount = countBlocks blocks
!biomes <- obj .: "biomes"
pure ChunkSection{..}
# INLINE parseNBT #
# SCC parseNBT #
instance FromNBT BlockStates where
parseNBT = withCompound $ \obj -> do
palette <- fmap lookupTag <$> obj .: "palette"
if | V.length palette == 1 -> pure . BlockStates . SingleValue . coerce $ V.unsafeHead palette
| otherwise -> do
(blockStates, len) <- S.unsafeToForeignPtr0 @Int64 <$> obj .: "data"
let bitsPerVal = len `div` 64 -- TODO Why does this work?
if | bitsPerVal < 4 -> error "TODO" -- TODO Error messages
| bitsPerVal < 9 ->
let !intPalette = Prim.generate (V.length palette) $ (coerce . (V.!) palette)
in pure . BlockStates . Indirect intPalette . P.unsafeDynamicFromForeignPtr bitsPerVal $ coerce blockStates
| otherwise -> pure . BlockStates . Global . P.unsafeStaticFromForeignPtr $ coerce blockStates
where
TODO This can further be optimized :
Currently this does a lookup ( propsToId ) into a ~22k sorted array based on the hash of ( BlockName , BlockProps )
-- The hash function is fast, but maybe we can have the data in a less pointer heavy format to boost it further
The array can be shrunk down to fewer elements if I do two lookups , one for BlockName and one for the props
-- Also we have to sort props, that as well can be faster if its not in list form, we can and should just do it
-- over a mutable vector
lookupTag :: Tag -> BlockState
lookupTag (TagCompound m) = maybe (error $ show m) id $ do
TagString name <- HM.lookup "Name" m
props <- case HM.lookup "Properties" m of
Just (TagCompound props) -> pure . fmap (fmap (\(TagString bs) -> bs)) $ HM.toList props
Nothing -> pure mempty
_ -> Nothing
pure . BlockState $ propsToId (coerce name) $ coerce $ sortOn fst props
lookupTag _ = error "Wut?"
{-# SCC lookupTag #-}
# INLINE parseNBT #
# SCC parseNBT #
biomeMap :: HM.HashMap BS.ByteString Int
biomeMap = HM.fromList $ zip (T.encodeUtf8 . T.pack . fst <$> all_biome_settings) [0..]
instance FromNBT Biomes where
parseNBT = withCompound $ \obj -> do
!intPalette <- lookupBiomes <$> obj .: "palette"
if | Prim.length intPalette == 1 -> pure . Biomes . SingleValue $ Prim.unsafeHead intPalette
| otherwise -> do
(biomes, len) <- S.unsafeToForeignPtr0 @Int64 <$> obj .: "data"
TODO
if | bitsPerVal < 4 -> pure . Biomes . Indirect intPalette . P.unsafeDynamicFromForeignPtr bitsPerVal $ coerce biomes
| otherwise -> pure . Biomes . Global . P.unsafeStaticFromForeignPtr $ coerce biomes
where
lookupBiomes v = Prim.generate (V.length v) $ \i -> lookupBiome (v V.! i)
lookupBiome :: Tag -> Int
lookupBiome (TagString name) = fromMaybe (error $ show name) $ HM.lookup (BS.drop 10 $ coerce name) biomeMap
lookupBiome _ = error "WUT=!"
# SCC lookupBiome #
# INLINE parseNBT #
# SCC parseNBT #
countBlocks :: BlockStates -> Int
countBlocks (BlockStates (SingleValue val))
| isAir $ BlockState val = 0
| otherwise = fromIntegral $ natVal @SectionSize undefined
countBlocks (BlockStates (Global vec))
= sz - P.countElems (coerce $ Prim.fromList $ coerce @_ @[Int] [Air, VoidAir, CaveAir]) vec
where !sz = fromIntegral $ natVal @SectionSize undefined
countBlocks (BlockStates (Indirect palette vec))
| Prim.null airs = sz
| otherwise = sz - P.countElems (coerce airs) vec
where
!airs = Prim.findIndices (\x -> isAir $ BlockState x) palette
!sz = fromIntegral $ natVal @SectionSize undefined
{-# SCC countBlocks #-}
isAir :: BlockState -> Bool
isAir Air = True
isAir VoidAir = True
isAir CaveAir = True
isAir _ = False
# INLINE isAir #
numSections :: Int
TODO config , also this depends on the dimension settings ? !
| null | https://raw.githubusercontent.com/1Jajen1/Brokkr/a0bff5e2fa3ad7cbb72efb29db7de53b596490b5/src/IO/Chunk.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE MultiWayIf #
Used to serialize and deserialize chunks to disk
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
# UNPACK #
TODO Make sure the Maybe is fully forced
TODO Why does this work?
TODO Error messages
The hash function is fast, but maybe we can have the data in a less pointer heavy format to boost it further
Also we have to sort props, that as well can be faster if its not in list form, we can and should just do it
over a mutable vector
# SCC lookupTag #
# SCC countBlocks # | # LANGUAGE RecordWildCards #
module IO.Chunk (
Chunk(..)
, ChunkSection(..)
, Biomes(..)
, BlockStates(..)
, countBlocks
, numSections
) where
import Registry.Biome
import Block.Internal.BlockState
import Block.Internal.Conversion
import Chunk.Heightmap
import Chunk.Position
import Control.DeepSeq
import Data.Coerce
import Data.Int
import Data.List (sortOn)
import qualified Data.ByteString as BS
import qualified Data.HashMap.Strict as HM
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Primitive as Prim
import GHC.Generics
import GHC.TypeLits
import Util.Binary
import Util.NBT
import Util.NBT.Internal
import Util.Vector.Packed (PackedVector, DynamicNat(..))
import qualified Util.Vector.Packed as P
import Util.PalettedVector
snapshot of a chunk on disk
data Chunk = Chunk {
}
deriving stock (Show, Generic)
deriving anyclass NFData
deriving (FromBinary) via BinaryNBT Chunk
type NibbleVector = PackedVector ('Static 4096) ('Static 4)
data ChunkSection = ChunkSection {
, blockLight :: !(Maybe NibbleVector)
, skyLight :: !(Maybe NibbleVector)
, blocks :: !BlockStates
, biomes :: !Biomes
}
deriving stock (Show, Generic)
deriving anyclass NFData
type BlockPaletteMaxBitsize = 1 + Log2 (HighestBlockStateId - 1)
type BiomePaletteMaxBitsze = 6
type SectionSize = 4096
type BiomeSectionSize = 64
newtype BlockStates = BlockStates (PalettedVector SectionSize BlockPaletteMaxBitsize)
deriving stock Show
deriving newtype (NFData, ToBinary)
newtype Biomes = Biomes (PalettedVector BiomeSectionSize BiomePaletteMaxBitsze)
deriving stock Show
deriving newtype (NFData, ToBinary)
instance FromNBT Chunk where
parseNBT = withCompound $ \obj -> do
!xPos <- fromIntegral @Int32 <$> obj .: "xPos"
!zPos <- fromIntegral @Int32 <$> obj .: "zPos"
let !position = ChunkPos xPos zPos
!lowestYSection <- fromIntegral @Int32 <$> obj .: "yPos"
TODO This may contain gaps ( can it ? )
!sectionsUnordered <- obj .: "sections"
let !sections = V.fromListN (V.length sectionsUnordered) . sortOn y $ V.toList sectionsUnordered
!heightmaps <- obj .: "Heightmaps"
pure Chunk{..}
# INLINE parseNBT #
# SCC parseNBT #
instance FromNBT ChunkSection where
parseNBT = withCompound $ \obj -> do
!y <- fromIntegral @Int8 <$> obj .: "Y"
!skyLight <- obj .:? "SkyLight"
!blocks <- obj .: "block_states"
let !blockCount = countBlocks blocks
!biomes <- obj .: "biomes"
pure ChunkSection{..}
# INLINE parseNBT #
# SCC parseNBT #
instance FromNBT BlockStates where
parseNBT = withCompound $ \obj -> do
palette <- fmap lookupTag <$> obj .: "palette"
if | V.length palette == 1 -> pure . BlockStates . SingleValue . coerce $ V.unsafeHead palette
| otherwise -> do
(blockStates, len) <- S.unsafeToForeignPtr0 @Int64 <$> obj .: "data"
| bitsPerVal < 9 ->
let !intPalette = Prim.generate (V.length palette) $ (coerce . (V.!) palette)
in pure . BlockStates . Indirect intPalette . P.unsafeDynamicFromForeignPtr bitsPerVal $ coerce blockStates
| otherwise -> pure . BlockStates . Global . P.unsafeStaticFromForeignPtr $ coerce blockStates
where
TODO This can further be optimized :
Currently this does a lookup ( propsToId ) into a ~22k sorted array based on the hash of ( BlockName , BlockProps )
The array can be shrunk down to fewer elements if I do two lookups , one for BlockName and one for the props
lookupTag :: Tag -> BlockState
lookupTag (TagCompound m) = maybe (error $ show m) id $ do
TagString name <- HM.lookup "Name" m
props <- case HM.lookup "Properties" m of
Just (TagCompound props) -> pure . fmap (fmap (\(TagString bs) -> bs)) $ HM.toList props
Nothing -> pure mempty
_ -> Nothing
pure . BlockState $ propsToId (coerce name) $ coerce $ sortOn fst props
lookupTag _ = error "Wut?"
# INLINE parseNBT #
# SCC parseNBT #
biomeMap :: HM.HashMap BS.ByteString Int
biomeMap = HM.fromList $ zip (T.encodeUtf8 . T.pack . fst <$> all_biome_settings) [0..]
instance FromNBT Biomes where
parseNBT = withCompound $ \obj -> do
!intPalette <- lookupBiomes <$> obj .: "palette"
if | Prim.length intPalette == 1 -> pure . Biomes . SingleValue $ Prim.unsafeHead intPalette
| otherwise -> do
(biomes, len) <- S.unsafeToForeignPtr0 @Int64 <$> obj .: "data"
TODO
if | bitsPerVal < 4 -> pure . Biomes . Indirect intPalette . P.unsafeDynamicFromForeignPtr bitsPerVal $ coerce biomes
| otherwise -> pure . Biomes . Global . P.unsafeStaticFromForeignPtr $ coerce biomes
where
lookupBiomes v = Prim.generate (V.length v) $ \i -> lookupBiome (v V.! i)
lookupBiome :: Tag -> Int
lookupBiome (TagString name) = fromMaybe (error $ show name) $ HM.lookup (BS.drop 10 $ coerce name) biomeMap
lookupBiome _ = error "WUT=!"
# SCC lookupBiome #
# INLINE parseNBT #
# SCC parseNBT #
countBlocks :: BlockStates -> Int
countBlocks (BlockStates (SingleValue val))
| isAir $ BlockState val = 0
| otherwise = fromIntegral $ natVal @SectionSize undefined
countBlocks (BlockStates (Global vec))
= sz - P.countElems (coerce $ Prim.fromList $ coerce @_ @[Int] [Air, VoidAir, CaveAir]) vec
where !sz = fromIntegral $ natVal @SectionSize undefined
countBlocks (BlockStates (Indirect palette vec))
| Prim.null airs = sz
| otherwise = sz - P.countElems (coerce airs) vec
where
!airs = Prim.findIndices (\x -> isAir $ BlockState x) palette
!sz = fromIntegral $ natVal @SectionSize undefined
isAir :: BlockState -> Bool
isAir Air = True
isAir VoidAir = True
isAir CaveAir = True
isAir _ = False
# INLINE isAir #
numSections :: Int
TODO config , also this depends on the dimension settings ? !
|
20c208ce4339bfa7e84b7615960e9ec5fbf9399c76fa2c79bb8b89e152f789c2 | clojure/clojurescript | core.cljs | (ns cljs-3284.core
(:require
cljs-3284.bean))
(defn maybe-bean
[x]
(if (object? x)
(cljs-3284.bean/some-type x)
x))
| null | https://raw.githubusercontent.com/clojure/clojurescript/fe0c6e9341a3c3613bbd90cf897a9c96b2cccd4f/src/test/cljs_build/cljs_3284/core.cljs | clojure | (ns cljs-3284.core
(:require
cljs-3284.bean))
(defn maybe-bean
[x]
(if (object? x)
(cljs-3284.bean/some-type x)
x))
|
|
7048a199f568094a99a7f15c169f97827fb9d7ec9e959b8051c7e46598ba2ea0 | ghcjs/jsaddle | JSaddle.hs | -----------------------------------------------------------------------------
--
-- Module : Language.Javascript.JSaddle
Copyright : ( c )
License : MIT
--
Maintainer : < >
--
| This package provides an EDSL for calling JavaScript that
can be used both from GHCJS and GHC . When using GHC
the application is run using Warp and WebSockets to
drive a small JavaScript helper .
-----------------------------------------------------------------------------
module Language.Javascript.JSaddle (
-- * JSaddle EDSL
-- | The 'JSM' monad gives us the context for evaluation. In keeping
-- with JavaScript the EDSL has
--
* /Weakish typing/ - type classes are used to convert to
-- and Object types
--
-- * /Strict evaluation/ - function in the 'JSM' monad can be passed in
place of a value and will evaluated and converted to or
Object and then passed on to JavaScript
--
-- JSaddle should be used to write wrappers for JavaScript libraries that provide
-- more type safety.
-- * Code Examples
-- | The code examples in this documentation are executed with a 'runjs'
function that executes the example code in the JSM monad and converts
-- the result to 'Text' with 'valToText'. It also catches unhandled
-- exceptions with 'catch'. The source code can be found in tests/TestJSaddle.hs
--
Where it makes sense code examples are given in two forms . One
that uses ' eval ' to run a purely JavaScript version and one that
-- uses more of the JSaddle EDSL feature being demonstrated.
* Calling Haskell from JavaScript
| You can call back into from JavaScript using ' fun ' to
convert a function in the JSM monad into a javascript
-- value.
* GHCJS Support
| When built with ghcjs the code works using JavaScript FFI by default .
* GHC Support
| When built with ghc the code runs a small Warp server that provides
-- index.html and jsaddle.js files. When a browser is connected the
code in jsaddle.js will open a WebSockets connection to the server
and the server will run the Haskell code . The JSaddle parts will
-- be executed by sending commands back to the browser.
Although the JavaScript code is executed in the strict order
set out by the EDSL it is done asynchronously to the code .
-- This improves the performance by reducing the number of round trips
needed between the and JavaScript code .
--
-- * Modules
module JSaddle
) where
import GHCJS.Marshal as JSaddle
import Language.Javascript.JSaddle.Types as JSaddle
import Language.Javascript.JSaddle.Classes as JSaddle
import Language.Javascript.JSaddle.Marshal.String as JSaddle ()
import Language.Javascript.JSaddle.Monad as JSaddle
import Language.Javascript.JSaddle.Exception as JSaddle
import Language.Javascript.JSaddle.Value as JSaddle
import Language.Javascript.JSaddle.Arguments as JSaddle ()
import Language.Javascript.JSaddle.Properties as JSaddle
import Language.Javascript.JSaddle.Object as JSaddle
import Language.Javascript.JSaddle.Evaluate as JSaddle
import Language.Javascript.JSaddle.String as JSaddle
| null | https://raw.githubusercontent.com/ghcjs/jsaddle/97273656e28790ab6e35c827f8086cf47bfbedca/jsaddle/src/Language/Javascript/JSaddle.hs | haskell | ---------------------------------------------------------------------------
Module : Language.Javascript.JSaddle
---------------------------------------------------------------------------
* JSaddle EDSL
| The 'JSM' monad gives us the context for evaluation. In keeping
with JavaScript the EDSL has
and Object types
* /Strict evaluation/ - function in the 'JSM' monad can be passed in
JSaddle should be used to write wrappers for JavaScript libraries that provide
more type safety.
* Code Examples
| The code examples in this documentation are executed with a 'runjs'
the result to 'Text' with 'valToText'. It also catches unhandled
exceptions with 'catch'. The source code can be found in tests/TestJSaddle.hs
uses more of the JSaddle EDSL feature being demonstrated.
value.
index.html and jsaddle.js files. When a browser is connected the
be executed by sending commands back to the browser.
This improves the performance by reducing the number of round trips
* Modules | Copyright : ( c )
License : MIT
Maintainer : < >
| This package provides an EDSL for calling JavaScript that
can be used both from GHCJS and GHC . When using GHC
the application is run using Warp and WebSockets to
drive a small JavaScript helper .
module Language.Javascript.JSaddle (
* /Weakish typing/ - type classes are used to convert to
place of a value and will evaluated and converted to or
Object and then passed on to JavaScript
function that executes the example code in the JSM monad and converts
Where it makes sense code examples are given in two forms . One
that uses ' eval ' to run a purely JavaScript version and one that
* Calling Haskell from JavaScript
| You can call back into from JavaScript using ' fun ' to
convert a function in the JSM monad into a javascript
* GHCJS Support
| When built with ghcjs the code works using JavaScript FFI by default .
* GHC Support
| When built with ghc the code runs a small Warp server that provides
code in jsaddle.js will open a WebSockets connection to the server
and the server will run the Haskell code . The JSaddle parts will
Although the JavaScript code is executed in the strict order
set out by the EDSL it is done asynchronously to the code .
needed between the and JavaScript code .
module JSaddle
) where
import GHCJS.Marshal as JSaddle
import Language.Javascript.JSaddle.Types as JSaddle
import Language.Javascript.JSaddle.Classes as JSaddle
import Language.Javascript.JSaddle.Marshal.String as JSaddle ()
import Language.Javascript.JSaddle.Monad as JSaddle
import Language.Javascript.JSaddle.Exception as JSaddle
import Language.Javascript.JSaddle.Value as JSaddle
import Language.Javascript.JSaddle.Arguments as JSaddle ()
import Language.Javascript.JSaddle.Properties as JSaddle
import Language.Javascript.JSaddle.Object as JSaddle
import Language.Javascript.JSaddle.Evaluate as JSaddle
import Language.Javascript.JSaddle.String as JSaddle
|
1260b1516f56583b256c1e8c7f586c52bd9d096662c50e658bb662e3d600f230 | mk270/blizanci | blizanci_router.erl | blizanci , a Gemini protocol server , by
%%
To the extent ( if any ) permissible by law , Copyright ( C ) 2020
%%
%% This programme is free software; you may redistribute and/or modify it under
the terms of the Apache Software Licence v2.0 .
-module(blizanci_router).
-export([prepare/1]).
-export([route/4]).
-include("blizanci_types.hrl").
-spec prepare([{string(), module(), authorisation(), [route_option()]}]) ->
{'ok', [route()]} |
{'error', atom()}.
% TBD
%% @doc
%% Check that a routing table entry is valid.
%% @end
prepare(RouteInfo) ->
try make_routes(RouteInfo) of
Routes -> {ok, Routes}
catch
Err -> {error, Err}
end.
% TBD: spec
make_routes(RouteInfo) ->
[ make_route(R) || R <- RouteInfo ].
-spec make_route({atom(), binary(), module(), authorisation(), [route_option()]})
-> route().
make_route({Proto, Regex, Module, AuthPolicy, Opts}) ->
{ok, RE} = re:compile(Regex),
case blizanci_auth:valid_authz_policy(AuthPolicy) of
{ok, _} -> #route{proto=Proto,
pattern=RE,
module=Module,
auth_policy=AuthPolicy,
options=Opts};
{error, _} -> throw(invalid_route)
end;
make_route(_) ->
throw(invalid_route).
-spec route(atom(), binary(), map(), server_config()) -> gemini_response().
%% @doc
Route a Gemini request to a handler .
%% The Config provides a routing table, which is an ordered list of regular
%% expressions and associated handler modules. route/3 searches for whether
%% the Request matches any of these routes, and if so dispatches it to the
%% appropriate handler module.
%%
%% @param The atom 'gemini' or similar
@param Path the Path in the Gemini request
@param Request the Gemini request
%% @param Config the server configuration, including the routing table
%% @end
route(Proto, Path, Request, Config=#server_config{routing=Routes}) ->
Relevant_Routes =
lists:filter(fun (Route) -> Route#route.proto =:= Proto end,
Routes),
try_route(Path, Request, Config, Relevant_Routes).
-spec try_route(binary(), map(), server_config(), [route()]) -> any().
try_route(_Path, _Request, _Config, []) ->
{error_code, file_not_found};
try_route(Path, Request, Config, [Route|Tail]) ->
case route_match(Path, Route) of
{match, Matches, Module, AuthPolicy, RouteOpts} ->
dispatch(Matches, Module, Request, AuthPolicy, Config, RouteOpts);
_ -> try_route(Path, Request, Config, Tail)
end.
-spec route_match(binary(), route()) ->
'nomatch' |
{'match', map(), module(), authorisation(), any()}.
% see the documentation for re:inspect/2 for what Matches represents and
% its format
route_match(Path, #route{pattern=Regex,
module=Module,
auth_policy=AuthPolicy,
options=RouteOpts}) ->
{namelist, Names} = re:inspect(Regex, namelist),
case re:run(Path, Regex, [{capture, all_names, binary}]) of
{match, M} ->
Matches = maps:from_list(lists:zip(Names, M)),
{match, Matches, Module, AuthPolicy, RouteOpts};
_ -> nomatch
end.
% TBD: typing could be improved
-spec dispatch(path_matches(), module(), map(), authorisation(),
server_config(), any()) ->
gemini_response().
dispatch(Matches, Module, Request, AuthPolicy, ServerConfig, RouteOpts) ->
case blizanci_auth:authorised(AuthPolicy, Request) of
authorised ->
blizanci_servlet_container:request(Module, Matches, Request,
ServerConfig, RouteOpts);
Error -> Error
end.
| null | https://raw.githubusercontent.com/mk270/blizanci/07f8be9f9e725aa6d9778fb663e54ea0d0b1ab4c/apps/blizanci/src/blizanci_router.erl | erlang |
This programme is free software; you may redistribute and/or modify it under
TBD
@doc
Check that a routing table entry is valid.
@end
TBD: spec
@doc
The Config provides a routing table, which is an ordered list of regular
expressions and associated handler modules. route/3 searches for whether
the Request matches any of these routes, and if so dispatches it to the
appropriate handler module.
@param The atom 'gemini' or similar
@param Config the server configuration, including the routing table
@end
see the documentation for re:inspect/2 for what Matches represents and
its format
TBD: typing could be improved | blizanci , a Gemini protocol server , by
To the extent ( if any ) permissible by law , Copyright ( C ) 2020
the terms of the Apache Software Licence v2.0 .
-module(blizanci_router).
-export([prepare/1]).
-export([route/4]).
-include("blizanci_types.hrl").
-spec prepare([{string(), module(), authorisation(), [route_option()]}]) ->
{'ok', [route()]} |
{'error', atom()}.
prepare(RouteInfo) ->
try make_routes(RouteInfo) of
Routes -> {ok, Routes}
catch
Err -> {error, Err}
end.
make_routes(RouteInfo) ->
[ make_route(R) || R <- RouteInfo ].
-spec make_route({atom(), binary(), module(), authorisation(), [route_option()]})
-> route().
make_route({Proto, Regex, Module, AuthPolicy, Opts}) ->
{ok, RE} = re:compile(Regex),
case blizanci_auth:valid_authz_policy(AuthPolicy) of
{ok, _} -> #route{proto=Proto,
pattern=RE,
module=Module,
auth_policy=AuthPolicy,
options=Opts};
{error, _} -> throw(invalid_route)
end;
make_route(_) ->
throw(invalid_route).
-spec route(atom(), binary(), map(), server_config()) -> gemini_response().
Route a Gemini request to a handler .
@param Path the Path in the Gemini request
@param Request the Gemini request
route(Proto, Path, Request, Config=#server_config{routing=Routes}) ->
Relevant_Routes =
lists:filter(fun (Route) -> Route#route.proto =:= Proto end,
Routes),
try_route(Path, Request, Config, Relevant_Routes).
-spec try_route(binary(), map(), server_config(), [route()]) -> any().
try_route(_Path, _Request, _Config, []) ->
{error_code, file_not_found};
try_route(Path, Request, Config, [Route|Tail]) ->
case route_match(Path, Route) of
{match, Matches, Module, AuthPolicy, RouteOpts} ->
dispatch(Matches, Module, Request, AuthPolicy, Config, RouteOpts);
_ -> try_route(Path, Request, Config, Tail)
end.
-spec route_match(binary(), route()) ->
'nomatch' |
{'match', map(), module(), authorisation(), any()}.
route_match(Path, #route{pattern=Regex,
module=Module,
auth_policy=AuthPolicy,
options=RouteOpts}) ->
{namelist, Names} = re:inspect(Regex, namelist),
case re:run(Path, Regex, [{capture, all_names, binary}]) of
{match, M} ->
Matches = maps:from_list(lists:zip(Names, M)),
{match, Matches, Module, AuthPolicy, RouteOpts};
_ -> nomatch
end.
-spec dispatch(path_matches(), module(), map(), authorisation(),
server_config(), any()) ->
gemini_response().
dispatch(Matches, Module, Request, AuthPolicy, ServerConfig, RouteOpts) ->
case blizanci_auth:authorised(AuthPolicy, Request) of
authorised ->
blizanci_servlet_container:request(Module, Matches, Request,
ServerConfig, RouteOpts);
Error -> Error
end.
|
7699325a8f0a2fb254bdb6f39294e2d4055366b23b5c83e28649f0bf8c6142f7 | lachenmayer/arrowsmith | CSRF.hs | {-# LANGUAGE OverloadedStrings #-}
module Snap.Extras.CSRF where
------------------------------------------------------------------------------
import qualified Data.ByteString.Char8 as B
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import Snap
import Snap.Snaplet.Session
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | A splice that makes the CSRF token available to templates. Typically we
-- use it by binding a splice and using the CSRF token provided by the session
-- snaplet as follows:
--
@(\"csrfToken\ " , csrfTokenSplice $ with session '
--
Where @session@ is a lens to the session snaplet . Then you can make it
-- available to javascript code by putting a meta tag at the top of every
-- page like this:
--
-- > <meta name="csrf-token" content="${csrfToken}">
csrfTokenSplice :: Monad m
=> m Text
-- ^ A computation in the runtime monad that gets the
-- CSRF protection token.
-> Splice m
csrfTokenSplice f = do
token <- lift f
textSplice token
------------------------------------------------------------------------------
| Adds a hidden _ csrf input field as the first child of the bound tag . For
-- full site protection against CSRF, you should bind this splice to the form
-- tag, and then make sure your app checks all POST requests for the presence
-- of this CSRF token and that the token is randomly generated and secure on a
-- per session basis.
secureForm :: MonadIO m
=> m Text
-- ^ A computation in the runtime monad that gets the CSRF
-- protection token.
-> Splice m
secureForm mToken = do
n <- getParamNode
token <- lift mToken
let input = X.Element "input"
[("type", "hidden"), ("name", "_csrf"), ("value", token)] []
case n of
X.Element nm as cs -> do
cs' <- runNodeList cs
let newCs = if take 1 cs' == [input] then cs' else (input : cs')
stopRecursion
return [X.Element nm as newCs]
_ -> return [n] -- "impossible"
------------------------------------------------------------------------------
-- | Use this function to wrap your whole site with CSRF protection. Due to
security considerations , the way Snap parses file uploads
-- means that the CSRF token cannot be checked before the file uploads have
-- been handled. This function protects your whole site except for handlers
-- of multipart/form-data forms (forms with file uploads). To protect those
-- handlers, you have to call handleCSRF explicitly after the file has been
-- processed.
blanketCSRF :: SnapletLens v SessionManager
^ Lens to the session snaplet
-> Handler b v ()
-- ^ Handler to run if the CSRF check fails
-> Handler b v ()
blanketCSRF session onFailure = do
h <- getHeader "Content-type" `fmap` getRequest
case maybe False (B.isInfixOf "multipart/form-data") h of
True -> return ()
False -> handleCSRF session onFailure
------------------------------------------------------------------------------
-- | If a request is a POST, check the CSRF token and fail with the specified
-- handler if the check fails. If if the token is correct or if it's not a
-- POST request, then control passes through as a no-op.
handleCSRF :: SnapletLens v SessionManager
^ Lens to the session snaplet
-> Handler b v ()
-- ^ Handler to run on failure
-> Handler b v ()
handleCSRF session onFailure = do
m <- getsRequest rqMethod
if m /= POST
then return ()
else do tok <- getParam "_csrf"
realTok <- with session csrfToken
if tok == Just (T.encodeUtf8 realTok)
then return ()
else onFailure >> getResponse >>= finishWith
| null | https://raw.githubusercontent.com/lachenmayer/arrowsmith/34b6bdeddddb2d8b9c6f41002e87ec65ce8a701a/snap-extras-0.9/src/Snap/Extras/CSRF.hs | haskell | # LANGUAGE OverloadedStrings #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
| A splice that makes the CSRF token available to templates. Typically we
use it by binding a splice and using the CSRF token provided by the session
snaplet as follows:
available to javascript code by putting a meta tag at the top of every
page like this:
> <meta name="csrf-token" content="${csrfToken}">
^ A computation in the runtime monad that gets the
CSRF protection token.
----------------------------------------------------------------------------
full site protection against CSRF, you should bind this splice to the form
tag, and then make sure your app checks all POST requests for the presence
of this CSRF token and that the token is randomly generated and secure on a
per session basis.
^ A computation in the runtime monad that gets the CSRF
protection token.
"impossible"
----------------------------------------------------------------------------
| Use this function to wrap your whole site with CSRF protection. Due to
means that the CSRF token cannot be checked before the file uploads have
been handled. This function protects your whole site except for handlers
of multipart/form-data forms (forms with file uploads). To protect those
handlers, you have to call handleCSRF explicitly after the file has been
processed.
^ Handler to run if the CSRF check fails
----------------------------------------------------------------------------
| If a request is a POST, check the CSRF token and fail with the specified
handler if the check fails. If if the token is correct or if it's not a
POST request, then control passes through as a no-op.
^ Handler to run on failure |
module Snap.Extras.CSRF where
import qualified Data.ByteString.Char8 as B
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import Snap
import Snap.Snaplet.Session
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
@(\"csrfToken\ " , csrfTokenSplice $ with session '
Where @session@ is a lens to the session snaplet . Then you can make it
csrfTokenSplice :: Monad m
=> m Text
-> Splice m
csrfTokenSplice f = do
token <- lift f
textSplice token
| Adds a hidden _ csrf input field as the first child of the bound tag . For
secureForm :: MonadIO m
=> m Text
-> Splice m
secureForm mToken = do
n <- getParamNode
token <- lift mToken
let input = X.Element "input"
[("type", "hidden"), ("name", "_csrf"), ("value", token)] []
case n of
X.Element nm as cs -> do
cs' <- runNodeList cs
let newCs = if take 1 cs' == [input] then cs' else (input : cs')
stopRecursion
return [X.Element nm as newCs]
security considerations , the way Snap parses file uploads
blanketCSRF :: SnapletLens v SessionManager
^ Lens to the session snaplet
-> Handler b v ()
-> Handler b v ()
blanketCSRF session onFailure = do
h <- getHeader "Content-type" `fmap` getRequest
case maybe False (B.isInfixOf "multipart/form-data") h of
True -> return ()
False -> handleCSRF session onFailure
handleCSRF :: SnapletLens v SessionManager
^ Lens to the session snaplet
-> Handler b v ()
-> Handler b v ()
handleCSRF session onFailure = do
m <- getsRequest rqMethod
if m /= POST
then return ()
else do tok <- getParam "_csrf"
realTok <- with session csrfToken
if tok == Just (T.encodeUtf8 realTok)
then return ()
else onFailure >> getResponse >>= finishWith
|
e424838e10da0541dda9b8274b0826b301086b3b33489de585c3b00fbcba7759 | hbrouwer/pdrt-sandbox | DRSTutorial.hs | -- This is a tutorial for creating and manipulating DRSs with PDRT-SANDBOX.
import Data.DRS
--------------------------------------------------------------------------------
* Creating a DRS
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| A Discourse Representation Structure ( DRS ) consists of two sets : the
first set contains the DRS referents , and the second set contains the DRS
conditions . The first example shows an empty DRS . The second example
shows a DRS containing one referent and a two simple conditions ( the
-- predicate "man", and the predicate "happy"). Independent of their arity,
-- predicates and relations are always referred to as 'Rel'.
--------------------------------------------------------------------------------
| empty DRS
exampleDRS1 = DRS [] []
-- | "A man is happy."
exampleDRS2 = DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "happy") [DRSRef "x"]]
--------------------------------------------------------------------------------
| A ' Rel ' condition takes two arguments : the name of the
predicate / relation , and a set of DRS referents . There are six other
conditions , called complex conditions , all of which take one or more DRSs
-- as arguments:
--
-- * unary complex conditions: negation ('Neg'), modal possibility
-- ('Diamond'), modal necessity ('Box');
--
-- * binary complex conditions: implication ('Imp') and disjunction ('Or');
--
-- * mixed complex condition: propositional condition ('Prop').
--
-- Below we show an example from each of these.
--------------------------------------------------------------------------------
-- | "A man is not happy."
exampleDRS3 = DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Neg (DRS [] [Rel (DRSRel "happy") [DRSRef "x"]])]
-- | "If a farmer owns a donkey, he feeds it."
exampleDRS4 = DRS []
[Imp
(DRS [DRSRef "x",DRSRef "y"]
[Rel (DRSRel "farmer") [DRSRef "x"]
,Rel (DRSRel "donkey") [DRSRef "y"]
,Rel (DRSRel "owns") [DRSRef "x",DRSRef "y"]])
(DRS [] [Rel (DRSRel "feeds") [DRSRef "x",DRSRef "y"]])]
-- | "A man believes he loves a woman."
exampleDRS5 = DRS [DRSRef "x",DRSRef "y",DRSRef "p"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "woman") [DRSRef "y"]
,Rel (DRSRel "believes") [DRSRef "x",DRSRef "p"]
,Prop (DRSRef "p") (DRS []
[Rel (DRSRel "loves") [DRSRef "x",DRSRef "y"]])]
--------------------------------------------------------------------------------
| Besides directly defining a DRS using the DRS syntax , it is also
-- possible to use a set-theoretical string input format directly.
--
-- The following names can be used for different operators (these are all
-- case insensitive):
--
-- * Negation operators: !, not, neg
-- * Implication operators (infix): imp, ->, =>, then
-- * Disjuction operators (infix): v, or
-- * Box operators: b, box, necessary
-- * Diamond operators: d, diamond, maybe.
--------------------------------------------------------------------------------
-- | "A man is happy and not sad."
exampleDRS6 = stringToDRS "<{x }, {man(x), happy(x), not <{},{sad(x)}> }>"
--------------------------------------------------------------------------------
-- * Showing DRSs
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- | The default format for showing DRSs is the Boxes output format.
-- However, in PDRT-SANDBOX different output formats can be used:
--
-- * Box-representations (default): 'Boxes'
-- * Linear notation: 'Linear'
-- * Set-theoretic notation: 'Set'
-- * PDRT-SANDBOX syntax output: 'Debug'
--------------------------------------------------------------------------------
exampleDRS7a = Boxes exampleDRS4
exampleDRS7b = Linear exampleDRS4
exampleDRS7c = Set exampleDRS4
exampleDRS7d = Debug exampleDRS4
--------------------------------------------------------------------------------
-- * Combining DRSs
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| Using the DRS syntax defined above , we can now combine two DRSs with
-- the merge operation, using the 'Merge' constructor, the merge operator
-- ('drsMerge'), or the infix merge operator ('<<+>>'). Finally, it is also
-- possible to visualize the entire merge equation (using 'printMerge').
--------------------------------------------------------------------------------
-- | "A man is happy and a man is not happy."
exampleDRSMerge1 = drsResolveMerges $ Merge exampleDRS2 exampleDRS3
-- | "A man is not happy. He is sad."
exampleDRSMerge2a = drsMerge exampleDRS3 (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
exampleDRSMerge2b = exampleDRS3 <<+>> (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
exampleDRSMerge2c = printMerge exampleDRS3 (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
--------------------------------------------------------------------------------
| Unresolved structures can simply be defined as functions .
-- Unresolved DRSs can be combined by means of function application. This can
-- be done directly, or via one of the available functions for showing the
-- complete equation for Lambda-resolution ('printDRSRefBetaReduct' and
-- 'printDRSBetaReduct').
--------------------------------------------------------------------------------
-- | λx.happy(x)
exampleDRSLambda1 x = DRS [] [Rel (DRSRel "happy") [x]]
-- | λx.happy(x) ("harm") = happy(harm)
exampleDRSLambda1a = exampleDRSLambda1 (DRSRef "harm")
exampleDRSLambda1b = printDRSRefBetaReduct exampleDRSLambda1 (DRSRef "harm")
-- | λK.Ǝx(man(x) ∧ happy(x) ∧ K)
exampleDRSLambda2 k = Merge (DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "happy") [DRSRef "x"]])
(k)
| λK.Ǝx(man(x ) ∧ happy(x ) ∧ K ) ( Ǝx(man(x ) ∧ ¬happy(x ) ) )
= Ǝx(man(x ) ∧ ) ∧ Ǝx'(man(x ' ) ∧ ¬happy(x ' ) ) )
exampleDRSLambda2a = exampleDRSLambda2 exampleDRS3
exampleDRSLambda2b = printDRSBetaReduct exampleDRSLambda2 exampleDRS3
-- | λP.Ǝx(man(x) ∧ P(x))
exampleDRSLambda3 p = Merge
(DRS [DRSRef "x"] [Rel (DRSRel "man") [DRSRef "x"]])
(p (DRSRef "x"))
| λP.Ǝx(man(x ) ∧ P(x ) ) ( λx.happy(x ) ) = Ǝx(man(x ) ∧ ) )
exampleDRSLambda3a = exampleDRSLambda3 exampleDRSLambda1
--------------------------------------------------------------------------------
* Translate to FOL
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| Each ( resolved ) DRS can be translated into a First Order Logic formula .
These FOL formulas will always be quantified relative to a world ' w ' , in
-- order to account for the modal operators.
--------------------------------------------------------------------------------
| " Maybe is not happy . " ( NB . here , the proper name " " is
-- described as a constant, but see the PDRT tutorial for a better
-- treatment of proper names.)
exampleDRSFOL = drsToFOL (DRS [] [Diamond (DRS []
[Neg (DRS [] [Rel (DRSRel "happy") [DRSRef "john"]])])])
| null | https://raw.githubusercontent.com/hbrouwer/pdrt-sandbox/4937424013b6a11bac4cd5444d3e173420fab98a/tutorials/DRSTutorial.hs | haskell | This is a tutorial for creating and manipulating DRSs with PDRT-SANDBOX.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
predicate "man", and the predicate "happy"). Independent of their arity,
predicates and relations are always referred to as 'Rel'.
------------------------------------------------------------------------------
| "A man is happy."
------------------------------------------------------------------------------
as arguments:
* unary complex conditions: negation ('Neg'), modal possibility
('Diamond'), modal necessity ('Box');
* binary complex conditions: implication ('Imp') and disjunction ('Or');
* mixed complex condition: propositional condition ('Prop').
Below we show an example from each of these.
------------------------------------------------------------------------------
| "A man is not happy."
| "If a farmer owns a donkey, he feeds it."
| "A man believes he loves a woman."
------------------------------------------------------------------------------
possible to use a set-theoretical string input format directly.
The following names can be used for different operators (these are all
case insensitive):
* Negation operators: !, not, neg
* Implication operators (infix): imp, ->, =>, then
* Disjuction operators (infix): v, or
* Box operators: b, box, necessary
* Diamond operators: d, diamond, maybe.
------------------------------------------------------------------------------
| "A man is happy and not sad."
------------------------------------------------------------------------------
* Showing DRSs
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| The default format for showing DRSs is the Boxes output format.
However, in PDRT-SANDBOX different output formats can be used:
* Box-representations (default): 'Boxes'
* Linear notation: 'Linear'
* Set-theoretic notation: 'Set'
* PDRT-SANDBOX syntax output: 'Debug'
------------------------------------------------------------------------------
------------------------------------------------------------------------------
* Combining DRSs
------------------------------------------------------------------------------
------------------------------------------------------------------------------
the merge operation, using the 'Merge' constructor, the merge operator
('drsMerge'), or the infix merge operator ('<<+>>'). Finally, it is also
possible to visualize the entire merge equation (using 'printMerge').
------------------------------------------------------------------------------
| "A man is happy and a man is not happy."
| "A man is not happy. He is sad."
------------------------------------------------------------------------------
Unresolved DRSs can be combined by means of function application. This can
be done directly, or via one of the available functions for showing the
complete equation for Lambda-resolution ('printDRSRefBetaReduct' and
'printDRSBetaReduct').
------------------------------------------------------------------------------
| λx.happy(x)
| λx.happy(x) ("harm") = happy(harm)
| λK.Ǝx(man(x) ∧ happy(x) ∧ K)
| λP.Ǝx(man(x) ∧ P(x))
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
order to account for the modal operators.
------------------------------------------------------------------------------
described as a constant, but see the PDRT tutorial for a better
treatment of proper names.) |
import Data.DRS
* Creating a DRS
| A Discourse Representation Structure ( DRS ) consists of two sets : the
first set contains the DRS referents , and the second set contains the DRS
conditions . The first example shows an empty DRS . The second example
shows a DRS containing one referent and a two simple conditions ( the
| empty DRS
exampleDRS1 = DRS [] []
exampleDRS2 = DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "happy") [DRSRef "x"]]
| A ' Rel ' condition takes two arguments : the name of the
predicate / relation , and a set of DRS referents . There are six other
conditions , called complex conditions , all of which take one or more DRSs
exampleDRS3 = DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Neg (DRS [] [Rel (DRSRel "happy") [DRSRef "x"]])]
exampleDRS4 = DRS []
[Imp
(DRS [DRSRef "x",DRSRef "y"]
[Rel (DRSRel "farmer") [DRSRef "x"]
,Rel (DRSRel "donkey") [DRSRef "y"]
,Rel (DRSRel "owns") [DRSRef "x",DRSRef "y"]])
(DRS [] [Rel (DRSRel "feeds") [DRSRef "x",DRSRef "y"]])]
exampleDRS5 = DRS [DRSRef "x",DRSRef "y",DRSRef "p"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "woman") [DRSRef "y"]
,Rel (DRSRel "believes") [DRSRef "x",DRSRef "p"]
,Prop (DRSRef "p") (DRS []
[Rel (DRSRel "loves") [DRSRef "x",DRSRef "y"]])]
| Besides directly defining a DRS using the DRS syntax , it is also
exampleDRS6 = stringToDRS "<{x }, {man(x), happy(x), not <{},{sad(x)}> }>"
exampleDRS7a = Boxes exampleDRS4
exampleDRS7b = Linear exampleDRS4
exampleDRS7c = Set exampleDRS4
exampleDRS7d = Debug exampleDRS4
| Using the DRS syntax defined above , we can now combine two DRSs with
exampleDRSMerge1 = drsResolveMerges $ Merge exampleDRS2 exampleDRS3
exampleDRSMerge2a = drsMerge exampleDRS3 (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
exampleDRSMerge2b = exampleDRS3 <<+>> (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
exampleDRSMerge2c = printMerge exampleDRS3 (DRS [] [Rel (DRSRel "sad") [DRSRef "x"]])
| Unresolved structures can simply be defined as functions .
exampleDRSLambda1 x = DRS [] [Rel (DRSRel "happy") [x]]
exampleDRSLambda1a = exampleDRSLambda1 (DRSRef "harm")
exampleDRSLambda1b = printDRSRefBetaReduct exampleDRSLambda1 (DRSRef "harm")
exampleDRSLambda2 k = Merge (DRS [DRSRef "x"]
[Rel (DRSRel "man") [DRSRef "x"]
,Rel (DRSRel "happy") [DRSRef "x"]])
(k)
| λK.Ǝx(man(x ) ∧ happy(x ) ∧ K ) ( Ǝx(man(x ) ∧ ¬happy(x ) ) )
= Ǝx(man(x ) ∧ ) ∧ Ǝx'(man(x ' ) ∧ ¬happy(x ' ) ) )
exampleDRSLambda2a = exampleDRSLambda2 exampleDRS3
exampleDRSLambda2b = printDRSBetaReduct exampleDRSLambda2 exampleDRS3
exampleDRSLambda3 p = Merge
(DRS [DRSRef "x"] [Rel (DRSRel "man") [DRSRef "x"]])
(p (DRSRef "x"))
| λP.Ǝx(man(x ) ∧ P(x ) ) ( λx.happy(x ) ) = Ǝx(man(x ) ∧ ) )
exampleDRSLambda3a = exampleDRSLambda3 exampleDRSLambda1
* Translate to FOL
| Each ( resolved ) DRS can be translated into a First Order Logic formula .
These FOL formulas will always be quantified relative to a world ' w ' , in
| " Maybe is not happy . " ( NB . here , the proper name " " is
exampleDRSFOL = drsToFOL (DRS [] [Diamond (DRS []
[Neg (DRS [] [Rel (DRSRel "happy") [DRSRef "john"]])])])
|
df46a91a9b1c96e3080b4983177b3d85113f345cfd01ffed79280b819864aa5f | tlehman/sicp-exercises | ex-1.26.scm | Exercise 1.26 : is having great difficulty doing Exercise 1.24 . His fast - prime ? test seems to run more slowly than his prime ? test . calls his friend over to help . When they examine ' code , they find that he has rewritten the expmod procedure to use an explicit multiplication , rather than calling square :
(load "helpers.scm")
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(remainder (* (expmod base (/ exp 2) m)
(expmod base (/ exp 2) m))
m))
(else
(remainder (* base (expmod base
(- exp 1)
m))
" I do n't see what difference that could make , " says . " I do . " says . " By writing the procedure like that , you have transformed the Theta(log(n ) ) process into a Theta(n ) process " . Explain
Because of applicative - order evaluation , the expression ( expmod base ( / exp 2 ) m ) is computed twice . If had used ( square ( expmod base ( / exp 2 ) ) ) , the expression ( expmod base ( / exp 2 ) ) would only be evaluated once , and the result would be squared . As a result , the double evaluation cancels out the gains in speed we get by using the successive squaring method .
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-1.26.scm | scheme | Exercise 1.26 : is having great difficulty doing Exercise 1.24 . His fast - prime ? test seems to run more slowly than his prime ? test . calls his friend over to help . When they examine ' code , they find that he has rewritten the expmod procedure to use an explicit multiplication , rather than calling square :
(load "helpers.scm")
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(remainder (* (expmod base (/ exp 2) m)
(expmod base (/ exp 2) m))
m))
(else
(remainder (* base (expmod base
(- exp 1)
m))
" I do n't see what difference that could make , " says . " I do . " says . " By writing the procedure like that , you have transformed the Theta(log(n ) ) process into a Theta(n ) process " . Explain
Because of applicative - order evaluation , the expression ( expmod base ( / exp 2 ) m ) is computed twice . If had used ( square ( expmod base ( / exp 2 ) ) ) , the expression ( expmod base ( / exp 2 ) ) would only be evaluated once , and the result would be squared . As a result , the double evaluation cancels out the gains in speed we get by using the successive squaring method .
|
|
4451c4277344cae481a19e317a936d14f108984906e474f3705b2f7950a2d4d1 | pascal-knodel/haskell-craft | E'9''9.hs | --
--
--
----------------
Exercise 9.9 .
----------------
--
--
--
module E'9''9 where
Notes :
--
-- - Use/See templates for structural induction.
- Note : Re/-member/-think/-view the definitions of " zip " , " unzip " , " fst " and " snd " .
-- ------------
-- Proposition:
-- ------------
--
zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) ) = pairs
--
--
-- Proof By Structural Induction:
-- ------------------------------
--
--
Induction Beginning ( I.B. ):
-- ---------------------------
--
--
( Base case 1 . ) : < = > pairs : = [ ]
--
= > ( left ) : = zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( Base case 1 . )
= zip ( fst ( unzip [ ] ) ) ( snd ( unzip [ ] ) )
-- | unzip
= zip ( fst ( [ ] , [ ] ) ) ( snd ( [ ] , [ ] ) )
-- | fst
= zip [ ] ( snd ( [ ] , [ ] ) )
-- | snd
-- = zip [] []
-- | zip
-- = []
--
--
-- (right) := pairs
| ( Base case 1 . )
-- = []
--
--
-- => (left) = (right)
--
-- ✔
--
--
Induction Hypothesis ( I.H. ):
-- ----------------------------
--
-- For an arbitrary, but fixed list "pairs", the statement ...
--
zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) ) = pairs
--
-- ... holds.
--
--
-- Induction Step (I.S.):
-- ----------------------
--
--
( left ) : = zip ( fst ( unzip ( pair : pairs ) ) ) ( snd ( unzip ( pair : pairs ) ) )
-- | zip
= pair : zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( I.H. )
-- = pair : pairs
--
--
-- (right) := pair : pairs
--
--
-- => (left) = (right)
--
-- ■
-- Note: More detailed induction:
--
( left ) : = zip ( fst ( unzip ( pair : pairs ) ) ) ( snd ( unzip ( pair : pairs ) ) )
--
= zip ( fst ( unzip ( ( firstComponent , secondComponent ) : pairs ) )
( snd ( unzip ( ( firstComponent , secondComponent ) : pairs ) )
--
= zip ( fst ( : , secondComponent : remainingSecondComponents ) )
( snd ( : , secondComponent : remainingSecondComponents ) )
--
= zip ( : ) ( secondComponent : remainingSecondComponents )
-- | zip
= ( , secondComponent ) : zip remainingFirstComponents remainingSecondComponents
--
= pair : zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( I.H. )
-- = pair : pairs
-- ------------
-- Proposition:
-- ------------
--
-- Assumption: length leftList = length rightList
--
-- => unzip ( zip leftList rightList ) = ( leftList , rightList )
--
--
-- Proof By Structural Induction:
-- ------------------------------
--
--
Induction Beginning ( I.B. ):
-- ---------------------------
--
--
( Base case 1 . ) : < = > leftList : = [ ]
-- | (Assumption.)
-- :=> rightList = []
--
-- => (left) := unzip ( zip leftList rightList )
| ( Base case 1 . )
-- = unzip ( zip [] [] )
-- | zip
-- = unzip ( [] )
-- | unzip
-- = ( [] , [] )
--
--
-- (right) := ( leftList , rightList )
| ( Base case 1 . )
-- = ( [] , [] )
--
--
-- => (left) = (right)
--
-- ✔
--
--
Induction Hypothesis ( I.H. ):
-- ----------------------------
--
-- For an arbitrary, but fixed list-length (a natural number), the statement ...
--
-- unzip ( zip leftList rightList ) = ( leftList , rightList )
--
-- ... holds.
--
--
-- Induction Step (I.S.):
-- ----------------------
--
--
-- (left) := unzip ( zip ( leftItem : remainingLeftItems ) ( rightItem : remainingRightItems ) )
-- | zip
| ( List length(s ) are at least 1 . )
-- | (Assumption.)
-- = unzip ( ( leftItem , rightItem ) : zip remainingLeftItems remainingRightItems )
-- | unzip
-- = ( leftItem : remainingLeftItems' , rightItem : remainingRightItems' )
-- where ( remainingLeftItems' , remainingRightItems' ) := unzip ( zip remainingLeftItems remainingRightItems )
| ( I.H. )
-- | (Assumption.)
-- = ( leftItem : remainingLeftItems , rightItem : remainingRightItems )
--
--
-- (right) := ( leftItem : remainingLeftItems , rightItem : remainingRightItems )
--
--
-- => (left) = (right)
--
-- ■
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Chapter%209/E'9''9.hs | haskell |
--------------
--------------
- Use/See templates for structural induction.
------------
Proposition:
------------
Proof By Structural Induction:
------------------------------
---------------------------
| unzip
| fst
| snd
= zip [] []
| zip
= []
(right) := pairs
= []
=> (left) = (right)
✔
----------------------------
For an arbitrary, but fixed list "pairs", the statement ...
... holds.
Induction Step (I.S.):
----------------------
| zip
= pair : pairs
(right) := pair : pairs
=> (left) = (right)
■
Note: More detailed induction:
| zip
= pair : pairs
------------
Proposition:
------------
Assumption: length leftList = length rightList
=> unzip ( zip leftList rightList ) = ( leftList , rightList )
Proof By Structural Induction:
------------------------------
---------------------------
| (Assumption.)
:=> rightList = []
=> (left) := unzip ( zip leftList rightList )
= unzip ( zip [] [] )
| zip
= unzip ( [] )
| unzip
= ( [] , [] )
(right) := ( leftList , rightList )
= ( [] , [] )
=> (left) = (right)
✔
----------------------------
For an arbitrary, but fixed list-length (a natural number), the statement ...
unzip ( zip leftList rightList ) = ( leftList , rightList )
... holds.
Induction Step (I.S.):
----------------------
(left) := unzip ( zip ( leftItem : remainingLeftItems ) ( rightItem : remainingRightItems ) )
| zip
| (Assumption.)
= unzip ( ( leftItem , rightItem ) : zip remainingLeftItems remainingRightItems )
| unzip
= ( leftItem : remainingLeftItems' , rightItem : remainingRightItems' )
where ( remainingLeftItems' , remainingRightItems' ) := unzip ( zip remainingLeftItems remainingRightItems )
| (Assumption.)
= ( leftItem : remainingLeftItems , rightItem : remainingRightItems )
(right) := ( leftItem : remainingLeftItems , rightItem : remainingRightItems )
=> (left) = (right)
■ | Exercise 9.9 .
module E'9''9 where
Notes :
- Note : Re/-member/-think/-view the definitions of " zip " , " unzip " , " fst " and " snd " .
zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) ) = pairs
Induction Beginning ( I.B. ):
( Base case 1 . ) : < = > pairs : = [ ]
= > ( left ) : = zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( Base case 1 . )
= zip ( fst ( unzip [ ] ) ) ( snd ( unzip [ ] ) )
= zip ( fst ( [ ] , [ ] ) ) ( snd ( [ ] , [ ] ) )
= zip [ ] ( snd ( [ ] , [ ] ) )
| ( Base case 1 . )
Induction Hypothesis ( I.H. ):
zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) ) = pairs
( left ) : = zip ( fst ( unzip ( pair : pairs ) ) ) ( snd ( unzip ( pair : pairs ) ) )
= pair : zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( I.H. )
( left ) : = zip ( fst ( unzip ( pair : pairs ) ) ) ( snd ( unzip ( pair : pairs ) ) )
= zip ( fst ( unzip ( ( firstComponent , secondComponent ) : pairs ) )
( snd ( unzip ( ( firstComponent , secondComponent ) : pairs ) )
= zip ( fst ( : , secondComponent : remainingSecondComponents ) )
( snd ( : , secondComponent : remainingSecondComponents ) )
= zip ( : ) ( secondComponent : remainingSecondComponents )
= ( , secondComponent ) : zip remainingFirstComponents remainingSecondComponents
= pair : zip ( fst ( unzip pairs ) ) ( snd ( unzip pairs ) )
| ( I.H. )
Induction Beginning ( I.B. ):
( Base case 1 . ) : < = > leftList : = [ ]
| ( Base case 1 . )
| ( Base case 1 . )
Induction Hypothesis ( I.H. ):
| ( List length(s ) are at least 1 . )
| ( I.H. )
|
665c4aea667ee6a29fc4183a853b6b665159b2087567bbeeebda1bc06092616d | mcorbin/meuse | crate.clj | (ns meuse.db.queries.crate
(:require [honeysql.core :as sql]
[honeysql.helpers :as h]))
(defn get-crate
[where-clause]
(-> (h/select :c.id
:c.name)
(h/from [:crates :c])
(h/where where-clause)
sql/format))
(defn by-name-join-version
[crate-name crate-version]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.yanked
:v.created_at
:v.download_count
:v.updated_at
:v.document_vectors
:v.crate_id)
(h/from [:crates :c])
(h/join [:crates_versions :v] [:and
[:= :c.id :v.crate_id]
[:= :v.version crate-version]])
(h/where [:= :c.name crate-name])
sql/format))
(defn by-name
[crate-name]
(get-crate [:= :c.name crate-name]))
(defn create
[metadata crate-id]
(-> (h/insert-into :crates)
(h/columns :id :name)
(h/values [[crate-id
(:name metadata)]])
sql/format))
(defn get-crates-and-versions
[]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
sql/format))
(defn get-crate-and-versions
[crate-name]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.metadata
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
(h/where [:= :c.name crate-name])
sql/format))
(defn get-crates-for-category
[category-id]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id]
[:crates_categories :cat]
[:= :cat.crate_id :c.id])
(h/where [:= :cat.category_id category-id])
sql/format))
(defn get-crates-range
[start end prefix]
(-> (h/select :c.id
:c.name
:%count.*)
(h/from [:crates :c])
(h/where [:like :c.name (str prefix "%")])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
(h/group :c.id)
(h/order-by :c.name)
(h/offset start)
(h/limit end)
sql/format))
(defn count-crates
[]
(-> (h/select :%count.*)
(h/from [:crates :c])
sql/format))
(defn count-crates-prefix
[prefix]
(-> (h/select :%count.*)
(h/from [:crates :c])
(h/where [:like :c.name (str prefix "%")])
sql/format))
| null | https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/src/meuse/db/queries/crate.clj | clojure | (ns meuse.db.queries.crate
(:require [honeysql.core :as sql]
[honeysql.helpers :as h]))
(defn get-crate
[where-clause]
(-> (h/select :c.id
:c.name)
(h/from [:crates :c])
(h/where where-clause)
sql/format))
(defn by-name-join-version
[crate-name crate-version]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.yanked
:v.created_at
:v.download_count
:v.updated_at
:v.document_vectors
:v.crate_id)
(h/from [:crates :c])
(h/join [:crates_versions :v] [:and
[:= :c.id :v.crate_id]
[:= :v.version crate-version]])
(h/where [:= :c.name crate-name])
sql/format))
(defn by-name
[crate-name]
(get-crate [:= :c.name crate-name]))
(defn create
[metadata crate-id]
(-> (h/insert-into :crates)
(h/columns :id :name)
(h/values [[crate-id
(:name metadata)]])
sql/format))
(defn get-crates-and-versions
[]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
sql/format))
(defn get-crate-and-versions
[crate-name]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.metadata
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
(h/where [:= :c.name crate-name])
sql/format))
(defn get-crates-for-category
[category-id]
(-> (h/select :c.id
:c.name
:v.id
:v.version
:v.description
:v.download_count
:v.yanked
:v.created_at
:v.updated_at)
(h/from [:crates :c])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id]
[:crates_categories :cat]
[:= :cat.crate_id :c.id])
(h/where [:= :cat.category_id category-id])
sql/format))
(defn get-crates-range
[start end prefix]
(-> (h/select :c.id
:c.name
:%count.*)
(h/from [:crates :c])
(h/where [:like :c.name (str prefix "%")])
(h/join [:crates_versions :v]
[:= :c.id :v.crate_id])
(h/group :c.id)
(h/order-by :c.name)
(h/offset start)
(h/limit end)
sql/format))
(defn count-crates
[]
(-> (h/select :%count.*)
(h/from [:crates :c])
sql/format))
(defn count-crates-prefix
[prefix]
(-> (h/select :%count.*)
(h/from [:crates :c])
(h/where [:like :c.name (str prefix "%")])
sql/format))
|
|
c6d136562014e4af6849d589c75c7a816dbd27a10a57ef05bff49bf0d00acabe | slipstream/SlipStreamServer | test_helper.clj | (ns com.sixsq.slipstream.auth.test-helper
(:refer-clojure :exclude [update])
(:require
[com.sixsq.slipstream.auth.internal :as ia]
[com.sixsq.slipstream.db.es.binding :as esb]
[com.sixsq.slipstream.db.es.utils :as esu]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.user :as ur]
[com.sixsq.slipstream.ssclj.resources.user-template :as ct]
[com.sixsq.slipstream.ssclj.resources.user-template-direct :as direct]
[com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu]))
(def rname ur/resource-url)
(def req-u-name "internal")
(def req-u-role "ADMIN")
(def req-template {:userTemplate
{:href (str ct/resource-url "/" direct/registration-method)
:method "direct"}})
(def request-base {:identity {:current req-u-name
:authentications {req-u-name {:roles #{req-u-role}
:identity req-u-name}}}
:sixsq.slipstream.authn/claims
{:username req-u-name
:roles #{req-u-role}}
:user-name req-u-name
:params {:resource-name rname}
:route-params {:resource-name rname}
:body req-template})
(defn- user-request
[{:keys [password state] :as user}]
(->> (assoc user :password (ia/hash-password password)
:state (or state "ACTIVE"))
(update-in request-base [:body :userTemplate] merge)))
(defn add-user-for-test!
[user]
(crud/add (user-request user)))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi/test/com/sixsq/slipstream/auth/test_helper.clj | clojure | (ns com.sixsq.slipstream.auth.test-helper
(:refer-clojure :exclude [update])
(:require
[com.sixsq.slipstream.auth.internal :as ia]
[com.sixsq.slipstream.db.es.binding :as esb]
[com.sixsq.slipstream.db.es.utils :as esu]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.user :as ur]
[com.sixsq.slipstream.ssclj.resources.user-template :as ct]
[com.sixsq.slipstream.ssclj.resources.user-template-direct :as direct]
[com.sixsq.slipstream.ssclj.resources.user.user-identifier-utils :as uiu]))
(def rname ur/resource-url)
(def req-u-name "internal")
(def req-u-role "ADMIN")
(def req-template {:userTemplate
{:href (str ct/resource-url "/" direct/registration-method)
:method "direct"}})
(def request-base {:identity {:current req-u-name
:authentications {req-u-name {:roles #{req-u-role}
:identity req-u-name}}}
:sixsq.slipstream.authn/claims
{:username req-u-name
:roles #{req-u-role}}
:user-name req-u-name
:params {:resource-name rname}
:route-params {:resource-name rname}
:body req-template})
(defn- user-request
[{:keys [password state] :as user}]
(->> (assoc user :password (ia/hash-password password)
:state (or state "ACTIVE"))
(update-in request-base [:body :userTemplate] merge)))
(defn add-user-for-test!
[user]
(crud/add (user-request user)))
|
|
b81932f06a8662fee927e9f0823f98f737d208ad2b5f00f9839929ecfbcdb69d | fulcrologic/video-series | session.cljs | (ns app.model.session
(:require
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.dom :as dom :refer [div a]]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom.html-entities :as ent]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]]
[app.routing :as routing]
[taoensso.timbre :as log]))
(defn handle-login [{::uism/keys [event-data] :as env}]
(let [user-class (uism/actor-class env :actor/user)]
(-> env
(uism/trigger-remote-mutation :actor/login-form `login
(merge event-data
{:com.fulcrologic.fulcro.mutations/returning user-class
:com.fulcrologic.fulcro.algorithms.data-targeting/target [:session/current-user]
::uism/ok-event :event/ok
::uism/error-event :event/error}))
(uism/activate :state/checking-credentials))))
(def main-events
{:event/logout {::uism/handler (fn [env]
(routing/route-to! "/login")
(-> env
(uism/trigger-remote-mutation :actor/login `logout {})
(uism/apply-action assoc-in [::session :current-user] {:user/id :nobody :user/valid? false})))}
:event/login {::uism/handler handle-login}})
(defstatemachine session-machine
{::uism/actor-name
#{:actor/user
:actor/login-form}
::uism/aliases
{:logged-in? [:actor/user :user/valid?]}
::uism/states
{:initial
{::uism/handler
(fn [{::uism/keys [event-data] :as env}]
(-> env
(uism/store :config event-data) ; save desired path for later routing
(uism/load :session/current-user :actor/user {::uism/ok-event :event/ok
::uism/error-event :event/error})
(uism/activate :state/checking-existing-session)))}
:state/checking-existing-session
{::uism/events
{:event/ok {::uism/handler (fn [env]
(let [logged-in? (uism/alias-value env :logged-in?)]
(when-not logged-in?
(routing/route-to! "/login"))
(uism/activate env :state/idle)))}
:event/error {::uism/handler (fn [env] (uism/activate env :state/server-failed))}}}
:state/bad-credentials
{::uism/events main-events}
:state/idle
{::uism/events main-events}
:state/checking-credentials
{::uism/events {:event/ok {::uism/handler (fn [env]
(let [logged-in? (uism/alias-value env :logged-in?)
{:keys [desired-path]} (uism/retrieve env :config)]
(when (and logged-in? desired-path)
(routing/route-to! desired-path))
(-> env
(uism/activate (if logged-in?
:state/idle
:state/bad-credentials)))))}
:event/error {::uism/handler (fn [env] (uism/activate env :state/server-failed))}}}
:state/server-failed
{::uism/events main-events}}})
(defsc CurrentUser [this {:keys [:user/id :user/email :user/valid?] :as props}]
{:query [:user/id :user/email :user/valid?]
:initial-state {:user/id :nobody :user/valid? false}
:ident (fn [] [::session :current-user])}
(dom/div :.item
(if valid?
(div :.content
email ent/nbsp (a {:onClick
(fn [] (uism/trigger! this ::sessions :event/logout))}
"Logout"))
(a {:onClick #(dr/change-route this ["login"])} "Login"))))
(def ui-current-user (comp/factory CurrentUser))
| null | https://raw.githubusercontent.com/fulcrologic/video-series/817969602a31aee5fbf546b35893d73f93f1d78c/src/app/model/session.cljs | clojure | save desired path for later routing | (ns app.model.session
(:require
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.dom :as dom :refer [div a]]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.dom.html-entities :as ent]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.algorithms.merge :as merge]
[com.fulcrologic.fulcro.ui-state-machines :as uism :refer [defstatemachine]]
[app.routing :as routing]
[taoensso.timbre :as log]))
(defn handle-login [{::uism/keys [event-data] :as env}]
(let [user-class (uism/actor-class env :actor/user)]
(-> env
(uism/trigger-remote-mutation :actor/login-form `login
(merge event-data
{:com.fulcrologic.fulcro.mutations/returning user-class
:com.fulcrologic.fulcro.algorithms.data-targeting/target [:session/current-user]
::uism/ok-event :event/ok
::uism/error-event :event/error}))
(uism/activate :state/checking-credentials))))
(def main-events
{:event/logout {::uism/handler (fn [env]
(routing/route-to! "/login")
(-> env
(uism/trigger-remote-mutation :actor/login `logout {})
(uism/apply-action assoc-in [::session :current-user] {:user/id :nobody :user/valid? false})))}
:event/login {::uism/handler handle-login}})
(defstatemachine session-machine
{::uism/actor-name
#{:actor/user
:actor/login-form}
::uism/aliases
{:logged-in? [:actor/user :user/valid?]}
::uism/states
{:initial
{::uism/handler
(fn [{::uism/keys [event-data] :as env}]
(-> env
(uism/load :session/current-user :actor/user {::uism/ok-event :event/ok
::uism/error-event :event/error})
(uism/activate :state/checking-existing-session)))}
:state/checking-existing-session
{::uism/events
{:event/ok {::uism/handler (fn [env]
(let [logged-in? (uism/alias-value env :logged-in?)]
(when-not logged-in?
(routing/route-to! "/login"))
(uism/activate env :state/idle)))}
:event/error {::uism/handler (fn [env] (uism/activate env :state/server-failed))}}}
:state/bad-credentials
{::uism/events main-events}
:state/idle
{::uism/events main-events}
:state/checking-credentials
{::uism/events {:event/ok {::uism/handler (fn [env]
(let [logged-in? (uism/alias-value env :logged-in?)
{:keys [desired-path]} (uism/retrieve env :config)]
(when (and logged-in? desired-path)
(routing/route-to! desired-path))
(-> env
(uism/activate (if logged-in?
:state/idle
:state/bad-credentials)))))}
:event/error {::uism/handler (fn [env] (uism/activate env :state/server-failed))}}}
:state/server-failed
{::uism/events main-events}}})
(defsc CurrentUser [this {:keys [:user/id :user/email :user/valid?] :as props}]
{:query [:user/id :user/email :user/valid?]
:initial-state {:user/id :nobody :user/valid? false}
:ident (fn [] [::session :current-user])}
(dom/div :.item
(if valid?
(div :.content
email ent/nbsp (a {:onClick
(fn [] (uism/trigger! this ::sessions :event/logout))}
"Logout"))
(a {:onClick #(dr/change-route this ["login"])} "Login"))))
(def ui-current-user (comp/factory CurrentUser))
|
ac39b91603e8e19497838a507974d0a18603ce59cc5154d7da05eac18b66d483 | pink-gorilla/webly | transit.clj | (ns modular.webserver.middleware.transit
(:require
[cognitect.transit :as transit]
[modular.encoding.transit :as e]
[muuntaja.core :as m]))
(def muuntaja
(m/create
(-> m/default-options
(update-in
[:formats "application/transit+json" :decoder-opts]
(partial merge e/decode))
(update-in
[:formats "application/transit+json" :encoder-opts]
(partial merge e/encode))))) | null | https://raw.githubusercontent.com/pink-gorilla/webly/d449a506e6101afc16d384300cdebb7425e3a7f3/webserver/src/modular/webserver/middleware/transit.clj | clojure | (ns modular.webserver.middleware.transit
(:require
[cognitect.transit :as transit]
[modular.encoding.transit :as e]
[muuntaja.core :as m]))
(def muuntaja
(m/create
(-> m/default-options
(update-in
[:formats "application/transit+json" :decoder-opts]
(partial merge e/decode))
(update-in
[:formats "application/transit+json" :encoder-opts]
(partial merge e/encode))))) |
|
c49c56454777a29c7ab952a2c578f388ac3d294950a48fa9db95236c25bdb04e | hipsleek/hipsleek | fixbag.ml | #include "xdebug.cppo"
open VarGen
(*
Call FixBag, send input to it
*)
open Globals
module DD = Debug
open Gen
open Exc.GTable
open Perm
open Cpure
open Context
module M = Lexer.Make(Token.Token)
module Pr = Cprinter
module CP = Cpure
module CF= Cformula
module MCP = Mcpure
module TP = Tpdispatcher
Operators
let op_lt = "<"
let op_lte = "<="
let op_gt = ">"
let op_gte = ">="
let op_eq = "="
let op_neq = "!="
let op_and = " && "
let op_or = " || "
let op_add = "+"
let op_sub = "-"
(*let is_self = CP.is_self_var*)
(*let is_null = CP.is_null*)
let rec string_of_elems elems string_of sep = match elems with
| [] -> ""
| h::[] -> string_of h
| h::t -> (string_of h) ^ sep ^ (string_of_elems t string_of sep)
let fixbag_of_spec_var x = match x with
| CP.SpecVar ( Named _ , i d , ) - > " " ^ i d
| CP.SpecVar ( Named _ , i d , Primed ) - > " NODPRI " ^ i d
| CP.SpecVar ( _ , i d , ) - > i d
| CP.SpecVar ( _ , i d , Primed ) - > " PRI " ^ i d
| CP.SpecVar (_, id, _) -> if is_anon_var x && not (is_bag_typ x) then "v_" ^ id else id
let rec fixbag_of_exp e = match e with
| CP.Null _ -> "null"
| CP.Var (x, _) -> fixbag_of_spec_var x
| CP.IConst (i, _) -> string_of_int i
| CP.FConst ( f , _ ) - > string_of_float f
| CP.Add (e1, e2, _) -> fixbag_of_exp e1 ^ op_add ^ fixbag_of_exp e2
| CP.Subtract (e1, e2, _) -> fixbag_of_exp e2
| CP.Bag (es, _) -> "{" ^ (string_of_elems es fixbag_of_exp ",") ^ "}"
| CP.BagUnion (es, _) -> string_of_elems es fixbag_of_exp "+"
| CP.BagIntersect (es, _) -> string_of_elems es fixbag_of_exp "."
| CP.BagDiff (e1, e2, _) -> fixbag_of_exp e1 ^ op_sub ^ fixbag_of_exp e2
| _ -> illegal_format ("Fixbag.fixbag_of_exp: Not supported expression")
let rec fixbag_of_b_formula b =
let (pf, _) = b in
match pf with
| CP.BConst (b,_) -> "{}={}"
| CP.BVar (x, _) -> fixbag_of_spec_var x
| CP.Lt (e1, e2, _) -> "{}={}"
| CP.Lte (e1, e2, _) -> "{}={}"
| CP.Gt (e1, e2, _) -> "{}={}"
| CP.Gte (e1, e2, _) -> "{}={}"
| CP.Eq (e1, e2, _) -> if CP.is_null e2 && not (is_bag e1) then fixbag_of_exp e1 ^op_lte^"0"
else if CP.is_null e1 && not(is_bag e2) then fixbag_of_exp e2 ^op_lte^"0"
else fixbag_of_exp e1 ^ op_eq ^ fixbag_of_exp e2
| CP.Neq (e1, e2, _) ->
if CP.is_null e2 && not (is_bag e1) then fixbag_of_exp e1 ^op_gt^"0"
else if CP.is_null e1 && not(is_bag e2) then fixbag_of_exp e2 ^op_gt^"0"
else if (* !allow_pred_spec *) not !dis_ps && (List.exists is_bag_typ (CP.bfv b) || is_bag e1 || is_bag e2) then "{}={}"
else
if List.exists is_int_typ (CP.bfv b) then fixbag_of_exp e1 ^ op_neq ^ fixbag_of_exp e2
else "!(" ^ fixbag_of_exp e1 ^ op_eq ^ fixbag_of_exp e2 ^ ")"
| CP.RelForm (id,args,_) -> (fixbag_of_spec_var id) ^ "(" ^ (string_of_elems args fixbag_of_exp ",") ^ ")"
| BagIn ( sv , e , _ ) - >
| ( sv , e , _ ) - >
| CP.BagSub (e1, e2, _) -> fixbag_of_exp e1 ^ op_lte ^ fixbag_of_exp e2
| BagMin ( sv1 , sv2 , _ ) - >
| ( sv1 , sv2 , _ ) - >
| _ -> illegal_format ("Fixbag.fixbag_of_b_formula: Do not support list or boolean vars")
let rec fixbag_of_pure_formula f = match f with
| CP.BForm ((CP.BVar (x,_),_),_) -> "$" ^ fixbag_of_spec_var x
| CP.BForm (b,_) -> fixbag_of_b_formula b
| CP.And (p1, p2, _) ->
"(" ^ fixbag_of_pure_formula p1 ^ op_and ^ fixbag_of_pure_formula p2 ^ ")"
| CP.AndList b -> "(" ^ String.concat op_and (List.map (fun (_,c)-> fixbag_of_pure_formula c) b) ^ ")"
| CP.Or (p1, p2,_ , _) ->
"(" ^ fixbag_of_pure_formula p1 ^ op_or ^ fixbag_of_pure_formula p2 ^ ")"
| CP.Not (p,_ , _) ->
begin
match p with
| CP.BForm ((CP.BVar (x,_),_),_) -> "!$" ^ fixbag_of_spec_var x
| _ -> "!(" ^ fixbag_of_pure_formula p ^ ")"
end
| CP.Forall (sv, p,_ , _) -> illegal_format ("Fixbag.fixbag_of_pure_formula: Do not support forall")
(* " (forall (" ^ fixbag_of_spec_var sv ^ ":" ^ fixbag_of_pure_formula p ^ ")) "*)
| CP.Exists (sv, p,_ , _) ->
" (exists " ^ fixbag_of_spec_var sv ^ ":" ^ fixbag_of_pure_formula p ^ ") "
let rec fixbag_of_h_formula f = match f with
| CF.Star {CF.h_formula_star_h1 = h1; CF.h_formula_star_h2 = h2} ->
"(" ^ fixbag_of_h_formula h1 ^ op_and ^ fixbag_of_h_formula h2 ^ ")"
| CF.Phase _ -> illegal_format ("Fixbag.fixbag_of_h_formula: Not supported Phase-formula")
| CF.Conj {CF.h_formula_conj_h1 = h1; CF.h_formula_conj_h2 = h2} ->
"(" ^ fixbag_of_h_formula h1 ^ op_or ^ fixbag_of_h_formula h2 ^ ")"
| CF.DataNode {CF.h_formula_data_node = sv; CF.h_formula_data_name = c;CF.h_formula_data_arguments = svs} ->
if CP.is_self_spec_var sv then self ^ op_gt ^ "0"
else c ^ "(" ^ (fixbag_of_spec_var sv) ^ "," ^ (string_of_elems svs fixbag_of_spec_var ",") ^ ")"
| CF.ViewNode {CF.h_formula_view_node = sv; CF.h_formula_view_name = c; CF.h_formula_view_arguments = svs} ->
if CP.is_self_spec_var sv then self ^ op_gt ^ "0"
else c ^ "(" ^ (fixbag_of_spec_var sv) ^","^ (string_of_elems svs fixbag_of_spec_var ",")^","^ res_name ^ ")"
| CF.HTrue -> "HTrue"
| CF.HFalse -> "HFalse"
| CF.HEmp -> "{}={}"
| CF.HRel _ -> "HTrue"
| CF.Hole _ -> illegal_format ("Fixbag.fixbag_of_h_formula: Not supported Hole-formula")
| _ -> illegal_format("Fixbag.fixbag_of_h_formula: Not Suppoted")
let fixbag_of_mix_formula (f,l) = match f with
| MCP.MemoF _ -> ""
| MCP.OnePF pf -> fixbag_of_pure_formula pf
let rec fixbag_of_formula e = match e with
| CF.Or _ -> illegal_format ("Fixbag.fixbag_of_formula: Not supported Or-formula")
| CF.Base {CF.formula_base_heap = h; CF.formula_base_pure = p; CF.formula_base_label = b} ->
"(" ^ fixbag_of_h_formula h ^ op_and ^ fixbag_of_mix_formula (p,b) ^ ")"
| CF.Exists {CF.formula_exists_qvars = svs; CF.formula_exists_heap = h;
CF.formula_exists_pure = p; CF.formula_exists_label = b} ->
"(exists " ^ (string_of_elems svs fixbag_of_spec_var ",") ^ ": " ^
fixbag_of_h_formula h ^ op_and ^ fixbag_of_mix_formula (p,b) ^ ")"
let fixbag = "fixbag4"
let syscall cmd =
let ic, oc = Unix.open_process cmd in
let buf = Buffer.create 16 in
(try
while true do
Buffer.add_channel buf ic 1
done
with End_of_file -> ());
let todo_unk = Unix.close_process (ic, oc) in
(Buffer.contents buf)
let rec remove_paren s n = if n=0 then "" else match s.[0] with
| '(' -> remove_paren (String.sub s 1 (n-1)) (n-1)
| ')' -> remove_paren (String.sub s 1 (n-1)) (n-1)
| _ -> (String.sub s 0 1) ^ (remove_paren (String.sub s 1 (n-1)) (n-1))
let compute_inv name vars fml pf no_of_disjs =
if not !Globals.do_infer_inv then pf
else
let rhs = string_of_elems fml (fun (c,_) ->fixbag_of_formula c) op_or in
let no = string_of_int no_of_disjs in
let input_fixbag =
try
name ^ "(" ^"self," ^ (string_of_elems vars fixbag_of_spec_var ",") ^ " -> "
^ res_name ^ ") := "
^ rhs
with _ -> report_error no_pos "Error in translating the input for fixbag"
in
(*print_endline ("\nINPUT: " ^ input_fixbag);*)
DD.info_pprint ">>>>>> compute_fixpoint <<<<<<" no_pos;
DD.info_zprint (lazy (("Input of fixbag: " ^ input_fixbag))) no_pos;
let output_of_sleek = " fixbag.inf " in
let oc = open_out output_of_sleek in
(* Printf.fprintf oc "%s" input_fixbag;*)
(* flush oc;*)
(* close_out oc;*)
let res = syscall (fixbag ^ " \'" ^ input_fixbag ^ "\' \'" ^ no ^ "\'") in
let res = remove_paren res (String.length res) in
(*print_endline ("RES: " ^ res);*)
DD.info_zprint (lazy (("Result of fixbag: " ^ res))) no_pos;
let new_pf = List.hd (Parse_fixbag.parse_fix res) in
let () = x_dinfo_hp (add_str "Result of fixbag (parsed): " !CP.print_formula) new_pf no_pos in
let check_imply = Omega.imply new_pf pf "1" 100.0 in
if check_imply then (
Pr.fmt_string "INV: ";
Pr.pr_angle name (fun x -> Pr.fmt_string (Pr.string_of_typed_spec_var x)) vars;
Pr.fmt_string ("\nOLD: " ^ (Pr.string_of_pure_formula pf) ^
"\nNEW: " ^ (Pr.string_of_pure_formula new_pf) ^ "\n\n");
new_pf)
else pf
let compute_fixpoint input_pairs =
let ( , rels ) = List.split input_pairs in
let rels = Gen. CP.equalFormula rels in
let rel_fml = match rels with
| [ ] - > report_error no_pos " Error in compute_fixpoint "
| [ hd ] - > hd
| _ - > report_error no_pos " Fixbag.ml : More than one input relation "
in
let ( name , vars ) = match rel_fml with
| CP.BForm ( ( CP.RelForm ( name , args , _ ) , _ ) , _ ) - > ( CP.name_of_spec_var name , ( List.concat ( List.map CP.afv args ) ) )
| _ - > report_error no_pos " Wrong format "
in
let pf = List.fold_left ( fun p1 p2 - > CP.mkOr p1 p2 None no_pos ) ( List.hd pfs ) ( List.tl pfs ) in
try
let rhs = fixbag_of_pure_formula pf in
let input_fixbag = name ^ " : = { [ " ^ ( string_of_elems vars fixbag_of_spec_var " , " )
^ " ] - > [ ] - > [ ] : " ^ rhs ^ " \n};\n\nFix1:=bottomup ( " ^ name ^ " , 1,SimHeur);\nFix1;\n "
^ " Fix2:=topdown ( " ^ name ^ " , 1,SimHeur);\nFix2 ; "
in
( * print_endline ( " \nINPUT : " ^ input_fixbag ) ;
let (pfs, rels) = List.split input_pairs in
let rels = Gen.BList.remove_dups_eq CP.equalFormula rels in
let rel_fml = match rels with
| [] -> report_error no_pos "Error in compute_fixpoint"
| [hd] -> hd
| _ -> report_error no_pos "Fixbag.ml: More than one input relation"
in
let (name,vars) = match rel_fml with
| CP.BForm ((CP.RelForm (name,args,_),_),_) -> (CP.name_of_spec_var name, (List.concat (List.map CP.afv args)))
| _ -> report_error no_pos "Wrong format"
in
let pf = List.fold_left (fun p1 p2 -> CP.mkOr p1 p2 None no_pos) (List.hd pfs) (List.tl pfs) in
try
let rhs = fixbag_of_pure_formula pf in
let input_fixbag = name ^ ":={[" ^ (string_of_elems vars fixbag_of_spec_var ",")
^ "] -> [] -> []: " ^ rhs ^ "\n};\n\nFix1:=bottomup(" ^ name ^ ",1,SimHeur);\nFix1;\n"
^ "Fix2:=topdown(" ^ name ^ ",1,SimHeur);\nFix2;"
in
(*print_endline ("\nINPUT: " ^ input_fixbag);*)
x_tinfo_hp (add_str "input_pairs: " (pr_list (pr_pair !CP.print_formula !CP.print_formula))) input_pairs no_pos;
x_dinfo_pp ">>>>>> compute_fixpoint <<<<<<" no_pos;
x_dinfo_pp ("Input of fixbag: " ^ input_fixbag) no_pos;
let output_of_sleek = "fixbag.inf" in
let oc = open_out output_of_sleek in
Printf.fprintf oc "%s" input_fixbag;
flush oc;
close_out oc;
let res = syscall (fixbag ^ " " ^ output_of_sleek) in
let res = remove_paren res (String.length res) in
(*print_endline ("RES: " ^ res);*)
x_dinfo_pp ("Result of fixbag: " ^ res) no_pos;
let fixpoint = Parse_fix.parse_fix res in
x_dinfo_hp (add_str "Result of fixbag (parsed): " (pr_list !CP.print_formula)) fixpoint no_pos;
let fixpoint = List.map (fun f ->
let args = CP.fv f in
let quan_vars = CP.diff_svl args vars in
TP.simplify_raw (CP.mkExists quan_vars f None no_pos)) fixpoint in
match fixpoint with
| [pre;post] -> (rel_fml, pre, post)
| _ -> report_error no_pos "Expecting a pair of pre-post"
with _ -> report_error no_pos "Unexpected error in computing fixpoint"*)
let rec is_rec pf = match pf with
| CP.BForm (bf,_) -> CP.is_RelForm pf
| CP.And (f1,f2,_) -> is_rec f1 || is_rec f2
| CP.AndList b -> exists_l_snd is_rec b
| CP.Or (f1,f2,_,_) -> is_rec f1 || is_rec f2
| CP.Not (f,_,_) -> is_rec f
| CP.Forall (_,f,_,_) -> is_rec f
| CP.Exists (_,f,_,_) -> is_rec f
let rec get_rel_vars pf = match pf with
| CP.BForm (bf,_) -> if CP.is_RelForm pf then CP.get_rel_args pf else []
| CP.And (f1,f2,_) -> get_rel_vars f1 @ get_rel_vars f2
| CP.AndList b -> fold_l_snd get_rel_vars b
| CP.Or (f1,f2,_,_) -> get_rel_vars f1 @ get_rel_vars f2
| CP.Not (f,_,_) -> get_rel_vars f
| CP.Forall (_,f,_,_) -> get_rel_vars f
| CP.Exists (_,f,_,_) -> get_rel_vars f
let substitute (e: CP.exp): (CP.exp * CP.formula list) = match e with
| CP.Var _ -> (e, [])
| _ -> (
try
let arb = List.hd (CP.afv e) in
let var = CP.fresh_spec_var_prefix "fb" arb in
let var = CP.mkVar var no_pos in
(var, [CP.mkEqExp var e no_pos])
with _ -> (e,[]))
let arr_para_order (rel: CP.formula) (rel_def: CP.formula) (ante_vars: CP.spec_var list) = match (rel,rel_def) with
| (CP.BForm ((CP.RelForm (id,args,p), o1), o2), CP.BForm ((CP.RelForm (id_def,args_def,_), _), _)) ->
if id = id_def then
let new_args_def =
let pre_args, post_args = List.partition (fun e -> Gen.BList.subset_eq CP.eq_spec_var (CP.afv e) ante_vars) args_def in
pre_args @ post_args
in
let pairs = List.combine args_def args in
let new_args = List.map (fun a -> List.assoc a pairs) new_args_def in
let new_args, subs = List.split (List.map (fun a -> substitute a) new_args) in
let id = match id with | CP.SpecVar (t,n,p) -> CP.SpecVar (t,"fixbagA"(* ^ n*),p) in
(CP.BForm ((CP.RelForm (id,new_args,p), o1), o2), [CP.conj_of_list (List.concat subs) no_pos])
else
let args, subs = List.split (List.map (fun a -> substitute a) args) in
let id = match id with | CP.SpecVar (t,n,p) -> CP.SpecVar (t,"fixbagA"(* ^ n*),p) in
(CP.BForm ((CP.RelForm (id,args,p), o1), o2), [CP.conj_of_list (List.concat subs) no_pos])
| _ -> report_error no_pos "Expecting relation formulae"
(*let arr_args rcase_orig rel ante_vars = *)
(* let rels = CP.get_RelForm rcase_orig in*)
let rels , lp = List.split ( List.map ( fun r - > arr_para_order r rel ante_vars ) rels ) in
let = TP.simplify_raw ( CP.drop_rel_formula rcase_orig ) in
CP.conj_of_list ( [ rcase]@rels@(List.concat lp ) ) no_pos
let propagate_exp exp1 exp2 = match ( exp1 , exp2 ) with ( * Need to cover all patterns
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Lte(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 > i4 then Some ( CP.Lte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(CP.IConst(i4 , _ ) , e3 , _ ) ) - >
if e1 e3 & & i2 > i4 then Some ( CP.Lte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(CP.IConst(i2 , _ ) , e1 , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
(* | (CP.Lte(CP.IConst(i2, _), e1, _), CP.Eq(CP.IConst(i4, _), e3, _)) ->*)
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Lt(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 > = i4 then Some ( CP.Lt(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Gte(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(CP.IConst(i4 , _ ) , e3 , _ ) ) - >
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Gt(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 < = i4 then Some ( CP.Gt(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
(* | _ -> None *)
let propagate_exp exp1 exp2 =
(* let pr0 = !CP.print_p_formula in*)
" propagate_exp " pr0 pr0 ( pr_option pr0 )
( fun _ _ - > propagate_exp exp1 exp2 ) exp1 exp2
let = match ( rcase , bcase ) with
| ( CP.BForm ( ( exp1 , _ ) , _ ) , CP.BForm ( ( exp2 , _ ) , _ ) ) - >
let exp = propagate_exp exp1 exp2 in
(* (match exp with*)
(* | None -> []*)
| Some e - > [ CP.BForm ( ( e , None),None ) ] )
(* | _ -> []*)
let =
(* let pr0 = !CP.print_formula in*)
" propagate_fml " pr0 pr0 ( pr_list pr0 )
( fun _ _ - > propagate_fml )
let matching_exp pf1 pf2 = match (pf1,pf2) with
| (Lt (Var (v1,p1), Var (v2,p2), p), Lt (Var (v3,_), Var (v4,_), _))
| (Gt (Var (v1,p1), Var (v2,p2), p), Gt (Var (v3,_), Var (v4,_), _)) ->
let res = eq_spec_var v1 v4 && eq_spec_var v2 v3 in
if res then (true, [Neq (Var (v1,p1), Var (v2,p2), p)]) else (false,[])
| (Eq (v1, Bag ([],_), _), Eq (v2, BagUnion (es,_), _))
| (Eq (v1, Bag ([],_), _), Eq (BagUnion (es,_), v2, _))
| (Eq (Bag ([],_), v1, _), Eq (v2, BagUnion (es,_), _))
| (Eq (Bag ([],_), v1, _), Eq (BagUnion (es,_), v2, _))
| (Eq (v2, BagUnion (es,_), _), Eq (v1, Bag ([],_), _))
| (Eq (v2, BagUnion (es,_), _), Eq (Bag ([],_), v1, _))
| (Eq (BagUnion (es,_), v2, _), Eq (v1, Bag ([],_), _))
| (Eq (BagUnion (es,_), v2, _), Eq (Bag ([],_), v1, _)) ->
begin
match (v1,v2) with
| (Var (b1,_), Var (b2,_))
| ( Subtract ( _ , Subtract ( _ , ( b1 , _ ) , _ ) , _ ) , ( b2 , _ ) )
| ( Var ( b1 , _ ) , Subtract ( _ , Subtract ( _ , ( b2 , _ ) , _ ) , _ ) )
| ( Subtract ( _ , Subtract ( _ , ( b1 , _ ) , _ ) , _ ) , Subtract ( _ , Subtract ( _ , ( b2 , _ ) , _ ) , _ ) )
-> (eq_spec_var b1 b2 && es != [],[])
| _ -> (false,[])
end
| _ -> (false,[])
let matching f1 f2 = match (f1,f2) with
| (BForm ((pf1,o),p), BForm ((pf2,_),_)) ->
(* x_dinfo_hp (add_str "matching: " (pr_list !CP.print_formula)) [f1;f2] no_pos;*)
let (res1,res2) = matching_exp pf1 pf2 in
if res2 = [] then (res1,[])
else (res1,List.map (fun r2 -> BForm((r2,o),p)) res2)
| _ -> (false,[])
let can_merge f1 f2 =
let conjs1 = CP.list_of_conjs f1 in
let conjs2 = CP.list_of_conjs f2 in
(* x_dinfo_hp (add_str "CONJ1: " (pr_list !CP.print_formula)) conjs1 no_pos;*)
x_dinfo_hp ( add_str " CONJ2 : " ( pr_list ! CP.print_formula ) ) conjs2 no_pos ;
let part_of_f1, others1 = List.partition (fun c -> Gen.BList.mem_eq (CP.equalFormula) c conjs1) conjs2 in
x_dinfo_hp ( add_str " PART1 : " ( pr_list ! CP.print_formula ) ) part_of_f1 ;
x_dinfo_hp ( add_str " other1 : " ( pr_list ! CP.print_formula ) ) ;
let part_of_f2, others2 = List.partition (fun c -> Gen.BList.mem_eq (CP.equalFormula) c conjs2) conjs1 in
x_dinfo_hp ( add_str " PART2 : " ( pr_list ! CP.print_formula ) ) part_of_f2 no_pos ;
(*x_dinfo_hp (add_str "other2: " (pr_list !CP.print_formula)) others2 no_pos;*)
let check1 = List.length part_of_f1 = List.length part_of_f2 && List.length others1 = List.length others2 in
(* TODO: *)
let matching = if check1 then List.map2 (fun o1 o2 -> matching o1 o2) others1 others2 else [] in
let added_conj = List.concat (List.map (fun (f1,f2) -> if f1 then f2 else []) matching) in
let check = check1 && List.for_all fst matching in
if check then (true, conj_of_list (part_of_f1@added_conj) no_pos)
else (false, f1)
let rec simplify flist = match flist with
| [] -> []
| [hd] -> [hd]
| hd::tl ->
let check_merge = List.map (fun f -> can_merge f hd) tl in
let (can_merge, others) = List.partition fst check_merge in
x_dinfo_hp ( add_str " : " ( pr_list ! CP.print_formula ) ) ( snd ( List.split can_merge ) ) no_pos ;
x_dinfo_hp ( add_str " OTHER : " ( pr_list ! CP.print_formula ) ) ( snd ( List.split others ) ) no_pos ;
if can_merge = [] then hd::(simplify tl)
else
(* TODO: *)
let hd = snd (List.hd (List.rev can_merge)) in
hd::(simplify (snd (List.split others)))
let pre_process vars fmls =
List.filter (fun f ->
let vs = List.filter (fun x -> CP.is_bag_typ x || CP.is_bool_typ x) (CP.fv f) in
x_dinfo_hp ( add_str " VARS : " ! print_svl ) vs no_pos ;
CP.subset vs vars) fmls
let rec create_alias_tbl vs aset all_rel_vars base_case = match vs with
| [] -> []
| [hd] ->
if base_case then
[hd::(List.filter (fun x -> not(List.mem x all_rel_vars)) (CP.EMapSV.find_equiv_all hd aset))]
else [List.filter (fun x -> not(List.mem x all_rel_vars)) (hd::(CP.EMapSV.find_equiv_all hd aset))]
| hd::tl ->
let res1 = create_alias_tbl [hd] aset all_rel_vars base_case in
let tl = List.filter (fun x -> not(List.mem x (List.hd res1))) tl in
res1@(create_alias_tbl tl aset all_rel_vars base_case)
let rewrite pure rel_lhs_vars rel_vars base_case =
let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure pure) in
(* DD.info_hprint (add_str "ALS: " (pr_list (pr_pair !print_sv !print_sv))) als no_pos;*)
let aset = CP.EMapSV.build_eset als in
let int_vars, other_vars = List.partition CP.is_int_typ (CP.fv pure) in
let alias = create_alias_tbl (rel_vars@int_vars@other_vars) aset rel_lhs_vars base_case in
let subst_lst = List.concat (List.map (fun vars -> if vars = [] then [] else
let hd = List.hd vars in List.map (fun v -> (v,hd)) (List.tl vars)) alias) in
DD.info_hprint ( add_str " SUBS : " ( pr_list ( pr_pair ! print_sv ! print_sv ) ) ) subst_lst ;
DD.info_hprint ( add_str " : " ( ! CP.print_formula ) ) pure no_pos ;
let pure = CP.subst subst_lst pure in
CP.remove_redundant_constraints pure
let pure rel_lhs_vars rel_vars =
(* let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure pure) in*)
(* let aset = CP.EMapSV.build_eset als in*)
(* let pure_vars = CP.fv pure in*)
let int_vars , other_vars = List.partition CP.is_int_typ pure_vars in
let alias = ( rel_vars@int_vars@other_vars ) aset rel_lhs_vars in
let subst_lst = List.concat ( List.map ( fun vars - > if vars = [ ] then [ ] else
(* let hd = List.hd vars in *)
List.concat ( List.map ( fun v - >
if mem_svl v pure_vars & & mem_svl then [ mkEqVar v hd no_pos ] else [ ] )
(* (List.tl vars))) alias) in*)
( * DD.info_hprint ( add_str " : " ( ! CP.print_formula ) ) pure no_pos ;
(* let pure = conj_of_list (pure::subst_lst) no_pos in*)
CP.remove_dup_constraints pure
let rec get_all_pairs conjs = match conjs with
| [] -> []
| c::cs ->
let lst = List.map (fun conj -> (c,conj)) cs in
lst @ (get_all_pairs cs)
let rec rewrite_by_subst pairs = match pairs with
| [] -> []
| [(e1,e2)] ->
begin
match (e1,e2) with
| (BForm ((pf1,_),_), BForm ((pf2,_),_)) ->
begin
match pf1,pf2 with
| Eq (exp1, exp2, _), Eq (exp3, exp4, _) ->
begin
match (exp1,exp2,exp3,exp4) with
(* Add more if necessary *)
| Var (sv11,_), BagUnion ([Var (sv12,_);Bag([Var (sv13,_)],_)],_),
Var (sv21,_), BagUnion ([BagUnion ([Var (sv22,_);Bag([Var (sv23,_)],_)],_);
Bag([Var (sv24,_)],_)],_)
| Var ( sv11 , _ ) , BagUnion ( [ Var ( sv12,_);Bag([Var ( sv13 , _ ) ] , _ ) ] , _ ) ,
( sv21 , _ ) , BagUnion ( [ Subtract ( _ , Subtract(_,BagUnion ( [ Var ( sv22 , _ ) ;
Bag([Var ( sv23 , _ ) ] , _ ) ] , _ ) , _ ) , _ ) ; Bag([Var ( sv24 , _ ) ] , _ ) ] , _ )
| Var (sv21,_), BagUnion ([BagUnion ([Var (sv22,_);Bag([Var (sv23,_)],_)],_);
Bag([Var (sv24,_)],_)],_),
Var (sv11,_), BagUnion ([Var (sv12,_);Bag([Var (sv13,_)],_)],_)
| Var ( sv21 , _ ) , BagUnion ( [ Subtract ( _ , Subtract(_,BagUnion ( [ Var ( sv22 , _ ) ;
Bag([Var ( sv23 , _ ) ] , _ ) ] , _ ) , _ ) , _ ) ; Bag([Var ( sv24 , _ ) ] , _ ) ] , _ ) ,
( sv11 , _ ) , BagUnion ( [ Var ( sv12,_);Bag([Var ( sv13 , _ ) ] , _ ) ] , _ )
->
if eq_spec_var sv12 sv22 && eq_spec_var sv13 sv23 then
[CP.mkEqExp (mkVar sv21 no_pos) (BagUnion ([mkVar sv11 no_pos; Bag([mkVar sv24 no_pos],no_pos)],no_pos)) no_pos]
else []
| Var (sv11,_), BagUnion ([Var (sv12,_);Var (sv13,_);Bag([Var (sv14,_)],_)],_),
Var (sv21,_), BagUnion ([Var (sv22,_);Var (sv23,_);Bag([Var (sv24,_)],_)],_)
->
if eq_spec_var sv13 sv23 && eq_spec_var sv14 sv24 then
[CP.mkEqExp (mkVar sv21 no_pos) (BagUnion ([mkVar sv22 no_pos;
Bag([mkVar (SpecVar (Int,"v_fb",Unprimed)) no_pos],no_pos)],no_pos)) no_pos;
CP.mkEqExp (mkVar sv11 no_pos) (BagUnion ([mkVar sv12 no_pos;
Bag([mkVar (SpecVar (Int,"v_fb",Unprimed)) no_pos],no_pos)],no_pos)) no_pos]
else []
| _ -> []
end
| _ -> []
end
| _ -> []
end
| p::ps -> (rewrite_by_subst [p]) @ (rewrite_by_subst ps)
let rec rewrite_by_subst2 pairs = match pairs with
| [] -> []
| [(f1,f2)] ->
begin
match (f1,f2) with
| (BForm ((Eq (exp1, exp2, _),_),_), BForm ((Eq (exp3, exp4, _),_),_)) ->
begin
match (exp1,exp2,exp3,exp4) with
| Var (sv1,_), Var (sv2,_), Var (sv3,_), BagUnion (es,_) ->
let evars = List.concat (List.map afv es) in
let subst =
if mem_svl sv3 evars && eq_spec_var sv1 sv3 && is_bag_typ sv1 then [(sv1,sv2)] else
if mem_svl sv3 evars && eq_spec_var sv2 sv3 && is_bag_typ sv1 then [(sv2,sv1)] else [] in
let exp = e_apply_subs subst exp4 in
if subst = [] then [] else [([f1;f2],[CP.mkEqExp (mkVar sv3 no_pos) exp no_pos])]
| _ -> []
end
| (Forall _, Forall _) -> [([f1;f2],[])]
| (Forall _,_) -> [([f1],[])]
| (_,Forall _) -> [([f2],[])]
| _ -> []
end
| p::ps -> (rewrite_by_subst2 [p]) @ (rewrite_by_subst2 ps)
let rec filter_var f vars =
match f with
| CP.Or (f1,f2,l,p) -> CP.mkOr (filter_var f1 vars) (filter_var f2 vars) l p
| _ -> CP.filter_var (CP.drop_rel_formula f) vars
let propagate_rec_helper rcase_orig rel ante_vars =
let rel_vars = CP.remove_dups_svl (get_rel_vars rcase_orig) in
(* x_dinfo_hp (add_str "Before: " (!CP.print_formula)) rcase_orig no_pos;*)
let = TP.simplify_raw ( CP.drop_rel_formula rcase_orig ) in
x_dinfo_hp ( add_str " After : " ( ! CP.print_formula ) ) rcase ;
let rcase = CP.drop_rel_formula rcase_orig in
let rel_lhs_vars = CP.fv rel in
let all_rel_vars = rel_vars @ rel_lhs_vars in
let rcase = filter_var rcase all_rel_vars in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let rcase = rewrite rcase rel_lhs_vars rel_vars false in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
(* let all_rel_vars = rel_vars @ (CP.fv rel) in*)
(* let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure rcase) in*)
(* let aset = CP.EMapSV.build_eset als in*)
let other_vars = ( fun x - > CP.is_int_typ x ) ( CP.fv rcase_orig ) in
(* let alias = create_alias_tbl (rel_vars@other_vars) aset (CP.fv rel) in*)
let subst_lst = List.concat ( List.map ( fun vars - > if vars = [ ] then [ ] else
let hd = List.hd vars in List.map ( fun v - > ( v , hd ) ) ( List.tl vars ) ) alias ) in
( * x_dinfo_hp ( add_str " SUBS : " ( pr_list ( pr_pair ! print_sv ! print_sv ) ) ) subst_lst ;
( * x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let = CP.subst subst_lst in
(* let rcase = MCP.remove_ptr_equations rcase false in*)
let rcase_conjs = CP.list_of_conjs rcase in
if List.exists (fun conj -> is_emp_bag conj rel_vars) rcase_conjs then CP.mkFalse no_pos
else
let rcase_conjs_eq = List.filter is_beq_exp rcase_conjs in
let rcase_conjs =
if List.length rcase_conjs_eq <= 4 then
let all_pairs = get_all_pairs rcase_conjs_eq in
DD.info_hprint ( add_str " : " ( pr_list ( pr_pair ! CP.print_formula ! CP.print_formula ) ) ) all_pairs ;
rcase_conjs @ (rewrite_by_subst all_pairs)
else rcase_conjs
in
let rcase = CP.conj_of_list (pre_process all_rel_vars rcase_conjs) no_pos in
let rcase = filter_var rcase all_rel_vars in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let rcase = if CP.diff_svl (List.filter is_bag_typ rel_vars) (CP.fv rcase) != [] then CP.mkFalse no_pos else rcase in
let rels = CP.get_RelForm rcase_orig in
let rels,lp = List.split (List.map (fun r -> arr_para_order r rel ante_vars) rels) in
(* let exists_vars = CP.diff_svl (CP.fv rcase) rel_vars in*)
let = TP.simplify_raw ( CP.mkExists exists_vars rcase None no_pos ) in
CP.conj_of_list ([rcase]@rels@(List.concat lp)) no_pos
(* try*)
(* let pairs = List.combine (CP.fv rel) rel_vars in*)
let = CP.subst pairs bcase_orig in
let pf = List.concat ( List.map ( fun b - > List.concat
( List.map ( fun r - > propagate_fml r b ) ( CP.list_of_conjs ) ) ) ( CP.list_of_conjs bcase ) ) in
CP.conj_of_list ( [ rcase]@rels@pf@(List.concat lp ) ) no_pos
( * print_endline ( " PURE : " ^ ) ;
( * print_endline ( " PURE2 : " ^ ) ;
( * print_endline ( " PURE3 : " ^ ) ;
(* with _ -> rcase_orig*)
let rec = match bcases with
| [ ] - > [ ]
| b::bs - >
if List.exists ( fun fml - > TP.imply_raw fml b ) bs then remove_weaker_bcase bs
else
b::(remove_weaker_bcase ( ( fun fml - > not(TP.imply_raw b fml ) ) bs ) )
| [] -> []
| b::bs ->
if List.exists (fun fml -> TP.imply_raw fml b) bs then remove_weaker_bcase bs
else
b::(remove_weaker_bcase (List.filter (fun fml -> not(TP.imply_raw b fml)) bs))*)
(* TODO: Need to handle computed relation in the future *)
(*let rec get_other_branches or_fml args = match or_fml with*)
(* | Or fml -> *)
(* (get_other_branches fml.formula_or_f1 args) @ (get_other_branches fml.formula_or_f2 args)*)
(* | _ ->*)
let _ , , _ , _ , _ = split_components or_fml in
let conjs = CP.list_of_conjs ( MCP.pure_of_mix p ) in
( fun pure - > CP.subset args ( CP.fv pure ) ) conjs
let rec transform fml v_synch fv_rel = match fml with
| BForm ((Eq (v1, BagUnion ([b2;Bag([Var (v,_)],_)],_), _), _),_)
| BForm ((Eq (v1, BagUnion ([Bag([Var (v,_)],_);b2],_), _), _),_)
| BForm ((Eq (BagUnion ([Bag([Var (v,_)],_);b2],_), v1, _), _),_)
| BForm ((Eq (BagUnion ([b2;Bag([Var (v,_)],_)],_), v1, _), _),_) ->
begin
match v1 with
| Var (b1,_) ->
if diff_svl (CP.fv fml) fv_rel = [] then
let vars = afv b2 in
let v_synch = List.filter (fun x -> not (eq_spec_var x v)) v_synch in
begin
match (vars,v_synch) with
| ([hd],[v_s]) ->
let v_new = v_s in
let b2_new = CP.fresh_spec_var_prefix "FB" hd in
let als1 = CP.mkEqVar v v_new no_pos in
let als2 = CP.mkEqVar hd b2_new no_pos in
let f_new = mkEqExp (mkVar b1 no_pos) (BagUnion([mkVar b2_new no_pos;Bag([mkVar v_new no_pos],no_pos)],no_pos)) no_pos in
conj_of_list [als1;als2;f_new] no_pos
| _ -> fml
end
else fml
| _ -> fml
end
| And (BForm f1, BForm f2, _) -> mkAnd (transform (BForm f1) v_synch fv_rel) (transform (BForm f2) v_synch fv_rel) no_pos
| And _ ->
let v_synch = List.filter CP.is_int_typ (CP.diff_svl v_synch fv_rel) in
let v_subst = List.filter CP.is_int_typ (CP.diff_svl (CP.fv fml) fv_rel) in
x_dinfo_hp ( add_str " VSYNCH : " ( ! print_svl ) ) v_synch no_pos ;
x_dinfo_hp ( add_str " VSUBST : " ( ! print_svl ) ) v_subst no_pos ;
(match (v_subst, v_synch) with
| ([hd],[v_s]) -> CP.subst [(hd,v_s)] fml
| _ -> fml
)
| _ -> fml
let rec remove_subtract_exp e = match e with
| CP.Subtract (_, Subtract (_,en,_), _) -> remove_subtract_exp en
| CP.Bag (es, p) -> Bag (List.map remove_subtract_exp es, p)
| CP.BagUnion (es, p) -> BagUnion (List.map remove_subtract_exp es, p)
| CP.BagIntersect (es, p) -> BagIntersect (List.map remove_subtract_exp es, p)
| CP.BagDiff (e1, e2, p) -> BagDiff (remove_subtract_exp e1, remove_subtract_exp e2, p)
| _ -> e
let remove_subtract_pf pf = match pf with
| CP.Lt (e1, e2, p) -> Lt(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Lte (e1, e2, p) -> Lte(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Gt (e1, e2, p) -> Gt(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Gte (e1, e2, p) -> Gte(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Eq (e1, e2, p) -> Eq(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Neq (e1, e2, p) -> Neq(remove_subtract_exp e1, remove_subtract_exp e2, p)
| _ -> pf
let rec remove_subtract pure = match pure with
| BForm ((pf,o1),o2) -> BForm ((remove_subtract_pf pf,o1),o2)
| And (f1,f2,_) -> CP.mkAnd (remove_subtract f1) (remove_subtract f2) no_pos
| Or (f1,f2,_,_) -> CP.mkOr (remove_subtract f1) (remove_subtract f2) None no_pos
| Not (f,_,_) -> CP.mkNot_s (remove_subtract f)
| Forall (v,f,o,p) -> Forall (v,remove_subtract f,o,p)
| Exists (v,f,o,p) -> Exists (v,remove_subtract f,o,p)
| AndList l -> AndList (map_l_snd remove_subtract l)
let isComp pure = match pure with
| BForm ((pf,_),_) ->
begin
match pf with
| Lt _ | Gt _ | Lte _ | Gte _ -> true
| _ -> false
end
| _ -> false
let propagate_rec pfs rel ante_vars = match CP.get_rel_id rel with
| None -> (pfs,1)
| Some ivs ->
let (rcases, bcases) = List.partition is_rec pfs in
(* let or_post = get_or_post specs (CP.get_rel_id_list rel) in*)
(* let bcases = *)
(* begin*)
(* match or_post with*)
(* | [] -> bcases*)
(* | [or_fml] ->*)
(* let other_branches = get_other_branches or_fml (CP.get_rel_args rel) in*)
let other_branches = ( fun p - > CP.mkNot_s p ) other_branches in
let pure_other_branches = CP.conj_of_list other_branches in
( fun b - > TP.is_sat_raw ( b pure_other_branches ) ) bcases
(* | _ -> bcases*)
(* end*)
(* in*)
let ( fun b - > let b in
(* let cond = List.exists (fun d -> let conjs = CP.list_of_conjs d in*)
(* List.exists (fun c -> CP.is_eq_const c) conjs) disjs in*)
if cond then 1 else ) bcases in
( * let no_of_disjs = List.map ( fun b - > b ) bcases in
let ( fun a b - > max a b ) 1 no_of_disjs in
let bcases = List.concat (List.map (fun x -> CP.list_of_disjs x) bcases) in
let rcases = List.concat (List.map (fun x -> CP.list_of_disjs (TP.simplify_raw x)) rcases) in
let bcases = List.map remove_subtract bcases in
let bcases = List.map (fun bcase ->
let conjs = list_of_conjs bcase in
let conjs = Gen.BList.remove_dups_eq CP.equalFormula (List.filter (fun x -> not (isComp x)) conjs) in
conj_of_list conjs no_pos) bcases in
let rcases = List.map remove_subtract rcases in
x_dinfo_hp (add_str "BCASE: " (pr_list !CP.print_formula)) bcases no_pos;
let bcases = simplify bcases in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
(* x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;*)
let rcases = simplify rcases in
x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;
let rcases = List.map (fun rcase -> propagate_rec_helper rcase rel ante_vars) rcases in
x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;
let fv_rel = get_rel_args rel in
let bcases = List.map (fun x -> let fv_x = CP.fv x in
)
let r = CP.mkExists (CP.diff_svl (CP.fv x) fv_rel) x None no_pos in
let r = Redlog.elim_exists_with_eq r in
TP.simplify_raw r) bcases in
let bcases = List.map ( fun x - > rewrite2 x [ ] fv_rel ) bcases in
let bcases = List.map remove_subtract bcases in
let bcases = List.map (fun x -> rewrite x fv_rel [] true) bcases in
let bcases = List.map (fun x -> rewrite x fv_rel [] true) bcases in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
let bcases = List.map (fun x -> CP.remove_cnts2 fv_rel x) bcases in
let v_synch = List.filter is_int_typ (List.concat (List.map fv rcases)) in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
let bcases = List.map (fun x -> transform x v_synch fv_rel) bcases in
x_dinfo_hp (add_str "BCASE: " (pr_list !CP.print_formula)) bcases no_pos;
let bcases = Gen.BList.remove_dups_eq (fun p1 p2 -> TP.imply_raw p1 p2 && TP.imply_raw p2 p1) bcases in
let bcases = if List.length fv_rel <= 5 then bcases else
List.map (fun bcase ->
let bcase = remove_subtract bcase in
let bcase_conjs = list_of_conjs bcase in
let all_pairs = get_all_pairs bcase_conjs in
DD.info_hprint ( add_str " : " ( pr_list ( pr_pair ! CP.print_formula ! CP.print_formula ) ) ) all_pairs ;
let (rem,add) = List.split (rewrite_by_subst2 all_pairs) in
let conjs = (Gen.BList.difference_eq (=) bcase_conjs (List.concat rem)) @ (List.concat add) in
conj_of_list conjs no_pos
) bcases
in
let bcases = List.map (fun bcase ->
if diff_svl fv_rel (fv bcase) != [] && diff_svl (fv bcase) fv_rel != []
then mkFalse no_pos else bcase) bcases in
let no_of_disjs = List.length bcases in
(bcases @ rcases, no_of_disjs)
(* match bcases with*)
| [ bcase ] - > ( [ bcase ] @ ( List.map ( fun rcase - > propagate_rec_helper rcase rel ante_vars ) rcases ) , no_of_disjs )
| _ - > ( bcases @ ( List.map ( fun rcase - > propagate_rec_helper rcase rel ante_vars ) rcases ) , no_of_disjs )
let new_bcases = remove_weaker_bcase bcases in
new_bcases @ ( List.map ( fun rcase - > rel ante_vars ) rcases )
new_bcases @ (List.map (fun rcase -> arr_args rcase rel ante_vars) rcases)*)
let rec no_of_cnts f = match f with
| BForm _ -> 1
| And (f1,f2,_) -> (no_of_cnts f1) + (no_of_cnts f2)
| Or (f1,f2,_,_) -> (no_of_cnts f1) + (no_of_cnts f2)
| Not (f,_,_) -> no_of_cnts f
| Forall (_,f,_,_) -> no_of_cnts f
| Exists (_,f,_,_) -> no_of_cnts f
| AndList l -> List.fold_left (fun a (_,c)-> a+(no_of_cnts c)) 0 l
let helper input_pairs rel ante_vars =
let pairs = List.filter (fun (p,r) -> CP.equalFormula r rel) input_pairs in
let pfs,_ = List.split pairs in
let pfs = List.map (fun p ->
let noc = no_of_cnts p in
DD.info_hprint ( add_str " NO : " string_of_int ) noc no_pos ;
let p = if noc > 20 then p else Redlog.elim_exists_with_eq p in
let p = TP.simplify_raw p in
let exists_node_vars = List.filter CP.is_node_typ (CP.fv p) in
let num_vars, others, num_vars_new = get_num_dom p in
x_dinfo_hp ( add_str " VARS : " ( ! print_svl ) ) others ;
let num_vars = if CP.intersect num_vars others = [] then num_vars else num_vars_new in
CP.remove_cnts (exists_node_vars@num_vars) p) pfs in
let pfs,no = propagate_rec pfs rel ante_vars in
let pfs = List.map (fun p ->
let exists_vars = CP.diff_svl (List.filter
(fun x -> not(CP.is_bag_typ x || CP.is_rel_typ x)) (CP.fv p)) (CP.fv rel) in
CP.mkExists exists_vars p None no_pos) pfs in
match pfs with
| [] -> []
| [ hd ] - > [ ( rel , hd , no ) ]
| _ -> [(rel, List.fold_left (fun p1 p2 -> CP.mkOr p1 p2 None no_pos) (CP.mkFalse no_pos) pfs, no)]
let simplify_res fixpoint =
let disjs = list_of_disjs fixpoint in
match disjs with
| [p1;p2] ->
if TP.imply_raw p1 p2 then p2 else
if TP.imply_raw p2 p1 then p1 else fixpoint
| _ -> fixpoint
let compute_fixpoint_aux rel_fml pf no_of_disjs ante_vars is_recur =
if CP.isConstFalse pf then (rel_fml, CP.mkFalse no_pos)
else (
let (name,vars) = match rel_fml with
| CP.BForm ((CP.RelForm (name,args,_),_),_) -> (CP.name_of_spec_var name, (List.concat (List.map CP.afv args)))
| _ -> report_error no_pos "Wrong format"
in
let pre_vars, post_vars = List.partition (fun v -> List.mem v ante_vars) vars in
try
let rhs = fixbag_of_pure_formula pf in
let no = string_of_int no_of_disjs in
let input_fixbag = "fixbagA" (*^ name *)^ "(" ^ (string_of_elems pre_vars fixbag_of_spec_var ",") ^ " -> "
^ (string_of_elems post_vars fixbag_of_spec_var ",") ^ ") := "
^ rhs
in
(*print_endline ("\nINPUT: " ^ input_fixbag);*)
x_dinfo_pp ">>>>>> compute_fixpoint <<<<<<" no_pos;
x_dinfo_pp ("Input of fixbag: " ^ input_fixbag) no_pos;
let output_of_sleek = " fixbag.inf " in
let oc = open_out output_of_sleek in
(* Printf.fprintf oc "%s" input_fixbag;*)
(* flush oc;*)
(* close_out oc;*)
let res = syscall (fixbag ^ " \'" ^ input_fixbag ^ "\' \'" ^ no ^ "\'") in
let res = remove_paren res (String.length res) in
(*print_endline ("RES: " ^ res);*)
x_dinfo_pp ("Result of fixbag: " ^ res) no_pos;
let fixpoint = Parse_fixbag.parse_fix res in
x_dinfo_hp (add_str "Result of fixbag (parsed): " (pr_list !CP.print_formula)) fixpoint no_pos;
match fixpoint with
| [post] -> (rel_fml, simplify_res post)
| _ -> report_error no_pos "Expecting a post"
with _ ->
if not(is_rec pf) then
let () = x_dinfo_hp (add_str "Input: " !CP.print_formula) pf no_pos in
let exists_vars = CP.diff_svl (CP.fv_wo_rel pf) (CP.fv rel_fml) in
let pf = TP.simplify_exists_raw exists_vars pf in
(rel_fml, remove_subtract pf)
else report_error no_pos "Unexpected error in computing fixpoint by FixBag"
)
let compute_fixpoint input_pairs ante_vars is_rec =
let (pfs, rels) = List.split input_pairs in
let rels = Gen.BList.remove_dups_eq CP.equalFormula rels in
let pairs = match rels with
| [] -> report_error no_pos "Error in compute_fixpoint"
(* | [hd] -> *)
let , no = in
let = List.map ( fun p - >
let exists_node_vars = ( CP.fv p ) in
let in
let exists_vars = CP.diff_svl ( List.filter
( fun x - > not(CP.is_bag_typ x ) ) ( CP.fv p ) ) ( CP.fv hd ) in
CP.mkExists exists_vars p None no_pos ) pfs in
let pf = List.fold_left ( fun p1 p2 - > CP.mkOr p1 p2 None no_pos ) ( CP.mkFalse no_pos ) pfs in [ ( hd , pf , no ) ]
| _ -> List.concat (List.map (fun r -> helper input_pairs r ante_vars) rels)
in
x_tinfo_hp (add_str "input_pairs: " (pr_list (pr_pair !CP.print_formula !CP.print_formula))) input_pairs no_pos;
List.map (fun (rel_fml,pf,no) -> compute_fixpoint_aux rel_fml pf no ante_vars is_rec) pairs
call the wrappers for :
1 . trasnform imm formula to imm - free formula and back
2 . disable fixcalc inner imm - free to imm transformation ( eg . calling simpilfy , etc )
1. trasnform imm formula to imm-free formula and back
2. disable fixcalc inner imm-free to imm transformation (eg. calling simpilfy, etc) *)
let compute_fixpoint input_pairs ante_vars is_rec =
let fixpt input_pairs = compute_fixpoint input_pairs ante_vars is_rec in
let pre = List.map (fold_pair1f (x_add_1 Immutable.map_imm_to_int_pure_formula)) in
let post = List.map (fold_pair1f (x_add_1 Immutable.map_int_to_imm_pure_formula)) in
let fixpt input_pairs = Wrapper.wrap_pre_post_process pre post fixpt input_pairs in
Wrapper.wrap_one_bool Globals.int2imm_conv false fixpt input_pairs
let compute_fixpoint (i:int) input_pairs pre_vars is_rec =
let pr0 = !CP.print_formula in
let pr1 = pr_list (pr_pair pr0 pr0) in
let pr2 = !CP.print_svl in
Debug.no_2_num i "compute_fixpoint" pr1 pr2 (pr_list (pr_pair pr0 pr0))
(fun _ _ -> compute_fixpoint input_pairs pre_vars is_rec) input_pairs pre_vars
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/src/fixbag.ml | ocaml |
Call FixBag, send input to it
let is_self = CP.is_self_var
let is_null = CP.is_null
!allow_pred_spec
" (forall (" ^ fixbag_of_spec_var sv ^ ":" ^ fixbag_of_pure_formula p ^ ")) "
print_endline ("\nINPUT: " ^ input_fixbag);
Printf.fprintf oc "%s" input_fixbag;
flush oc;
close_out oc;
print_endline ("RES: " ^ res);
print_endline ("\nINPUT: " ^ input_fixbag);
print_endline ("RES: " ^ res);
^ n
^ n
let arr_args rcase_orig rel ante_vars =
let rels = CP.get_RelForm rcase_orig in
| (CP.Lte(CP.IConst(i2, _), e1, _), CP.Eq(CP.IConst(i4, _), e3, _)) ->
| _ -> None
let pr0 = !CP.print_p_formula in
(match exp with
| None -> []
| _ -> []
let pr0 = !CP.print_formula in
x_dinfo_hp (add_str "matching: " (pr_list !CP.print_formula)) [f1;f2] no_pos;
x_dinfo_hp (add_str "CONJ1: " (pr_list !CP.print_formula)) conjs1 no_pos;
x_dinfo_hp (add_str "other2: " (pr_list !CP.print_formula)) others2 no_pos;
TODO:
TODO:
DD.info_hprint (add_str "ALS: " (pr_list (pr_pair !print_sv !print_sv))) als no_pos;
let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure pure) in
let aset = CP.EMapSV.build_eset als in
let pure_vars = CP.fv pure in
let hd = List.hd vars in
(List.tl vars))) alias) in
let pure = conj_of_list (pure::subst_lst) no_pos in
Add more if necessary
x_dinfo_hp (add_str "Before: " (!CP.print_formula)) rcase_orig no_pos;
let all_rel_vars = rel_vars @ (CP.fv rel) in
let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure rcase) in
let aset = CP.EMapSV.build_eset als in
let alias = create_alias_tbl (rel_vars@other_vars) aset (CP.fv rel) in
let rcase = MCP.remove_ptr_equations rcase false in
let exists_vars = CP.diff_svl (CP.fv rcase) rel_vars in
try
let pairs = List.combine (CP.fv rel) rel_vars in
with _ -> rcase_orig
TODO: Need to handle computed relation in the future
let rec get_other_branches or_fml args = match or_fml with
| Or fml ->
(get_other_branches fml.formula_or_f1 args) @ (get_other_branches fml.formula_or_f2 args)
| _ ->
let or_post = get_or_post specs (CP.get_rel_id_list rel) in
let bcases =
begin
match or_post with
| [] -> bcases
| [or_fml] ->
let other_branches = get_other_branches or_fml (CP.get_rel_args rel) in
| _ -> bcases
end
in
let cond = List.exists (fun d -> let conjs = CP.list_of_conjs d in
List.exists (fun c -> CP.is_eq_const c) conjs) disjs in
x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;
match bcases with
^ name
print_endline ("\nINPUT: " ^ input_fixbag);
Printf.fprintf oc "%s" input_fixbag;
flush oc;
close_out oc;
print_endline ("RES: " ^ res);
| [hd] -> | #include "xdebug.cppo"
open VarGen
open Globals
module DD = Debug
open Gen
open Exc.GTable
open Perm
open Cpure
open Context
module M = Lexer.Make(Token.Token)
module Pr = Cprinter
module CP = Cpure
module CF= Cformula
module MCP = Mcpure
module TP = Tpdispatcher
Operators
let op_lt = "<"
let op_lte = "<="
let op_gt = ">"
let op_gte = ">="
let op_eq = "="
let op_neq = "!="
let op_and = " && "
let op_or = " || "
let op_add = "+"
let op_sub = "-"
let rec string_of_elems elems string_of sep = match elems with
| [] -> ""
| h::[] -> string_of h
| h::t -> (string_of h) ^ sep ^ (string_of_elems t string_of sep)
let fixbag_of_spec_var x = match x with
| CP.SpecVar ( Named _ , i d , ) - > " " ^ i d
| CP.SpecVar ( Named _ , i d , Primed ) - > " NODPRI " ^ i d
| CP.SpecVar ( _ , i d , ) - > i d
| CP.SpecVar ( _ , i d , Primed ) - > " PRI " ^ i d
| CP.SpecVar (_, id, _) -> if is_anon_var x && not (is_bag_typ x) then "v_" ^ id else id
let rec fixbag_of_exp e = match e with
| CP.Null _ -> "null"
| CP.Var (x, _) -> fixbag_of_spec_var x
| CP.IConst (i, _) -> string_of_int i
| CP.FConst ( f , _ ) - > string_of_float f
| CP.Add (e1, e2, _) -> fixbag_of_exp e1 ^ op_add ^ fixbag_of_exp e2
| CP.Subtract (e1, e2, _) -> fixbag_of_exp e2
| CP.Bag (es, _) -> "{" ^ (string_of_elems es fixbag_of_exp ",") ^ "}"
| CP.BagUnion (es, _) -> string_of_elems es fixbag_of_exp "+"
| CP.BagIntersect (es, _) -> string_of_elems es fixbag_of_exp "."
| CP.BagDiff (e1, e2, _) -> fixbag_of_exp e1 ^ op_sub ^ fixbag_of_exp e2
| _ -> illegal_format ("Fixbag.fixbag_of_exp: Not supported expression")
let rec fixbag_of_b_formula b =
let (pf, _) = b in
match pf with
| CP.BConst (b,_) -> "{}={}"
| CP.BVar (x, _) -> fixbag_of_spec_var x
| CP.Lt (e1, e2, _) -> "{}={}"
| CP.Lte (e1, e2, _) -> "{}={}"
| CP.Gt (e1, e2, _) -> "{}={}"
| CP.Gte (e1, e2, _) -> "{}={}"
| CP.Eq (e1, e2, _) -> if CP.is_null e2 && not (is_bag e1) then fixbag_of_exp e1 ^op_lte^"0"
else if CP.is_null e1 && not(is_bag e2) then fixbag_of_exp e2 ^op_lte^"0"
else fixbag_of_exp e1 ^ op_eq ^ fixbag_of_exp e2
| CP.Neq (e1, e2, _) ->
if CP.is_null e2 && not (is_bag e1) then fixbag_of_exp e1 ^op_gt^"0"
else if CP.is_null e1 && not(is_bag e2) then fixbag_of_exp e2 ^op_gt^"0"
else
if List.exists is_int_typ (CP.bfv b) then fixbag_of_exp e1 ^ op_neq ^ fixbag_of_exp e2
else "!(" ^ fixbag_of_exp e1 ^ op_eq ^ fixbag_of_exp e2 ^ ")"
| CP.RelForm (id,args,_) -> (fixbag_of_spec_var id) ^ "(" ^ (string_of_elems args fixbag_of_exp ",") ^ ")"
| BagIn ( sv , e , _ ) - >
| ( sv , e , _ ) - >
| CP.BagSub (e1, e2, _) -> fixbag_of_exp e1 ^ op_lte ^ fixbag_of_exp e2
| BagMin ( sv1 , sv2 , _ ) - >
| ( sv1 , sv2 , _ ) - >
| _ -> illegal_format ("Fixbag.fixbag_of_b_formula: Do not support list or boolean vars")
let rec fixbag_of_pure_formula f = match f with
| CP.BForm ((CP.BVar (x,_),_),_) -> "$" ^ fixbag_of_spec_var x
| CP.BForm (b,_) -> fixbag_of_b_formula b
| CP.And (p1, p2, _) ->
"(" ^ fixbag_of_pure_formula p1 ^ op_and ^ fixbag_of_pure_formula p2 ^ ")"
| CP.AndList b -> "(" ^ String.concat op_and (List.map (fun (_,c)-> fixbag_of_pure_formula c) b) ^ ")"
| CP.Or (p1, p2,_ , _) ->
"(" ^ fixbag_of_pure_formula p1 ^ op_or ^ fixbag_of_pure_formula p2 ^ ")"
| CP.Not (p,_ , _) ->
begin
match p with
| CP.BForm ((CP.BVar (x,_),_),_) -> "!$" ^ fixbag_of_spec_var x
| _ -> "!(" ^ fixbag_of_pure_formula p ^ ")"
end
| CP.Forall (sv, p,_ , _) -> illegal_format ("Fixbag.fixbag_of_pure_formula: Do not support forall")
| CP.Exists (sv, p,_ , _) ->
" (exists " ^ fixbag_of_spec_var sv ^ ":" ^ fixbag_of_pure_formula p ^ ") "
let rec fixbag_of_h_formula f = match f with
| CF.Star {CF.h_formula_star_h1 = h1; CF.h_formula_star_h2 = h2} ->
"(" ^ fixbag_of_h_formula h1 ^ op_and ^ fixbag_of_h_formula h2 ^ ")"
| CF.Phase _ -> illegal_format ("Fixbag.fixbag_of_h_formula: Not supported Phase-formula")
| CF.Conj {CF.h_formula_conj_h1 = h1; CF.h_formula_conj_h2 = h2} ->
"(" ^ fixbag_of_h_formula h1 ^ op_or ^ fixbag_of_h_formula h2 ^ ")"
| CF.DataNode {CF.h_formula_data_node = sv; CF.h_formula_data_name = c;CF.h_formula_data_arguments = svs} ->
if CP.is_self_spec_var sv then self ^ op_gt ^ "0"
else c ^ "(" ^ (fixbag_of_spec_var sv) ^ "," ^ (string_of_elems svs fixbag_of_spec_var ",") ^ ")"
| CF.ViewNode {CF.h_formula_view_node = sv; CF.h_formula_view_name = c; CF.h_formula_view_arguments = svs} ->
if CP.is_self_spec_var sv then self ^ op_gt ^ "0"
else c ^ "(" ^ (fixbag_of_spec_var sv) ^","^ (string_of_elems svs fixbag_of_spec_var ",")^","^ res_name ^ ")"
| CF.HTrue -> "HTrue"
| CF.HFalse -> "HFalse"
| CF.HEmp -> "{}={}"
| CF.HRel _ -> "HTrue"
| CF.Hole _ -> illegal_format ("Fixbag.fixbag_of_h_formula: Not supported Hole-formula")
| _ -> illegal_format("Fixbag.fixbag_of_h_formula: Not Suppoted")
let fixbag_of_mix_formula (f,l) = match f with
| MCP.MemoF _ -> ""
| MCP.OnePF pf -> fixbag_of_pure_formula pf
let rec fixbag_of_formula e = match e with
| CF.Or _ -> illegal_format ("Fixbag.fixbag_of_formula: Not supported Or-formula")
| CF.Base {CF.formula_base_heap = h; CF.formula_base_pure = p; CF.formula_base_label = b} ->
"(" ^ fixbag_of_h_formula h ^ op_and ^ fixbag_of_mix_formula (p,b) ^ ")"
| CF.Exists {CF.formula_exists_qvars = svs; CF.formula_exists_heap = h;
CF.formula_exists_pure = p; CF.formula_exists_label = b} ->
"(exists " ^ (string_of_elems svs fixbag_of_spec_var ",") ^ ": " ^
fixbag_of_h_formula h ^ op_and ^ fixbag_of_mix_formula (p,b) ^ ")"
let fixbag = "fixbag4"
let syscall cmd =
let ic, oc = Unix.open_process cmd in
let buf = Buffer.create 16 in
(try
while true do
Buffer.add_channel buf ic 1
done
with End_of_file -> ());
let todo_unk = Unix.close_process (ic, oc) in
(Buffer.contents buf)
let rec remove_paren s n = if n=0 then "" else match s.[0] with
| '(' -> remove_paren (String.sub s 1 (n-1)) (n-1)
| ')' -> remove_paren (String.sub s 1 (n-1)) (n-1)
| _ -> (String.sub s 0 1) ^ (remove_paren (String.sub s 1 (n-1)) (n-1))
let compute_inv name vars fml pf no_of_disjs =
if not !Globals.do_infer_inv then pf
else
let rhs = string_of_elems fml (fun (c,_) ->fixbag_of_formula c) op_or in
let no = string_of_int no_of_disjs in
let input_fixbag =
try
name ^ "(" ^"self," ^ (string_of_elems vars fixbag_of_spec_var ",") ^ " -> "
^ res_name ^ ") := "
^ rhs
with _ -> report_error no_pos "Error in translating the input for fixbag"
in
DD.info_pprint ">>>>>> compute_fixpoint <<<<<<" no_pos;
DD.info_zprint (lazy (("Input of fixbag: " ^ input_fixbag))) no_pos;
let output_of_sleek = " fixbag.inf " in
let oc = open_out output_of_sleek in
let res = syscall (fixbag ^ " \'" ^ input_fixbag ^ "\' \'" ^ no ^ "\'") in
let res = remove_paren res (String.length res) in
DD.info_zprint (lazy (("Result of fixbag: " ^ res))) no_pos;
let new_pf = List.hd (Parse_fixbag.parse_fix res) in
let () = x_dinfo_hp (add_str "Result of fixbag (parsed): " !CP.print_formula) new_pf no_pos in
let check_imply = Omega.imply new_pf pf "1" 100.0 in
if check_imply then (
Pr.fmt_string "INV: ";
Pr.pr_angle name (fun x -> Pr.fmt_string (Pr.string_of_typed_spec_var x)) vars;
Pr.fmt_string ("\nOLD: " ^ (Pr.string_of_pure_formula pf) ^
"\nNEW: " ^ (Pr.string_of_pure_formula new_pf) ^ "\n\n");
new_pf)
else pf
let compute_fixpoint input_pairs =
let ( , rels ) = List.split input_pairs in
let rels = Gen. CP.equalFormula rels in
let rel_fml = match rels with
| [ ] - > report_error no_pos " Error in compute_fixpoint "
| [ hd ] - > hd
| _ - > report_error no_pos " Fixbag.ml : More than one input relation "
in
let ( name , vars ) = match rel_fml with
| CP.BForm ( ( CP.RelForm ( name , args , _ ) , _ ) , _ ) - > ( CP.name_of_spec_var name , ( List.concat ( List.map CP.afv args ) ) )
| _ - > report_error no_pos " Wrong format "
in
let pf = List.fold_left ( fun p1 p2 - > CP.mkOr p1 p2 None no_pos ) ( List.hd pfs ) ( List.tl pfs ) in
try
let rhs = fixbag_of_pure_formula pf in
let input_fixbag = name ^ " : = { [ " ^ ( string_of_elems vars fixbag_of_spec_var " , " )
^ " ] - > [ ] - > [ ] : " ^ rhs ^ " \n};\n\nFix1:=bottomup ( " ^ name ^ " , 1,SimHeur);\nFix1;\n "
^ " Fix2:=topdown ( " ^ name ^ " , 1,SimHeur);\nFix2 ; "
in
( * print_endline ( " \nINPUT : " ^ input_fixbag ) ;
let (pfs, rels) = List.split input_pairs in
let rels = Gen.BList.remove_dups_eq CP.equalFormula rels in
let rel_fml = match rels with
| [] -> report_error no_pos "Error in compute_fixpoint"
| [hd] -> hd
| _ -> report_error no_pos "Fixbag.ml: More than one input relation"
in
let (name,vars) = match rel_fml with
| CP.BForm ((CP.RelForm (name,args,_),_),_) -> (CP.name_of_spec_var name, (List.concat (List.map CP.afv args)))
| _ -> report_error no_pos "Wrong format"
in
let pf = List.fold_left (fun p1 p2 -> CP.mkOr p1 p2 None no_pos) (List.hd pfs) (List.tl pfs) in
try
let rhs = fixbag_of_pure_formula pf in
let input_fixbag = name ^ ":={[" ^ (string_of_elems vars fixbag_of_spec_var ",")
^ "] -> [] -> []: " ^ rhs ^ "\n};\n\nFix1:=bottomup(" ^ name ^ ",1,SimHeur);\nFix1;\n"
^ "Fix2:=topdown(" ^ name ^ ",1,SimHeur);\nFix2;"
in
x_tinfo_hp (add_str "input_pairs: " (pr_list (pr_pair !CP.print_formula !CP.print_formula))) input_pairs no_pos;
x_dinfo_pp ">>>>>> compute_fixpoint <<<<<<" no_pos;
x_dinfo_pp ("Input of fixbag: " ^ input_fixbag) no_pos;
let output_of_sleek = "fixbag.inf" in
let oc = open_out output_of_sleek in
Printf.fprintf oc "%s" input_fixbag;
flush oc;
close_out oc;
let res = syscall (fixbag ^ " " ^ output_of_sleek) in
let res = remove_paren res (String.length res) in
x_dinfo_pp ("Result of fixbag: " ^ res) no_pos;
let fixpoint = Parse_fix.parse_fix res in
x_dinfo_hp (add_str "Result of fixbag (parsed): " (pr_list !CP.print_formula)) fixpoint no_pos;
let fixpoint = List.map (fun f ->
let args = CP.fv f in
let quan_vars = CP.diff_svl args vars in
TP.simplify_raw (CP.mkExists quan_vars f None no_pos)) fixpoint in
match fixpoint with
| [pre;post] -> (rel_fml, pre, post)
| _ -> report_error no_pos "Expecting a pair of pre-post"
with _ -> report_error no_pos "Unexpected error in computing fixpoint"*)
let rec is_rec pf = match pf with
| CP.BForm (bf,_) -> CP.is_RelForm pf
| CP.And (f1,f2,_) -> is_rec f1 || is_rec f2
| CP.AndList b -> exists_l_snd is_rec b
| CP.Or (f1,f2,_,_) -> is_rec f1 || is_rec f2
| CP.Not (f,_,_) -> is_rec f
| CP.Forall (_,f,_,_) -> is_rec f
| CP.Exists (_,f,_,_) -> is_rec f
let rec get_rel_vars pf = match pf with
| CP.BForm (bf,_) -> if CP.is_RelForm pf then CP.get_rel_args pf else []
| CP.And (f1,f2,_) -> get_rel_vars f1 @ get_rel_vars f2
| CP.AndList b -> fold_l_snd get_rel_vars b
| CP.Or (f1,f2,_,_) -> get_rel_vars f1 @ get_rel_vars f2
| CP.Not (f,_,_) -> get_rel_vars f
| CP.Forall (_,f,_,_) -> get_rel_vars f
| CP.Exists (_,f,_,_) -> get_rel_vars f
let substitute (e: CP.exp): (CP.exp * CP.formula list) = match e with
| CP.Var _ -> (e, [])
| _ -> (
try
let arb = List.hd (CP.afv e) in
let var = CP.fresh_spec_var_prefix "fb" arb in
let var = CP.mkVar var no_pos in
(var, [CP.mkEqExp var e no_pos])
with _ -> (e,[]))
let arr_para_order (rel: CP.formula) (rel_def: CP.formula) (ante_vars: CP.spec_var list) = match (rel,rel_def) with
| (CP.BForm ((CP.RelForm (id,args,p), o1), o2), CP.BForm ((CP.RelForm (id_def,args_def,_), _), _)) ->
if id = id_def then
let new_args_def =
let pre_args, post_args = List.partition (fun e -> Gen.BList.subset_eq CP.eq_spec_var (CP.afv e) ante_vars) args_def in
pre_args @ post_args
in
let pairs = List.combine args_def args in
let new_args = List.map (fun a -> List.assoc a pairs) new_args_def in
let new_args, subs = List.split (List.map (fun a -> substitute a) new_args) in
(CP.BForm ((CP.RelForm (id,new_args,p), o1), o2), [CP.conj_of_list (List.concat subs) no_pos])
else
let args, subs = List.split (List.map (fun a -> substitute a) args) in
(CP.BForm ((CP.RelForm (id,args,p), o1), o2), [CP.conj_of_list (List.concat subs) no_pos])
| _ -> report_error no_pos "Expecting relation formulae"
let rels , lp = List.split ( List.map ( fun r - > arr_para_order r rel ante_vars ) rels ) in
let = TP.simplify_raw ( CP.drop_rel_formula rcase_orig ) in
CP.conj_of_list ( [ rcase]@rels@(List.concat lp ) ) no_pos
let propagate_exp exp1 exp2 = match ( exp1 , exp2 ) with ( * Need to cover all patterns
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Lte(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 > i4 then Some ( CP.Lte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(CP.IConst(i4 , _ ) , e3 , _ ) ) - >
if e1 e3 & & i2 > i4 then Some ( CP.Lte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(CP.IConst(i2 , _ ) , e1 , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Lte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Lt(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 > = i4 then Some ( CP.Lt(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Gte(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(e3 , CP.IConst(i4 , _ ) , _ ) )
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Eq(CP.IConst(i4 , _ ) , e3 , _ ) ) - >
if e1 e3 & & i2 < i4 then Some ( CP.Gte(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
| ( CP.Gte(e1 , CP.IConst(i2 , _ ) , _ ) , CP.Gt(e3 , CP.IConst(i4 , _ ) , _ ) ) - >
if e1 e3 & & i2 < = i4 then Some ( CP.Gt(e1 , CP.IConst(i4 , no_pos ) , no_pos ) ) else None
let propagate_exp exp1 exp2 =
" propagate_exp " pr0 pr0 ( pr_option pr0 )
( fun _ _ - > propagate_exp exp1 exp2 ) exp1 exp2
let = match ( rcase , bcase ) with
| ( CP.BForm ( ( exp1 , _ ) , _ ) , CP.BForm ( ( exp2 , _ ) , _ ) ) - >
let exp = propagate_exp exp1 exp2 in
| Some e - > [ CP.BForm ( ( e , None),None ) ] )
let =
" propagate_fml " pr0 pr0 ( pr_list pr0 )
( fun _ _ - > propagate_fml )
let matching_exp pf1 pf2 = match (pf1,pf2) with
| (Lt (Var (v1,p1), Var (v2,p2), p), Lt (Var (v3,_), Var (v4,_), _))
| (Gt (Var (v1,p1), Var (v2,p2), p), Gt (Var (v3,_), Var (v4,_), _)) ->
let res = eq_spec_var v1 v4 && eq_spec_var v2 v3 in
if res then (true, [Neq (Var (v1,p1), Var (v2,p2), p)]) else (false,[])
| (Eq (v1, Bag ([],_), _), Eq (v2, BagUnion (es,_), _))
| (Eq (v1, Bag ([],_), _), Eq (BagUnion (es,_), v2, _))
| (Eq (Bag ([],_), v1, _), Eq (v2, BagUnion (es,_), _))
| (Eq (Bag ([],_), v1, _), Eq (BagUnion (es,_), v2, _))
| (Eq (v2, BagUnion (es,_), _), Eq (v1, Bag ([],_), _))
| (Eq (v2, BagUnion (es,_), _), Eq (Bag ([],_), v1, _))
| (Eq (BagUnion (es,_), v2, _), Eq (v1, Bag ([],_), _))
| (Eq (BagUnion (es,_), v2, _), Eq (Bag ([],_), v1, _)) ->
begin
match (v1,v2) with
| (Var (b1,_), Var (b2,_))
| ( Subtract ( _ , Subtract ( _ , ( b1 , _ ) , _ ) , _ ) , ( b2 , _ ) )
| ( Var ( b1 , _ ) , Subtract ( _ , Subtract ( _ , ( b2 , _ ) , _ ) , _ ) )
| ( Subtract ( _ , Subtract ( _ , ( b1 , _ ) , _ ) , _ ) , Subtract ( _ , Subtract ( _ , ( b2 , _ ) , _ ) , _ ) )
-> (eq_spec_var b1 b2 && es != [],[])
| _ -> (false,[])
end
| _ -> (false,[])
let matching f1 f2 = match (f1,f2) with
| (BForm ((pf1,o),p), BForm ((pf2,_),_)) ->
let (res1,res2) = matching_exp pf1 pf2 in
if res2 = [] then (res1,[])
else (res1,List.map (fun r2 -> BForm((r2,o),p)) res2)
| _ -> (false,[])
let can_merge f1 f2 =
let conjs1 = CP.list_of_conjs f1 in
let conjs2 = CP.list_of_conjs f2 in
x_dinfo_hp ( add_str " CONJ2 : " ( pr_list ! CP.print_formula ) ) conjs2 no_pos ;
let part_of_f1, others1 = List.partition (fun c -> Gen.BList.mem_eq (CP.equalFormula) c conjs1) conjs2 in
x_dinfo_hp ( add_str " PART1 : " ( pr_list ! CP.print_formula ) ) part_of_f1 ;
x_dinfo_hp ( add_str " other1 : " ( pr_list ! CP.print_formula ) ) ;
let part_of_f2, others2 = List.partition (fun c -> Gen.BList.mem_eq (CP.equalFormula) c conjs2) conjs1 in
x_dinfo_hp ( add_str " PART2 : " ( pr_list ! CP.print_formula ) ) part_of_f2 no_pos ;
let check1 = List.length part_of_f1 = List.length part_of_f2 && List.length others1 = List.length others2 in
let matching = if check1 then List.map2 (fun o1 o2 -> matching o1 o2) others1 others2 else [] in
let added_conj = List.concat (List.map (fun (f1,f2) -> if f1 then f2 else []) matching) in
let check = check1 && List.for_all fst matching in
if check then (true, conj_of_list (part_of_f1@added_conj) no_pos)
else (false, f1)
let rec simplify flist = match flist with
| [] -> []
| [hd] -> [hd]
| hd::tl ->
let check_merge = List.map (fun f -> can_merge f hd) tl in
let (can_merge, others) = List.partition fst check_merge in
x_dinfo_hp ( add_str " : " ( pr_list ! CP.print_formula ) ) ( snd ( List.split can_merge ) ) no_pos ;
x_dinfo_hp ( add_str " OTHER : " ( pr_list ! CP.print_formula ) ) ( snd ( List.split others ) ) no_pos ;
if can_merge = [] then hd::(simplify tl)
else
let hd = snd (List.hd (List.rev can_merge)) in
hd::(simplify (snd (List.split others)))
let pre_process vars fmls =
List.filter (fun f ->
let vs = List.filter (fun x -> CP.is_bag_typ x || CP.is_bool_typ x) (CP.fv f) in
x_dinfo_hp ( add_str " VARS : " ! print_svl ) vs no_pos ;
CP.subset vs vars) fmls
let rec create_alias_tbl vs aset all_rel_vars base_case = match vs with
| [] -> []
| [hd] ->
if base_case then
[hd::(List.filter (fun x -> not(List.mem x all_rel_vars)) (CP.EMapSV.find_equiv_all hd aset))]
else [List.filter (fun x -> not(List.mem x all_rel_vars)) (hd::(CP.EMapSV.find_equiv_all hd aset))]
| hd::tl ->
let res1 = create_alias_tbl [hd] aset all_rel_vars base_case in
let tl = List.filter (fun x -> not(List.mem x (List.hd res1))) tl in
res1@(create_alias_tbl tl aset all_rel_vars base_case)
let rewrite pure rel_lhs_vars rel_vars base_case =
let als = MCP.ptr_bag_equations_without_null (MCP.mix_of_pure pure) in
let aset = CP.EMapSV.build_eset als in
let int_vars, other_vars = List.partition CP.is_int_typ (CP.fv pure) in
let alias = create_alias_tbl (rel_vars@int_vars@other_vars) aset rel_lhs_vars base_case in
let subst_lst = List.concat (List.map (fun vars -> if vars = [] then [] else
let hd = List.hd vars in List.map (fun v -> (v,hd)) (List.tl vars)) alias) in
DD.info_hprint ( add_str " SUBS : " ( pr_list ( pr_pair ! print_sv ! print_sv ) ) ) subst_lst ;
DD.info_hprint ( add_str " : " ( ! CP.print_formula ) ) pure no_pos ;
let pure = CP.subst subst_lst pure in
CP.remove_redundant_constraints pure
let pure rel_lhs_vars rel_vars =
let int_vars , other_vars = List.partition CP.is_int_typ pure_vars in
let alias = ( rel_vars@int_vars@other_vars ) aset rel_lhs_vars in
let subst_lst = List.concat ( List.map ( fun vars - > if vars = [ ] then [ ] else
List.concat ( List.map ( fun v - >
if mem_svl v pure_vars & & mem_svl then [ mkEqVar v hd no_pos ] else [ ] )
( * DD.info_hprint ( add_str " : " ( ! CP.print_formula ) ) pure no_pos ;
CP.remove_dup_constraints pure
let rec get_all_pairs conjs = match conjs with
| [] -> []
| c::cs ->
let lst = List.map (fun conj -> (c,conj)) cs in
lst @ (get_all_pairs cs)
let rec rewrite_by_subst pairs = match pairs with
| [] -> []
| [(e1,e2)] ->
begin
match (e1,e2) with
| (BForm ((pf1,_),_), BForm ((pf2,_),_)) ->
begin
match pf1,pf2 with
| Eq (exp1, exp2, _), Eq (exp3, exp4, _) ->
begin
match (exp1,exp2,exp3,exp4) with
| Var (sv11,_), BagUnion ([Var (sv12,_);Bag([Var (sv13,_)],_)],_),
Var (sv21,_), BagUnion ([BagUnion ([Var (sv22,_);Bag([Var (sv23,_)],_)],_);
Bag([Var (sv24,_)],_)],_)
| Var ( sv11 , _ ) , BagUnion ( [ Var ( sv12,_);Bag([Var ( sv13 , _ ) ] , _ ) ] , _ ) ,
( sv21 , _ ) , BagUnion ( [ Subtract ( _ , Subtract(_,BagUnion ( [ Var ( sv22 , _ ) ;
Bag([Var ( sv23 , _ ) ] , _ ) ] , _ ) , _ ) , _ ) ; Bag([Var ( sv24 , _ ) ] , _ ) ] , _ )
| Var (sv21,_), BagUnion ([BagUnion ([Var (sv22,_);Bag([Var (sv23,_)],_)],_);
Bag([Var (sv24,_)],_)],_),
Var (sv11,_), BagUnion ([Var (sv12,_);Bag([Var (sv13,_)],_)],_)
| Var ( sv21 , _ ) , BagUnion ( [ Subtract ( _ , Subtract(_,BagUnion ( [ Var ( sv22 , _ ) ;
Bag([Var ( sv23 , _ ) ] , _ ) ] , _ ) , _ ) , _ ) ; Bag([Var ( sv24 , _ ) ] , _ ) ] , _ ) ,
( sv11 , _ ) , BagUnion ( [ Var ( sv12,_);Bag([Var ( sv13 , _ ) ] , _ ) ] , _ )
->
if eq_spec_var sv12 sv22 && eq_spec_var sv13 sv23 then
[CP.mkEqExp (mkVar sv21 no_pos) (BagUnion ([mkVar sv11 no_pos; Bag([mkVar sv24 no_pos],no_pos)],no_pos)) no_pos]
else []
| Var (sv11,_), BagUnion ([Var (sv12,_);Var (sv13,_);Bag([Var (sv14,_)],_)],_),
Var (sv21,_), BagUnion ([Var (sv22,_);Var (sv23,_);Bag([Var (sv24,_)],_)],_)
->
if eq_spec_var sv13 sv23 && eq_spec_var sv14 sv24 then
[CP.mkEqExp (mkVar sv21 no_pos) (BagUnion ([mkVar sv22 no_pos;
Bag([mkVar (SpecVar (Int,"v_fb",Unprimed)) no_pos],no_pos)],no_pos)) no_pos;
CP.mkEqExp (mkVar sv11 no_pos) (BagUnion ([mkVar sv12 no_pos;
Bag([mkVar (SpecVar (Int,"v_fb",Unprimed)) no_pos],no_pos)],no_pos)) no_pos]
else []
| _ -> []
end
| _ -> []
end
| _ -> []
end
| p::ps -> (rewrite_by_subst [p]) @ (rewrite_by_subst ps)
let rec rewrite_by_subst2 pairs = match pairs with
| [] -> []
| [(f1,f2)] ->
begin
match (f1,f2) with
| (BForm ((Eq (exp1, exp2, _),_),_), BForm ((Eq (exp3, exp4, _),_),_)) ->
begin
match (exp1,exp2,exp3,exp4) with
| Var (sv1,_), Var (sv2,_), Var (sv3,_), BagUnion (es,_) ->
let evars = List.concat (List.map afv es) in
let subst =
if mem_svl sv3 evars && eq_spec_var sv1 sv3 && is_bag_typ sv1 then [(sv1,sv2)] else
if mem_svl sv3 evars && eq_spec_var sv2 sv3 && is_bag_typ sv1 then [(sv2,sv1)] else [] in
let exp = e_apply_subs subst exp4 in
if subst = [] then [] else [([f1;f2],[CP.mkEqExp (mkVar sv3 no_pos) exp no_pos])]
| _ -> []
end
| (Forall _, Forall _) -> [([f1;f2],[])]
| (Forall _,_) -> [([f1],[])]
| (_,Forall _) -> [([f2],[])]
| _ -> []
end
| p::ps -> (rewrite_by_subst2 [p]) @ (rewrite_by_subst2 ps)
let rec filter_var f vars =
match f with
| CP.Or (f1,f2,l,p) -> CP.mkOr (filter_var f1 vars) (filter_var f2 vars) l p
| _ -> CP.filter_var (CP.drop_rel_formula f) vars
let propagate_rec_helper rcase_orig rel ante_vars =
let rel_vars = CP.remove_dups_svl (get_rel_vars rcase_orig) in
let = TP.simplify_raw ( CP.drop_rel_formula rcase_orig ) in
x_dinfo_hp ( add_str " After : " ( ! CP.print_formula ) ) rcase ;
let rcase = CP.drop_rel_formula rcase_orig in
let rel_lhs_vars = CP.fv rel in
let all_rel_vars = rel_vars @ rel_lhs_vars in
let rcase = filter_var rcase all_rel_vars in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let rcase = rewrite rcase rel_lhs_vars rel_vars false in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let other_vars = ( fun x - > CP.is_int_typ x ) ( CP.fv rcase_orig ) in
let subst_lst = List.concat ( List.map ( fun vars - > if vars = [ ] then [ ] else
let hd = List.hd vars in List.map ( fun v - > ( v , hd ) ) ( List.tl vars ) ) alias ) in
( * x_dinfo_hp ( add_str " SUBS : " ( pr_list ( pr_pair ! print_sv ! print_sv ) ) ) subst_lst ;
( * x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let = CP.subst subst_lst in
let rcase_conjs = CP.list_of_conjs rcase in
if List.exists (fun conj -> is_emp_bag conj rel_vars) rcase_conjs then CP.mkFalse no_pos
else
let rcase_conjs_eq = List.filter is_beq_exp rcase_conjs in
let rcase_conjs =
if List.length rcase_conjs_eq <= 4 then
let all_pairs = get_all_pairs rcase_conjs_eq in
DD.info_hprint ( add_str " : " ( pr_list ( pr_pair ! CP.print_formula ! CP.print_formula ) ) ) all_pairs ;
rcase_conjs @ (rewrite_by_subst all_pairs)
else rcase_conjs
in
let rcase = CP.conj_of_list (pre_process all_rel_vars rcase_conjs) no_pos in
let rcase = filter_var rcase all_rel_vars in
x_dinfo_hp ( add_str " RCASE : " ( ! CP.print_formula ) ) rcase ;
let rcase = if CP.diff_svl (List.filter is_bag_typ rel_vars) (CP.fv rcase) != [] then CP.mkFalse no_pos else rcase in
let rels = CP.get_RelForm rcase_orig in
let rels,lp = List.split (List.map (fun r -> arr_para_order r rel ante_vars) rels) in
let = TP.simplify_raw ( CP.mkExists exists_vars rcase None no_pos ) in
CP.conj_of_list ([rcase]@rels@(List.concat lp)) no_pos
let = CP.subst pairs bcase_orig in
let pf = List.concat ( List.map ( fun b - > List.concat
( List.map ( fun r - > propagate_fml r b ) ( CP.list_of_conjs ) ) ) ( CP.list_of_conjs bcase ) ) in
CP.conj_of_list ( [ rcase]@rels@pf@(List.concat lp ) ) no_pos
( * print_endline ( " PURE : " ^ ) ;
( * print_endline ( " PURE2 : " ^ ) ;
( * print_endline ( " PURE3 : " ^ ) ;
let rec = match bcases with
| [ ] - > [ ]
| b::bs - >
if List.exists ( fun fml - > TP.imply_raw fml b ) bs then remove_weaker_bcase bs
else
b::(remove_weaker_bcase ( ( fun fml - > not(TP.imply_raw b fml ) ) bs ) )
| [] -> []
| b::bs ->
if List.exists (fun fml -> TP.imply_raw fml b) bs then remove_weaker_bcase bs
else
b::(remove_weaker_bcase (List.filter (fun fml -> not(TP.imply_raw b fml)) bs))*)
let _ , , _ , _ , _ = split_components or_fml in
let conjs = CP.list_of_conjs ( MCP.pure_of_mix p ) in
( fun pure - > CP.subset args ( CP.fv pure ) ) conjs
let rec transform fml v_synch fv_rel = match fml with
| BForm ((Eq (v1, BagUnion ([b2;Bag([Var (v,_)],_)],_), _), _),_)
| BForm ((Eq (v1, BagUnion ([Bag([Var (v,_)],_);b2],_), _), _),_)
| BForm ((Eq (BagUnion ([Bag([Var (v,_)],_);b2],_), v1, _), _),_)
| BForm ((Eq (BagUnion ([b2;Bag([Var (v,_)],_)],_), v1, _), _),_) ->
begin
match v1 with
| Var (b1,_) ->
if diff_svl (CP.fv fml) fv_rel = [] then
let vars = afv b2 in
let v_synch = List.filter (fun x -> not (eq_spec_var x v)) v_synch in
begin
match (vars,v_synch) with
| ([hd],[v_s]) ->
let v_new = v_s in
let b2_new = CP.fresh_spec_var_prefix "FB" hd in
let als1 = CP.mkEqVar v v_new no_pos in
let als2 = CP.mkEqVar hd b2_new no_pos in
let f_new = mkEqExp (mkVar b1 no_pos) (BagUnion([mkVar b2_new no_pos;Bag([mkVar v_new no_pos],no_pos)],no_pos)) no_pos in
conj_of_list [als1;als2;f_new] no_pos
| _ -> fml
end
else fml
| _ -> fml
end
| And (BForm f1, BForm f2, _) -> mkAnd (transform (BForm f1) v_synch fv_rel) (transform (BForm f2) v_synch fv_rel) no_pos
| And _ ->
let v_synch = List.filter CP.is_int_typ (CP.diff_svl v_synch fv_rel) in
let v_subst = List.filter CP.is_int_typ (CP.diff_svl (CP.fv fml) fv_rel) in
x_dinfo_hp ( add_str " VSYNCH : " ( ! print_svl ) ) v_synch no_pos ;
x_dinfo_hp ( add_str " VSUBST : " ( ! print_svl ) ) v_subst no_pos ;
(match (v_subst, v_synch) with
| ([hd],[v_s]) -> CP.subst [(hd,v_s)] fml
| _ -> fml
)
| _ -> fml
let rec remove_subtract_exp e = match e with
| CP.Subtract (_, Subtract (_,en,_), _) -> remove_subtract_exp en
| CP.Bag (es, p) -> Bag (List.map remove_subtract_exp es, p)
| CP.BagUnion (es, p) -> BagUnion (List.map remove_subtract_exp es, p)
| CP.BagIntersect (es, p) -> BagIntersect (List.map remove_subtract_exp es, p)
| CP.BagDiff (e1, e2, p) -> BagDiff (remove_subtract_exp e1, remove_subtract_exp e2, p)
| _ -> e
let remove_subtract_pf pf = match pf with
| CP.Lt (e1, e2, p) -> Lt(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Lte (e1, e2, p) -> Lte(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Gt (e1, e2, p) -> Gt(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Gte (e1, e2, p) -> Gte(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Eq (e1, e2, p) -> Eq(remove_subtract_exp e1, remove_subtract_exp e2, p)
| CP.Neq (e1, e2, p) -> Neq(remove_subtract_exp e1, remove_subtract_exp e2, p)
| _ -> pf
let rec remove_subtract pure = match pure with
| BForm ((pf,o1),o2) -> BForm ((remove_subtract_pf pf,o1),o2)
| And (f1,f2,_) -> CP.mkAnd (remove_subtract f1) (remove_subtract f2) no_pos
| Or (f1,f2,_,_) -> CP.mkOr (remove_subtract f1) (remove_subtract f2) None no_pos
| Not (f,_,_) -> CP.mkNot_s (remove_subtract f)
| Forall (v,f,o,p) -> Forall (v,remove_subtract f,o,p)
| Exists (v,f,o,p) -> Exists (v,remove_subtract f,o,p)
| AndList l -> AndList (map_l_snd remove_subtract l)
let isComp pure = match pure with
| BForm ((pf,_),_) ->
begin
match pf with
| Lt _ | Gt _ | Lte _ | Gte _ -> true
| _ -> false
end
| _ -> false
let propagate_rec pfs rel ante_vars = match CP.get_rel_id rel with
| None -> (pfs,1)
| Some ivs ->
let (rcases, bcases) = List.partition is_rec pfs in
let other_branches = ( fun p - > CP.mkNot_s p ) other_branches in
let pure_other_branches = CP.conj_of_list other_branches in
( fun b - > TP.is_sat_raw ( b pure_other_branches ) ) bcases
let ( fun b - > let b in
if cond then 1 else ) bcases in
( * let no_of_disjs = List.map ( fun b - > b ) bcases in
let ( fun a b - > max a b ) 1 no_of_disjs in
let bcases = List.concat (List.map (fun x -> CP.list_of_disjs x) bcases) in
let rcases = List.concat (List.map (fun x -> CP.list_of_disjs (TP.simplify_raw x)) rcases) in
let bcases = List.map remove_subtract bcases in
let bcases = List.map (fun bcase ->
let conjs = list_of_conjs bcase in
let conjs = Gen.BList.remove_dups_eq CP.equalFormula (List.filter (fun x -> not (isComp x)) conjs) in
conj_of_list conjs no_pos) bcases in
let rcases = List.map remove_subtract rcases in
x_dinfo_hp (add_str "BCASE: " (pr_list !CP.print_formula)) bcases no_pos;
let bcases = simplify bcases in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
let rcases = simplify rcases in
x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;
let rcases = List.map (fun rcase -> propagate_rec_helper rcase rel ante_vars) rcases in
x_dinfo_hp (add_str "RCASE: " (pr_list !CP.print_formula)) rcases no_pos;
let fv_rel = get_rel_args rel in
let bcases = List.map (fun x -> let fv_x = CP.fv x in
)
let r = CP.mkExists (CP.diff_svl (CP.fv x) fv_rel) x None no_pos in
let r = Redlog.elim_exists_with_eq r in
TP.simplify_raw r) bcases in
let bcases = List.map ( fun x - > rewrite2 x [ ] fv_rel ) bcases in
let bcases = List.map remove_subtract bcases in
let bcases = List.map (fun x -> rewrite x fv_rel [] true) bcases in
let bcases = List.map (fun x -> rewrite x fv_rel [] true) bcases in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
let bcases = List.map (fun x -> CP.remove_cnts2 fv_rel x) bcases in
let v_synch = List.filter is_int_typ (List.concat (List.map fv rcases)) in
x_dinfo_hp ( add_str " BCASE : " ( pr_list ! CP.print_formula ) ) bcases no_pos ;
let bcases = List.map (fun x -> transform x v_synch fv_rel) bcases in
x_dinfo_hp (add_str "BCASE: " (pr_list !CP.print_formula)) bcases no_pos;
let bcases = Gen.BList.remove_dups_eq (fun p1 p2 -> TP.imply_raw p1 p2 && TP.imply_raw p2 p1) bcases in
let bcases = if List.length fv_rel <= 5 then bcases else
List.map (fun bcase ->
let bcase = remove_subtract bcase in
let bcase_conjs = list_of_conjs bcase in
let all_pairs = get_all_pairs bcase_conjs in
DD.info_hprint ( add_str " : " ( pr_list ( pr_pair ! CP.print_formula ! CP.print_formula ) ) ) all_pairs ;
let (rem,add) = List.split (rewrite_by_subst2 all_pairs) in
let conjs = (Gen.BList.difference_eq (=) bcase_conjs (List.concat rem)) @ (List.concat add) in
conj_of_list conjs no_pos
) bcases
in
let bcases = List.map (fun bcase ->
if diff_svl fv_rel (fv bcase) != [] && diff_svl (fv bcase) fv_rel != []
then mkFalse no_pos else bcase) bcases in
let no_of_disjs = List.length bcases in
(bcases @ rcases, no_of_disjs)
| [ bcase ] - > ( [ bcase ] @ ( List.map ( fun rcase - > propagate_rec_helper rcase rel ante_vars ) rcases ) , no_of_disjs )
| _ - > ( bcases @ ( List.map ( fun rcase - > propagate_rec_helper rcase rel ante_vars ) rcases ) , no_of_disjs )
let new_bcases = remove_weaker_bcase bcases in
new_bcases @ ( List.map ( fun rcase - > rel ante_vars ) rcases )
new_bcases @ (List.map (fun rcase -> arr_args rcase rel ante_vars) rcases)*)
let rec no_of_cnts f = match f with
| BForm _ -> 1
| And (f1,f2,_) -> (no_of_cnts f1) + (no_of_cnts f2)
| Or (f1,f2,_,_) -> (no_of_cnts f1) + (no_of_cnts f2)
| Not (f,_,_) -> no_of_cnts f
| Forall (_,f,_,_) -> no_of_cnts f
| Exists (_,f,_,_) -> no_of_cnts f
| AndList l -> List.fold_left (fun a (_,c)-> a+(no_of_cnts c)) 0 l
let helper input_pairs rel ante_vars =
let pairs = List.filter (fun (p,r) -> CP.equalFormula r rel) input_pairs in
let pfs,_ = List.split pairs in
let pfs = List.map (fun p ->
let noc = no_of_cnts p in
DD.info_hprint ( add_str " NO : " string_of_int ) noc no_pos ;
let p = if noc > 20 then p else Redlog.elim_exists_with_eq p in
let p = TP.simplify_raw p in
let exists_node_vars = List.filter CP.is_node_typ (CP.fv p) in
let num_vars, others, num_vars_new = get_num_dom p in
x_dinfo_hp ( add_str " VARS : " ( ! print_svl ) ) others ;
let num_vars = if CP.intersect num_vars others = [] then num_vars else num_vars_new in
CP.remove_cnts (exists_node_vars@num_vars) p) pfs in
let pfs,no = propagate_rec pfs rel ante_vars in
let pfs = List.map (fun p ->
let exists_vars = CP.diff_svl (List.filter
(fun x -> not(CP.is_bag_typ x || CP.is_rel_typ x)) (CP.fv p)) (CP.fv rel) in
CP.mkExists exists_vars p None no_pos) pfs in
match pfs with
| [] -> []
| [ hd ] - > [ ( rel , hd , no ) ]
| _ -> [(rel, List.fold_left (fun p1 p2 -> CP.mkOr p1 p2 None no_pos) (CP.mkFalse no_pos) pfs, no)]
let simplify_res fixpoint =
let disjs = list_of_disjs fixpoint in
match disjs with
| [p1;p2] ->
if TP.imply_raw p1 p2 then p2 else
if TP.imply_raw p2 p1 then p1 else fixpoint
| _ -> fixpoint
let compute_fixpoint_aux rel_fml pf no_of_disjs ante_vars is_recur =
if CP.isConstFalse pf then (rel_fml, CP.mkFalse no_pos)
else (
let (name,vars) = match rel_fml with
| CP.BForm ((CP.RelForm (name,args,_),_),_) -> (CP.name_of_spec_var name, (List.concat (List.map CP.afv args)))
| _ -> report_error no_pos "Wrong format"
in
let pre_vars, post_vars = List.partition (fun v -> List.mem v ante_vars) vars in
try
let rhs = fixbag_of_pure_formula pf in
let no = string_of_int no_of_disjs in
^ (string_of_elems post_vars fixbag_of_spec_var ",") ^ ") := "
^ rhs
in
x_dinfo_pp ">>>>>> compute_fixpoint <<<<<<" no_pos;
x_dinfo_pp ("Input of fixbag: " ^ input_fixbag) no_pos;
let output_of_sleek = " fixbag.inf " in
let oc = open_out output_of_sleek in
let res = syscall (fixbag ^ " \'" ^ input_fixbag ^ "\' \'" ^ no ^ "\'") in
let res = remove_paren res (String.length res) in
x_dinfo_pp ("Result of fixbag: " ^ res) no_pos;
let fixpoint = Parse_fixbag.parse_fix res in
x_dinfo_hp (add_str "Result of fixbag (parsed): " (pr_list !CP.print_formula)) fixpoint no_pos;
match fixpoint with
| [post] -> (rel_fml, simplify_res post)
| _ -> report_error no_pos "Expecting a post"
with _ ->
if not(is_rec pf) then
let () = x_dinfo_hp (add_str "Input: " !CP.print_formula) pf no_pos in
let exists_vars = CP.diff_svl (CP.fv_wo_rel pf) (CP.fv rel_fml) in
let pf = TP.simplify_exists_raw exists_vars pf in
(rel_fml, remove_subtract pf)
else report_error no_pos "Unexpected error in computing fixpoint by FixBag"
)
let compute_fixpoint input_pairs ante_vars is_rec =
let (pfs, rels) = List.split input_pairs in
let rels = Gen.BList.remove_dups_eq CP.equalFormula rels in
let pairs = match rels with
| [] -> report_error no_pos "Error in compute_fixpoint"
let , no = in
let = List.map ( fun p - >
let exists_node_vars = ( CP.fv p ) in
let in
let exists_vars = CP.diff_svl ( List.filter
( fun x - > not(CP.is_bag_typ x ) ) ( CP.fv p ) ) ( CP.fv hd ) in
CP.mkExists exists_vars p None no_pos ) pfs in
let pf = List.fold_left ( fun p1 p2 - > CP.mkOr p1 p2 None no_pos ) ( CP.mkFalse no_pos ) pfs in [ ( hd , pf , no ) ]
| _ -> List.concat (List.map (fun r -> helper input_pairs r ante_vars) rels)
in
x_tinfo_hp (add_str "input_pairs: " (pr_list (pr_pair !CP.print_formula !CP.print_formula))) input_pairs no_pos;
List.map (fun (rel_fml,pf,no) -> compute_fixpoint_aux rel_fml pf no ante_vars is_rec) pairs
call the wrappers for :
1 . trasnform imm formula to imm - free formula and back
2 . disable fixcalc inner imm - free to imm transformation ( eg . calling simpilfy , etc )
1. trasnform imm formula to imm-free formula and back
2. disable fixcalc inner imm-free to imm transformation (eg. calling simpilfy, etc) *)
let compute_fixpoint input_pairs ante_vars is_rec =
let fixpt input_pairs = compute_fixpoint input_pairs ante_vars is_rec in
let pre = List.map (fold_pair1f (x_add_1 Immutable.map_imm_to_int_pure_formula)) in
let post = List.map (fold_pair1f (x_add_1 Immutable.map_int_to_imm_pure_formula)) in
let fixpt input_pairs = Wrapper.wrap_pre_post_process pre post fixpt input_pairs in
Wrapper.wrap_one_bool Globals.int2imm_conv false fixpt input_pairs
let compute_fixpoint (i:int) input_pairs pre_vars is_rec =
let pr0 = !CP.print_formula in
let pr1 = pr_list (pr_pair pr0 pr0) in
let pr2 = !CP.print_svl in
Debug.no_2_num i "compute_fixpoint" pr1 pr2 (pr_list (pr_pair pr0 pr0))
(fun _ _ -> compute_fixpoint input_pairs pre_vars is_rec) input_pairs pre_vars
|
fd74c7a6234629936cc0ceed3c53c3cb93efe7c29cda9c5a8409d4ffa8850aef | tonyg/kali-scheme | scan-package.scm | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1998 by NEC Research Institute , Inc. See file COPYING .
; Scanning structures and processing package clauses.
; Utility for compile-structures (link/link.scm) and
; ensure-loaded (env/load-package.scm).
;
Returns a list of all packages reachable from STRUCTS that answer true to
; INCLUDE-THIS-PACKAGE?.
(define (collect-packages structs include-this-package?)
(let ((package-seen '())
(structure-seen '())
(packages '()))
(letrec ((recur
(lambda (structure)
(if (not (memq structure structure-seen))
(begin
(set! structure-seen (cons structure structure-seen))
(let ((package (structure-package structure)))
(if (not (memq package package-seen))
(begin
(set! package-seen (cons package package-seen))
(if (include-this-package? package)
(begin
(for-each recur (package-opens package))
(for-each (lambda (name+struct)
(recur (cdr name+struct)))
(package-accesses package))
(set! packages (cons package packages))))))))))))
(for-each recur structs)
(reverse packages))))
; Walk through PACKAGE's clauses to find the source code. The relevent
; clauses are:
; (file name ...)
; (begin form ...)
; (define-all-operators)
; (usual-transforms)
;
; Returns a list of pairs (file . (node1 node2 ...)), a list of names
; of standard transforms, and a boolean value which is true if the package
; is to include definitions of all primitives.
(define (package-source package)
(let* ((config-file (package-file-name package))
(dir (if config-file
(file-name-directory config-file)
#f)))
(fold->3 (lambda (clause stuff transforms primitives?)
(case (car clause)
((files)
(values (read-files (cdr clause) stuff dir package)
transforms
primitives?))
((begin)
(values (cons (cons config-file (cdr clause))
stuff)
transforms
primitives?))
((integrate)
(set-package-integrate?! package
(or (null? (cdr clause))
(cadr clause)))
(values stuff transforms primitives?))
((optimize)
(values stuff transforms primitives?))
((define-all-operators)
(values stuff transforms #t))
((usual-transforms)
(values stuff
(append (cdr clause) transforms)
primitives?))
(else
(error "unrecognized define-structure keyword"
clause))))
(reverse (package-clauses package))
'() '() #f)))
; Also prints out the filenames (courtesy of READ-FORMS).
(define (read-files all-files stuff dir package)
(force-output (current-output-port)) ; just to be nice
(fold (lambda (filespec stuff)
(let ((file (namestring filespec
dir
*scheme-file-type*)))
(display #\space (current-noise-port))
(cons (cons file (read-forms file package))
stuff)))
(reverse all-files)
stuff))
(define (package-optimizer-names package)
(if (package-integrate? package)
(let ((opts (apply append
(map cdr (filter (lambda (clause)
(eq? (car clause) 'optimize))
(package-clauses package))))))
(reduce (lambda (name opts)
(if (memq name opts)
opts
(cons name opts)))
opts
'()))
'()))
(define (check-structure structure)
(let ((undefined '()))
(for-each-export
(lambda (name want-type binding)
(if (binding? binding)
(let ((have-type (binding-type binding)))
(if (not (compatible-types? have-type want-type))
(warn "Type in interface doesn't match binding"
name
`(binding: ,(type->sexp have-type #t))
`(interface: ,(type->sexp want-type #t))
structure)))
(set! undefined (cons name undefined))))
structure)
(if (not (null? undefined))
(warn "Structure has undefined exports"
structure
undefined))))
| null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/bcomp/scan-package.scm | scheme | Scanning structures and processing package clauses.
Utility for compile-structures (link/link.scm) and
ensure-loaded (env/load-package.scm).
INCLUDE-THIS-PACKAGE?.
Walk through PACKAGE's clauses to find the source code. The relevent
clauses are:
(file name ...)
(begin form ...)
(define-all-operators)
(usual-transforms)
Returns a list of pairs (file . (node1 node2 ...)), a list of names
of standard transforms, and a boolean value which is true if the package
is to include definitions of all primitives.
Also prints out the filenames (courtesy of READ-FORMS).
just to be nice | Copyright ( c ) 1993 , 1994 by and .
Copyright ( c ) 1998 by NEC Research Institute , Inc. See file COPYING .
Returns a list of all packages reachable from STRUCTS that answer true to
(define (collect-packages structs include-this-package?)
(let ((package-seen '())
(structure-seen '())
(packages '()))
(letrec ((recur
(lambda (structure)
(if (not (memq structure structure-seen))
(begin
(set! structure-seen (cons structure structure-seen))
(let ((package (structure-package structure)))
(if (not (memq package package-seen))
(begin
(set! package-seen (cons package package-seen))
(if (include-this-package? package)
(begin
(for-each recur (package-opens package))
(for-each (lambda (name+struct)
(recur (cdr name+struct)))
(package-accesses package))
(set! packages (cons package packages))))))))))))
(for-each recur structs)
(reverse packages))))
(define (package-source package)
(let* ((config-file (package-file-name package))
(dir (if config-file
(file-name-directory config-file)
#f)))
(fold->3 (lambda (clause stuff transforms primitives?)
(case (car clause)
((files)
(values (read-files (cdr clause) stuff dir package)
transforms
primitives?))
((begin)
(values (cons (cons config-file (cdr clause))
stuff)
transforms
primitives?))
((integrate)
(set-package-integrate?! package
(or (null? (cdr clause))
(cadr clause)))
(values stuff transforms primitives?))
((optimize)
(values stuff transforms primitives?))
((define-all-operators)
(values stuff transforms #t))
((usual-transforms)
(values stuff
(append (cdr clause) transforms)
primitives?))
(else
(error "unrecognized define-structure keyword"
clause))))
(reverse (package-clauses package))
'() '() #f)))
(define (read-files all-files stuff dir package)
(fold (lambda (filespec stuff)
(let ((file (namestring filespec
dir
*scheme-file-type*)))
(display #\space (current-noise-port))
(cons (cons file (read-forms file package))
stuff)))
(reverse all-files)
stuff))
(define (package-optimizer-names package)
(if (package-integrate? package)
(let ((opts (apply append
(map cdr (filter (lambda (clause)
(eq? (car clause) 'optimize))
(package-clauses package))))))
(reduce (lambda (name opts)
(if (memq name opts)
opts
(cons name opts)))
opts
'()))
'()))
(define (check-structure structure)
(let ((undefined '()))
(for-each-export
(lambda (name want-type binding)
(if (binding? binding)
(let ((have-type (binding-type binding)))
(if (not (compatible-types? have-type want-type))
(warn "Type in interface doesn't match binding"
name
`(binding: ,(type->sexp have-type #t))
`(interface: ,(type->sexp want-type #t))
structure)))
(set! undefined (cons name undefined))))
structure)
(if (not (null? undefined))
(warn "Structure has undefined exports"
structure
undefined))))
|
5a2a333fea9d10199665b42337951f305e47b08bf2692f34388b78a26641f2dd | modular-macros/ocaml-macros | expect_test.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, Jane Street Europe
(* *)
Copyright 2016 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
Execute a list of phrase from a .ml file and compare the result to the
expected output , written inside [ % % expect ... ] nodes . At the end , create
a .corrected file containing the corrected expectations . The test is
successul if there is no differences between the two files .
An [ % % expect ] node always contains both the expected outcome with and
without -principal . When the two differ the expection is written as follow :
{ [
[ % % expect { |
output without -principal
| } , Principal{|
output with -principal
| } ]
] }
expected output, written inside [%%expect ...] nodes. At the end, create
a .corrected file containing the corrected expectations. The test is
successul if there is no differences between the two files.
An [%%expect] node always contains both the expected outcome with and
without -principal. When the two differ the expection is written as follow:
{[
[%%expect {|
output without -principal
|}, Principal{|
output with -principal
|}]
]}
*)
[@@@ocaml.warning "-40"]
open StdLabels
(* representation of: {tag|str|tag} *)
type string_constant =
{ str : string
; tag : string
}
type expectation =
{ extid_loc : Location.t (* Location of "expect" in "[%%expect ...]" *)
; payload_loc : Location.t (* Location of the whole payload *)
; normal : string_constant (* expectation without -principal *)
; principal : string_constant (* expectation with -principal *)
}
(* A list of phrases with the expected toplevel output *)
type chunk =
{ phrases : Parsetree.toplevel_phrase list
; expectation : expectation
}
type correction =
{ corrected_expectations : expectation list
; trailing_output : string
}
let match_expect_extension (ext : Parsetree.extension) =
match ext with
| ({Asttypes.txt="expect"|"ocaml.expect"; loc = extid_loc}, payload) ->
let invalid_payload () =
Location.raise_errorf ~loc:extid_loc
"invalid [%%%%expect payload]"
in
let string_constant (e : Parsetree.expression) =
match e.pexp_desc with
| Pexp_constant (Pconst_string (str, Some tag)) ->
{ str; tag }
| _ -> invalid_payload ()
in
let expectation =
match payload with
| PStr [{ pstr_desc = Pstr_eval (e, []) }] ->
let normal, principal =
match e.pexp_desc with
| Pexp_tuple
[ a
; { pexp_desc = Pexp_construct
({ txt = Lident "Principal"; _ }, Some b) }
] ->
(string_constant a, string_constant b)
| _ -> let s = string_constant e in (s, s)
in
{ extid_loc
; payload_loc = e.pexp_loc
; normal
; principal
}
| PStr [] ->
let s = { tag = ""; str = "" } in
{ extid_loc
; payload_loc = { extid_loc with loc_start = extid_loc.loc_end }
; normal = s
; principal = s
}
| _ -> invalid_payload ()
in
Some expectation
| _ ->
None
Split a list of phrases from a .ml file
let split_chunks phrases =
let rec loop (phrases : Parsetree.toplevel_phrase list) code_acc acc =
match phrases with
| [] ->
if code_acc = [] then
(List.rev acc, None)
else
(List.rev acc, Some (List.rev code_acc))
| phrase :: phrases ->
match phrase with
| Ptop_def [] -> loop phrases code_acc acc
| Ptop_def [{pstr_desc = Pstr_extension(ext, [])}] -> begin
match match_expect_extension ext with
| None -> loop phrases (phrase :: code_acc) acc
| Some expectation ->
let chunk =
{ phrases = List.rev code_acc
; expectation
}
in
loop phrases [] (chunk :: acc)
end
| _ -> loop phrases (phrase :: code_acc) acc
in
loop phrases [] []
module Compiler_messages = struct
let print_loc ppf (loc : Location.t) =
let startchar = loc.loc_start.pos_cnum - loc.loc_start.pos_bol in
let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in
Format.fprintf ppf "Line _";
if startchar >= 0 then
Format.fprintf ppf ", characters %d-%d" startchar endchar;
Format.fprintf ppf ":@."
let rec error_reporter ppf ({loc; msg; sub; if_highlight=_} : Location.error)=
print_loc ppf loc;
Format.fprintf ppf "%a %s" Location.print_error_prefix () msg;
List.iter sub ~f:(fun err ->
Format.fprintf ppf "@\n@[<2>%a@]" error_reporter err)
let warning_printer loc ppf w =
if Warnings.is_active w then begin
print_loc ppf loc;
Format.fprintf ppf "Warning %a@." Warnings.print w
end
let capture ppf ~f =
Misc.protect_refs
[ R (Location.formatter_for_warnings , ppf )
; R (Location.warning_printer , warning_printer)
; R (Location.error_reporter , error_reporter )
]
f
end
let collect_formatters buf pps ~f =
List.iter (fun pp -> Format.pp_print_flush pp ()) pps;
let save =
List.map (fun pp -> Format.pp_get_formatter_out_functions pp ()) pps
in
let restore () =
List.iter2
(fun pp out_functions ->
Format.pp_print_flush pp ();
Format.pp_set_formatter_out_functions pp out_functions)
pps save
in
let out_string str ofs len = Buffer.add_substring buf str ofs len
and out_flush = ignore
and out_newline () = Buffer.add_char buf '\n'
and out_spaces n = for i = 1 to n do Buffer.add_char buf ' ' done in
let out_functions =
{ Format.out_string; out_flush; out_newline; out_spaces }
in
List.iter
(fun pp -> Format.pp_set_formatter_out_functions pp out_functions)
pps;
match f () with
| x -> restore (); x
| exception exn -> restore (); raise exn
Invariant : ppf = Format.formatter_of_buffer buf
let capture_everything buf ppf ~f =
collect_formatters buf [Format.std_formatter; Format.err_formatter]
~f:(fun () -> Compiler_messages.capture ppf ~f)
let exec_phrase ppf phrase =
if !Clflags.dump_parsetree then Printast. top_phrase ppf phrase;
if !Clflags.dump_source then Pprintast.top_phrase ppf phrase;
Toploop.execute_phrase true ppf phrase
let parse_contents ~fname contents =
let lexbuf = Lexing.from_string contents in
Location.init lexbuf fname;
Location.input_name := fname;
Parse.use_file lexbuf
let eval_expectation expectation ~output =
let s =
if !Clflags.principal then
expectation.principal
else
expectation.normal
in
if s.str = output then
None
else
let s = { s with str = output } in
Some (
if !Clflags.principal then
{ expectation with principal = s }
else
{ expectation with normal = s }
)
let shift_lines delta phrases =
let position (pos : Lexing.position) =
{ pos with pos_lnum = pos.pos_lnum + delta }
in
let location _this (loc : Location.t) =
{ loc with
loc_start = position loc.loc_start
; loc_end = position loc.loc_end
}
in
let mapper = { Ast_mapper.default_mapper with location } in
List.map phrases ~f:(function
| Parsetree.Ptop_dir _ as p -> p
| Parsetree.Ptop_def st ->
Parsetree.Ptop_def (mapper.structure mapper st))
let rec min_line_number : Parsetree.toplevel_phrase list -> int option =
function
| [] -> None
| (Ptop_dir _ | Ptop_def []) :: l -> min_line_number l
| Ptop_def (st :: _) :: _ -> Some st.pstr_loc.loc_start.pos_lnum
let eval_expect_file _fname ~file_contents =
Warnings.reset_fatal ();
let chunks, trailing_code =
parse_contents ~fname:"" file_contents |> split_chunks
in
let buf = Buffer.create 1024 in
let ppf = Format.formatter_of_buffer buf in
let exec_phrases phrases =
let phrases =
match min_line_number phrases with
| None -> phrases
| Some lnum -> shift_lines (1 - lnum) phrases
in
(* For formatting purposes *)
Buffer.add_char buf '\n';
let _ : bool =
List.fold_left phrases ~init:true ~f:(fun acc phrase ->
acc &&
try
exec_phrase ppf phrase
with exn ->
Location.report_exception ppf exn;
false)
in
Format.pp_print_flush ppf ();
let len = Buffer.length buf in
if len > 0 && Buffer.nth buf (len - 1) <> '\n' then
(* For formatting purposes *)
Buffer.add_char buf '\n';
let s = Buffer.contents buf in
Buffer.clear buf;
Misc.delete_eol_spaces s
in
let corrected_expectations =
capture_everything buf ppf ~f:(fun () ->
List.fold_left chunks ~init:[] ~f:(fun acc chunk ->
let output = exec_phrases chunk.phrases in
match eval_expectation chunk.expectation ~output with
| None -> acc
| Some correction -> correction :: acc)
|> List.rev)
in
let trailing_output =
match trailing_code with
| None -> ""
| Some phrases ->
capture_everything buf ppf ~f:(fun () -> exec_phrases phrases)
in
{ corrected_expectations; trailing_output }
let output_slice oc s a b =
output_string oc (String.sub s ~pos:a ~len:(b - a))
let output_corrected oc ~file_contents correction =
let output_body oc { str; tag } =
Printf.fprintf oc "{%s|%s|%s}" tag str tag
in
let ofs =
List.fold_left correction.corrected_expectations ~init:0
~f:(fun ofs c ->
output_slice oc file_contents ofs c.payload_loc.loc_start.pos_cnum;
output_body oc c.normal;
if c.normal.str <> c.principal.str then begin
output_string oc ", Principal";
output_body oc c.principal
end;
c.payload_loc.loc_end.pos_cnum)
in
output_slice oc file_contents ofs (String.length file_contents);
match correction.trailing_output with
| "" -> ()
| s -> Printf.fprintf oc "\n[%%%%expect{|%s|}]\n" s
let write_corrected ~file ~file_contents correction =
let oc = open_out_bin file in
output_corrected oc ~file_contents correction;
close_out oc
let process_expect_file fname =
let corrected_fname = fname ^ ".corrected" in
let file_contents =
let ic = open_in_bin fname in
match really_input_string ic (in_channel_length ic) with
| s -> close_in ic; s
| exception e -> close_in ic; raise e
in
let correction = eval_expect_file fname ~file_contents in
write_corrected ~file:corrected_fname ~file_contents correction
let repo_root = ref ""
let main fname =
Toploop.override_sys_argv
(Array.sub Sys.argv ~pos:!Arg.current
~len:(Array.length Sys.argv - !Arg.current));
Ignore = b to be reproducible
Printexc.record_backtrace false;
List.iter [ "stdlib" ] ~f:(fun s ->
Topdirs.dir_directory (Filename.concat !repo_root s));
Toploop.initialize_toplevel_env ();
Sys.interactive := false;
process_expect_file fname;
exit 0
let args =
Arg.align
[ "-repo-root", Set_string repo_root,
"<dir> root of the OCaml repository"
; "-principal", Set Clflags.principal,
" Evaluate the file with -principal set"
]
let usage = "Usage: expect_test <options> [script-file [arguments]]\n\
options are:"
let () =
Clflags.error_size := 0;
try
Arg.parse args main usage;
Printf.eprintf "expect_test: no input file\n";
exit 2
with exn ->
Location.report_exception Format.err_formatter exn;
exit 2
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tools/expect_test.ml | ocaml | ************************************************************************
OCaml
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
representation of: {tag|str|tag}
Location of "expect" in "[%%expect ...]"
Location of the whole payload
expectation without -principal
expectation with -principal
A list of phrases with the expected toplevel output
For formatting purposes
For formatting purposes | , Jane Street Europe
Copyright 2016 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
Execute a list of phrase from a .ml file and compare the result to the
expected output , written inside [ % % expect ... ] nodes . At the end , create
a .corrected file containing the corrected expectations . The test is
successul if there is no differences between the two files .
An [ % % expect ] node always contains both the expected outcome with and
without -principal . When the two differ the expection is written as follow :
{ [
[ % % expect { |
output without -principal
| } , Principal{|
output with -principal
| } ]
] }
expected output, written inside [%%expect ...] nodes. At the end, create
a .corrected file containing the corrected expectations. The test is
successul if there is no differences between the two files.
An [%%expect] node always contains both the expected outcome with and
without -principal. When the two differ the expection is written as follow:
{[
[%%expect {|
output without -principal
|}, Principal{|
output with -principal
|}]
]}
*)
[@@@ocaml.warning "-40"]
open StdLabels
type string_constant =
{ str : string
; tag : string
}
type expectation =
}
type chunk =
{ phrases : Parsetree.toplevel_phrase list
; expectation : expectation
}
type correction =
{ corrected_expectations : expectation list
; trailing_output : string
}
let match_expect_extension (ext : Parsetree.extension) =
match ext with
| ({Asttypes.txt="expect"|"ocaml.expect"; loc = extid_loc}, payload) ->
let invalid_payload () =
Location.raise_errorf ~loc:extid_loc
"invalid [%%%%expect payload]"
in
let string_constant (e : Parsetree.expression) =
match e.pexp_desc with
| Pexp_constant (Pconst_string (str, Some tag)) ->
{ str; tag }
| _ -> invalid_payload ()
in
let expectation =
match payload with
| PStr [{ pstr_desc = Pstr_eval (e, []) }] ->
let normal, principal =
match e.pexp_desc with
| Pexp_tuple
[ a
; { pexp_desc = Pexp_construct
({ txt = Lident "Principal"; _ }, Some b) }
] ->
(string_constant a, string_constant b)
| _ -> let s = string_constant e in (s, s)
in
{ extid_loc
; payload_loc = e.pexp_loc
; normal
; principal
}
| PStr [] ->
let s = { tag = ""; str = "" } in
{ extid_loc
; payload_loc = { extid_loc with loc_start = extid_loc.loc_end }
; normal = s
; principal = s
}
| _ -> invalid_payload ()
in
Some expectation
| _ ->
None
Split a list of phrases from a .ml file
let split_chunks phrases =
let rec loop (phrases : Parsetree.toplevel_phrase list) code_acc acc =
match phrases with
| [] ->
if code_acc = [] then
(List.rev acc, None)
else
(List.rev acc, Some (List.rev code_acc))
| phrase :: phrases ->
match phrase with
| Ptop_def [] -> loop phrases code_acc acc
| Ptop_def [{pstr_desc = Pstr_extension(ext, [])}] -> begin
match match_expect_extension ext with
| None -> loop phrases (phrase :: code_acc) acc
| Some expectation ->
let chunk =
{ phrases = List.rev code_acc
; expectation
}
in
loop phrases [] (chunk :: acc)
end
| _ -> loop phrases (phrase :: code_acc) acc
in
loop phrases [] []
module Compiler_messages = struct
let print_loc ppf (loc : Location.t) =
let startchar = loc.loc_start.pos_cnum - loc.loc_start.pos_bol in
let endchar = loc.loc_end.pos_cnum - loc.loc_start.pos_cnum + startchar in
Format.fprintf ppf "Line _";
if startchar >= 0 then
Format.fprintf ppf ", characters %d-%d" startchar endchar;
Format.fprintf ppf ":@."
let rec error_reporter ppf ({loc; msg; sub; if_highlight=_} : Location.error)=
print_loc ppf loc;
Format.fprintf ppf "%a %s" Location.print_error_prefix () msg;
List.iter sub ~f:(fun err ->
Format.fprintf ppf "@\n@[<2>%a@]" error_reporter err)
let warning_printer loc ppf w =
if Warnings.is_active w then begin
print_loc ppf loc;
Format.fprintf ppf "Warning %a@." Warnings.print w
end
let capture ppf ~f =
Misc.protect_refs
[ R (Location.formatter_for_warnings , ppf )
; R (Location.warning_printer , warning_printer)
; R (Location.error_reporter , error_reporter )
]
f
end
let collect_formatters buf pps ~f =
List.iter (fun pp -> Format.pp_print_flush pp ()) pps;
let save =
List.map (fun pp -> Format.pp_get_formatter_out_functions pp ()) pps
in
let restore () =
List.iter2
(fun pp out_functions ->
Format.pp_print_flush pp ();
Format.pp_set_formatter_out_functions pp out_functions)
pps save
in
let out_string str ofs len = Buffer.add_substring buf str ofs len
and out_flush = ignore
and out_newline () = Buffer.add_char buf '\n'
and out_spaces n = for i = 1 to n do Buffer.add_char buf ' ' done in
let out_functions =
{ Format.out_string; out_flush; out_newline; out_spaces }
in
List.iter
(fun pp -> Format.pp_set_formatter_out_functions pp out_functions)
pps;
match f () with
| x -> restore (); x
| exception exn -> restore (); raise exn
Invariant : ppf = Format.formatter_of_buffer buf
let capture_everything buf ppf ~f =
collect_formatters buf [Format.std_formatter; Format.err_formatter]
~f:(fun () -> Compiler_messages.capture ppf ~f)
let exec_phrase ppf phrase =
if !Clflags.dump_parsetree then Printast. top_phrase ppf phrase;
if !Clflags.dump_source then Pprintast.top_phrase ppf phrase;
Toploop.execute_phrase true ppf phrase
let parse_contents ~fname contents =
let lexbuf = Lexing.from_string contents in
Location.init lexbuf fname;
Location.input_name := fname;
Parse.use_file lexbuf
let eval_expectation expectation ~output =
let s =
if !Clflags.principal then
expectation.principal
else
expectation.normal
in
if s.str = output then
None
else
let s = { s with str = output } in
Some (
if !Clflags.principal then
{ expectation with principal = s }
else
{ expectation with normal = s }
)
let shift_lines delta phrases =
let position (pos : Lexing.position) =
{ pos with pos_lnum = pos.pos_lnum + delta }
in
let location _this (loc : Location.t) =
{ loc with
loc_start = position loc.loc_start
; loc_end = position loc.loc_end
}
in
let mapper = { Ast_mapper.default_mapper with location } in
List.map phrases ~f:(function
| Parsetree.Ptop_dir _ as p -> p
| Parsetree.Ptop_def st ->
Parsetree.Ptop_def (mapper.structure mapper st))
let rec min_line_number : Parsetree.toplevel_phrase list -> int option =
function
| [] -> None
| (Ptop_dir _ | Ptop_def []) :: l -> min_line_number l
| Ptop_def (st :: _) :: _ -> Some st.pstr_loc.loc_start.pos_lnum
let eval_expect_file _fname ~file_contents =
Warnings.reset_fatal ();
let chunks, trailing_code =
parse_contents ~fname:"" file_contents |> split_chunks
in
let buf = Buffer.create 1024 in
let ppf = Format.formatter_of_buffer buf in
let exec_phrases phrases =
let phrases =
match min_line_number phrases with
| None -> phrases
| Some lnum -> shift_lines (1 - lnum) phrases
in
Buffer.add_char buf '\n';
let _ : bool =
List.fold_left phrases ~init:true ~f:(fun acc phrase ->
acc &&
try
exec_phrase ppf phrase
with exn ->
Location.report_exception ppf exn;
false)
in
Format.pp_print_flush ppf ();
let len = Buffer.length buf in
if len > 0 && Buffer.nth buf (len - 1) <> '\n' then
Buffer.add_char buf '\n';
let s = Buffer.contents buf in
Buffer.clear buf;
Misc.delete_eol_spaces s
in
let corrected_expectations =
capture_everything buf ppf ~f:(fun () ->
List.fold_left chunks ~init:[] ~f:(fun acc chunk ->
let output = exec_phrases chunk.phrases in
match eval_expectation chunk.expectation ~output with
| None -> acc
| Some correction -> correction :: acc)
|> List.rev)
in
let trailing_output =
match trailing_code with
| None -> ""
| Some phrases ->
capture_everything buf ppf ~f:(fun () -> exec_phrases phrases)
in
{ corrected_expectations; trailing_output }
let output_slice oc s a b =
output_string oc (String.sub s ~pos:a ~len:(b - a))
let output_corrected oc ~file_contents correction =
let output_body oc { str; tag } =
Printf.fprintf oc "{%s|%s|%s}" tag str tag
in
let ofs =
List.fold_left correction.corrected_expectations ~init:0
~f:(fun ofs c ->
output_slice oc file_contents ofs c.payload_loc.loc_start.pos_cnum;
output_body oc c.normal;
if c.normal.str <> c.principal.str then begin
output_string oc ", Principal";
output_body oc c.principal
end;
c.payload_loc.loc_end.pos_cnum)
in
output_slice oc file_contents ofs (String.length file_contents);
match correction.trailing_output with
| "" -> ()
| s -> Printf.fprintf oc "\n[%%%%expect{|%s|}]\n" s
let write_corrected ~file ~file_contents correction =
let oc = open_out_bin file in
output_corrected oc ~file_contents correction;
close_out oc
let process_expect_file fname =
let corrected_fname = fname ^ ".corrected" in
let file_contents =
let ic = open_in_bin fname in
match really_input_string ic (in_channel_length ic) with
| s -> close_in ic; s
| exception e -> close_in ic; raise e
in
let correction = eval_expect_file fname ~file_contents in
write_corrected ~file:corrected_fname ~file_contents correction
let repo_root = ref ""
let main fname =
Toploop.override_sys_argv
(Array.sub Sys.argv ~pos:!Arg.current
~len:(Array.length Sys.argv - !Arg.current));
Ignore = b to be reproducible
Printexc.record_backtrace false;
List.iter [ "stdlib" ] ~f:(fun s ->
Topdirs.dir_directory (Filename.concat !repo_root s));
Toploop.initialize_toplevel_env ();
Sys.interactive := false;
process_expect_file fname;
exit 0
let args =
Arg.align
[ "-repo-root", Set_string repo_root,
"<dir> root of the OCaml repository"
; "-principal", Set Clflags.principal,
" Evaluate the file with -principal set"
]
let usage = "Usage: expect_test <options> [script-file [arguments]]\n\
options are:"
let () =
Clflags.error_size := 0;
try
Arg.parse args main usage;
Printf.eprintf "expect_test: no input file\n";
exit 2
with exn ->
Location.report_exception Format.err_formatter exn;
exit 2
|
88d5380f99faf7c7cbe09c500d3dc50507f83677476a395b12bdf171273e903f | rotatef/cl-html5-parser | inputstream.lisp | ;;;; HTML5 parser for Common Lisp
;;;;
Copyright ( C ) 2012 < >
Copyright ( C ) 2012 < >
Copyright ( C ) 2012
Copyright ( C ) 2012 < >
;;;;
;;;; 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 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
You should have received a copy of the GNU General Public License
;;;; along with this library. If not, see </>.
(in-package :html5-parser)
(deftype array-length ()
"Type of an array index."
'(integer 0 #.array-dimension-limit))
(deftype chunk ()
"Type of the input stream buffer."
'(vector character *))
(defparameter *default-encoding* :utf-8)
(defclass html-input-stream ()
((source :initarg :source)
(encoding :reader html5-stream-encoding)
(char-stream :initform nil)
(chunk)
(chunk-offset)
(pending-cr)
(errors :initform nil :accessor html5-stream-errors)))
(defun make-html-input-stream (source &key override-encoding fallback-encoding)
(when (stringp source)
;; Encoding is not relevant when input is a string,
but we set it utf-8 here to avoid auto detecting taking place .
(setf override-encoding :utf-8))
(let ((self (make-instance 'html-input-stream :source source)))
(with-slots (encoding stream) self
(setf encoding (detect-encoding self
(find-encoding override-encoding)
(find-encoding fallback-encoding)))
(open-char-stream self))
self))
12.2.2.2 Character encodings
(defun find-encoding (encoding-name)
;; Normalize the string designator
(setf encoding-name (string-upcase (substitute #\- #\_ (string-trim +space-characters+ (string encoding-name)))))
;; All known encoding will already be interned in the keyword package so find-symbol is fine here
(setf encoding-name (find-symbol encoding-name :keyword))
(handler-case
Verfiy that flexi - streams knows the encoding and resolve aliases
(case (flex:external-format-name (flex:make-external-format encoding-name))
;; Some encoding should be replaced by some other.
;; Only those supported by flexi-streams are listed here.
iso-8859 - 11 should be replaced by windows-874 , but flexi - streams does n't that encoding .
(:iso-8859-1 :windows-1252)
(:iso-8859-9 :windows-1254)
(:us-ascii :windows-1252)
(otherwise encoding-name))
(flex:external-format-error ())))
;; 12.2.2.1 Determining the character encoding
(defun detect-encoding (stream override-encoding fallback-encoding)
(with-slots (encoding) stream
(block nil
1 . and 2 . encoding overridden by user or transport layer
(when override-encoding
(return (cons override-encoding :certain)))
3 . wait for 1024 bytes , not implemented
4 . Detect BOM
(let ((bom-encoding (detect-bom stream)))
(when bom-encoding
(return (cons bom-encoding :certain))))
5 . Prescan not implemented
6 . Use fallback encoding
(when fallback-encoding
(return (cons encoding :tentative)))
7 . Autodect not implemented
8 . Implementation - defined default
(return (cons *default-encoding* :tentative)))))
(defmacro handle-encoding-errors (stream &body body)
`(handler-bind ((flex:external-format-encoding-error
(lambda (x)
(declare (ignore x))
(push :invalid-codepoint (html5-stream-errors ,stream))
(use-value #\uFFFD))))
,@body))
(defun open-char-stream (self)
(with-slots (source encoding char-stream chunk chunk-offset pending-cr) self
(setf chunk (make-array (* 10 1024) :element-type 'character :fill-pointer 0))
(setf chunk-offset 0)
(setf pending-cr nil)
(when char-stream
(close char-stream))
(setf char-stream
(if (stringp source)
(make-string-input-stream source)
(flex:make-flexi-stream
(etypecase source
(pathname
(open source :element-type '(unsigned-byte 8)))
(stream
source)
(vector
(flex:make-in-memory-input-stream source)))
:external-format (flex:make-external-format (car encoding) :eol-style :lf))))
12.2.2.4 says we should always skip the first byte order mark
(handle-encoding-errors self
(let ((first-char (peek-char nil char-stream nil)))
(when (eql first-char #\ufeff)
(read-char char-stream))))))
(defun detect-bom (self)
(with-slots (source) self
(let (byte-0 byte-1 byte-2)
(etypecase source
(vector
(when (> (length source) 0) (setf byte-0 (aref source 0)))
(when (> (length source) 1) (setf byte-1 (aref source 1)))
(when (> (length source) 2) (setf byte-2 (aref source 2))))
(pathname
(with-open-file (in source :element-type '(unsigned-byte 8))
(setf byte-0 (read-byte in nil))
(setf byte-1 (read-byte in nil))
(setf byte-2 (read-byte in nil))))
(stream
(error "Can't detect encoding when source is a stream.")))
(cond ((and (eql byte-0 #xfe)
(eql byte-1 #xff))
:utf-16be)
((and (eql byte-0 #xff)
(eql byte-1 #xfe))
:utf-16le)
((and (eql byte-0 #xef)
(eql byte-1 #xbb)
(eql byte-2 #xbf))
:utf-8)))))
;; 12.2.2.3 Changing the encoding while parsing
(defun html5-stream-change-encoding (stream new-encoding)
(setf new-encoding (find-encoding new-encoding))
(with-slots (encoding char-stream) stream
1 .
(when (member (car encoding) '(:utf-16le :utf-16be))
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
2 .
(when (member new-encoding '(:utf-16le :utf-16be))
(setf new-encoding :utf-8))
3 .
(when (eql (car encoding) new-encoding)
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
4 . Not impleneted
5 . Restart paring from scratch
(setf encoding (cons new-encoding :certain))
(open-char-stream stream)
(throw 'please-reparse t)))
(defun html5-stream-char (stream)
(with-slots (chunk chunk-offset) stream
(when (>= chunk-offset (length chunk))
(unless (read-chunk stream)
(return-from html5-stream-char +eof+)))
(prog1 (char chunk chunk-offset)
(incf chunk-offset))))
(defun our-scan (chars opposite-p chunk &key start)
(loop for i from start below (length chunk)
for char = (char chunk i)
while (if opposite-p
(position char chars)
(not (position char chars)))
finally (return i)))
(defun html5-stream-chars-until (stream characters &optional opposite-p)
"Returns a string of characters from the stream up to but not
including any character in characters or end of file.
"
(with-slots (chunk chunk-offset) stream
(declare (array-length chunk-offset) (chunk chunk))
(with-output-to-string (data)
(loop for end = (our-scan characters opposite-p chunk :start chunk-offset) do
;; If nothing matched, and it wasn't because we ran out of chunk,
;; then stop
(when (and (not end)
(/= chunk-offset (length chunk)))
(return))
;; If not the whole chunk matched, return everything
;; up to the part that didn't match
(when (and end
(/= chunk-offset (length chunk)))
(write-string chunk data :start chunk-offset :end end)
(setf chunk-offset end)
(return))
;; If the whole remainder of the chunk matched,
;; use it all and read the next chunk
(write-string chunk data :start chunk-offset)
(unless (read-chunk stream)
(return))))))
(defun html5-stream-unget (stream char)
(with-slots (chunk chunk-offset) stream
(unless (eql char +eof+)
(cond ((zerop chunk-offset)
(cond ((< (fill-pointer chunk) (array-dimension chunk 0))
(incf (fill-pointer chunk))
(replace chunk chunk :start1 1))
(t
(let ((new-chunk (make-array (1+ (array-dimension chunk 0))
:element-type 'character
:fill-pointer (1+ (fill-pointer chunk)))))
(replace new-chunk chunk :start1 1)
(setf chunk new-chunk))))
(setf (char chunk 0) char))
(t
(decf chunk-offset)
(assert (char= char (char chunk chunk-offset))))))))
(defun read-chunk (stream)
(declare (optimize speed))
(with-slots (char-stream chunk chunk-offset pending-cr) stream
(declare (array-length chunk-offset)
(chunk chunk))
(setf chunk-offset 0)
(let ((start 0))
(when pending-cr
(setf (char chunk 0) #\Return)
(setf start 1)
(setf pending-cr nil))
(setf (fill-pointer chunk) (array-dimension chunk 0))
(handle-encoding-errors stream
(setf (fill-pointer chunk) (read-sequence chunk char-stream :start start)))
(unless (zerop (length chunk))
check if last char is CR and EOF was not reached
(when (and (= (length chunk) (array-dimension chunk 0))
(eql (char chunk (1- (length chunk))) #\Return))
(setf pending-cr t)
(decf (fill-pointer chunk)))
(report-character-errors stream chunk)
Python code replaces surrugate pairs with U+FFFD here . Why ?
;; Normalize line endings (CR LF)
(loop for previous = nil then current
for current across chunk
for index of-type array-length from 0
with offset of-type array-length = 0
do (unless (and (eql previous #\Return)
(eql current #\Newline))
(unless (= index offset)
(setf (char chunk offset) current))
(when (eql current #\Return)
(setf (char chunk offset) #\Newline))
(incf offset))
finally (setf (fill-pointer chunk) offset))
t))))
(defun char-range (char1 char2)
(loop for i from (char-code char1) to (char-code char2)
collect (code-char i)))
(defparameter *invalid-unicode*
`(,@(char-range #\u0001 #\u0008)
#\u000B
,@(char-range #\u000E #\u001F)
,@(char-range #\u007F #\u009F)
The following are noncharacter as defined by Unicode .
;; Clozure Common Lisp doesn't like them.
#-(or abcl ccl mezzano) ,@`(
,@(char-range #\uD800 #\uDFFF)
,@(char-range #\uFDD0 #\uFDEF)
#\uFFFE
#\uFFFF
#\u0001FFFE
#\u0001FFFF
#\u0002FFFE
#\u0002FFFF
#\u0003FFFE
#\u0003FFFF
#\u0004FFFE
#\u0004FFFF
#\u0005FFFE
#\u0005FFFF
#\u0006FFFE
#\u0006FFFF
#\u0007FFFE
#\u0007FFFF
#\u0008FFFE
#\u0008FFFF
#\u0009FFFE
#\u0009FFFF
#\u000AFFFE
#\u000AFFFF
#\u000BFFFE
#\u000BFFFF
#\u000CFFFE
#\u000CFFFF
#\u000DFFFE
#\u000DFFFF
#\u000EFFFE
#\u000EFFFF
#\u000FFFFE
#\u000FFFFF
#\u0010FFFE
#\u0010FFFF)))
(defparameter *invalid-unicode-hash* (make-hash-table))
(dolist (char *invalid-unicode*)
(setf (gethash char *invalid-unicode-hash*) char))
(defun report-character-errors (stream data)
(loop for char across data
when (gethash char *invalid-unicode-hash*)
do (push :invalid-codepoint (html5-stream-errors stream))))
| null | https://raw.githubusercontent.com/rotatef/cl-html5-parser/74a92eb3a183a0afd089ea33350e816e6b9aeefa/inputstream.lisp | lisp | HTML5 parser for Common Lisp
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
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this library. If not, see </>.
Encoding is not relevant when input is a string,
Normalize the string designator
All known encoding will already be interned in the keyword package so find-symbol is fine here
Some encoding should be replaced by some other.
Only those supported by flexi-streams are listed here.
12.2.2.1 Determining the character encoding
12.2.2.3 Changing the encoding while parsing
If nothing matched, and it wasn't because we ran out of chunk,
then stop
If not the whole chunk matched, return everything
up to the part that didn't match
If the whole remainder of the chunk matched,
use it all and read the next chunk
Normalize line endings (CR LF)
Clozure Common Lisp doesn't like them. | Copyright ( C ) 2012 < >
Copyright ( C ) 2012 < >
Copyright ( C ) 2012
Copyright ( C ) 2012 < >
by the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :html5-parser)
(deftype array-length ()
"Type of an array index."
'(integer 0 #.array-dimension-limit))
(deftype chunk ()
"Type of the input stream buffer."
'(vector character *))
(defparameter *default-encoding* :utf-8)
(defclass html-input-stream ()
((source :initarg :source)
(encoding :reader html5-stream-encoding)
(char-stream :initform nil)
(chunk)
(chunk-offset)
(pending-cr)
(errors :initform nil :accessor html5-stream-errors)))
(defun make-html-input-stream (source &key override-encoding fallback-encoding)
(when (stringp source)
but we set it utf-8 here to avoid auto detecting taking place .
(setf override-encoding :utf-8))
(let ((self (make-instance 'html-input-stream :source source)))
(with-slots (encoding stream) self
(setf encoding (detect-encoding self
(find-encoding override-encoding)
(find-encoding fallback-encoding)))
(open-char-stream self))
self))
12.2.2.2 Character encodings
(defun find-encoding (encoding-name)
(setf encoding-name (string-upcase (substitute #\- #\_ (string-trim +space-characters+ (string encoding-name)))))
(setf encoding-name (find-symbol encoding-name :keyword))
(handler-case
Verfiy that flexi - streams knows the encoding and resolve aliases
(case (flex:external-format-name (flex:make-external-format encoding-name))
iso-8859 - 11 should be replaced by windows-874 , but flexi - streams does n't that encoding .
(:iso-8859-1 :windows-1252)
(:iso-8859-9 :windows-1254)
(:us-ascii :windows-1252)
(otherwise encoding-name))
(flex:external-format-error ())))
(defun detect-encoding (stream override-encoding fallback-encoding)
(with-slots (encoding) stream
(block nil
1 . and 2 . encoding overridden by user or transport layer
(when override-encoding
(return (cons override-encoding :certain)))
3 . wait for 1024 bytes , not implemented
4 . Detect BOM
(let ((bom-encoding (detect-bom stream)))
(when bom-encoding
(return (cons bom-encoding :certain))))
5 . Prescan not implemented
6 . Use fallback encoding
(when fallback-encoding
(return (cons encoding :tentative)))
7 . Autodect not implemented
8 . Implementation - defined default
(return (cons *default-encoding* :tentative)))))
(defmacro handle-encoding-errors (stream &body body)
`(handler-bind ((flex:external-format-encoding-error
(lambda (x)
(declare (ignore x))
(push :invalid-codepoint (html5-stream-errors ,stream))
(use-value #\uFFFD))))
,@body))
(defun open-char-stream (self)
(with-slots (source encoding char-stream chunk chunk-offset pending-cr) self
(setf chunk (make-array (* 10 1024) :element-type 'character :fill-pointer 0))
(setf chunk-offset 0)
(setf pending-cr nil)
(when char-stream
(close char-stream))
(setf char-stream
(if (stringp source)
(make-string-input-stream source)
(flex:make-flexi-stream
(etypecase source
(pathname
(open source :element-type '(unsigned-byte 8)))
(stream
source)
(vector
(flex:make-in-memory-input-stream source)))
:external-format (flex:make-external-format (car encoding) :eol-style :lf))))
12.2.2.4 says we should always skip the first byte order mark
(handle-encoding-errors self
(let ((first-char (peek-char nil char-stream nil)))
(when (eql first-char #\ufeff)
(read-char char-stream))))))
(defun detect-bom (self)
(with-slots (source) self
(let (byte-0 byte-1 byte-2)
(etypecase source
(vector
(when (> (length source) 0) (setf byte-0 (aref source 0)))
(when (> (length source) 1) (setf byte-1 (aref source 1)))
(when (> (length source) 2) (setf byte-2 (aref source 2))))
(pathname
(with-open-file (in source :element-type '(unsigned-byte 8))
(setf byte-0 (read-byte in nil))
(setf byte-1 (read-byte in nil))
(setf byte-2 (read-byte in nil))))
(stream
(error "Can't detect encoding when source is a stream.")))
(cond ((and (eql byte-0 #xfe)
(eql byte-1 #xff))
:utf-16be)
((and (eql byte-0 #xff)
(eql byte-1 #xfe))
:utf-16le)
((and (eql byte-0 #xef)
(eql byte-1 #xbb)
(eql byte-2 #xbf))
:utf-8)))))
(defun html5-stream-change-encoding (stream new-encoding)
(setf new-encoding (find-encoding new-encoding))
(with-slots (encoding char-stream) stream
1 .
(when (member (car encoding) '(:utf-16le :utf-16be))
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
2 .
(when (member new-encoding '(:utf-16le :utf-16be))
(setf new-encoding :utf-8))
3 .
(when (eql (car encoding) new-encoding)
(setf encoding (cons (car encoding) :certain))
(return-from html5-stream-change-encoding))
4 . Not impleneted
5 . Restart paring from scratch
(setf encoding (cons new-encoding :certain))
(open-char-stream stream)
(throw 'please-reparse t)))
(defun html5-stream-char (stream)
(with-slots (chunk chunk-offset) stream
(when (>= chunk-offset (length chunk))
(unless (read-chunk stream)
(return-from html5-stream-char +eof+)))
(prog1 (char chunk chunk-offset)
(incf chunk-offset))))
(defun our-scan (chars opposite-p chunk &key start)
(loop for i from start below (length chunk)
for char = (char chunk i)
while (if opposite-p
(position char chars)
(not (position char chars)))
finally (return i)))
(defun html5-stream-chars-until (stream characters &optional opposite-p)
"Returns a string of characters from the stream up to but not
including any character in characters or end of file.
"
(with-slots (chunk chunk-offset) stream
(declare (array-length chunk-offset) (chunk chunk))
(with-output-to-string (data)
(loop for end = (our-scan characters opposite-p chunk :start chunk-offset) do
(when (and (not end)
(/= chunk-offset (length chunk)))
(return))
(when (and end
(/= chunk-offset (length chunk)))
(write-string chunk data :start chunk-offset :end end)
(setf chunk-offset end)
(return))
(write-string chunk data :start chunk-offset)
(unless (read-chunk stream)
(return))))))
(defun html5-stream-unget (stream char)
(with-slots (chunk chunk-offset) stream
(unless (eql char +eof+)
(cond ((zerop chunk-offset)
(cond ((< (fill-pointer chunk) (array-dimension chunk 0))
(incf (fill-pointer chunk))
(replace chunk chunk :start1 1))
(t
(let ((new-chunk (make-array (1+ (array-dimension chunk 0))
:element-type 'character
:fill-pointer (1+ (fill-pointer chunk)))))
(replace new-chunk chunk :start1 1)
(setf chunk new-chunk))))
(setf (char chunk 0) char))
(t
(decf chunk-offset)
(assert (char= char (char chunk chunk-offset))))))))
(defun read-chunk (stream)
(declare (optimize speed))
(with-slots (char-stream chunk chunk-offset pending-cr) stream
(declare (array-length chunk-offset)
(chunk chunk))
(setf chunk-offset 0)
(let ((start 0))
(when pending-cr
(setf (char chunk 0) #\Return)
(setf start 1)
(setf pending-cr nil))
(setf (fill-pointer chunk) (array-dimension chunk 0))
(handle-encoding-errors stream
(setf (fill-pointer chunk) (read-sequence chunk char-stream :start start)))
(unless (zerop (length chunk))
check if last char is CR and EOF was not reached
(when (and (= (length chunk) (array-dimension chunk 0))
(eql (char chunk (1- (length chunk))) #\Return))
(setf pending-cr t)
(decf (fill-pointer chunk)))
(report-character-errors stream chunk)
Python code replaces surrugate pairs with U+FFFD here . Why ?
(loop for previous = nil then current
for current across chunk
for index of-type array-length from 0
with offset of-type array-length = 0
do (unless (and (eql previous #\Return)
(eql current #\Newline))
(unless (= index offset)
(setf (char chunk offset) current))
(when (eql current #\Return)
(setf (char chunk offset) #\Newline))
(incf offset))
finally (setf (fill-pointer chunk) offset))
t))))
(defun char-range (char1 char2)
(loop for i from (char-code char1) to (char-code char2)
collect (code-char i)))
(defparameter *invalid-unicode*
`(,@(char-range #\u0001 #\u0008)
#\u000B
,@(char-range #\u000E #\u001F)
,@(char-range #\u007F #\u009F)
The following are noncharacter as defined by Unicode .
#-(or abcl ccl mezzano) ,@`(
,@(char-range #\uD800 #\uDFFF)
,@(char-range #\uFDD0 #\uFDEF)
#\uFFFE
#\uFFFF
#\u0001FFFE
#\u0001FFFF
#\u0002FFFE
#\u0002FFFF
#\u0003FFFE
#\u0003FFFF
#\u0004FFFE
#\u0004FFFF
#\u0005FFFE
#\u0005FFFF
#\u0006FFFE
#\u0006FFFF
#\u0007FFFE
#\u0007FFFF
#\u0008FFFE
#\u0008FFFF
#\u0009FFFE
#\u0009FFFF
#\u000AFFFE
#\u000AFFFF
#\u000BFFFE
#\u000BFFFF
#\u000CFFFE
#\u000CFFFF
#\u000DFFFE
#\u000DFFFF
#\u000EFFFE
#\u000EFFFF
#\u000FFFFE
#\u000FFFFF
#\u0010FFFE
#\u0010FFFF)))
(defparameter *invalid-unicode-hash* (make-hash-table))
(dolist (char *invalid-unicode*)
(setf (gethash char *invalid-unicode-hash*) char))
(defun report-character-errors (stream data)
(loop for char across data
when (gethash char *invalid-unicode-hash*)
do (push :invalid-codepoint (html5-stream-errors stream))))
|
e21d357b6b739c2b95a8698bf2693cd233b93df694793fbd3d53f1cab292e36b | mklinik/hmud | RealData.hs | module Hmud.RealData where
import Hmud.Item
import Hmud.Describable
import Hmud.Room
import Hmud.World
theScrollOfForgery :: Item
theScrollOfForgery = Item { itemName = "scroll of forgery", itemDescription = "enables the forge command" }
tavern :: Room
tavern = mkRoom
"Black Unicorn"
"a dusty dark tavern. It smells of delicious food. You hear cheery background music."
[(name townSquare)]
[theScrollOfForgery]
townSquare :: Room
townSquare = mkRoom
"town square"
"the central meeting place of the town. There is a fountain, trees and flowers, and lots of people that are busy with their daily routine. The sun shines, birds sing and everybody is quite happy."
[(name tavern), (name ivoryTower)]
[]
ivoryTower :: Room
ivoryTower = mkRoom
"ivory tower"
"a tall white building with long hallways, large laboratories and a big library. Inside it is completely quiet, except for the occasional reverberant sound of footsteps. In this place, scholars develop new crazy magic spells. You are at the very top of the tower, in a small chamber with windows to all sides. You can see the whole town from up here."
[(name townSquare)]
[theScrollOfForgery]
world :: World
world = World { worldRooms = [tavern, townSquare, ivoryTower], idleCharacters = [] }
| null | https://raw.githubusercontent.com/mklinik/hmud/5ba32f29170a098e007d50688df32cf8919b6bf1/Hmud/RealData.hs | haskell | module Hmud.RealData where
import Hmud.Item
import Hmud.Describable
import Hmud.Room
import Hmud.World
theScrollOfForgery :: Item
theScrollOfForgery = Item { itemName = "scroll of forgery", itemDescription = "enables the forge command" }
tavern :: Room
tavern = mkRoom
"Black Unicorn"
"a dusty dark tavern. It smells of delicious food. You hear cheery background music."
[(name townSquare)]
[theScrollOfForgery]
townSquare :: Room
townSquare = mkRoom
"town square"
"the central meeting place of the town. There is a fountain, trees and flowers, and lots of people that are busy with their daily routine. The sun shines, birds sing and everybody is quite happy."
[(name tavern), (name ivoryTower)]
[]
ivoryTower :: Room
ivoryTower = mkRoom
"ivory tower"
"a tall white building with long hallways, large laboratories and a big library. Inside it is completely quiet, except for the occasional reverberant sound of footsteps. In this place, scholars develop new crazy magic spells. You are at the very top of the tower, in a small chamber with windows to all sides. You can see the whole town from up here."
[(name townSquare)]
[theScrollOfForgery]
world :: World
world = World { worldRooms = [tavern, townSquare, ivoryTower], idleCharacters = [] }
|
|
4b61d0600e8191bdbe7ed01630d27518a43478f1e319e21bef1b17d6ebc9e013 | GrammaTech/sel | rest.lisp | rest.lisp --- RESTful server definition for SEL .
;;;
Rest server definition for Software Evolution Library
;;;
The Rest API for Software Evolution Library is implemented as a web
;;; service which may be accessed via HTTP resources. This file serves as an
;;; entry point to these definitions, providing a simple way to start up the
;;; main REST service.
;;;
;;; It attempts to conform to principals described here:
;;; @uref{,
Representational State Transfer }
;;;
;;; @subsection Dependencies
;;;
The Rest API leverages a number of Common Lisp components , which
are open - source and generally available via Quicklisp . These
;;; packages support JSON <-> Common Lisp translations, JSON
;;; streaming, HTTP web server functions, client HTTP support and
;;; RESTful interface utilities.
;;;
CL - JSON
and generate JSON format
;;; ST-JSON
;;; Stream support for JSON format
CLACK
;;; utility to easily launch web services
DRAKMA
http client utilities for Common Lisp ( for calling Rest
;;; APIs/testing
;;; HUNCHENTOOT
Web server , written in Common Lisp , hosts Rest APIs
SNOOZE
;;; Rest API framework
;;;
;;; @subsection Running the Rest API Web Service
;;;
;;; Starting the server:
;;;
;;; (start-server)
;;;
;;; Stopping the server:
;;;
;;; (stop-server)
;;;
;;; Restart the server:
;;;
;;; (start-server) ;; will stop, if running, then start
;;;
@subsection REST Services
;;;
;;; By default, this provides the endpoints defined in sessions, the standard
;;; REST API, and asynchronous jobs, plus providing the define-command-endpoint
;;; macro. If you would like to create a rest serevr without all of these
;;; resources, you should recreate a similar file but omit the imports you wish
;;; to avoid using.
;;;
;;; @texi{rest}
(defpackage :software-evolution-library/rest
(:nicknames :sel/rest)
(:use
:gt/full
:snooze
:cl-json
:software-evolution-library/software-evolution-library
:software-evolution-library/components/test-suite
:software-evolution-library/components/formatting
:software-evolution-library/software/parseable
:software-evolution-library/software/clang
:software-evolution-library/rest/utility
:software-evolution-library/rest/sessions
:software-evolution-library/rest/std-api
:software-evolution-library/rest/async-jobs
:software-evolution-library/rest/define-command-endpoint
:software-evolution-library/command-line)
(:shadowing-import-from :clack :clackup :stop)
(:export :lookup-session
:session-property
:start-server
:stop-server
:define-async-job
:apply-async-job-func))
(in-package :software-evolution-library/rest)
(in-readtable :curry-compose-reader-macros)
(setf snooze::*catch-http-conditions* nil)
(setf snooze::*catch-errors* :verbose)
(defvar *server* nil)
(defvar *default-rest-port* 9003)
(defun start-server (&optional (port *default-rest-port*))
(if *server*
(stop-server))
(setf *server* (clack:clackup (snooze:make-clack-app) :port port)))
(defun stop-server ()
(when *server*
(clack:stop *server*)
(setf *server* nil)))
;;; Main REST server Command
(define-command rest-server
(port &spec +common-command-line-options+ &aux handler)
"Run the SEL rest server."
#.(format nil
"~%Built from SEL ~a, and ~a ~a.~%"
+software-evolution-library-version+
(lisp-implementation-type) (lisp-implementation-version))
(declare (ignorable quiet verbose load eval out-dir
read-seed save-seed language))
(flet ((shutdown (&optional (message "quit") (errno 0))
(format t "Stopping server on ~a~%" message)
(stop handler)
(exit-command rest-server errno)))
(when help (show-help-for-rest-server) (exit-command rest-server 0))
(setf handler (clackup (make-clack-app) :port (parse-integer port)))
From
(handler-case
(iter (for char = (read-char))
(when (or (eql char #\q) (eql char #\Q))
(shutdown)))
;; Catch a user's C-c
(#+sbcl sb-sys:interactive-interrupt
#+ccl ccl:interrupt-signal-condition
#+clisp system::simple-interrupt-condition
#+ecl ext:interactive-interrupt
#+allegro excl:interrupt-signal
() (shutdown "abort" 0))
(error (e)
(shutdown (format nil "unexpected error ~S" e) 1)))))
| null | https://raw.githubusercontent.com/GrammaTech/sel/a59174c02a454e8d588614e221cf281260cf12f8/rest.lisp | lisp |
service which may be accessed via HTTP resources. This file serves as an
entry point to these definitions, providing a simple way to start up the
main REST service.
It attempts to conform to principals described here:
@uref{,
@subsection Dependencies
packages support JSON <-> Common Lisp translations, JSON
streaming, HTTP web server functions, client HTTP support and
RESTful interface utilities.
ST-JSON
Stream support for JSON format
utility to easily launch web services
APIs/testing
HUNCHENTOOT
Rest API framework
@subsection Running the Rest API Web Service
Starting the server:
(start-server)
Stopping the server:
(stop-server)
Restart the server:
(start-server) ;; will stop, if running, then start
By default, this provides the endpoints defined in sessions, the standard
REST API, and asynchronous jobs, plus providing the define-command-endpoint
macro. If you would like to create a rest serevr without all of these
resources, you should recreate a similar file but omit the imports you wish
to avoid using.
@texi{rest}
Main REST server Command
Catch a user's C-c | rest.lisp --- RESTful server definition for SEL .
Rest server definition for Software Evolution Library
The Rest API for Software Evolution Library is implemented as a web
Representational State Transfer }
The Rest API leverages a number of Common Lisp components , which
are open - source and generally available via Quicklisp . These
CL - JSON
and generate JSON format
CLACK
DRAKMA
http client utilities for Common Lisp ( for calling Rest
Web server , written in Common Lisp , hosts Rest APIs
SNOOZE
@subsection REST Services
(defpackage :software-evolution-library/rest
(:nicknames :sel/rest)
(:use
:gt/full
:snooze
:cl-json
:software-evolution-library/software-evolution-library
:software-evolution-library/components/test-suite
:software-evolution-library/components/formatting
:software-evolution-library/software/parseable
:software-evolution-library/software/clang
:software-evolution-library/rest/utility
:software-evolution-library/rest/sessions
:software-evolution-library/rest/std-api
:software-evolution-library/rest/async-jobs
:software-evolution-library/rest/define-command-endpoint
:software-evolution-library/command-line)
(:shadowing-import-from :clack :clackup :stop)
(:export :lookup-session
:session-property
:start-server
:stop-server
:define-async-job
:apply-async-job-func))
(in-package :software-evolution-library/rest)
(in-readtable :curry-compose-reader-macros)
(setf snooze::*catch-http-conditions* nil)
(setf snooze::*catch-errors* :verbose)
(defvar *server* nil)
(defvar *default-rest-port* 9003)
(defun start-server (&optional (port *default-rest-port*))
(if *server*
(stop-server))
(setf *server* (clack:clackup (snooze:make-clack-app) :port port)))
(defun stop-server ()
(when *server*
(clack:stop *server*)
(setf *server* nil)))
(define-command rest-server
(port &spec +common-command-line-options+ &aux handler)
"Run the SEL rest server."
#.(format nil
"~%Built from SEL ~a, and ~a ~a.~%"
+software-evolution-library-version+
(lisp-implementation-type) (lisp-implementation-version))
(declare (ignorable quiet verbose load eval out-dir
read-seed save-seed language))
(flet ((shutdown (&optional (message "quit") (errno 0))
(format t "Stopping server on ~a~%" message)
(stop handler)
(exit-command rest-server errno)))
(when help (show-help-for-rest-server) (exit-command rest-server 0))
(setf handler (clackup (make-clack-app) :port (parse-integer port)))
From
(handler-case
(iter (for char = (read-char))
(when (or (eql char #\q) (eql char #\Q))
(shutdown)))
(#+sbcl sb-sys:interactive-interrupt
#+ccl ccl:interrupt-signal-condition
#+clisp system::simple-interrupt-condition
#+ecl ext:interactive-interrupt
#+allegro excl:interrupt-signal
() (shutdown "abort" 0))
(error (e)
(shutdown (format nil "unexpected error ~S" e) 1)))))
|
27f209f24146986b3794bed1f4d823da625d04871d23792d5291294858e51501 | ItsMeijers/Lambdabox | Side.hs | {-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-}
module Lambdabox.Trade.Side
( Side(..)
, ExchangePairSide
, buy
, sell
) where
import Lambdabox.ExchangePair
import Lambdabox.Translate
import Lambdabox.Exchange
import Data.Text (Text)
data Side = Buy
| Sell
deriving (Show, Eq)
instance Translate Binance Side Text where
translate _ Buy = "BUY"
translate _ Sell = "SELL"
type ExchangePairSide e a b = (ExchangePair e a b, Side)
buy :: ExchangePair e a b -> ExchangePairSide e a b
buy ep = (ep, Buy)
sell :: ExchangePair e a b -> ExchangePairSide e a b
sell ep = (ep, Sell) | null | https://raw.githubusercontent.com/ItsMeijers/Lambdabox/c19a8ae7d37b9f8ab5054d558fe788a5d4483092/src/Lambdabox/Trade/Side.hs | haskell | # LANGUAGE OverloadedStrings, MultiParamTypeClasses # |
module Lambdabox.Trade.Side
( Side(..)
, ExchangePairSide
, buy
, sell
) where
import Lambdabox.ExchangePair
import Lambdabox.Translate
import Lambdabox.Exchange
import Data.Text (Text)
data Side = Buy
| Sell
deriving (Show, Eq)
instance Translate Binance Side Text where
translate _ Buy = "BUY"
translate _ Sell = "SELL"
type ExchangePairSide e a b = (ExchangePair e a b, Side)
buy :: ExchangePair e a b -> ExchangePairSide e a b
buy ep = (ep, Buy)
sell :: ExchangePair e a b -> ExchangePairSide e a b
sell ep = (ep, Sell) |
89dcfafe7b810c04144396d166331abdf7f5d3e50975849ef45979952578f112 | haskell/haskell-language-server | Unused.hs | {-# LANGUAGE Haskell2010 #-}
# LANGUAGE RecordWildCards #
module Unused where
data MyRec = MyRec
{ foo :: Int
, bar :: Int
, baz :: Char
}
convertMe :: MyRec -> String
convertMe MyRec {..} = show foo ++ show bar
| null | https://raw.githubusercontent.com/haskell/haskell-language-server/b83ceb4f7d63433190a66f7ac4190c722a5b165b/plugins/hls-explicit-record-fields-plugin/test/testdata/Unused.hs | haskell | # LANGUAGE Haskell2010 # | # LANGUAGE RecordWildCards #
module Unused where
data MyRec = MyRec
{ foo :: Int
, bar :: Int
, baz :: Char
}
convertMe :: MyRec -> String
convertMe MyRec {..} = show foo ++ show bar
|
24012aaf0f48697a2de6f850e1df3f81f36a6c48f4e1604ee191ee1cc9572344 | mzp/coq-ruby | coqinit.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : coqinit.mli 5920 2004 - 07 - 16 20:01:26Z herbelin $ i
(* Initialization. *)
val set_debug : unit -> unit
val set_rcfile : string -> unit
val set_rcuser : string -> unit
val no_load_rc : unit -> unit
val load_rcfile : unit -> unit
val push_include : string * Names.dir_path -> unit
val push_rec_include : string * Names.dir_path -> unit
val init_load_path : unit -> unit
val init_library_roots : unit -> unit
val init_ocaml_path : unit -> unit
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/toplevel/coqinit.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Initialization. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : coqinit.mli 5920 2004 - 07 - 16 20:01:26Z herbelin $ i
val set_debug : unit -> unit
val set_rcfile : string -> unit
val set_rcuser : string -> unit
val no_load_rc : unit -> unit
val load_rcfile : unit -> unit
val push_include : string * Names.dir_path -> unit
val push_rec_include : string * Names.dir_path -> unit
val init_load_path : unit -> unit
val init_library_roots : unit -> unit
val init_ocaml_path : unit -> unit
|
fa3cd76b21424bb6e3feefdb4820fb8ff42a9a3792a245905c0f44a02f8cf827 | mauricioszabo/generic-lsp | atom.cljs | (ns generic-lsp.atom
(:require ["atom" :refer [CompositeDisposable]]
["url" :as url]))
(defonce subscriptions (atom (CompositeDisposable.)))
(defn info! [message]
(.. js/atom -notifications (addInfo message))
nil)
(defn error!
([message] (error! message nil))
([message detail]
(.. js/atom -notifications (addError message #js {:detail detail}))
nil))
(defn warn! [message]
(.. js/atom -notifications (addWarning message))
nil)
(defn open-editor [result]
(let [result (if (vector? result) (first result) result)
{:keys [uri range]} result
start (:start range)
line (:line start)
column (:character start)
file-name (url/fileURLToPath uri)
position (clj->js (cond-> {:initialLine line :searchAllPanes true}
column (assoc :initialColumn column)))]
(.. js/atom -workspace (open file-name position))))
(defonce open-paths (atom {}))
| null | https://raw.githubusercontent.com/mauricioszabo/generic-lsp/2b3fd212a442eaa1080a78b5a3361d981ab0be9e/src/generic_lsp/atom.cljs | clojure | (ns generic-lsp.atom
(:require ["atom" :refer [CompositeDisposable]]
["url" :as url]))
(defonce subscriptions (atom (CompositeDisposable.)))
(defn info! [message]
(.. js/atom -notifications (addInfo message))
nil)
(defn error!
([message] (error! message nil))
([message detail]
(.. js/atom -notifications (addError message #js {:detail detail}))
nil))
(defn warn! [message]
(.. js/atom -notifications (addWarning message))
nil)
(defn open-editor [result]
(let [result (if (vector? result) (first result) result)
{:keys [uri range]} result
start (:start range)
line (:line start)
column (:character start)
file-name (url/fileURLToPath uri)
position (clj->js (cond-> {:initialLine line :searchAllPanes true}
column (assoc :initialColumn column)))]
(.. js/atom -workspace (open file-name position))))
(defonce open-paths (atom {}))
|
|
4337faf94d90aa6dd9fbbdbcb16192846f73b04ced84692a4b00e87843875390 | dmjio/aoc2020 | Main.hs | {-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
# LANGUAGE ViewPatterns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
# LANGUAGE ScopedTypeVariables #
module Main where
import Data.Bits
import Data.Char
import Data.Function (on)
import qualified Data.IntMap.Strict as IM
import Data.IntMap.Strict (IntMap)
import Data.List (sortBy, find, foldl', isPrefixOf)
import Data.List.Split
import Data.Maybe
import Debug.Trace (traceShow)
import Text.Read
main :: IO ()
main = day15
day15 :: IO ()
day15 = do
putStrLn "day 15"
let nums = [19,20,14,0,9,1]
print (findSpoken 2020 nums)
print (findSpoken 30000000 nums)
findSpoken :: Int -> [Int] -> Int
findSpoken spokenNum nums = do
let
spokenTurns = IM.fromList (zipWith (\n t -> (n,[t])) nums [1..])
spokenCount = IM.fromList (zip nums (repeat 1))
initial = ( length nums + 1
, last nums
, spokenCount
, spokenTurns
)
getSpoken (until (\(getTurn -> t) -> t > spokenNum) go initial)
getTurn :: (a,b,c,d) -> a
getTurn (t,_,_,_) = t
getSpoken :: (a,b,c,d) -> b
getSpoken (_,x,_,_) = x
go :: (Int, Int, IntMap Int, IntMap [Int])
-> (Int, Int, IntMap Int, IntMap [Int])
go (!turn, !lastSpoken, spokenCount, spokenTurns) = do
case IM.lookup lastSpoken spokenCount of
Nothing ->
( turn + 1
, 0
, IM.insertWith (+) 0 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) lastSpoken [turn] spokenTurns
)
Just 1 ->
( turn + 1
, 0
, IM.insertWith (+) 0 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) 0 [turn] spokenTurns
)
Just _ ->
let
[x,y] = take 2 (spokenTurns IM.! lastSpoken)
nextSpoken = x-y
in
( turn + 1
, nextSpoken
, IM.insertWith (+) nextSpoken 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) nextSpoken [turn] spokenTurns
)
| null | https://raw.githubusercontent.com/dmjio/aoc2020/83c1d55a2dad3b2318666debaf18b5368cff8738/15/Main.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings # | # LANGUAGE ViewPatterns #
# LANGUAGE TypeApplications #
# LANGUAGE ScopedTypeVariables #
module Main where
import Data.Bits
import Data.Char
import Data.Function (on)
import qualified Data.IntMap.Strict as IM
import Data.IntMap.Strict (IntMap)
import Data.List (sortBy, find, foldl', isPrefixOf)
import Data.List.Split
import Data.Maybe
import Debug.Trace (traceShow)
import Text.Read
main :: IO ()
main = day15
day15 :: IO ()
day15 = do
putStrLn "day 15"
let nums = [19,20,14,0,9,1]
print (findSpoken 2020 nums)
print (findSpoken 30000000 nums)
findSpoken :: Int -> [Int] -> Int
findSpoken spokenNum nums = do
let
spokenTurns = IM.fromList (zipWith (\n t -> (n,[t])) nums [1..])
spokenCount = IM.fromList (zip nums (repeat 1))
initial = ( length nums + 1
, last nums
, spokenCount
, spokenTurns
)
getSpoken (until (\(getTurn -> t) -> t > spokenNum) go initial)
getTurn :: (a,b,c,d) -> a
getTurn (t,_,_,_) = t
getSpoken :: (a,b,c,d) -> b
getSpoken (_,x,_,_) = x
go :: (Int, Int, IntMap Int, IntMap [Int])
-> (Int, Int, IntMap Int, IntMap [Int])
go (!turn, !lastSpoken, spokenCount, spokenTurns) = do
case IM.lookup lastSpoken spokenCount of
Nothing ->
( turn + 1
, 0
, IM.insertWith (+) 0 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) lastSpoken [turn] spokenTurns
)
Just 1 ->
( turn + 1
, 0
, IM.insertWith (+) 0 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) 0 [turn] spokenTurns
)
Just _ ->
let
[x,y] = take 2 (spokenTurns IM.! lastSpoken)
nextSpoken = x-y
in
( turn + 1
, nextSpoken
, IM.insertWith (+) nextSpoken 1 spokenCount
, IM.insertWith (\new old -> new ++ take 1 old) nextSpoken [turn] spokenTurns
)
|
78a469c65986a18806b8ea4b66332aeae3ded16a681df8fc57d0cb18dbfd79cb | mtpearce/idyom | params.lisp | ;;;; ======================================================================
;;;; File: params.lisp
Author : < >
Created : < 2003 - 06 - 16 >
Time - stamp : < 2019 - 06 - 13 13:22:30 marcusp >
;;;; ======================================================================
(cl:in-package #:mvs)
(defvar *ep-cache-dir* nil "Directory for storing cached predictions.")
(defparameter *ltm-mixtures* t)
(defparameter *ltm-escape* :c) ;:a, :b, :c, :d, :x
(defparameter *ltm-order-bound* nil)
(defparameter *ltm-update-exclusion* nil)
(defparameter *ltm-exclusion* t)
(defparameter *stm-mixtures* t)
(defparameter *stm-escape* :x) ;:a, :b, :c, :d, :x
(defparameter *stm-order-bound* nil)
(defparameter *stm-update-exclusion* t)
(defparameter *stm-exclusion* t)
Define a set of parameters for a memory store , e.g. an STM or LTM .
(defun memory-store-params (order-bound mixtures update-exclusion escape exclusion)
`(:order-bound ,order-bound :mixtures ,mixtures :update-exclusion ,update-exclusion :escape ,escape :exclusion ,exclusion))
;;; Default store specs
(defparameter *ltm-params* (memory-store-params mvs::*ltm-order-bound* mvs::*ltm-mixtures* mvs::*ltm-update-exclusion* mvs::*ltm-escape* mvs::*ltm-exclusion*))
(defparameter *stm-params* (memory-store-params mvs::*stm-order-bound* mvs::*stm-mixtures* mvs::*stm-update-exclusion* mvs::*stm-escape* mvs::*stm-exclusion*))
(defparameter *marginalise-using-current-event* 2
"Specifies the list of basic viewpoints which assume their full
alphabets in prediction rather than being marginalised out based on
their value in the current event. See mvs:set-model-alphabets for
details. Default = 2, all basic viewpoints.")
: ltm , : ltm+ , : , : both , :
;arithmetic-combination
;geometric-combination
;bayesian-combination
;ranked-combination
(defparameter *ltm-stm-combination* 'geometric-combination)
(defparameter *viewpoint-combination* 'geometric-combination)
(defparameter *ltm-stm-bias* 7)
(defparameter *viewpoint-bias* 2)
| null | https://raw.githubusercontent.com/mtpearce/idyom/d0449a978c79f8ded74c509fdfad7c1a253c5a80/mvs/params.lisp | lisp | ======================================================================
File: params.lisp
======================================================================
:a, :b, :c, :d, :x
:a, :b, :c, :d, :x
Default store specs
arithmetic-combination
geometric-combination
bayesian-combination
ranked-combination | Author : < >
Created : < 2003 - 06 - 16 >
Time - stamp : < 2019 - 06 - 13 13:22:30 marcusp >
(cl:in-package #:mvs)
(defvar *ep-cache-dir* nil "Directory for storing cached predictions.")
(defparameter *ltm-mixtures* t)
(defparameter *ltm-order-bound* nil)
(defparameter *ltm-update-exclusion* nil)
(defparameter *ltm-exclusion* t)
(defparameter *stm-mixtures* t)
(defparameter *stm-order-bound* nil)
(defparameter *stm-update-exclusion* t)
(defparameter *stm-exclusion* t)
Define a set of parameters for a memory store , e.g. an STM or LTM .
(defun memory-store-params (order-bound mixtures update-exclusion escape exclusion)
`(:order-bound ,order-bound :mixtures ,mixtures :update-exclusion ,update-exclusion :escape ,escape :exclusion ,exclusion))
(defparameter *ltm-params* (memory-store-params mvs::*ltm-order-bound* mvs::*ltm-mixtures* mvs::*ltm-update-exclusion* mvs::*ltm-escape* mvs::*ltm-exclusion*))
(defparameter *stm-params* (memory-store-params mvs::*stm-order-bound* mvs::*stm-mixtures* mvs::*stm-update-exclusion* mvs::*stm-escape* mvs::*stm-exclusion*))
(defparameter *marginalise-using-current-event* 2
"Specifies the list of basic viewpoints which assume their full
alphabets in prediction rather than being marginalised out based on
their value in the current event. See mvs:set-model-alphabets for
details. Default = 2, all basic viewpoints.")
: ltm , : ltm+ , : , : both , :
(defparameter *ltm-stm-combination* 'geometric-combination)
(defparameter *viewpoint-combination* 'geometric-combination)
(defparameter *ltm-stm-bias* 7)
(defparameter *viewpoint-bias* 2)
|
1a111a4d6da9b70019632df511b801010f09bae5a3fd77e4e294281e0ba9d0ab | folivetti/ITEA | Shape.hs | |
Module : IT.Shape
Description : Measuring shape constraints with interval arithmetic
Copyright : ( c ) , 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Support functions to measure imposed shape constraints into the image of the function and its derivatives .
Module : IT.Shape
Description : Measuring shape constraints with interval arithmetic
Copyright : (c) Fabricio Olivetti de Franca, 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Support functions to measure imposed shape constraints into the image of the function and its derivatives.
-}
module IT.Shape where
import IT
import IT.Eval
import IT.Algorithms
import Control.Arrow
import Numeric.Interval
type ImgFun = [Interval Double] -> Expr -> [Double] -> Interval Double
data Shape = Image (Double, Double)
| DiffImg Int (Double, Double) | NonIncreasing Int | NonDecreasing Int
| PartialNonIncreasing Int (Double, Double) | PartialNonDecreasing Int (Double, Double)
( 0,0 ) , ( 0,Infinity ) , ( -Infinitiy,0 )
deriving (Show, Read)
type Domains = Maybe [(Double, Double)]
-- * Constraint functions
unconstrained :: Constraint
unconstrained _ _ = 0
-- violationImg evalImage
-- violationImg (evalDiffImage ix)
violationImg :: ImgFun -> [Interval Double] -> Interval Double -> Constraint
violationImg imgfun domains img expr ws
| img' == empty = 1e+10
| otherwise =
let (lo, hi) = (inf &&& sup) img
(lo', hi') = (inf &&& sup) img'
loDiff = if lo' > lo && lo' < hi then 0 else abs (lo - lo')
hiDiff = if hi' < hi && hi' > lo then 0 else abs (hi' - hi)
in loDiff + hiDiff
where
img' = imgfun domains expr ws
violationNonIncreasing, violationNonDecreasing :: Int -> [Interval Double] -> Constraint
violationNonIncreasing ix domains expr ws -- (-Infinity .. 0)
| img == empty = 1e+10
| otherwise = max 0 $ sup img
where img = evalDiffImage ix domains expr ws
violationNonDecreasing ix domains expr ws -- (0 .. Infinity)
| img == empty = 1e+10
| otherwise = negate $ min 0 $ inf img
where img = evalDiffImage ix domains expr ws
violationInflection, violationConcave, violationConvex :: Int -> Int -> [Interval Double] -> Constraint
violationInflection ix iy domains expr ws -- (0 .. 0)
| img == empty = 1e+10
| otherwise = if abs (inf img) + abs (sup img) < 1e-2 then 0 else abs (inf img) + abs (sup img)
where img = evalSndDiffImage ix iy domains expr ws
violationConvex ix iy domains expr ws -- (0 .. Infinity)
| img == empty = 1e+10
| otherwise = negate $ min 0 $ inf img
where img = evalSndDiffImage ix iy domains expr ws
violationConcave ix iy domains expr ws -- (-Infinity .. 0)
| img == empty = 1e+10
| otherwise = max 0 $ sup img
where img = evalSndDiffImage ix iy domains expr ws
constraintFrom :: [Constraint] -> Constraint
constraintFrom funs expr ws = let c = foldr (\f tot -> abs (f expr ws) + tot) 0 funs
in if c < 1e-60 then 0 else c
fromShapes :: [Shape] -> Domains -> Constraint
fromShapes _ Nothing = unconstrained
fromShapes [] _ = unconstrained
fromShapes shapes (Just domains) = constraintFrom (map toFun shapes)
where
domains' = map (uncurry (...)) domains
replace ds ix rng = let rng' = (fst rng ... snd rng)
in take ix ds ++ (rng' : drop (ix+1) ds)
toFun (Image (lo, hi)) = violationImg evalImage domains' (lo ... hi)
toFun (DiffImg ix (lo, hi)) = violationImg (evalDiffImage ix) domains' (lo ... hi)
toFun (NonIncreasing ix) = violationNonIncreasing ix domains'
toFun (NonDecreasing ix) = violationNonDecreasing ix domains'
toFun (PartialNonIncreasing ix range) = violationNonIncreasing ix $ replace domains' ix range
toFun (PartialNonDecreasing ix range) = violationNonDecreasing ix $ replace domains' ix range
toFun (Inflection ix iy) = violationInflection ix iy domains'
toFun (Convex ix iy) = violationConvex ix iy domains'
toFun (Concave ix iy) = violationConcave ix iy domains'
| null | https://raw.githubusercontent.com/folivetti/ITEA/fc8360ae2f8ffe4c46867329f7c8fa91a85a21af/src/IT/Shape.hs | haskell | * Constraint functions
violationImg evalImage
violationImg (evalDiffImage ix)
(-Infinity .. 0)
(0 .. Infinity)
(0 .. 0)
(0 .. Infinity)
(-Infinity .. 0) | |
Module : IT.Shape
Description : Measuring shape constraints with interval arithmetic
Copyright : ( c ) , 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Support functions to measure imposed shape constraints into the image of the function and its derivatives .
Module : IT.Shape
Description : Measuring shape constraints with interval arithmetic
Copyright : (c) Fabricio Olivetti de Franca, 2020
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Support functions to measure imposed shape constraints into the image of the function and its derivatives.
-}
module IT.Shape where
import IT
import IT.Eval
import IT.Algorithms
import Control.Arrow
import Numeric.Interval
type ImgFun = [Interval Double] -> Expr -> [Double] -> Interval Double
data Shape = Image (Double, Double)
| DiffImg Int (Double, Double) | NonIncreasing Int | NonDecreasing Int
| PartialNonIncreasing Int (Double, Double) | PartialNonDecreasing Int (Double, Double)
( 0,0 ) , ( 0,Infinity ) , ( -Infinitiy,0 )
deriving (Show, Read)
type Domains = Maybe [(Double, Double)]
unconstrained :: Constraint
unconstrained _ _ = 0
violationImg :: ImgFun -> [Interval Double] -> Interval Double -> Constraint
violationImg imgfun domains img expr ws
| img' == empty = 1e+10
| otherwise =
let (lo, hi) = (inf &&& sup) img
(lo', hi') = (inf &&& sup) img'
loDiff = if lo' > lo && lo' < hi then 0 else abs (lo - lo')
hiDiff = if hi' < hi && hi' > lo then 0 else abs (hi' - hi)
in loDiff + hiDiff
where
img' = imgfun domains expr ws
violationNonIncreasing, violationNonDecreasing :: Int -> [Interval Double] -> Constraint
| img == empty = 1e+10
| otherwise = max 0 $ sup img
where img = evalDiffImage ix domains expr ws
| img == empty = 1e+10
| otherwise = negate $ min 0 $ inf img
where img = evalDiffImage ix domains expr ws
violationInflection, violationConcave, violationConvex :: Int -> Int -> [Interval Double] -> Constraint
| img == empty = 1e+10
| otherwise = if abs (inf img) + abs (sup img) < 1e-2 then 0 else abs (inf img) + abs (sup img)
where img = evalSndDiffImage ix iy domains expr ws
| img == empty = 1e+10
| otherwise = negate $ min 0 $ inf img
where img = evalSndDiffImage ix iy domains expr ws
| img == empty = 1e+10
| otherwise = max 0 $ sup img
where img = evalSndDiffImage ix iy domains expr ws
constraintFrom :: [Constraint] -> Constraint
constraintFrom funs expr ws = let c = foldr (\f tot -> abs (f expr ws) + tot) 0 funs
in if c < 1e-60 then 0 else c
fromShapes :: [Shape] -> Domains -> Constraint
fromShapes _ Nothing = unconstrained
fromShapes [] _ = unconstrained
fromShapes shapes (Just domains) = constraintFrom (map toFun shapes)
where
domains' = map (uncurry (...)) domains
replace ds ix rng = let rng' = (fst rng ... snd rng)
in take ix ds ++ (rng' : drop (ix+1) ds)
toFun (Image (lo, hi)) = violationImg evalImage domains' (lo ... hi)
toFun (DiffImg ix (lo, hi)) = violationImg (evalDiffImage ix) domains' (lo ... hi)
toFun (NonIncreasing ix) = violationNonIncreasing ix domains'
toFun (NonDecreasing ix) = violationNonDecreasing ix domains'
toFun (PartialNonIncreasing ix range) = violationNonIncreasing ix $ replace domains' ix range
toFun (PartialNonDecreasing ix range) = violationNonDecreasing ix $ replace domains' ix range
toFun (Inflection ix iy) = violationInflection ix iy domains'
toFun (Convex ix iy) = violationConvex ix iy domains'
toFun (Concave ix iy) = violationConcave ix iy domains'
|
8e6ea7fcebbcafb83d05bf5fe1b52139ed6ee033a819aa7984d90fade73d8cf0 | Kakadu/fp2022 | demo.ml | * Copyright 2022 - 2023 ,
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Ocamlprintf_lib
open Interpret.Interpret (Interpret.Result)
let () = run (Stdio.In_channel.input_all stdin)
| null | https://raw.githubusercontent.com/Kakadu/fp2022/0ecfd0a84158d9897c26d07108437e9036b92f05/OCamlPrintf/demos/demo.ml | ocaml | * Copyright 2022 - 2023 ,
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Ocamlprintf_lib
open Interpret.Interpret (Interpret.Result)
let () = run (Stdio.In_channel.input_all stdin)
|
|
5e2500a979ec3e1d7f703802aae5b63aaf9e217f67bb87d93e7ccfffae5fc469 | Clozure/ccl-tests | package-use-list.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Feb 22 06:55:56 2004
;;;; Contains: Tests of PACKAGE-USE-LIST
(in-package :cl-test)
;;; Most tests of this function are in files for other package-related operators
Specialized sequence tests
(defmacro def-package-use-list-test (test-name name-form)
`(deftest ,test-name
(let ((name ,name-form))
(safely-delete-package name)
(let ((p (make-package name :use nil)))
(package-use-list p)))
nil))
(def-package-use-list-test package-use-list.1
(make-array 5 :element-type 'base-char :initial-contents "TEST1"))
(def-package-use-list-test package-use-list.2
(make-array 10 :element-type 'base-char
:fill-pointer 5
:initial-contents "TEST1?????"))
(def-package-use-list-test package-use-list.3
(make-array 10 :element-type 'character
:fill-pointer 5
:initial-contents "TEST1?????"))
(def-package-use-list-test package-use-list.4
(make-array 5 :element-type 'base-char :adjustable t
:initial-contents "TEST1"))
(def-package-use-list-test package-use-list.5
(make-array 5 :element-type 'character :adjustable t
:initial-contents "TEST1"))
(def-package-use-list-test package-use-list.6
(let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "XXTEST1XXX")))
(make-array 5 :element-type etype :displaced-to name0
:displaced-index-offset 2)))
(def-package-use-list-test package-use-list.7
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "XXTEST1XXX")))
(make-array 5 :element-type etype :displaced-to name0
:displaced-index-offset 2)))
;;; Error tests
(deftest package-use-list.error.1
(signals-error (package-use-list) program-error)
t)
(deftest package-use-list.error.2
(signals-error (package-use-list "CL" nil) program-error)
t)
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/package-use-list.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of PACKAGE-USE-LIST
Most tests of this function are in files for other package-related operators
Error tests | Author :
Created : Sun Feb 22 06:55:56 2004
(in-package :cl-test)
Specialized sequence tests
(defmacro def-package-use-list-test (test-name name-form)
`(deftest ,test-name
(let ((name ,name-form))
(safely-delete-package name)
(let ((p (make-package name :use nil)))
(package-use-list p)))
nil))
(def-package-use-list-test package-use-list.1
(make-array 5 :element-type 'base-char :initial-contents "TEST1"))
(def-package-use-list-test package-use-list.2
(make-array 10 :element-type 'base-char
:fill-pointer 5
:initial-contents "TEST1?????"))
(def-package-use-list-test package-use-list.3
(make-array 10 :element-type 'character
:fill-pointer 5
:initial-contents "TEST1?????"))
(def-package-use-list-test package-use-list.4
(make-array 5 :element-type 'base-char :adjustable t
:initial-contents "TEST1"))
(def-package-use-list-test package-use-list.5
(make-array 5 :element-type 'character :adjustable t
:initial-contents "TEST1"))
(def-package-use-list-test package-use-list.6
(let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "XXTEST1XXX")))
(make-array 5 :element-type etype :displaced-to name0
:displaced-index-offset 2)))
(def-package-use-list-test package-use-list.7
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "XXTEST1XXX")))
(make-array 5 :element-type etype :displaced-to name0
:displaced-index-offset 2)))
(deftest package-use-list.error.1
(signals-error (package-use-list) program-error)
t)
(deftest package-use-list.error.2
(signals-error (package-use-list "CL" nil) program-error)
t)
|
cb0d4ea80b7a01b7c4ed96c80d98980e8ecf64b2dad0fe6169a7017cf14bd8bb | johnlawrenceaspden/hobby-code | unexpected-schlemiel-the-painter.clj | The Unexpected Appearance of Schlemiel , the Painter
;; So, it is clear that my model of how things are done was badly broken
I am doing some statistics , one day , and so I define :
;; the average of a finite sequence
(defn average [sq] (/ (reduce + sq) (count sq)))
;; and the square of a number
(defn square [x] (* x x))
;; and a way of forgetting about all the fiddly little digits at the end
(defn twosf [x] (float (/ (Math/round (* x 100.0)) 100)))
;; but for the variance I am a little torn between:
(defn variance-one [sq]
(let [av (average sq)]
(average (map #(square (- % av)) sq))))
;; ;
(defn variance-two [sq]
(let [sqdiff #(square (- % (average sq)))]
(average (map sqdiff sq))))
;; and (I have a regrettable weakness for the terse...)
(defn variance-one-liner [sq] (average (map #(square (- % (average sq))) sq)))
;; but what I am not expecting, is this:
(let [s (repeatedly 1000 #(rand))]
(twosf (reduce + s)) ;; just to force the sequence to be generated before timing things
[(time (twosf (reduce + s)))
(time (twosf (average s)))
(time (twosf (variance-one s)))
(time (twosf (variance-two s)))
(time (twosf (variance-one-liner s)))])
" Elapsed time : 0.535715 msecs "
" Elapsed time : 0.834523 msecs "
" Elapsed time : 1.417108 msecs "
" Elapsed time : 251.650722 msecs "
" Elapsed time : 248.196331 msecs "
[ 496.83 0.5 0.09 0.09 0.09 ]
;; It seems that all these functions are correct, in the sense that they are producing
;; correct-looking answers, and yet:
;; It seems that variance-one is doing what I expect, running down the sequence twice and ending up
;; taking about twice as long as averaging it.
But that the other two are taking hundreds of times longer , possibly because they are
;; re-calculating the average of the sequence every time.
I had a nice hour or so , thinking about what was going on here , and why , and wonder if you might
;; enjoy the same thoughts, dear readers.
| null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/unexpected-schlemiel-the-painter.clj | clojure | So, it is clear that my model of how things are done was badly broken
the average of a finite sequence
and the square of a number
and a way of forgetting about all the fiddly little digits at the end
but for the variance I am a little torn between:
;
and (I have a regrettable weakness for the terse...)
but what I am not expecting, is this:
just to force the sequence to be generated before timing things
It seems that all these functions are correct, in the sense that they are producing
correct-looking answers, and yet:
It seems that variance-one is doing what I expect, running down the sequence twice and ending up
taking about twice as long as averaging it.
re-calculating the average of the sequence every time.
enjoy the same thoughts, dear readers. | The Unexpected Appearance of Schlemiel , the Painter
I am doing some statistics , one day , and so I define :
(defn average [sq] (/ (reduce + sq) (count sq)))
(defn square [x] (* x x))
(defn twosf [x] (float (/ (Math/round (* x 100.0)) 100)))
(defn variance-one [sq]
(let [av (average sq)]
(average (map #(square (- % av)) sq))))
(defn variance-two [sq]
(let [sqdiff #(square (- % (average sq)))]
(average (map sqdiff sq))))
(defn variance-one-liner [sq] (average (map #(square (- % (average sq))) sq)))
(let [s (repeatedly 1000 #(rand))]
[(time (twosf (reduce + s)))
(time (twosf (average s)))
(time (twosf (variance-one s)))
(time (twosf (variance-two s)))
(time (twosf (variance-one-liner s)))])
" Elapsed time : 0.535715 msecs "
" Elapsed time : 0.834523 msecs "
" Elapsed time : 1.417108 msecs "
" Elapsed time : 251.650722 msecs "
" Elapsed time : 248.196331 msecs "
[ 496.83 0.5 0.09 0.09 0.09 ]
But that the other two are taking hundreds of times longer , possibly because they are
I had a nice hour or so , thinking about what was going on here , and why , and wonder if you might
|
30b83240eac1552b840aaaea9867135a4463214bf87d4e21dfe0181c70bcaabb | scrintal/heroicons-reagent | chat_bubble_bottom_center_text.cljs | (ns com.scrintal.heroicons.mini.chat-bubble-bottom-center-text)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M10 2c-2.236 0-4.43.18-6.57.524C1.993 2.755 1 4.014 1 5.426v5.148c0 1.413.993 2.67 2.43 2.902 1.168.188 2.352.327 3.55.414.28.02.521.18.642.413l1.713 3.293a.75.75 0 001.33 0l1.713-3.293a.783.783 0 01.642-.413 41.102 41.102 0 003.55-.414c1.437-.231 2.43-1.49 2.43-2.902V5.426c0-1.413-.993-2.67-2.43-2.902A41.289 41.289 0 0010 2zM6.75 6a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-6.5zm0 2.5a.75.75 0 000 1.5h3.5a.75.75 0 000-1.5h-3.5z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/mini/chat_bubble_bottom_center_text.cljs | clojure | (ns com.scrintal.heroicons.mini.chat-bubble-bottom-center-text)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 20 20"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M10 2c-2.236 0-4.43.18-6.57.524C1.993 2.755 1 4.014 1 5.426v5.148c0 1.413.993 2.67 2.43 2.902 1.168.188 2.352.327 3.55.414.28.02.521.18.642.413l1.713 3.293a.75.75 0 001.33 0l1.713-3.293a.783.783 0 01.642-.413 41.102 41.102 0 003.55-.414c1.437-.231 2.43-1.49 2.43-2.902V5.426c0-1.413-.993-2.67-2.43-2.902A41.289 41.289 0 0010 2zM6.75 6a.75.75 0 000 1.5h6.5a.75.75 0 000-1.5h-6.5zm0 2.5a.75.75 0 000 1.5h3.5a.75.75 0 000-1.5h-3.5z"
:clipRule "evenodd"}]]) |
|
8f0d1bc8ab4bbc154a80e864e961da017dab97a857266cce9ba0c2eeb26a70b3 | tek/ribosome | FilterTest.hs | module Ribosome.Menu.Test.FilterTest where
import Lens.Micro.Mtl (view)
import Polysemy.Test (UnitTest, runTestAuto, (===))
import Ribosome.Menu.Combinators (sortEntriesText)
import Ribosome.Menu.Data.Filter (Filter (Fuzzy))
import Ribosome.Menu.Data.FilterMode (FilterMode (FilterMode))
import Ribosome.Menu.Data.MenuItem (Items, simpleItems)
import Ribosome.Menu.Effect.MenuFilter (FilterJob (Initial), menuFilter)
import Ribosome.Menu.Interpreter.MenuFilter (defaultFilter)
items :: Items ()
items =
simpleItems [
"xaxbx",
"xabc",
"xaxbxcx",
"ab"
]
test_filterFuzzy :: UnitTest
test_filterFuzzy =
runTestAuto do
r <- defaultFilter (menuFilter (FilterMode Fuzzy (Just . view #text)) "ab" (Initial items))
["ab", "xabc", "xaxbx", "xaxbxcx"] === sortEntriesText r
| null | https://raw.githubusercontent.com/tek/ribosome/ec3dd63ad47322e7fec66043dd7e6ade2f547ac1/packages/menu/test/Ribosome/Menu/Test/FilterTest.hs | haskell | module Ribosome.Menu.Test.FilterTest where
import Lens.Micro.Mtl (view)
import Polysemy.Test (UnitTest, runTestAuto, (===))
import Ribosome.Menu.Combinators (sortEntriesText)
import Ribosome.Menu.Data.Filter (Filter (Fuzzy))
import Ribosome.Menu.Data.FilterMode (FilterMode (FilterMode))
import Ribosome.Menu.Data.MenuItem (Items, simpleItems)
import Ribosome.Menu.Effect.MenuFilter (FilterJob (Initial), menuFilter)
import Ribosome.Menu.Interpreter.MenuFilter (defaultFilter)
items :: Items ()
items =
simpleItems [
"xaxbx",
"xabc",
"xaxbxcx",
"ab"
]
test_filterFuzzy :: UnitTest
test_filterFuzzy =
runTestAuto do
r <- defaultFilter (menuFilter (FilterMode Fuzzy (Just . view #text)) "ab" (Initial items))
["ab", "xabc", "xaxbx", "xaxbxcx"] === sortEntriesText r
|
|
1a300d0d86ef1c050519c888b7dca9d7251c6aa6d971fa281386754440b50d97 | dreixel/syb | Main.hs |
module Main where
import Test.Tasty
import Test.Tasty.HUnit
import System.Exit
import qualified Bits
import qualified Builders
import qualified Datatype
import qualified Ext1
import qualified Ext2
import qualified FoldTree
import qualified FreeNames
import qualified GEq
import qualified GMapQAssoc
import qualified GRead
import qualified GShow
import qualified GShow2
import qualified GZip
import qualified GenUpTo
import qualified GetC
import qualified HList
import qualified HOPat
import qualified Labels
import qualified Newtype
import qualified Paradise
import qualified Perm
import qualified Reify
import qualified Strings
import qualified Tree
import qualified Twin
import qualified Typecase1
import qualified Typecase2
import qualified Where
import qualified XML
import qualified Encode -- no tests, should compile
import qualified Ext -- no tests, should compile
import qualified GRead2 -- no tests, should compile
import qualified LocalQuantors -- no tests, should compile
import qualified NestedDatatypes -- no tests, should compile
import qualified Polymatch -- no tests, should compile
main = defaultMain $ testGroup "All"
[ testCase "Datatype" Datatype.tests
, testCase "FoldTree" FoldTree.tests
, testCase "GetC" GetC.tests
, testCase "GMapQAssoc" GMapQAssoc.tests
, testCase "GRead" GRead.tests
, testCase "GShow" GShow.tests
, testCase "GShow2" GShow2.tests
, testCase "HList" HList.tests
, testCase "HOPat" HOPat.tests
, testCase "Labels" Labels.tests
, testCase "Newtype" Newtype.tests
, testCase "Perm" Perm.tests
, testCase "Twin" Twin.tests
, testCase "Typecase1" Typecase1.tests
, testCase "Typecase2" Typecase2.tests
, testCase "Where" Where.tests
, testCase "XML" XML.tests
, testCase "Tree" Tree.tests
, testCase "Strings" Strings.tests
, testCase "Reify" Reify.tests
, testCase "Paradise" Paradise.tests
, testCase "GZip" GZip.tests
, testCase "GEq" GEq.tests
, testCase "GenUpTo" GenUpTo.tests
, testCase "FreeNames" FreeNames.tests
, testCase "Ext1" Ext1.tests
, testCase "Ext2" Ext2.tests
, testCase "Bits" Bits.tests
, testCase "Builders" Builders.tests
]
| null | https://raw.githubusercontent.com/dreixel/syb/f741a437f18768f71586eeb47ffb43c0915f331b/tests/Main.hs | haskell | no tests, should compile
no tests, should compile
no tests, should compile
no tests, should compile
no tests, should compile
no tests, should compile |
module Main where
import Test.Tasty
import Test.Tasty.HUnit
import System.Exit
import qualified Bits
import qualified Builders
import qualified Datatype
import qualified Ext1
import qualified Ext2
import qualified FoldTree
import qualified FreeNames
import qualified GEq
import qualified GMapQAssoc
import qualified GRead
import qualified GShow
import qualified GShow2
import qualified GZip
import qualified GenUpTo
import qualified GetC
import qualified HList
import qualified HOPat
import qualified Labels
import qualified Newtype
import qualified Paradise
import qualified Perm
import qualified Reify
import qualified Strings
import qualified Tree
import qualified Twin
import qualified Typecase1
import qualified Typecase2
import qualified Where
import qualified XML
main = defaultMain $ testGroup "All"
[ testCase "Datatype" Datatype.tests
, testCase "FoldTree" FoldTree.tests
, testCase "GetC" GetC.tests
, testCase "GMapQAssoc" GMapQAssoc.tests
, testCase "GRead" GRead.tests
, testCase "GShow" GShow.tests
, testCase "GShow2" GShow2.tests
, testCase "HList" HList.tests
, testCase "HOPat" HOPat.tests
, testCase "Labels" Labels.tests
, testCase "Newtype" Newtype.tests
, testCase "Perm" Perm.tests
, testCase "Twin" Twin.tests
, testCase "Typecase1" Typecase1.tests
, testCase "Typecase2" Typecase2.tests
, testCase "Where" Where.tests
, testCase "XML" XML.tests
, testCase "Tree" Tree.tests
, testCase "Strings" Strings.tests
, testCase "Reify" Reify.tests
, testCase "Paradise" Paradise.tests
, testCase "GZip" GZip.tests
, testCase "GEq" GEq.tests
, testCase "GenUpTo" GenUpTo.tests
, testCase "FreeNames" FreeNames.tests
, testCase "Ext1" Ext1.tests
, testCase "Ext2" Ext2.tests
, testCase "Bits" Bits.tests
, testCase "Builders" Builders.tests
]
|
94a1cabd3c551049bd98d77fb47a3e399117e433f7d81c53b11feaca8710b9eb | genmeblog/techtest | core.clj | (ns techtest.core
(:require [tech.ml.dataset :as ds]
[tech.ml.dataset.column :as col]
[tech.v2.datatype.functional :as dfn] ))
;; created with tech.ml.dataset version "2.0-beta-24"
;; further versions may simplify some things
;; Working thrugh R `data.table` type and confronting with tech.ml.dataset
;; -project.org/web/packages/data.table/vignettes/datatable-intro.html
;; # Preparation
(require '[clojisr.v1.r :as r :refer [r]]
'[clojisr.v1.require :refer [require-r]])
;; load R package
(require-r '[base]
'[utils]
'[data.table :as dt])
(r.base/options :width 160)
;; # Read data from URL
;; input <- ""
;; flights <- fread(input)
;; --------- R
(def R-flights (time (dt/fread "")))
;; --------- Clojure
(def flights (time (ds/->dataset "")))
;; # Taking the shape of loaded data
;; dim(flights)
;; --------- R
(r.base/dim R-flights)
= > [ 1 ] 253316 11
;; --------- Clojure
= > 11
= > 253316
;; TODO: maybe add those numbers to a metadata? Like in `column` case?
(meta flights)
;; => {:name ""}
;; # Basics
;; ## What is `data.table`?
;; DT = data.table(
;; ID = c("b","b","b","a","a","c"),
a = 1:6 ,
;; b = 7:12,
c = 13:18
;; )
;;
;; class(DT$ID)
;; --------- R
(def R-DT (dt/data-table :ID ["b" "b" "b" "c" "c" "a"]
:a (r/colon 1 6)
:b (r/colon 7 12)
:c (r/colon 13 18)))
R-DT
;; => ID a b c
1 : b 1 7 13
2 : b 2 8 14
3 : b 3 9 15
4 : c 4 10 16
5 : c 5 11 17
6 : a 6 12 18
(r.base/class (r.base/$ R-DT 'ID))
= > [ 1 ] " character "
;; --------- Clojure
(def DT (ds/name-values-seq->dataset {:ID ["b" "b" "b" "c" "c" "a"]
:a (range 1 7)
:b (range 7 13)
:c (range 13 19)}))
DT
= > _ unnamed [ 6 4 ] :
;; | :ID | :a | :b | :c |
;; |-----+----+----+----|
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
;; | c | 4 | 10 | 16 |
;; | c | 5 | 11 | 17 |
;; | a | 6 | 12 | 18 |
(meta (DT :ID))
= > { : categorical ? true , : name : ID , : size 6 , : datatype : string }
(:datatype (meta (ds/column DT :ID)))
;; => :string
;; # Subset rows
# # Get all the flights with “ ” as the origin airport in the month of June .
ans < - flights[origin = = " JFK " & month = = 6L ]
;; --------- R
(def ans (r/bra R-flights '(& (== origin "JFK")
(== month 6))))
(r.utils/head ans)
= > year month day carrier origin dest air_time distance hour
1 : 2014 6 1 -9 -5 AA JFK LAX 324 2475 8
2 : 2014 6 1 -10 -13 AA JFK LAX 329 2475 12
3 : 2014 6 1 18 -1 AA JFK LAX 326 2475 7
4 : 2014 6 1 -6 -16 AA JFK LAX 320 2475 10
5 : 2014 6 1 -4 -45 AA JFK LAX 326 2475 18
6 : 2014 6 1 -6 -23 AA JFK LAX 329 2475 14
;; --------- Clojure
(def ans (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights))
;; TODO: maybe add head/tail for rows? or accept positive number (for head) and negative number (for tail) `
(ds/select-rows ans (range 6))
= > [ 6 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
;; | 2014 | 6 | 1 | -9 | -5 | AA | JFK | LAX | 324 | 2475 | 8 |
| 2014 | 6 | 1 | -10 | -13 | AA | JFK | LAX | 329 | 2475 | 12 |
| 2014 | 6 | 1 | 18 | -1 | AA | JFK | LAX | 326 | 2475 | 7 |
| 2014 | 6 | 1 | -6 | -16 | AA | JFK | LAX | 320 | 2475 | 10 |
| 2014 | 6 | 1 | -4 | -45 | AA | JFK | LAX | 326 | 2475 | 18 |
| 2014 | 6 | 1 | -6 | -23 | AA | JFK | LAX | 329 | 2475 | 14 |
# # Get first two rows from ` flights `
;; ans <- flights[1:2]
;; --------- R
(def ans (r/bra R-flights (r/colon 1 2)))
ans
= > year month day carrier origin dest air_time distance hour
1 : 2014 1 1 14 13 AA JFK LAX 359 2475 9
2 : 2014 1 1 -3 13 AA JFK LAX 363 2475 11
;; --------- Clojure
(def ans (ds/select-rows flights (range 2)))
ans
= > [ 2 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
| 2014 | 1 | 1 | 14 | 13 | AA | JFK | LAX | 359 | 2475 | 9 |
| 2014 | 1 | 1 | -3 | 13 | AA | JFK | LAX | 363 | 2475 | 11 |
# # Sort ` flights ` first by column ` origin ` in ascending order , and then by ` dest ` in descending order
;; ans <- flights[order(origin, -dest)]
;; --------- R
(def ans (r/bra R-flights '(order origin (- dest))))
(r.utils/head ans)
= > year month day carrier origin dest air_time distance hour
1 : 2014 1 5 6 49 EV EWR XNA 195 1131 8
2 : 2014 1 6 7 13 EV EWR XNA 190 1131 8
3 : 2014 1 7 -6 -13 EV EWR XNA 179 1131 8
4 : 2014 1 8 -7 -12 EV EWR XNA 184 1131 8
5 : 2014 1 9 16 7 EV EWR XNA 181 1131 8
6 : 2014 1 13 66 66 EV EWR XNA 188 1131 9
;; --------- Clojure
;; TODO: below I want to sort dataset by origin ascending and dest descending. Maybe such case should be
;; wrapped into the function? Writing comparators is not convinient in this quite common case.
(defn string-pair-comparator
[[o1 d1] [o2 d2]]
(let [compare-first (compare o1 o2)]
(if-not (zero? compare-first)
compare-first
(- (compare d1 d2)))))
(def ans (time (ds/sort-by #(vector (get % "origin")
(get % "dest"))
string-pair-comparator flights)))
(ds/select-rows ans (range 6))
= > [ 6 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
;; | 2014 | 6 | 3 | -6 | -38 | EV | EWR | XNA | 154 | 1131 | 6 |
| 2014 | 1 | 20 | -9 | -17 | EV | EWR | XNA | 177 | 1131 | 8 |
| 2014 | 3 | 19 | -6 | 10 | EV | EWR | XNA | 201 | 1131 | 6 |
| 2014 | 2 | 3 | 231 | 268 | EV | EWR | XNA | 184 | 1131 | 12 |
| 2014 | 4 | 25 | -8 | -32 | EV | EWR | XNA | 159 | 1131 | 6 |
| 2014 | 2 | 19 | 21 | 10 | EV | EWR | XNA | 176 | 1131 | 8 |
;; # Select column(s)
;; ## Select `arr_delay` column, but return it as a vector.
;; ans <- flights[, arr_delay]
;; --------- R
;; this should work but we have a bug in `clojisr` (addressed)
;; (def ans (r/bra R-flights nil 'arr_delay))
(def ans (r '(bra ~R-flights nil arr_delay)))
(r.utils/head ans)
= > [ 1 ] 13 13 9 -26 1 0
;; --------- Clojure
(def ans (flights "arr_delay"))
(take 6 ans)
= > ( 13 13 9 -26 1 0 )
;; or
(def ans (ds/column flights "arr_delay"))
(take 6 ans)
= > ( 13 13 9 -26 1 0 )
;; ## Select `arr_delay` column, but return as a data.table instead
;; ans <- flights[, list(arr_delay)]
;; --------- R
(def ans (r '(bra ~R-flights nil [:!list arr_delay])))
(r.utils/head ans)
;; => arr_delay
1 : 13
2 : 13
3 : 9
4 : -26
5 : 1
6 : 0
;; --------- Clojure
(def ans (ds/select-columns flights ["arr_delay"]))
(ds/select-rows ans (range 6))
= > [ 6 1 ] :
|
;; |-----------|
| 13 |
| 13 |
| 9 |
;; | -26 |
| 1 |
;; | 0 |
TODO : question : consider IFn returns dataset by default . Arguments :
;; * column name - returns dataset with single column
;; * sequence of columns - returns dataset with selected columns
;; * map - returns dataset with selected and renamed columns
;; ## Select both `arr_delay` and `dep_delay` columns
ans < - flights [ , .(arr_delay , ) ]
;; ans <- flights[, list(arr_delay, dep_delay)]
;; --------- R
(def ans (r '(bra ~R-flights nil (. arr_delay dep_delay))))
(r.utils/head ans)
;; => arr_delay dep_delay
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
;; or
(def ans (r '(bra ~R-flights nil [:!list arr_delay dep_delay])))
(r.utils/head ans)
;; => arr_delay dep_delay
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
;; --------- Clojure
(def ans (ds/select-columns flights ["arr_delay" "dep_delay"]))
(ds/select-rows ans (range 6))
= > [ 6 2 ] :
| dep_delay |
;; |-----------+-----------|
| 13 | 14 |
;; | 13 | -3 |
| 9 | 2 |
;; | -26 | -8 |
| 1 | 2 |
;; | 0 | 4 |
# # Select both ` arr_delay ` and ` dep_delay ` columns and rename them to ` ` and ` delay_dep `
ans < - flights [ , = arr_delay , delay_dep = ) ]
;; --------- R
(def ans (r '(bra ~R-flights nil (. :delay_arr arr_delay :delay_dep dep_delay))))
(r.utils/head ans)
= > delay_dep
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
;; --------- Clojure
;; TODO: Propose to do as in R, when you provide a map to `select` names will be changed
(def ans (-> (ds/select-columns flights ["arr_delay" "dep_delay"])
(ds/rename-columns {"arr_delay" "delay_arr"
"dep_delay" "delay_dep"})))
(ds/select-rows ans (range 6))
= > [ 6 2 ] :
| delay_arr | delay_dep |
;; |-----------+-----------|
| 13 | 14 |
;; | 13 | -3 |
| 9 | 2 |
;; | -26 | -8 |
| 1 | 2 |
;; | 0 | 4 |
;; ## How many trips have had total delay < 0?
;; ans <- flights[, sum( (arr_delay + dep_delay) < 0 )]
;; --------- R
(def ans (r '(bra ~R-flights nil (sum (< (+ arr_delay dep_delay) 0)))))
ans
= > [ 1 ] 141814
;; --------- Clojure
;; TODO: maybe ds should be also countable?
(def ans (-> (ds/filter #(neg? (+ (get % "arr_delay")
(get % "dep_delay"))) flights)
(ds/row-count)))
ans
;; => 141814
# # Calculate the average arrival and departure delay for all flights with “ ” as the origin airport in the month of June .
ans < - flights[origin = = " JFK " & month = = 6L ,
;; .(m_arr = mean(arr_delay), m_dep = mean(dep_delay))]
;; --------- R
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'(. :m_arr (mean arr_delay)
:m_dep (mean dep_delay))))
ans
;; => m_arr m_dep
1 : 5.839349 9.807884
;; --------- Clojure
;; TODO: I would prefer to get dataset here
(def ans (->> (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/select-columns ["arr_delay" "dep_delay"]))
(map dfn/mean)))
ans
= > ( 5.839349323200929 9.807884113037279 )
;; or
(defn aggregate
([agg-fns-map ds]
(aggregate {} agg-fns-map ds))
([m agg-fns-map ds]
(into m (map (fn [[k agg-fn]]
[k (agg-fn ds)]) agg-fns-map))))
(def aggregate->dataset (comp ds/->dataset vector aggregate))
(def ans (->> (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/select-columns ["arr_delay" "dep_delay"]))
(aggregate->dataset {:m_arr #(dfn/mean (ds/column % "arr_delay"))
:m_dep #(dfn/mean (ds/column % "dep_delay"))})))
ans
= > _ unnamed [ 1 2 ] :
| : | : m_dep |
;; |--------+--------|
| 5.839 | 9.808 |
# # How many trips have been made in 2014 from “ ” airport in the month of June ?
ans < - flights[origin = = " JFK " & month = = 6L , length(dest ) ]
ans < - flights[origin = = " JFK " & month = = 6L , .N ]
;; --------- R
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'(length dest)))
ans
= > [ 1 ] 8422
;; or
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'.N))
ans
= > [ 1 ] 8422
;; --------- Clojure
(def ans (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/row-count)))
ans
= > 8422
;; ## Select both arr_delay and dep_delay columns the data.frame way.
;; ## Select columns named in a variable using the .. prefix
;; ## Select columns named in a variable using with = FALSE
;; ans <- flights[, c("arr_delay", "dep_delay")]
;; select_cols = c("arr_delay", "dep_delay")
;; flights[ , ..select_cols]
;; flights[ , select_cols, with = FALSE]
;; --------- R
(def ans (r '(bra ~R-flights nil ["arr_delay" "dep_delay"])))
(r.utils/head ans)
;; => arr_delay dep_delay
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
;; or
(def select_cols (r.base/<- 'select_cols ["arr_delay" "dep_delay"]))
(r '(bra ~R-flights nil ..select_cols))
;; => arr_delay dep_delay
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
;; ---
;; 253312: -30 1
253313 : -14 -5
253314 : 16 -8
253315 : 15 -4
253316 : 1 -5
;; or
(r '(bra ~R-flights nil select_cols :with false))
;; => arr_delay dep_delay
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
;; ---
;; 253312: -30 1
253313 : -14 -5
253314 : 16 -8
253315 : 15 -4
253316 : 1 -5
;; --------- Clojure
(def select_cols ["arr_delay" "dep_delay"])
(ds/select-columns flights select_cols)
= > [ 253316 2 ] :
| dep_delay |
;; |-----------+-----------|
| 13 | 14 |
;; | 13 | -3 |
| 9 | 2 |
;; | -26 | -8 |
| 1 | 2 |
;; | 0 | 4 |
;; | -18 | -2 |
;; | -14 | -3 |
;; | -17 | -1 |
;; | -14 | -2 |
;; | -17 | -5 |
;; | -5 | 7 |
| 1 | 3 |
| 133 | 142 |
;; | -26 | -5 |
;; | 69 | 18 |
;; | 36 | 25 |
| 1 | -1 |
| 185 | 191 |
;; | -6 | -7 |
;; | 0 | -7 |
;; | -17 | -8 |
;; | 15 | -2 |
| 1 | -3 |
| 42 | 44 |
;; ## Deselect columns
;; ans <- flights[, !c("arr_delay", "dep_delay")]
;; ans <- flights[, -c("arr_delay", "dep_delay")]
;; --------- R
(r '(bra ~R-flights nil (! ["arr_delay" "dep_delay"])))
;; => year month day carrier origin dest air_time distance hour
1 : 2014 1 1 AA JFK LAX 359 2475 9
2 : 2014 1 1 AA JFK LAX 363 2475 11
3 : 2014 1 1 AA JFK LAX 351 2475 19
4 : 2014 1 1 AA LGA PBI 157 1035 7
5 : 2014 1 1 AA JFK LAX 350 2475 13
;; ---
253312 : 2014 10 31 UA LGA IAH 201 1416 14
253313 : 2014 10 31 UA EWR IAH 189 1400 8
253314 : 2014 10 31 MQ LGA RDU 83 431 11
: 2014 10 31 MQ LGA DTW 75 502 11
253316 : 2014 10 31 MQ LGA SDF 110 659 8
;; or
(r '(bra ~R-flights nil (- ["arr_delay" "dep_delay"])))
;; => year month day carrier origin dest air_time distance hour
1 : 2014 1 1 AA JFK LAX 359 2475 9
2 : 2014 1 1 AA JFK LAX 363 2475 11
3 : 2014 1 1 AA JFK LAX 351 2475 19
4 : 2014 1 1 AA LGA PBI 157 1035 7
5 : 2014 1 1 AA JFK LAX 350 2475 13
;; ---
253312 : 2014 10 31 UA LGA IAH 201 1416 14
253313 : 2014 10 31 UA EWR IAH 189 1400 8
253314 : 2014 10 31 MQ LGA RDU 83 431 11
: 2014 10 31 MQ LGA DTW 75 502 11
253316 : 2014 10 31 MQ LGA SDF 110 659 8
;; --------- Clojure
(ds/remove-columns flights ["arr_delay" "dep_delay"])
= > [ 253316 9 ] :
| year | month | day | carrier | origin | dest | air_time | distance | hour |
;; |------+-------+-----+---------+--------+------+----------+----------+------|
| 2014 | 1 | 1 | AA | JFK | LAX | 359 | 2475 | 9 |
| 2014 | 1 | 1 | AA | JFK | LAX | 363 | 2475 | 11 |
| 2014 | 1 | 1 | AA | JFK | LAX | 351 | 2475 | 19 |
| 2014 | 1 | 1 | AA | LGA | PBI | 157 | 1035 | 7 |
| 2014 | 1 | 1 | AA | JFK | LAX | 350 | 2475 | 13 |
| 2014 | 1 | 1 | AA | EWR | LAX | 339 | 2454 | 18 |
| 2014 | 1 | 1 | AA | JFK | LAX | 338 | 2475 | 21 |
| 2014 | 1 | 1 | AA | JFK | LAX | 356 | 2475 | 15 |
| 2014 | 1 | 1 | AA | JFK | MIA | 161 | 1089 | 15 |
| 2014 | 1 | 1 | AA | JFK | SEA | 349 | 2422 | 18 |
| 2014 | 1 | 1 | AA | EWR | MIA | 161 | 1085 | 16 |
| 2014 | 1 | 1 | AA | JFK | SFO | 365 | 2586 | 17 |
| 2014 | 1 | 1 | AA | JFK | BOS | 39 | 187 | 12 |
| 2014 | 1 | 1 | AA | JFK | LAX | 345 | 2475 | 19 |
| 2014 | 1 | 1 | AA | JFK | BOS | 35 | 187 | 17 |
| 2014 | 1 | 1 | AA | JFK | ORD | 155 | 740 | 17 |
| 2014 | 1 | 1 | AA | JFK | IAH | 234 | 1417 | 16 |
| 2014 | 1 | 1 | AA | JFK | AUS | 232 | 1521 | 17 |
| 2014 | 1 | 1 | AA | EWR | DFW | 214 | 1372 | 16 |
| 2014 | 1 | 1 | AA | LGA | ORD | 142 | 733 | 5 |
| 2014 | 1 | 1 | AA | LGA | ORD | 143 | 733 | 6 |
| 2014 | 1 | 1 | AA | LGA | ORD | 139 | 733 | 6 |
| 2014 | 1 | 1 | AA | LGA | ORD | 145 | 733 | 7 |
| 2014 | 1 | 1 | AA | LGA | ORD | 139 | 733 | 8 |
| 2014 | 1 | 1 | AA | LGA | ORD | 141 | 733 | 10 |
;;
;; # Aggregation
;;
(defn map-v [f coll]
(reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))
;; ## How can we get the number of trips corresponding to each origin airport?
;; ans <- flights[, .(.N), by = .(origin)]
;; ans <- flights[, .(.N), by = "origin"]
;; --------- R
(def ans (r '(bra ~R-flights nil (. .N) :by (. origin))))
ans
;; => origin N
1 : JFK 81483
2 : LGA 84433
3 : EWR 87400
;; or
(def ans (r '(bra ~R-flights nil (. .N) :by "origin")))
ans
;; => origin N
1 : JFK 81483
2 : LGA 84433
3 : EWR 87400
;; --------- Clojure
;; TODO: maybe add `group-by-and-aggregate` which returns dataset after group-by and aggregation?
(def ans (->> flights
(ds/group-by-column "origin")
(map-v ds/row-count)))
ans
= > { " EWR " 87400 , " LGA " 84433 , " " 81483 }
;; or (wrong)
(def ans (->> flights
(ds/group-by-column "origin")
(map-v (comp vector ds/row-count))
(ds/name-values-seq->dataset)))
ans
= > _ unnamed [ 1 3 ] :
;; | EWR | LGA | JFK |
;; |-------+-------+-------|
;; | 87400 | 84433 | 81483 |
;; or (good)
(defn group-by-columns-and-aggregate
[gr-colls agg-fns-map ds]
(->> (ds/group-by identity gr-colls ds)
(map (fn [[group-idx group-ds]]
(aggregate group-idx agg-fns-map group-ds)))
ds/->dataset))
(def ans (group-by-columns-and-aggregate ["origin"] {"N" ds/row-count} flights))
ans
= > _ unnamed [ 3 2 ] :
;; | origin | N |
;; |--------+-------|
;; | LGA | 84433 |
;; | EWR | 87400 |
;; | JFK | 81483 |
# # How can we calculate the number of trips for each origin airport for carrier code " AA " ?
ans < - flights[carrier = = " AA " , .N , by = origin ]
;; --------- R
(def ans (r/bra R-flights '(== carrier "AA") '.N :by 'origin))
ans
;; => origin N
1 : 11923
2 : LGA 11730
3 : EWR 2649
;; --------- Clojure
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin"] {"N" ds/row-count})))
ans
= > _ unnamed [ 3 2 ] :
;; | origin | N |
;; |--------+-------|
;; | LGA | 11730 |
;; | EWR | 2649 |
;; | JFK | 11923 |
# # How can we get the total number of trips for each origin , dest pair for carrier code " AA " ?
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest ) ]
;; --------- R
(def ans (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest)))
(r.utils/head ans)
;; => origin dest N
1 : JFK LAX 3387
2 : LGA PBI 245
3 : EWR LAX 62
4 : JFK MIA 1876
5 : JFK SEA 298
6 : EWR MIA 848
;; or
(def ans (r/bra R-flights '(== carrier "AA") '.N :by ["origin" "dest"]))
(r.utils/head ans)
;; => origin dest N
1 : JFK LAX 3387
2 : LGA PBI 245
3 : EWR LAX 62
4 : JFK MIA 1876
5 : JFK SEA 298
6 : EWR MIA 848
;; --------- Clojure
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest"] {"N" ds/row-count})))
(ds/select-rows ans (range 6))
= > _ unnamed [ 6 3 ] :
;; | origin | dest | N |
;; |--------+------+------|
| EWR | PHX | 121 |
;; | LGA | MIA | 3334 |
;; | JFK | LAX | 3387 |
;; | JFK | IAH | 7 |
| | LAS | 595 |
| JFK | MCO | 597 |
# # How can we get the average arrival and departure delay for each orig , dest pair for each month for carrier code " AA " ?
;; ans <- flights[carrier == "AA",
;; .(mean(arr_delay), mean(dep_delay)),
;; by = .(origin, dest, month)]
;; --------- R
(def ans (r/bra R-flights '(== carrier "AA") '(. (mean arr_delay)
(mean dep_delay)) :by '(. origin dest month)))
ans
= > origin dest month V1 V2
1 : JFK LAX 1 6.590361 14.2289157
2 : LGA PBI 1 -7.758621 0.3103448
3 : EWR LAX 1 1.366667 7.5000000
4 : MIA 1 15.720670 18.7430168
5 : JFK SEA 1 14.357143 30.7500000
;; ---
196 : LGA MIA 10 -6.251799 -1.4208633
197 : MIA 10 -1.880184 6.6774194
198 : EWR PHX 10 -3.032258 -4.2903226
199 : JFK MCO 10 -10.048387 -1.6129032
200 : DCA 10 16.483871 15.5161290
;; --------- Clojure
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest" "month"]
{"V1" #(dfn/mean (% "arr_delay"))
"V2" #(dfn/mean (% "dep_delay"))})))
ans
= > _ unnamed [ 200 5 ] :
;; | origin | dest | month | V2 | V1 |
;; |--------+------+-------+---------+---------|
| JFK | SEA | 9 | 16.83 | 8.567 |
| JFK | MCO | 2 | 10.15 | 8.453 |
| LGA | MIA | 1 | 5.417 | 6.130 |
| | LAS | 3 | 6.869 | 13.18 |
| | LAS | 1 | 19.15 | 17.69 |
| LGA | MIA | 4 | 0.6552 | -3.828 |
| JFK | EGE | 2 | 57.46 | 53.79 |
| LGA | DFW | 3 | -1.285 | -0.2461 |
| EWR | DFW | 8 | 22.07 | 16.94 |
;; | LGA | MIA | 6 | 8.467 | -2.458 |
| LGA | PBI | 5 | -6.857 | -10.36 |
| EWR | PHX | 9 | -1.667 | -4.233 |
| JFK | SAN | 9 | 12.83 | 18.80 |
| JFK | SFO | 3 | 10.03 | 5.586 |
| JFK | AUS | 4 | -0.1333 | 4.367 |
| JFK | SAN | 8 | 14.19 | 10.74 |
| LGA | ORD | 6 | 17.30 | 18.91 |
| JFK | SFO | 9 | 6.207 | 7.233 |
| LGA | DFW | 10 | 4.553 | 3.500 |
| JFK | ORD | 7 | 34.39 | 23.14 |
| JFK | SJU | 9 | 11.38 | 1.688 |
| JFK | SEA | 7 | 20.55 | 21.97 |
| | LAS | 10 | 14.55 | 18.23 |
| JFK | ORD | 2 | 41.74 | 34.11 |
| JFK | STT | 6 | 0.9667 | -4.667 |
;; ## So how can we directly order by all the grouping variables?
;; ans <- flights[carrier == "AA",
;; .(mean(arr_delay), mean(dep_delay)),
= .(origin , dest , month ) ]
;; --------- R
(def ans (r/bra R-flights '(== carrier "AA") '(. (mean arr_delay)
(mean dep_delay)) :keyby '(. origin dest month)))
ans
= > origin dest month V1 V2
1 : EWR DFW 1 6.427673 10.0125786
2 : EWR DFW 2 10.536765 11.3455882
3 : EWR DFW 3 12.865031 8.0797546
4 : EWR DFW 4 17.792683 12.9207317
5 : EWR DFW 5 18.487805 18.6829268
;; ---
196 : LGA PBI 1 -7.758621 0.3103448
197 : LGA PBI 2 -7.865385 2.4038462
198 : LGA PBI 3 -5.754098 3.0327869
199 : LGA PBI 4 -13.966667 -4.7333333
200 : LGA PBI 5 -10.357143 -6.8571429
;; --------- Clojure
(defn asc-desc-comparator
[orders]
(if (every? #(= % :asc) orders)
compare
(let [mults (map #(if (= % :asc) 1 -1) orders)]
(fn [v1 v2]
(reduce (fn [_ [a b mult]]
(let [c (compare a b)]
(if-not (zero? c)
(reduced (* mult c))
c))) 0 (map vector v1 v2 mults))))))
(defn sort-by-columns-with-orders
([cols ds]
(sort-by-columns-with-orders cols (repeat (count cols) :asc) ds))
([cols orders ds]
(let [sel (apply juxt (map #(fn [ds] (get ds %)) cols))
comp-fn (asc-desc-comparator orders)]
(ds/sort-by sel comp-fn ds))))
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest" "month"]
{"V1" #(dfn/mean (% "arr_delay"))
"V2" #(dfn/mean (% "dep_delay"))})
(sort-by-columns-with-orders ["origin" "dest" "month"])))
ans
= > _ unnamed [ 200 5 ] :
| origin | dest | month | V2 | V1 |
;; |--------+------+-------+--------+---------|
| EWR | DFW | 1 | 10.01 | 6.428 |
| EWR | DFW | 2 | 11.35 | 10.54 |
| EWR | DFW | 3 | 8.080 | 12.87 |
| EWR | DFW | 4 | 12.92 | 17.79 |
| EWR | DFW | 5 | 18.68 | 18.49 |
| EWR | DFW | 6 | 38.74 | 37.01 |
| EWR | DFW | 7 | 21.15 | 20.25 |
| EWR | DFW | 8 | 22.07 | 16.94 |
| EWR | DFW | 9 | 13.06 | 5.865 |
| EWR | DFW | 10 | 18.89 | 18.81 |
| EWR | LAX | 1 | 7.500 | 1.367 |
| EWR | LAX | 2 | 4.111 | 10.33 |
;; | EWR | LAX | 3 | -6.800 | -4.400 |
| EWR | MIA | 1 | 12.12 | 11.01 |
| EWR | MIA | 2 | 4.756 | 1.564 |
| EWR | MIA | 3 | 0.4444 | -4.111 |
| EWR | MIA | 4 | 6.433 | 3.189 |
| EWR | MIA | 5 | 6.344 | -2.538 |
| EWR | MIA | 6 | 16.20 | 7.307 |
| EWR | MIA | 7 | 26.35 | 25.22 |
| EWR | MIA | 8 | 0.8462 | -6.125 |
;; | EWR | MIA | 9 | 0.3594 | -0.9063 |
;; | EWR | MIA | 10 | -3.787 | -4.475 |
;; | EWR | PHX | 7 | 0.2759 | -5.103 |
| EWR | PHX | 8 | 6.226 | 3.548 |
;; ## How can we order ans using the columns origin in ascending order, and dest in descending order?
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest ) ]
;; ans <- ans[order(origin, -dest)]
;;
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest)][order(origin , -dest ) ]
;; --------- R
(def ans (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest)))
(def ans (r/bra ans '(order origin (- dest))))
(r.utils/head ans)
;; => origin dest N
1 : EWR PHX 121
2 : EWR MIA 848
3 : EWR LAX 62
4 : EWR DFW 1618
5 : JFK STT 229
6 : JFK SJU 690
;; or
(def ans (-> (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest))
(r/bra '(order origin (- dest)))))
(r.utils/head ans)
;; => origin dest N
1 : EWR PHX 121
2 : EWR MIA 848
3 : EWR LAX 62
4 : EWR DFW 1618
5 : JFK STT 229
6 : JFK SJU 690
;; --------- Clojure
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest"]
{"N" ds/row-count})
(sort-by-columns-with-orders ["origin" "dest"] [:asc :desc])))
(ds/select-rows ans (range 6))
= > _ unnamed [ 6 3 ] :
;; | origin | dest | N |
;; |--------+------+------|
| EWR | PHX | 121 |
| EWR | MIA | 848 |
| EWR | LAX | 62 |
;; | EWR | DFW | 1618 |
| JFK | STT | 229 |
| JFK | SJU | 690 |
;; ## Can by accept expressions as well or does it just take columns
ans < - flights [ , .N , .(dep_delay>0 , arr_delay>0 ) ]
;; --------- R
(def ans (r '(bra ~R-flights nil .N (. (> dep_delay 0)
(> arr_delay 0)))))
ans
= > N
1 : TRUE TRUE 72836
2 : FALSE TRUE 34583
3 : FALSE FALSE 119304
4 : TRUE FALSE 26593
;; --------- Clojure
;; TODO: group by inline transformation on several columns
;; changed to `new-column`
(def ans (->> (-> flights
(ds/new-column :pos_dep_delay (dfn/> (flights "dep_delay") 0))
(ds/new-column :pos_arr_delay (dfn/> (flights "arr_delay") 0)))
(group-by-columns-and-aggregate [:pos_dep_delay :pos_arr_delay]
{"N" ds/row-count})))
ans
= > _ unnamed [ 4 3 ] :
;; | :pos_dep_delay | :pos_arr_delay | N |
;; |----------------+----------------+--------|
;; | false | true | 34583 |
| true | false | 26593 |
;; | false | false | 119304 |
;; | true | true | 72836 |
;; ## Do we have to compute mean() for each column individually?
DT
;; DT[, print(.SD), by = ID]
DT [ , lapply(.SD , mean ) , by = ID ]
;; --------- R
R-DT
;; => ID a b c
1 : b 1 7 13
2 : b 2 8 14
3 : b 3 9 15
4 : c 4 10 16
5 : c 5 11 17
6 : a 6 12 18
(r '(bra ~R-DT nil (print .SD) :by ID))
= > Empty data.table ( 0 rows and 1 cols ): ID
;; prints:
;; a b c
1 : 1 7 13
2 : 2 8 14
3 : 3 9 15
;; a b c
1 : 4 10 16
2 : 5 11 17
;; a b c
1 : 6 12 18
(r '(bra ~R-DT nil (lapply .SD mean) :by ID))
;; => ID a b c
1 : b 2.0 8.0 14.0
2 : c 4.5 10.5 16.5
3 : a 6.0 12.0 18.0
;; --------- Clojure
DT
= > _ unnamed [ 6 4 ] :
;; | :ID | :a | :b | :c |
;; |-----+----+----+----|
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
;; | c | 4 | 10 | 16 |
;; | c | 5 | 11 | 17 |
;; | a | 6 | 12 | 18 |
(ds/group-by-column :ID DT)
= > { " a " a [ 1 4 ] :
;; | :ID | :a | :b | :c |
;; |-----+----+----+----|
;; | a | 6 | 12 | 18 |
, " b " b [ 3 4 ] :
;; | :ID | :a | :b | :c |
;; |-----+----+----+----|
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
, " c " c [ 2 4 ] :
;; | :ID | :a | :b | :c |
;; |-----+----+----+----|
;; | c | 4 | 10 | 16 |
;; | c | 5 | 11 | 17 |
;; }
(group-by-columns-and-aggregate [:ID]
(into {} (map (fn [col]
[col #(dfn/mean (% col))])
(rest (ds/column-names DT)))) DT)
= > _ unnamed [ 3 4 ] :
;; | :ID | :c | :b | :a |
|-----+-------+-------+-------|
;; | a | 18.00 | 12.00 | 6.000 |
;; | b | 14.00 | 8.000 | 2.000 |
| c | 16.50 | 10.50 | 4.500 |
;; ## How can we specify just the columns we would like to compute the mean() on?
flights[carrier = = " AA " , # # Only on trips with carrier " AA "
;; lapply(.SD, mean), ## compute the mean
by = .(origin , dest , month ) , # # for every ' origin , dest , month '
.SDcols = c("arr_delay " , " dep_delay " ) ] # # for just those specified in .SDcols
;; --------- R
(r/bra R-flights
'(== carrier "AA")
'(lapply .SD mean)
:by '(. origin dest month)
:.SDcols ["arr_delay", "dep_delay"])
= > origin dest month arr_delay dep_delay
1 : JFK LAX 1 6.590361 14.2289157
2 : LGA PBI 1 -7.758621 0.3103448
3 : EWR LAX 1 1.366667 7.5000000
4 : MIA 1 15.720670 18.7430168
5 : JFK SEA 1 14.357143 30.7500000
;; ---
196 : LGA MIA 10 -6.251799 -1.4208633
197 : MIA 10 -1.880184 6.6774194
198 : EWR PHX 10 -3.032258 -4.2903226
199 : JFK MCO 10 -10.048387 -1.6129032
200 : DCA 10 16.483871 15.5161290
;; --------- Clojure
(->> flights
(ds/filter #(= (get % "carrier") "AA"))
(group-by-columns-and-aggregate ["origin", "dest", "month"]
(into {} (map (fn [col]
[col #(dfn/mean (% col))])
["arr_delay" "dep_delay"]))))
= > _ unnamed [ 200 5 ] :
| origin | dest | month | dep_delay | arr_delay |
;; |--------+------+-------+-----------+-----------|
| JFK | SEA | 9 | 16.83 | 8.567 |
| JFK | MCO | 2 | 10.15 | 8.453 |
| LGA | MIA | 1 | 5.417 | 6.130 |
| | LAS | 3 | 6.869 | 13.18 |
| | LAS | 1 | 19.15 | 17.69 |
;; | LGA | MIA | 4 | 0.6552 | -3.828 |
| JFK | EGE | 2 | 57.46 | 53.79 |
| LGA | DFW | 3 | -1.285 | -0.2461 |
| EWR | DFW | 8 | 22.07 | 16.94 |
| LGA | MIA | 6 | 8.467 | -2.458 |
| LGA | PBI | 5 | -6.857 | |
;; | EWR | PHX | 9 | -1.667 | -4.233 |
| JFK | SAN | 9 | 12.83 | 18.80 |
| JFK | SFO | 3 | 10.03 | 5.586 |
| JFK | AUS | 4 | -0.1333 | 4.367 |
| JFK | SAN | 8 | 14.19 | 10.74 |
| LGA | ORD | 6 | 17.30 | 18.91 |
| JFK | SFO | 9 | 6.207 | 7.233 |
| LGA | DFW | 10 | 4.553 | 3.500 |
| JFK | ORD | 7 | 34.39 | 23.14 |
| JFK | SJU | 9 | 11.38 | 1.688 |
| JFK | SEA | 7 | 20.55 | 21.97 |
| | LAS | 10 | 14.55 | 18.23 |
| JFK | ORD | 2 | 41.74 | 34.11 |
;; | JFK | STT | 6 | 0.9667 | -4.667 |
# # How can we return the first two rows for each month ?
ans < - flights [ , head(.SD , 2 ) , by = month ]
;; --------- R
(def ans (r '(bra ~R-flights nil (head .SD 2) :by month)))
(r.utils/head ans)
= > month year day carrier origin dest air_time distance hour
1 : 1 2014 1 14 13 AA JFK LAX 359 2475 9
2 : 1 2014 1 -3 13 AA JFK LAX 363 2475 11
3 : 2 2014 1 -1 1 AA JFK LAX 358 2475 8
4 : 2 2014 1 -5 3 AA JFK LAX 358 2475 11
5 : 3 2014 1 -11 36 AA JFK LAX 375 2475 8
6 : 3 2014 1 -3 14 AA JFK LAX 368 2475 11
;; --------- Clojure
(def ans (->> flights
(ds/group-by-column "month")
(vals)
(map #(ds/select-rows % [1 2]))
(reduce ds/concat)))
(ds/select-rows ans (range 6))
= > null [ 6 11 ] :
| dep_delay | origin | air_time | hour | arr_delay | dest | distance | year | month | day | carrier |
;; |-----------+--------+----------+------+-----------+------+----------+------+-------+-----+---------|
| -6 | EWR | 320 | 9 | -14 | LAX | 2454 | 2014 | 7 | 1 | VX |
| -3 | EWR | 326 | 12 | -14 | LAX | 2454 | 2014 | 7 | 1 | VX |
| -3 | JFK | 363 | 11 | 13 | LAX | 2475 | 2014 | 1 | 1 | AA |
| 2 | JFK | 351 | 19 | 9 | LAX | 2475 | 2014 | 1 | 1 | AA |
| -8 | LGA | 71 | 18 | -11 | RDU | 431 | 2014 | 4 | 1 | MQ |
| -4 | LGA | 113 | 8 | -2 | BNA | 764 | 2014 | 4 | 1 | MQ |
;; ## How can we concatenate columns a and b for each group in ID?
;; DT[, .(val = c(a,b)), by = ID]
;; --------- R
(r '(bra ~R-DT nil (. :val [a b]) :by ID))
= >
1 : b 1
2 : b 2
3 : b 3
4 : b 7
5 : b 8
6 : b 9
7 : c 4
8 : c 5
9 : c 10
10 : c 11
11 : a 6
12 : a 12
;; --------- Clojure
;; TODO: reshape?
(ds/concat (-> (ds/select-columns DT [:ID :a])
(ds/rename-columns {:a :val}))
(-> (ds/select-columns DT [:ID :b])
(ds/rename-columns {:b :val})))
= > null [ 12 2 ] :
;; | :ID | :val |
;; |-----+------|
;; | b | 1 |
;; | b | 2 |
;; | b | 3 |
;; | c | 4 |
;; | c | 5 |
;; | a | 6 |
;; | b | 7 |
;; | b | 8 |
;; | b | 9 |
| c | 10 |
| c | 11 |
| a | 12 |
;; ## What if we would like to have all the values of column a and b concatenated, but returned as a list column?
;; --------- R
DT [ , .(val = list(c(a , b ) ) ) , by = ID ]
(r '(bra ~R-DT nil (. :val (list [a b])) :by ID))
;; => ID val
1 : b 1,2,3,7,8,9
2 : c 4 , 5,10,11
3 : a 6,12
;; --------- Clojure
(group-by-columns-and-aggregate [:ID]
{:val #(concat (% :a) (% :b))}
DT)
= > _ unnamed [ 3 2 ] :
;; | :ID | :val |
;; |-----+-------------------------------|
;; | a | clojure.lang.LazySeq@487 |
;; | b | clojure.lang.LazySeq@36b8bb47 |
;; | c | clojure.lang.LazySeq@ffd03 |
;; or
;; TODO: printing should realize sequences
(group-by-columns-and-aggregate [:ID]
{:val #(vec (concat (seq (% :a)) (seq (% :b))))}
DT)
= > _ unnamed [ 3 2 ] :
| : ID | : |
;; |-----+---------------|
| a | [ 6 12 ] |
| b | [ 1 2 3 7 8 9 ] |
| c | [ 4 5 10 11 ] |
| null | https://raw.githubusercontent.com/genmeblog/techtest/4b8111fde17fcffd7f7fb6fa9454d030f1847adc/src/techtest/core.clj | clojure | created with tech.ml.dataset version "2.0-beta-24"
further versions may simplify some things
Working thrugh R `data.table` type and confronting with tech.ml.dataset
-project.org/web/packages/data.table/vignettes/datatable-intro.html
# Preparation
load R package
# Read data from URL
input <- ""
flights <- fread(input)
--------- R
--------- Clojure
# Taking the shape of loaded data
dim(flights)
--------- R
--------- Clojure
TODO: maybe add those numbers to a metadata? Like in `column` case?
=> {:name ""}
# Basics
## What is `data.table`?
DT = data.table(
ID = c("b","b","b","a","a","c"),
b = 7:12,
)
class(DT$ID)
--------- R
=> ID a b c
--------- Clojure
| :ID | :a | :b | :c |
|-----+----+----+----|
| c | 4 | 10 | 16 |
| c | 5 | 11 | 17 |
| a | 6 | 12 | 18 |
=> :string
# Subset rows
--------- R
--------- Clojure
TODO: maybe add head/tail for rows? or accept positive number (for head) and negative number (for tail) `
| 2014 | 6 | 1 | -9 | -5 | AA | JFK | LAX | 324 | 2475 | 8 |
ans <- flights[1:2]
--------- R
--------- Clojure
ans <- flights[order(origin, -dest)]
--------- R
--------- Clojure
TODO: below I want to sort dataset by origin ascending and dest descending. Maybe such case should be
wrapped into the function? Writing comparators is not convinient in this quite common case.
| 2014 | 6 | 3 | -6 | -38 | EV | EWR | XNA | 154 | 1131 | 6 |
# Select column(s)
## Select `arr_delay` column, but return it as a vector.
ans <- flights[, arr_delay]
--------- R
this should work but we have a bug in `clojisr` (addressed)
(def ans (r/bra R-flights nil 'arr_delay))
--------- Clojure
or
## Select `arr_delay` column, but return as a data.table instead
ans <- flights[, list(arr_delay)]
--------- R
=> arr_delay
--------- Clojure
|-----------|
| -26 |
| 0 |
* column name - returns dataset with single column
* sequence of columns - returns dataset with selected columns
* map - returns dataset with selected and renamed columns
## Select both `arr_delay` and `dep_delay` columns
ans <- flights[, list(arr_delay, dep_delay)]
--------- R
=> arr_delay dep_delay
or
=> arr_delay dep_delay
--------- Clojure
|-----------+-----------|
| 13 | -3 |
| -26 | -8 |
| 0 | 4 |
--------- R
--------- Clojure
TODO: Propose to do as in R, when you provide a map to `select` names will be changed
|-----------+-----------|
| 13 | -3 |
| -26 | -8 |
| 0 | 4 |
## How many trips have had total delay < 0?
ans <- flights[, sum( (arr_delay + dep_delay) < 0 )]
--------- R
--------- Clojure
TODO: maybe ds should be also countable?
=> 141814
.(m_arr = mean(arr_delay), m_dep = mean(dep_delay))]
--------- R
=> m_arr m_dep
--------- Clojure
TODO: I would prefer to get dataset here
or
|--------+--------|
--------- R
or
--------- Clojure
## Select both arr_delay and dep_delay columns the data.frame way.
## Select columns named in a variable using the .. prefix
## Select columns named in a variable using with = FALSE
ans <- flights[, c("arr_delay", "dep_delay")]
select_cols = c("arr_delay", "dep_delay")
flights[ , ..select_cols]
flights[ , select_cols, with = FALSE]
--------- R
=> arr_delay dep_delay
or
=> arr_delay dep_delay
---
253312: -30 1
or
=> arr_delay dep_delay
---
253312: -30 1
--------- Clojure
|-----------+-----------|
| 13 | -3 |
| -26 | -8 |
| 0 | 4 |
| -18 | -2 |
| -14 | -3 |
| -17 | -1 |
| -14 | -2 |
| -17 | -5 |
| -5 | 7 |
| -26 | -5 |
| 69 | 18 |
| 36 | 25 |
| -6 | -7 |
| 0 | -7 |
| -17 | -8 |
| 15 | -2 |
## Deselect columns
ans <- flights[, !c("arr_delay", "dep_delay")]
ans <- flights[, -c("arr_delay", "dep_delay")]
--------- R
=> year month day carrier origin dest air_time distance hour
---
or
=> year month day carrier origin dest air_time distance hour
---
--------- Clojure
|------+-------+-----+---------+--------+------+----------+----------+------|
# Aggregation
## How can we get the number of trips corresponding to each origin airport?
ans <- flights[, .(.N), by = .(origin)]
ans <- flights[, .(.N), by = "origin"]
--------- R
=> origin N
or
=> origin N
--------- Clojure
TODO: maybe add `group-by-and-aggregate` which returns dataset after group-by and aggregation?
or (wrong)
| EWR | LGA | JFK |
|-------+-------+-------|
| 87400 | 84433 | 81483 |
or (good)
| origin | N |
|--------+-------|
| LGA | 84433 |
| EWR | 87400 |
| JFK | 81483 |
--------- R
=> origin N
--------- Clojure
| origin | N |
|--------+-------|
| LGA | 11730 |
| EWR | 2649 |
| JFK | 11923 |
--------- R
=> origin dest N
or
=> origin dest N
--------- Clojure
| origin | dest | N |
|--------+------+------|
| LGA | MIA | 3334 |
| JFK | LAX | 3387 |
| JFK | IAH | 7 |
ans <- flights[carrier == "AA",
.(mean(arr_delay), mean(dep_delay)),
by = .(origin, dest, month)]
--------- R
---
--------- Clojure
| origin | dest | month | V2 | V1 |
|--------+------+-------+---------+---------|
| LGA | MIA | 6 | 8.467 | -2.458 |
## So how can we directly order by all the grouping variables?
ans <- flights[carrier == "AA",
.(mean(arr_delay), mean(dep_delay)),
--------- R
---
--------- Clojure
|--------+------+-------+--------+---------|
| EWR | LAX | 3 | -6.800 | -4.400 |
| EWR | MIA | 9 | 0.3594 | -0.9063 |
| EWR | MIA | 10 | -3.787 | -4.475 |
| EWR | PHX | 7 | 0.2759 | -5.103 |
## How can we order ans using the columns origin in ascending order, and dest in descending order?
ans <- ans[order(origin, -dest)]
--------- R
=> origin dest N
or
=> origin dest N
--------- Clojure
| origin | dest | N |
|--------+------+------|
| EWR | DFW | 1618 |
## Can by accept expressions as well or does it just take columns
--------- R
--------- Clojure
TODO: group by inline transformation on several columns
changed to `new-column`
| :pos_dep_delay | :pos_arr_delay | N |
|----------------+----------------+--------|
| false | true | 34583 |
| false | false | 119304 |
| true | true | 72836 |
## Do we have to compute mean() for each column individually?
DT[, print(.SD), by = ID]
--------- R
=> ID a b c
prints:
a b c
a b c
a b c
=> ID a b c
--------- Clojure
| :ID | :a | :b | :c |
|-----+----+----+----|
| c | 4 | 10 | 16 |
| c | 5 | 11 | 17 |
| a | 6 | 12 | 18 |
| :ID | :a | :b | :c |
|-----+----+----+----|
| a | 6 | 12 | 18 |
| :ID | :a | :b | :c |
|-----+----+----+----|
| :ID | :a | :b | :c |
|-----+----+----+----|
| c | 4 | 10 | 16 |
| c | 5 | 11 | 17 |
}
| :ID | :c | :b | :a |
| a | 18.00 | 12.00 | 6.000 |
| b | 14.00 | 8.000 | 2.000 |
## How can we specify just the columns we would like to compute the mean() on?
lapply(.SD, mean), ## compute the mean
--------- R
---
--------- Clojure
|--------+------+-------+-----------+-----------|
| LGA | MIA | 4 | 0.6552 | -3.828 |
| EWR | PHX | 9 | -1.667 | -4.233 |
| JFK | STT | 6 | 0.9667 | -4.667 |
--------- R
--------- Clojure
|-----------+--------+----------+------+-----------+------+----------+------+-------+-----+---------|
## How can we concatenate columns a and b for each group in ID?
DT[, .(val = c(a,b)), by = ID]
--------- R
--------- Clojure
TODO: reshape?
| :ID | :val |
|-----+------|
| b | 1 |
| b | 2 |
| b | 3 |
| c | 4 |
| c | 5 |
| a | 6 |
| b | 7 |
| b | 8 |
| b | 9 |
## What if we would like to have all the values of column a and b concatenated, but returned as a list column?
--------- R
=> ID val
--------- Clojure
| :ID | :val |
|-----+-------------------------------|
| a | clojure.lang.LazySeq@487 |
| b | clojure.lang.LazySeq@36b8bb47 |
| c | clojure.lang.LazySeq@ffd03 |
or
TODO: printing should realize sequences
|-----+---------------| | (ns techtest.core
(:require [tech.ml.dataset :as ds]
[tech.ml.dataset.column :as col]
[tech.v2.datatype.functional :as dfn] ))
(require '[clojisr.v1.r :as r :refer [r]]
'[clojisr.v1.require :refer [require-r]])
(require-r '[base]
'[utils]
'[data.table :as dt])
(r.base/options :width 160)
(def R-flights (time (dt/fread "")))
(def flights (time (ds/->dataset "")))
(r.base/dim R-flights)
= > [ 1 ] 253316 11
= > 11
= > 253316
(meta flights)
a = 1:6 ,
c = 13:18
(def R-DT (dt/data-table :ID ["b" "b" "b" "c" "c" "a"]
:a (r/colon 1 6)
:b (r/colon 7 12)
:c (r/colon 13 18)))
R-DT
1 : b 1 7 13
2 : b 2 8 14
3 : b 3 9 15
4 : c 4 10 16
5 : c 5 11 17
6 : a 6 12 18
(r.base/class (r.base/$ R-DT 'ID))
= > [ 1 ] " character "
(def DT (ds/name-values-seq->dataset {:ID ["b" "b" "b" "c" "c" "a"]
:a (range 1 7)
:b (range 7 13)
:c (range 13 19)}))
DT
= > _ unnamed [ 6 4 ] :
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
(meta (DT :ID))
= > { : categorical ? true , : name : ID , : size 6 , : datatype : string }
(:datatype (meta (ds/column DT :ID)))
# # Get all the flights with “ ” as the origin airport in the month of June .
ans < - flights[origin = = " JFK " & month = = 6L ]
(def ans (r/bra R-flights '(& (== origin "JFK")
(== month 6))))
(r.utils/head ans)
= > year month day carrier origin dest air_time distance hour
1 : 2014 6 1 -9 -5 AA JFK LAX 324 2475 8
2 : 2014 6 1 -10 -13 AA JFK LAX 329 2475 12
3 : 2014 6 1 18 -1 AA JFK LAX 326 2475 7
4 : 2014 6 1 -6 -16 AA JFK LAX 320 2475 10
5 : 2014 6 1 -4 -45 AA JFK LAX 326 2475 18
6 : 2014 6 1 -6 -23 AA JFK LAX 329 2475 14
(def ans (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights))
(ds/select-rows ans (range 6))
= > [ 6 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
| 2014 | 6 | 1 | -10 | -13 | AA | JFK | LAX | 329 | 2475 | 12 |
| 2014 | 6 | 1 | 18 | -1 | AA | JFK | LAX | 326 | 2475 | 7 |
| 2014 | 6 | 1 | -6 | -16 | AA | JFK | LAX | 320 | 2475 | 10 |
| 2014 | 6 | 1 | -4 | -45 | AA | JFK | LAX | 326 | 2475 | 18 |
| 2014 | 6 | 1 | -6 | -23 | AA | JFK | LAX | 329 | 2475 | 14 |
# # Get first two rows from ` flights `
(def ans (r/bra R-flights (r/colon 1 2)))
ans
= > year month day carrier origin dest air_time distance hour
1 : 2014 1 1 14 13 AA JFK LAX 359 2475 9
2 : 2014 1 1 -3 13 AA JFK LAX 363 2475 11
(def ans (ds/select-rows flights (range 2)))
ans
= > [ 2 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
| 2014 | 1 | 1 | 14 | 13 | AA | JFK | LAX | 359 | 2475 | 9 |
| 2014 | 1 | 1 | -3 | 13 | AA | JFK | LAX | 363 | 2475 | 11 |
# # Sort ` flights ` first by column ` origin ` in ascending order , and then by ` dest ` in descending order
(def ans (r/bra R-flights '(order origin (- dest))))
(r.utils/head ans)
= > year month day carrier origin dest air_time distance hour
1 : 2014 1 5 6 49 EV EWR XNA 195 1131 8
2 : 2014 1 6 7 13 EV EWR XNA 190 1131 8
3 : 2014 1 7 -6 -13 EV EWR XNA 179 1131 8
4 : 2014 1 8 -7 -12 EV EWR XNA 184 1131 8
5 : 2014 1 9 16 7 EV EWR XNA 181 1131 8
6 : 2014 1 13 66 66 EV EWR XNA 188 1131 9
(defn string-pair-comparator
[[o1 d1] [o2 d2]]
(let [compare-first (compare o1 o2)]
(if-not (zero? compare-first)
compare-first
(- (compare d1 d2)))))
(def ans (time (ds/sort-by #(vector (get % "origin")
(get % "dest"))
string-pair-comparator flights)))
(ds/select-rows ans (range 6))
= > [ 6 11 ] :
| year | month | day | dep_delay | arr_delay | carrier | origin | dest | air_time | distance | hour |
|------+-------+-----+-----------+-----------+---------+--------+------+----------+----------+------|
| 2014 | 1 | 20 | -9 | -17 | EV | EWR | XNA | 177 | 1131 | 8 |
| 2014 | 3 | 19 | -6 | 10 | EV | EWR | XNA | 201 | 1131 | 6 |
| 2014 | 2 | 3 | 231 | 268 | EV | EWR | XNA | 184 | 1131 | 12 |
| 2014 | 4 | 25 | -8 | -32 | EV | EWR | XNA | 159 | 1131 | 6 |
| 2014 | 2 | 19 | 21 | 10 | EV | EWR | XNA | 176 | 1131 | 8 |
(def ans (r '(bra ~R-flights nil arr_delay)))
(r.utils/head ans)
= > [ 1 ] 13 13 9 -26 1 0
(def ans (flights "arr_delay"))
(take 6 ans)
= > ( 13 13 9 -26 1 0 )
(def ans (ds/column flights "arr_delay"))
(take 6 ans)
= > ( 13 13 9 -26 1 0 )
(def ans (r '(bra ~R-flights nil [:!list arr_delay])))
(r.utils/head ans)
1 : 13
2 : 13
3 : 9
4 : -26
5 : 1
6 : 0
(def ans (ds/select-columns flights ["arr_delay"]))
(ds/select-rows ans (range 6))
= > [ 6 1 ] :
|
| 13 |
| 13 |
| 9 |
| 1 |
TODO : question : consider IFn returns dataset by default . Arguments :
ans < - flights [ , .(arr_delay , ) ]
(def ans (r '(bra ~R-flights nil (. arr_delay dep_delay))))
(r.utils/head ans)
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
(def ans (r '(bra ~R-flights nil [:!list arr_delay dep_delay])))
(r.utils/head ans)
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
(def ans (ds/select-columns flights ["arr_delay" "dep_delay"]))
(ds/select-rows ans (range 6))
= > [ 6 2 ] :
| dep_delay |
| 13 | 14 |
| 9 | 2 |
| 1 | 2 |
# # Select both ` arr_delay ` and ` dep_delay ` columns and rename them to ` ` and ` delay_dep `
ans < - flights [ , = arr_delay , delay_dep = ) ]
(def ans (r '(bra ~R-flights nil (. :delay_arr arr_delay :delay_dep dep_delay))))
(r.utils/head ans)
= > delay_dep
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
(def ans (-> (ds/select-columns flights ["arr_delay" "dep_delay"])
(ds/rename-columns {"arr_delay" "delay_arr"
"dep_delay" "delay_dep"})))
(ds/select-rows ans (range 6))
= > [ 6 2 ] :
| delay_arr | delay_dep |
| 13 | 14 |
| 9 | 2 |
| 1 | 2 |
(def ans (r '(bra ~R-flights nil (sum (< (+ arr_delay dep_delay) 0)))))
ans
= > [ 1 ] 141814
(def ans (-> (ds/filter #(neg? (+ (get % "arr_delay")
(get % "dep_delay"))) flights)
(ds/row-count)))
ans
# # Calculate the average arrival and departure delay for all flights with “ ” as the origin airport in the month of June .
ans < - flights[origin = = " JFK " & month = = 6L ,
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'(. :m_arr (mean arr_delay)
:m_dep (mean dep_delay))))
ans
1 : 5.839349 9.807884
(def ans (->> (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/select-columns ["arr_delay" "dep_delay"]))
(map dfn/mean)))
ans
= > ( 5.839349323200929 9.807884113037279 )
(defn aggregate
([agg-fns-map ds]
(aggregate {} agg-fns-map ds))
([m agg-fns-map ds]
(into m (map (fn [[k agg-fn]]
[k (agg-fn ds)]) agg-fns-map))))
(def aggregate->dataset (comp ds/->dataset vector aggregate))
(def ans (->> (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/select-columns ["arr_delay" "dep_delay"]))
(aggregate->dataset {:m_arr #(dfn/mean (ds/column % "arr_delay"))
:m_dep #(dfn/mean (ds/column % "dep_delay"))})))
ans
= > _ unnamed [ 1 2 ] :
| : | : m_dep |
| 5.839 | 9.808 |
# # How many trips have been made in 2014 from “ ” airport in the month of June ?
ans < - flights[origin = = " JFK " & month = = 6L , length(dest ) ]
ans < - flights[origin = = " JFK " & month = = 6L , .N ]
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'(length dest)))
ans
= > [ 1 ] 8422
(def ans (r/bra R-flights
'(& (== origin "JFK")
(== month 6))
'.N))
ans
= > [ 1 ] 8422
(def ans (-> (ds/filter #(and (= (get % "origin") "JFK")
(= (get % "month") 6)) flights)
(ds/row-count)))
ans
= > 8422
(def ans (r '(bra ~R-flights nil ["arr_delay" "dep_delay"])))
(r.utils/head ans)
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
6 : 0 4
(def select_cols (r.base/<- 'select_cols ["arr_delay" "dep_delay"]))
(r '(bra ~R-flights nil ..select_cols))
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
253313 : -14 -5
253314 : 16 -8
253315 : 15 -4
253316 : 1 -5
(r '(bra ~R-flights nil select_cols :with false))
1 : 13 14
2 : 13 -3
3 : 9 2
4 : -26 -8
5 : 1 2
253313 : -14 -5
253314 : 16 -8
253315 : 15 -4
253316 : 1 -5
(def select_cols ["arr_delay" "dep_delay"])
(ds/select-columns flights select_cols)
= > [ 253316 2 ] :
| dep_delay |
| 13 | 14 |
| 9 | 2 |
| 1 | 2 |
| 1 | 3 |
| 133 | 142 |
| 1 | -1 |
| 185 | 191 |
| 1 | -3 |
| 42 | 44 |
(r '(bra ~R-flights nil (! ["arr_delay" "dep_delay"])))
1 : 2014 1 1 AA JFK LAX 359 2475 9
2 : 2014 1 1 AA JFK LAX 363 2475 11
3 : 2014 1 1 AA JFK LAX 351 2475 19
4 : 2014 1 1 AA LGA PBI 157 1035 7
5 : 2014 1 1 AA JFK LAX 350 2475 13
253312 : 2014 10 31 UA LGA IAH 201 1416 14
253313 : 2014 10 31 UA EWR IAH 189 1400 8
253314 : 2014 10 31 MQ LGA RDU 83 431 11
: 2014 10 31 MQ LGA DTW 75 502 11
253316 : 2014 10 31 MQ LGA SDF 110 659 8
(r '(bra ~R-flights nil (- ["arr_delay" "dep_delay"])))
1 : 2014 1 1 AA JFK LAX 359 2475 9
2 : 2014 1 1 AA JFK LAX 363 2475 11
3 : 2014 1 1 AA JFK LAX 351 2475 19
4 : 2014 1 1 AA LGA PBI 157 1035 7
5 : 2014 1 1 AA JFK LAX 350 2475 13
253312 : 2014 10 31 UA LGA IAH 201 1416 14
253313 : 2014 10 31 UA EWR IAH 189 1400 8
253314 : 2014 10 31 MQ LGA RDU 83 431 11
: 2014 10 31 MQ LGA DTW 75 502 11
253316 : 2014 10 31 MQ LGA SDF 110 659 8
(ds/remove-columns flights ["arr_delay" "dep_delay"])
= > [ 253316 9 ] :
| year | month | day | carrier | origin | dest | air_time | distance | hour |
| 2014 | 1 | 1 | AA | JFK | LAX | 359 | 2475 | 9 |
| 2014 | 1 | 1 | AA | JFK | LAX | 363 | 2475 | 11 |
| 2014 | 1 | 1 | AA | JFK | LAX | 351 | 2475 | 19 |
| 2014 | 1 | 1 | AA | LGA | PBI | 157 | 1035 | 7 |
| 2014 | 1 | 1 | AA | JFK | LAX | 350 | 2475 | 13 |
| 2014 | 1 | 1 | AA | EWR | LAX | 339 | 2454 | 18 |
| 2014 | 1 | 1 | AA | JFK | LAX | 338 | 2475 | 21 |
| 2014 | 1 | 1 | AA | JFK | LAX | 356 | 2475 | 15 |
| 2014 | 1 | 1 | AA | JFK | MIA | 161 | 1089 | 15 |
| 2014 | 1 | 1 | AA | JFK | SEA | 349 | 2422 | 18 |
| 2014 | 1 | 1 | AA | EWR | MIA | 161 | 1085 | 16 |
| 2014 | 1 | 1 | AA | JFK | SFO | 365 | 2586 | 17 |
| 2014 | 1 | 1 | AA | JFK | BOS | 39 | 187 | 12 |
| 2014 | 1 | 1 | AA | JFK | LAX | 345 | 2475 | 19 |
| 2014 | 1 | 1 | AA | JFK | BOS | 35 | 187 | 17 |
| 2014 | 1 | 1 | AA | JFK | ORD | 155 | 740 | 17 |
| 2014 | 1 | 1 | AA | JFK | IAH | 234 | 1417 | 16 |
| 2014 | 1 | 1 | AA | JFK | AUS | 232 | 1521 | 17 |
| 2014 | 1 | 1 | AA | EWR | DFW | 214 | 1372 | 16 |
| 2014 | 1 | 1 | AA | LGA | ORD | 142 | 733 | 5 |
| 2014 | 1 | 1 | AA | LGA | ORD | 143 | 733 | 6 |
| 2014 | 1 | 1 | AA | LGA | ORD | 139 | 733 | 6 |
| 2014 | 1 | 1 | AA | LGA | ORD | 145 | 733 | 7 |
| 2014 | 1 | 1 | AA | LGA | ORD | 139 | 733 | 8 |
| 2014 | 1 | 1 | AA | LGA | ORD | 141 | 733 | 10 |
(defn map-v [f coll]
(reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))
(def ans (r '(bra ~R-flights nil (. .N) :by (. origin))))
ans
1 : JFK 81483
2 : LGA 84433
3 : EWR 87400
(def ans (r '(bra ~R-flights nil (. .N) :by "origin")))
ans
1 : JFK 81483
2 : LGA 84433
3 : EWR 87400
(def ans (->> flights
(ds/group-by-column "origin")
(map-v ds/row-count)))
ans
= > { " EWR " 87400 , " LGA " 84433 , " " 81483 }
(def ans (->> flights
(ds/group-by-column "origin")
(map-v (comp vector ds/row-count))
(ds/name-values-seq->dataset)))
ans
= > _ unnamed [ 1 3 ] :
(defn group-by-columns-and-aggregate
[gr-colls agg-fns-map ds]
(->> (ds/group-by identity gr-colls ds)
(map (fn [[group-idx group-ds]]
(aggregate group-idx agg-fns-map group-ds)))
ds/->dataset))
(def ans (group-by-columns-and-aggregate ["origin"] {"N" ds/row-count} flights))
ans
= > _ unnamed [ 3 2 ] :
# # How can we calculate the number of trips for each origin airport for carrier code " AA " ?
ans < - flights[carrier = = " AA " , .N , by = origin ]
(def ans (r/bra R-flights '(== carrier "AA") '.N :by 'origin))
ans
1 : 11923
2 : LGA 11730
3 : EWR 2649
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin"] {"N" ds/row-count})))
ans
= > _ unnamed [ 3 2 ] :
# # How can we get the total number of trips for each origin , dest pair for carrier code " AA " ?
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest ) ]
(def ans (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest)))
(r.utils/head ans)
1 : JFK LAX 3387
2 : LGA PBI 245
3 : EWR LAX 62
4 : JFK MIA 1876
5 : JFK SEA 298
6 : EWR MIA 848
(def ans (r/bra R-flights '(== carrier "AA") '.N :by ["origin" "dest"]))
(r.utils/head ans)
1 : JFK LAX 3387
2 : LGA PBI 245
3 : EWR LAX 62
4 : JFK MIA 1876
5 : JFK SEA 298
6 : EWR MIA 848
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest"] {"N" ds/row-count})))
(ds/select-rows ans (range 6))
= > _ unnamed [ 6 3 ] :
| EWR | PHX | 121 |
| | LAS | 595 |
| JFK | MCO | 597 |
# # How can we get the average arrival and departure delay for each orig , dest pair for each month for carrier code " AA " ?
(def ans (r/bra R-flights '(== carrier "AA") '(. (mean arr_delay)
(mean dep_delay)) :by '(. origin dest month)))
ans
= > origin dest month V1 V2
1 : JFK LAX 1 6.590361 14.2289157
2 : LGA PBI 1 -7.758621 0.3103448
3 : EWR LAX 1 1.366667 7.5000000
4 : MIA 1 15.720670 18.7430168
5 : JFK SEA 1 14.357143 30.7500000
196 : LGA MIA 10 -6.251799 -1.4208633
197 : MIA 10 -1.880184 6.6774194
198 : EWR PHX 10 -3.032258 -4.2903226
199 : JFK MCO 10 -10.048387 -1.6129032
200 : DCA 10 16.483871 15.5161290
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest" "month"]
{"V1" #(dfn/mean (% "arr_delay"))
"V2" #(dfn/mean (% "dep_delay"))})))
ans
= > _ unnamed [ 200 5 ] :
| JFK | SEA | 9 | 16.83 | 8.567 |
| JFK | MCO | 2 | 10.15 | 8.453 |
| LGA | MIA | 1 | 5.417 | 6.130 |
| | LAS | 3 | 6.869 | 13.18 |
| | LAS | 1 | 19.15 | 17.69 |
| LGA | MIA | 4 | 0.6552 | -3.828 |
| JFK | EGE | 2 | 57.46 | 53.79 |
| LGA | DFW | 3 | -1.285 | -0.2461 |
| EWR | DFW | 8 | 22.07 | 16.94 |
| LGA | PBI | 5 | -6.857 | -10.36 |
| EWR | PHX | 9 | -1.667 | -4.233 |
| JFK | SAN | 9 | 12.83 | 18.80 |
| JFK | SFO | 3 | 10.03 | 5.586 |
| JFK | AUS | 4 | -0.1333 | 4.367 |
| JFK | SAN | 8 | 14.19 | 10.74 |
| LGA | ORD | 6 | 17.30 | 18.91 |
| JFK | SFO | 9 | 6.207 | 7.233 |
| LGA | DFW | 10 | 4.553 | 3.500 |
| JFK | ORD | 7 | 34.39 | 23.14 |
| JFK | SJU | 9 | 11.38 | 1.688 |
| JFK | SEA | 7 | 20.55 | 21.97 |
| | LAS | 10 | 14.55 | 18.23 |
| JFK | ORD | 2 | 41.74 | 34.11 |
| JFK | STT | 6 | 0.9667 | -4.667 |
= .(origin , dest , month ) ]
(def ans (r/bra R-flights '(== carrier "AA") '(. (mean arr_delay)
(mean dep_delay)) :keyby '(. origin dest month)))
ans
= > origin dest month V1 V2
1 : EWR DFW 1 6.427673 10.0125786
2 : EWR DFW 2 10.536765 11.3455882
3 : EWR DFW 3 12.865031 8.0797546
4 : EWR DFW 4 17.792683 12.9207317
5 : EWR DFW 5 18.487805 18.6829268
196 : LGA PBI 1 -7.758621 0.3103448
197 : LGA PBI 2 -7.865385 2.4038462
198 : LGA PBI 3 -5.754098 3.0327869
199 : LGA PBI 4 -13.966667 -4.7333333
200 : LGA PBI 5 -10.357143 -6.8571429
(defn asc-desc-comparator
[orders]
(if (every? #(= % :asc) orders)
compare
(let [mults (map #(if (= % :asc) 1 -1) orders)]
(fn [v1 v2]
(reduce (fn [_ [a b mult]]
(let [c (compare a b)]
(if-not (zero? c)
(reduced (* mult c))
c))) 0 (map vector v1 v2 mults))))))
(defn sort-by-columns-with-orders
([cols ds]
(sort-by-columns-with-orders cols (repeat (count cols) :asc) ds))
([cols orders ds]
(let [sel (apply juxt (map #(fn [ds] (get ds %)) cols))
comp-fn (asc-desc-comparator orders)]
(ds/sort-by sel comp-fn ds))))
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest" "month"]
{"V1" #(dfn/mean (% "arr_delay"))
"V2" #(dfn/mean (% "dep_delay"))})
(sort-by-columns-with-orders ["origin" "dest" "month"])))
ans
= > _ unnamed [ 200 5 ] :
| origin | dest | month | V2 | V1 |
| EWR | DFW | 1 | 10.01 | 6.428 |
| EWR | DFW | 2 | 11.35 | 10.54 |
| EWR | DFW | 3 | 8.080 | 12.87 |
| EWR | DFW | 4 | 12.92 | 17.79 |
| EWR | DFW | 5 | 18.68 | 18.49 |
| EWR | DFW | 6 | 38.74 | 37.01 |
| EWR | DFW | 7 | 21.15 | 20.25 |
| EWR | DFW | 8 | 22.07 | 16.94 |
| EWR | DFW | 9 | 13.06 | 5.865 |
| EWR | DFW | 10 | 18.89 | 18.81 |
| EWR | LAX | 1 | 7.500 | 1.367 |
| EWR | LAX | 2 | 4.111 | 10.33 |
| EWR | MIA | 1 | 12.12 | 11.01 |
| EWR | MIA | 2 | 4.756 | 1.564 |
| EWR | MIA | 3 | 0.4444 | -4.111 |
| EWR | MIA | 4 | 6.433 | 3.189 |
| EWR | MIA | 5 | 6.344 | -2.538 |
| EWR | MIA | 6 | 16.20 | 7.307 |
| EWR | MIA | 7 | 26.35 | 25.22 |
| EWR | MIA | 8 | 0.8462 | -6.125 |
| EWR | PHX | 8 | 6.226 | 3.548 |
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest ) ]
ans < - flights[carrier = = " AA " , .N , by = .(origin , dest)][order(origin , -dest ) ]
(def ans (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest)))
(def ans (r/bra ans '(order origin (- dest))))
(r.utils/head ans)
1 : EWR PHX 121
2 : EWR MIA 848
3 : EWR LAX 62
4 : EWR DFW 1618
5 : JFK STT 229
6 : JFK SJU 690
(def ans (-> (r/bra R-flights '(== carrier "AA") '.N :by '(. origin dest))
(r/bra '(order origin (- dest)))))
(r.utils/head ans)
1 : EWR PHX 121
2 : EWR MIA 848
3 : EWR LAX 62
4 : EWR DFW 1618
5 : JFK STT 229
6 : JFK SJU 690
(def ans (->> flights
(ds/filter #(= "AA" (get % "carrier")))
(group-by-columns-and-aggregate ["origin" "dest"]
{"N" ds/row-count})
(sort-by-columns-with-orders ["origin" "dest"] [:asc :desc])))
(ds/select-rows ans (range 6))
= > _ unnamed [ 6 3 ] :
| EWR | PHX | 121 |
| EWR | MIA | 848 |
| EWR | LAX | 62 |
| JFK | STT | 229 |
| JFK | SJU | 690 |
ans < - flights [ , .N , .(dep_delay>0 , arr_delay>0 ) ]
(def ans (r '(bra ~R-flights nil .N (. (> dep_delay 0)
(> arr_delay 0)))))
ans
= > N
1 : TRUE TRUE 72836
2 : FALSE TRUE 34583
3 : FALSE FALSE 119304
4 : TRUE FALSE 26593
(def ans (->> (-> flights
(ds/new-column :pos_dep_delay (dfn/> (flights "dep_delay") 0))
(ds/new-column :pos_arr_delay (dfn/> (flights "arr_delay") 0)))
(group-by-columns-and-aggregate [:pos_dep_delay :pos_arr_delay]
{"N" ds/row-count})))
ans
= > _ unnamed [ 4 3 ] :
| true | false | 26593 |
DT
DT [ , lapply(.SD , mean ) , by = ID ]
R-DT
1 : b 1 7 13
2 : b 2 8 14
3 : b 3 9 15
4 : c 4 10 16
5 : c 5 11 17
6 : a 6 12 18
(r '(bra ~R-DT nil (print .SD) :by ID))
= > Empty data.table ( 0 rows and 1 cols ): ID
1 : 1 7 13
2 : 2 8 14
3 : 3 9 15
1 : 4 10 16
2 : 5 11 17
1 : 6 12 18
(r '(bra ~R-DT nil (lapply .SD mean) :by ID))
1 : b 2.0 8.0 14.0
2 : c 4.5 10.5 16.5
3 : a 6.0 12.0 18.0
DT
= > _ unnamed [ 6 4 ] :
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
(ds/group-by-column :ID DT)
= > { " a " a [ 1 4 ] :
, " b " b [ 3 4 ] :
| b | 1 | 7 | 13 |
| b | 2 | 8 | 14 |
| b | 3 | 9 | 15 |
, " c " c [ 2 4 ] :
(group-by-columns-and-aggregate [:ID]
(into {} (map (fn [col]
[col #(dfn/mean (% col))])
(rest (ds/column-names DT)))) DT)
= > _ unnamed [ 3 4 ] :
|-----+-------+-------+-------|
| c | 16.50 | 10.50 | 4.500 |
flights[carrier = = " AA " , # # Only on trips with carrier " AA "
by = .(origin , dest , month ) , # # for every ' origin , dest , month '
.SDcols = c("arr_delay " , " dep_delay " ) ] # # for just those specified in .SDcols
(r/bra R-flights
'(== carrier "AA")
'(lapply .SD mean)
:by '(. origin dest month)
:.SDcols ["arr_delay", "dep_delay"])
= > origin dest month arr_delay dep_delay
1 : JFK LAX 1 6.590361 14.2289157
2 : LGA PBI 1 -7.758621 0.3103448
3 : EWR LAX 1 1.366667 7.5000000
4 : MIA 1 15.720670 18.7430168
5 : JFK SEA 1 14.357143 30.7500000
196 : LGA MIA 10 -6.251799 -1.4208633
197 : MIA 10 -1.880184 6.6774194
198 : EWR PHX 10 -3.032258 -4.2903226
199 : JFK MCO 10 -10.048387 -1.6129032
200 : DCA 10 16.483871 15.5161290
(->> flights
(ds/filter #(= (get % "carrier") "AA"))
(group-by-columns-and-aggregate ["origin", "dest", "month"]
(into {} (map (fn [col]
[col #(dfn/mean (% col))])
["arr_delay" "dep_delay"]))))
= > _ unnamed [ 200 5 ] :
| origin | dest | month | dep_delay | arr_delay |
| JFK | SEA | 9 | 16.83 | 8.567 |
| JFK | MCO | 2 | 10.15 | 8.453 |
| LGA | MIA | 1 | 5.417 | 6.130 |
| | LAS | 3 | 6.869 | 13.18 |
| | LAS | 1 | 19.15 | 17.69 |
| JFK | EGE | 2 | 57.46 | 53.79 |
| LGA | DFW | 3 | -1.285 | -0.2461 |
| EWR | DFW | 8 | 22.07 | 16.94 |
| LGA | MIA | 6 | 8.467 | -2.458 |
| LGA | PBI | 5 | -6.857 | |
| JFK | SAN | 9 | 12.83 | 18.80 |
| JFK | SFO | 3 | 10.03 | 5.586 |
| JFK | AUS | 4 | -0.1333 | 4.367 |
| JFK | SAN | 8 | 14.19 | 10.74 |
| LGA | ORD | 6 | 17.30 | 18.91 |
| JFK | SFO | 9 | 6.207 | 7.233 |
| LGA | DFW | 10 | 4.553 | 3.500 |
| JFK | ORD | 7 | 34.39 | 23.14 |
| JFK | SJU | 9 | 11.38 | 1.688 |
| JFK | SEA | 7 | 20.55 | 21.97 |
| | LAS | 10 | 14.55 | 18.23 |
| JFK | ORD | 2 | 41.74 | 34.11 |
# # How can we return the first two rows for each month ?
ans < - flights [ , head(.SD , 2 ) , by = month ]
(def ans (r '(bra ~R-flights nil (head .SD 2) :by month)))
(r.utils/head ans)
= > month year day carrier origin dest air_time distance hour
1 : 1 2014 1 14 13 AA JFK LAX 359 2475 9
2 : 1 2014 1 -3 13 AA JFK LAX 363 2475 11
3 : 2 2014 1 -1 1 AA JFK LAX 358 2475 8
4 : 2 2014 1 -5 3 AA JFK LAX 358 2475 11
5 : 3 2014 1 -11 36 AA JFK LAX 375 2475 8
6 : 3 2014 1 -3 14 AA JFK LAX 368 2475 11
(def ans (->> flights
(ds/group-by-column "month")
(vals)
(map #(ds/select-rows % [1 2]))
(reduce ds/concat)))
(ds/select-rows ans (range 6))
= > null [ 6 11 ] :
| dep_delay | origin | air_time | hour | arr_delay | dest | distance | year | month | day | carrier |
| -6 | EWR | 320 | 9 | -14 | LAX | 2454 | 2014 | 7 | 1 | VX |
| -3 | EWR | 326 | 12 | -14 | LAX | 2454 | 2014 | 7 | 1 | VX |
| -3 | JFK | 363 | 11 | 13 | LAX | 2475 | 2014 | 1 | 1 | AA |
| 2 | JFK | 351 | 19 | 9 | LAX | 2475 | 2014 | 1 | 1 | AA |
| -8 | LGA | 71 | 18 | -11 | RDU | 431 | 2014 | 4 | 1 | MQ |
| -4 | LGA | 113 | 8 | -2 | BNA | 764 | 2014 | 4 | 1 | MQ |
(r '(bra ~R-DT nil (. :val [a b]) :by ID))
= >
1 : b 1
2 : b 2
3 : b 3
4 : b 7
5 : b 8
6 : b 9
7 : c 4
8 : c 5
9 : c 10
10 : c 11
11 : a 6
12 : a 12
(ds/concat (-> (ds/select-columns DT [:ID :a])
(ds/rename-columns {:a :val}))
(-> (ds/select-columns DT [:ID :b])
(ds/rename-columns {:b :val})))
= > null [ 12 2 ] :
| c | 10 |
| c | 11 |
| a | 12 |
DT [ , .(val = list(c(a , b ) ) ) , by = ID ]
(r '(bra ~R-DT nil (. :val (list [a b])) :by ID))
1 : b 1,2,3,7,8,9
2 : c 4 , 5,10,11
3 : a 6,12
(group-by-columns-and-aggregate [:ID]
{:val #(concat (% :a) (% :b))}
DT)
= > _ unnamed [ 3 2 ] :
(group-by-columns-and-aggregate [:ID]
{:val #(vec (concat (seq (% :a)) (seq (% :b))))}
DT)
= > _ unnamed [ 3 2 ] :
| : ID | : |
| a | [ 6 12 ] |
| b | [ 1 2 3 7 8 9 ] |
| c | [ 4 5 10 11 ] |
|
a9012b654f72e057aa5ed057b019c27ba539044de64b69d83e784cce933eee89 | well-typed/cborg | Mini.hs | module Mini
( benchmarks -- :: [Benchmark]
) where
import System.FilePath
import Criterion.Main
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BS
import Macro.DeepSeq ()
import qualified Macro.PkgBinary as PkgBinary
import qualified Macro.PkgCereal as PkgCereal
import qualified Macro.PkgStore as PkgStore
import qualified Macro.CBOR as CBOR
benchmarks :: [Benchmark]
benchmarks =
[ bgroup "decode-index"
[ bgroup "binary"
[ envBinary $ \v ->
bench "deserialise" $ nf PkgBinary.deserialise v
]
, bgroup "cereal"
[ envCereal $ \v ->
bench "deserialise" $ nf PkgCereal.deserialise v
]
, bgroup "store"
[ envStore $ \v ->
bench "deserialise" $ nf PkgStore.deserialise v
]
, bgroup "cbor"
[ envCBOR $ \v ->
bench "deserialise" $ nf CBOR.deserialise v
]
]
, bgroup "decode-index-noaccum"
[ bgroup "binary"
[ envBinary $ \v ->
bench "deserialise" $ nf PkgBinary.deserialiseNull v
]
, bgroup "cereal"
[ envCereal $ \v ->
bench "deserialise" $ nf PkgCereal.deserialiseNull v
]
, bgroup "cbor"
[ envCBOR $ \v ->
bench "deserialise" $ nf CBOR.deserialiseNull v
]
]
]
where
Helpers for using Criterion environments .
envBinary = env (fmap BS.fromStrict (readBin "binary"))
envCereal = env (fmap BS.fromStrict (readBin "cereal"))
envStore = env (readBin "store")
envCBOR = env (fmap BS.fromStrict (readBin "cbor"))
| Read one of the pre - encoded binary files out of the
-- data directory.
readBin :: FilePath -> IO B.ByteString
readBin f = B.readFile ("bench" </> "data" </> f <.> "bin")
| null | https://raw.githubusercontent.com/well-typed/cborg/9be3fd5437f9d2ec1df784d5d939efb9a85fd1fb/serialise/bench/versus/Mini.hs | haskell | :: [Benchmark]
data directory. | module Mini
) where
import System.FilePath
import Criterion.Main
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BS
import Macro.DeepSeq ()
import qualified Macro.PkgBinary as PkgBinary
import qualified Macro.PkgCereal as PkgCereal
import qualified Macro.PkgStore as PkgStore
import qualified Macro.CBOR as CBOR
benchmarks :: [Benchmark]
benchmarks =
[ bgroup "decode-index"
[ bgroup "binary"
[ envBinary $ \v ->
bench "deserialise" $ nf PkgBinary.deserialise v
]
, bgroup "cereal"
[ envCereal $ \v ->
bench "deserialise" $ nf PkgCereal.deserialise v
]
, bgroup "store"
[ envStore $ \v ->
bench "deserialise" $ nf PkgStore.deserialise v
]
, bgroup "cbor"
[ envCBOR $ \v ->
bench "deserialise" $ nf CBOR.deserialise v
]
]
, bgroup "decode-index-noaccum"
[ bgroup "binary"
[ envBinary $ \v ->
bench "deserialise" $ nf PkgBinary.deserialiseNull v
]
, bgroup "cereal"
[ envCereal $ \v ->
bench "deserialise" $ nf PkgCereal.deserialiseNull v
]
, bgroup "cbor"
[ envCBOR $ \v ->
bench "deserialise" $ nf CBOR.deserialiseNull v
]
]
]
where
Helpers for using Criterion environments .
envBinary = env (fmap BS.fromStrict (readBin "binary"))
envCereal = env (fmap BS.fromStrict (readBin "cereal"))
envStore = env (readBin "store")
envCBOR = env (fmap BS.fromStrict (readBin "cbor"))
| Read one of the pre - encoded binary files out of the
readBin :: FilePath -> IO B.ByteString
readBin f = B.readFile ("bench" </> "data" </> f <.> "bin")
|
625d8fe4efbc13fd73b6e417921141cef89c90a7a58ebe15dbd7450d7abfeebf | TrustInSoft/tis-interpreter | dump.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 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- Dump Report on Output --- *)
(* -------------------------------------------------------------------------- *)
open Property_status
let bar = String.make 80 '-'
let dim = 9 (* Size for status [----] *)
let tab = String.make (dim+3) ' '
let pp_status fmt s =
let n = String.length s in
if n < dim then
let m = String.make dim ' ' in
let p = (dim - n) / 2 in
String.blit s 0 m p n ;
Format.fprintf fmt "[%s]" m
else Format.fprintf fmt "[%s]" s
open Consolidation
module E = Emitter.Usable_emitter
class dumper out =
object(self)
val mutable st_unknown = 0 ; (* no status *)
val mutable st_partial = 0 ; (* locally valid but missing hyp *)
val mutable st_extern = 0 ; (* considered valid *)
val mutable st_complete = 0 ; (* valid and complete *)
val mutable st_bug = 0 ; (* invalid and complete *)
val mutable st_alarm = 0 ; (* invalid but missing hyp *)
val mutable st_dead = 0 ; (* under invalid hyp *)
val mutable st_maybe_unreachable = 0 ; (* possible unreachable *)
val mutable st_unreachable = 0 ; (* confirmed unreachable *)
val mutable st_reachable = 0 ; (* confirmed reachable *)
val mutable st_inconsistent = 0 ; (* unsound *)
val mutable kf : Description.kf = `Always
method started = ()
method global_section =
Format.fprintf out "%s@\n--- Global Properties@\n%s@\n@." bar bar
method function_section thekf =
Format.fprintf out "@\n%s@\n--- Properties of Function '%s'@\n%s@\n@."
bar (Kernel_function.get_name thekf) bar ;
kf <- `Context thekf
method category ip st =
match ip, st with
(* Special display for unreachable *)
| Property.IPReachable _, Invalid _ ->
st_unreachable <- succ st_unreachable; "Unreachable"
| Property.IPReachable _, (Valid _ | Considered_valid) ->
st_reachable <- succ st_reachable; "Reachable"
| Property.IPReachable _, _ ->
st_maybe_unreachable <- succ st_maybe_unreachable;
"-r-"
(* All other cases *)
| _, (Never_tried | Unknown _) -> st_unknown <- succ st_unknown ; "-"
| _, Considered_valid -> st_extern <- succ st_extern ; "Extern"
| _, Valid _ -> st_complete <- succ st_complete ; "Valid"
| _, Invalid _ -> st_bug <- succ st_bug ; "Bug"
| _, Valid_under_hyp _ -> st_partial <- succ st_partial ; "Partial"
| _, Invalid_under_hyp _ -> st_alarm <- succ st_alarm ; "Alarm"
| _, (Valid_but_dead _ | Invalid_but_dead _ | Unknown_but_dead _) ->
st_dead <- succ st_dead ; "Dead"
| _, Inconsistent _ -> st_inconsistent <- succ st_inconsistent ; "Unsound"
method emitter e = Format.fprintf out "%s@[<hov 2>by %a.@]@\n" tab E.pretty e
method emitters es = E.Set.iter self#emitter es
method tried_emitters ps =
let es = E.Map.fold (fun e _ es -> e::es) ps [] in
match es with
| [] -> ()
| e::es ->
Format.fprintf out "%s@[<hov 2>tried with %a" tab E.pretty e ;
List.iter (fun e -> Format.fprintf out ",@ %a" E.pretty e) es ;
Format.fprintf out ".@]@\n"
method dead_reasons ps =
E.Map.iter
(fun e ps ->
Format.fprintf out "%s@[<hov 2>By %a because:@]@\n" tab E.pretty e ;
Property.Set.iter
(fun p -> Format.fprintf out "%s@[<hov 3> - %a@]@\n" tab
(Description.pp_localized ~kf ~ki:true ~kloc:true) p) ps
) (Scan.partial_pending ps)
method partial_pending ps =
E.Map.iter
(fun e ps ->
Format.fprintf out "%s@[<hov 2>By %a, with pending:@]@\n" tab E.pretty e ;
Property.Set.iter
(fun p -> Format.fprintf out "%s@[<hov 3> - %a@]@\n" tab
(Description.pp_localized ~kf ~ki:true ~kloc:true) p) ps
) (Scan.partial_pending ps)
method property ip st =
begin
Format.fprintf out "%a @[%a@]@\n" pp_status (self#category ip st)
(Description.pp_localized ~kf:`Never ~ki:true ~kloc:true) ip ;
if Report_parameters.PrintProperties.get () then
Format.fprintf out "%s@[%a@]@\n" tab Property.pretty ip;
match st with
| Never_tried -> ()
| Unknown emitters -> self#tried_emitters emitters
| Valid emitters -> self#emitters emitters
| Invalid emitters -> self#emitters emitters
| Invalid_but_dead pending ->
Format.fprintf out "%sLocally invalid, but unreachable.@\n" tab ;
self#dead_reasons pending
| Valid_but_dead pending ->
Format.fprintf out "%sLocally valid, but unreachable.@\n" tab ;
self#dead_reasons pending
| Unknown_but_dead pending ->
Format.fprintf out "%sLocally unknown, but unreachable.@\n"tab ;
self#dead_reasons pending
| Invalid_under_hyp pending | Valid_under_hyp pending ->
self#partial_pending pending
| Considered_valid ->
Format.fprintf out "%sUnverifiable but considered Valid.@\n" tab
| Inconsistent s ->
let p = ref 0 in
let n = String.length s in
while !p < n do
try
let k = String.index_from s !p '\n' in
Format.fprintf out "%s%s@\n" tab (String.sub s !p (k - !p)) ;
p := succ k ;
with Not_found ->
Format.fprintf out "%s%s@\n" tab (String.sub s !p (n - !p)) ;
p := n ;
done
end
method finished =
Format.fprintf out "@\n%s@\n--- Status Report Summary@\n%s@\n" bar bar ;
if st_complete > 0 then
Format.fprintf out " %4d Completely validated@\n" st_complete ;
if st_partial > 0 then
Format.fprintf out " %4d Locally validated@\n" st_partial ;
if st_extern > 0 then
Format.fprintf out " %4d Considered valid@\n" st_extern ;
if st_unknown > 0 then
Format.fprintf out " %4d To be validated@\n" st_unknown ;
if st_alarm = 1 then
Format.fprintf out " %4d Alarm emitted@\n" st_alarm ;
if st_alarm > 1 then
Format.fprintf out " %4d Alarms emitted@\n" st_alarm ;
if st_bug > 0 then
Format.fprintf out " %4d Bugs found@\n" st_bug ;
if st_dead > 1 then
Format.fprintf out " %4d Dead properties@\n" st_dead ;
if st_dead = 1 then
Format.fprintf out " 1 Dead property@\n" ;
if st_reachable > 0 then
Format.fprintf out " %4d Reachable@\n" st_reachable ;
if st_maybe_unreachable > 0 then
Format.fprintf out " %4d Unconfirmed unreachable@\n"
st_maybe_unreachable ;
if st_unreachable > 0 then
Format.fprintf out " %4d Unreachable@\n" st_unreachable ;
if st_inconsistent > 1
then Format.fprintf out " %4d Inconsistencies@\n" st_inconsistent ;
if st_inconsistent = 1
then Format.fprintf out " 1 Inconsistency@\n" ;
let total =
st_complete + st_partial + st_extern + st_unknown + st_alarm + st_bug
+ st_dead + st_reachable + st_unreachable + st_maybe_unreachable
+ st_inconsistent
in
Format.fprintf out " %5d Total@\n%s@." total bar ;
method empty =
Format.fprintf out "%s@\n--- No status to report@\n%s@." bar bar ;
end
let create out = (new dumper out :> Scan.inspector)
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/report/dump.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.
************************************************************************
--------------------------------------------------------------------------
--- Dump Report on Output ---
--------------------------------------------------------------------------
Size for status [----]
no status
locally valid but missing hyp
considered valid
valid and complete
invalid and complete
invalid but missing hyp
under invalid hyp
possible unreachable
confirmed unreachable
confirmed reachable
unsound
Special display for unreachable
All other cases
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 ) .
open Property_status
let bar = String.make 80 '-'
let tab = String.make (dim+3) ' '
let pp_status fmt s =
let n = String.length s in
if n < dim then
let m = String.make dim ' ' in
let p = (dim - n) / 2 in
String.blit s 0 m p n ;
Format.fprintf fmt "[%s]" m
else Format.fprintf fmt "[%s]" s
open Consolidation
module E = Emitter.Usable_emitter
class dumper out =
object(self)
val mutable kf : Description.kf = `Always
method started = ()
method global_section =
Format.fprintf out "%s@\n--- Global Properties@\n%s@\n@." bar bar
method function_section thekf =
Format.fprintf out "@\n%s@\n--- Properties of Function '%s'@\n%s@\n@."
bar (Kernel_function.get_name thekf) bar ;
kf <- `Context thekf
method category ip st =
match ip, st with
| Property.IPReachable _, Invalid _ ->
st_unreachable <- succ st_unreachable; "Unreachable"
| Property.IPReachable _, (Valid _ | Considered_valid) ->
st_reachable <- succ st_reachable; "Reachable"
| Property.IPReachable _, _ ->
st_maybe_unreachable <- succ st_maybe_unreachable;
"-r-"
| _, (Never_tried | Unknown _) -> st_unknown <- succ st_unknown ; "-"
| _, Considered_valid -> st_extern <- succ st_extern ; "Extern"
| _, Valid _ -> st_complete <- succ st_complete ; "Valid"
| _, Invalid _ -> st_bug <- succ st_bug ; "Bug"
| _, Valid_under_hyp _ -> st_partial <- succ st_partial ; "Partial"
| _, Invalid_under_hyp _ -> st_alarm <- succ st_alarm ; "Alarm"
| _, (Valid_but_dead _ | Invalid_but_dead _ | Unknown_but_dead _) ->
st_dead <- succ st_dead ; "Dead"
| _, Inconsistent _ -> st_inconsistent <- succ st_inconsistent ; "Unsound"
method emitter e = Format.fprintf out "%s@[<hov 2>by %a.@]@\n" tab E.pretty e
method emitters es = E.Set.iter self#emitter es
method tried_emitters ps =
let es = E.Map.fold (fun e _ es -> e::es) ps [] in
match es with
| [] -> ()
| e::es ->
Format.fprintf out "%s@[<hov 2>tried with %a" tab E.pretty e ;
List.iter (fun e -> Format.fprintf out ",@ %a" E.pretty e) es ;
Format.fprintf out ".@]@\n"
method dead_reasons ps =
E.Map.iter
(fun e ps ->
Format.fprintf out "%s@[<hov 2>By %a because:@]@\n" tab E.pretty e ;
Property.Set.iter
(fun p -> Format.fprintf out "%s@[<hov 3> - %a@]@\n" tab
(Description.pp_localized ~kf ~ki:true ~kloc:true) p) ps
) (Scan.partial_pending ps)
method partial_pending ps =
E.Map.iter
(fun e ps ->
Format.fprintf out "%s@[<hov 2>By %a, with pending:@]@\n" tab E.pretty e ;
Property.Set.iter
(fun p -> Format.fprintf out "%s@[<hov 3> - %a@]@\n" tab
(Description.pp_localized ~kf ~ki:true ~kloc:true) p) ps
) (Scan.partial_pending ps)
method property ip st =
begin
Format.fprintf out "%a @[%a@]@\n" pp_status (self#category ip st)
(Description.pp_localized ~kf:`Never ~ki:true ~kloc:true) ip ;
if Report_parameters.PrintProperties.get () then
Format.fprintf out "%s@[%a@]@\n" tab Property.pretty ip;
match st with
| Never_tried -> ()
| Unknown emitters -> self#tried_emitters emitters
| Valid emitters -> self#emitters emitters
| Invalid emitters -> self#emitters emitters
| Invalid_but_dead pending ->
Format.fprintf out "%sLocally invalid, but unreachable.@\n" tab ;
self#dead_reasons pending
| Valid_but_dead pending ->
Format.fprintf out "%sLocally valid, but unreachable.@\n" tab ;
self#dead_reasons pending
| Unknown_but_dead pending ->
Format.fprintf out "%sLocally unknown, but unreachable.@\n"tab ;
self#dead_reasons pending
| Invalid_under_hyp pending | Valid_under_hyp pending ->
self#partial_pending pending
| Considered_valid ->
Format.fprintf out "%sUnverifiable but considered Valid.@\n" tab
| Inconsistent s ->
let p = ref 0 in
let n = String.length s in
while !p < n do
try
let k = String.index_from s !p '\n' in
Format.fprintf out "%s%s@\n" tab (String.sub s !p (k - !p)) ;
p := succ k ;
with Not_found ->
Format.fprintf out "%s%s@\n" tab (String.sub s !p (n - !p)) ;
p := n ;
done
end
method finished =
Format.fprintf out "@\n%s@\n--- Status Report Summary@\n%s@\n" bar bar ;
if st_complete > 0 then
Format.fprintf out " %4d Completely validated@\n" st_complete ;
if st_partial > 0 then
Format.fprintf out " %4d Locally validated@\n" st_partial ;
if st_extern > 0 then
Format.fprintf out " %4d Considered valid@\n" st_extern ;
if st_unknown > 0 then
Format.fprintf out " %4d To be validated@\n" st_unknown ;
if st_alarm = 1 then
Format.fprintf out " %4d Alarm emitted@\n" st_alarm ;
if st_alarm > 1 then
Format.fprintf out " %4d Alarms emitted@\n" st_alarm ;
if st_bug > 0 then
Format.fprintf out " %4d Bugs found@\n" st_bug ;
if st_dead > 1 then
Format.fprintf out " %4d Dead properties@\n" st_dead ;
if st_dead = 1 then
Format.fprintf out " 1 Dead property@\n" ;
if st_reachable > 0 then
Format.fprintf out " %4d Reachable@\n" st_reachable ;
if st_maybe_unreachable > 0 then
Format.fprintf out " %4d Unconfirmed unreachable@\n"
st_maybe_unreachable ;
if st_unreachable > 0 then
Format.fprintf out " %4d Unreachable@\n" st_unreachable ;
if st_inconsistent > 1
then Format.fprintf out " %4d Inconsistencies@\n" st_inconsistent ;
if st_inconsistent = 1
then Format.fprintf out " 1 Inconsistency@\n" ;
let total =
st_complete + st_partial + st_extern + st_unknown + st_alarm + st_bug
+ st_dead + st_reachable + st_unreachable + st_maybe_unreachable
+ st_inconsistent
in
Format.fprintf out " %5d Total@\n%s@." total bar ;
method empty =
Format.fprintf out "%s@\n--- No status to report@\n%s@." bar bar ;
end
let create out = (new dumper out :> Scan.inspector)
|
6a51fd375cee66538b83738cf057babce4f608fc152c991e4b84c1f704608861 | justinethier/nugget | fibfp.scm | FIBFP -- Computes ) using floating point
#; (import (scheme base)
(scheme read)
(scheme write)
(scheme time))
(define (fibfp n)
(if (< n 2.)
n
(+ (fibfp (- n 1.))
(fibfp (- n 2.)))))
(define (main)
(let* ((count (read))
(input (read))
(output (read))
(s2 (number->string count))
(s1 (number->string input))
(name "fibfp"))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s2)
count
(lambda () (fibfp (hide count input)))
(lambda (result) (= result output)))))
;;; The following code is appended to all benchmarks.
;;; Given an integer and an object, returns the object
;;; without making it too easy for compilers to tell
;;; the object will be returned.
(define (hide r x)
(call-with-values
(lambda ()
(values (vector values (lambda (x) x))
(if (< r 100) 0 1)))
(lambda (v i)
((vector-ref v i) x))))
;;; Given the name of a benchmark,
;;; the number of times it should be executed,
;;; a thunk that runs the benchmark once,
;;; and a unary predicate that is true of the
;;; correct results the thunk may return,
;;; runs the benchmark for the number of specified iterations.
(define (run-r7rs-benchmark name count thunk ok?)
Rounds to thousandths .
(define (rounded x)
(/ (round (* 1000 x)) 1000))
(display "Running ")
(display name)
(newline)
;(flush-output-port)
(let* ((j/s 1 #;(jiffies-per-second))
(t0 1 #;(current-second))
(j0 1 #;(current-jiffy)))
(let loop ((i 0)
(result (if #f #f)))
(cond ((< i count)
(loop (+ i 1) (thunk)))
((ok? result)
(let* ((j1 1 #;(current-jiffy))
(t1 1 #;(current-second))
(jifs (- j1 j0))
(secs (exact->inexact (/ jifs j/s)))
(secs2 (rounded (- t1 t0))))
(display "Elapsed time: ")
(write secs)
(display " seconds (")
(write secs2)
(display ") for ")
(display name)
(newline))
result)
(else
(display "ERROR: returned incorrect result: ")
(write result)
(newline)
result)))))
(main)
| null | https://raw.githubusercontent.com/justinethier/nugget/0c4e3e9944684ea83191671d58b5c8c342f64343/benchmarks/chicken/fibfp.scm | scheme | (import (scheme base)
The following code is appended to all benchmarks.
Given an integer and an object, returns the object
without making it too easy for compilers to tell
the object will be returned.
Given the name of a benchmark,
the number of times it should be executed,
a thunk that runs the benchmark once,
and a unary predicate that is true of the
correct results the thunk may return,
runs the benchmark for the number of specified iterations.
(flush-output-port)
(jiffies-per-second))
(current-second))
(current-jiffy)))
(current-jiffy))
(current-second)) | FIBFP -- Computes ) using floating point
(scheme read)
(scheme write)
(scheme time))
(define (fibfp n)
(if (< n 2.)
n
(+ (fibfp (- n 1.))
(fibfp (- n 2.)))))
(define (main)
(let* ((count (read))
(input (read))
(output (read))
(s2 (number->string count))
(s1 (number->string input))
(name "fibfp"))
(run-r7rs-benchmark
(string-append name ":" s1 ":" s2)
count
(lambda () (fibfp (hide count input)))
(lambda (result) (= result output)))))
(define (hide r x)
(call-with-values
(lambda ()
(values (vector values (lambda (x) x))
(if (< r 100) 0 1)))
(lambda (v i)
((vector-ref v i) x))))
(define (run-r7rs-benchmark name count thunk ok?)
Rounds to thousandths .
(define (rounded x)
(/ (round (* 1000 x)) 1000))
(display "Running ")
(display name)
(newline)
(let loop ((i 0)
(result (if #f #f)))
(cond ((< i count)
(loop (+ i 1) (thunk)))
((ok? result)
(jifs (- j1 j0))
(secs (exact->inexact (/ jifs j/s)))
(secs2 (rounded (- t1 t0))))
(display "Elapsed time: ")
(write secs)
(display " seconds (")
(write secs2)
(display ") for ")
(display name)
(newline))
result)
(else
(display "ERROR: returned incorrect result: ")
(write result)
(newline)
result)))))
(main)
|
02fc853c6021f664d915d5f2c243263e9bdb91db38f5da3751f6cd582d87fd41 | gwathlobal/CotD | options.lisp | (in-package :cotd)
(defstruct options
(tiles 'large) ;;; 'large - use small tiles
;;; 'small - use large tiles
(font 'font-8x13) ;;; 'font-6x13 - use small font
;;; 'font-8x13 - use large font
(player-name "Player") ;;; default name of the player
(ignore-singlemind-messages nil) ;;; if the singlemind messages shall be hidden from the player
)
(defun read-options (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(unless (typep s-expr 'list)
(return-from read-options nil))
(cond
((equal (first s-expr) 'tiles) (set-options-tiles s-expr options))
((equal (first s-expr) 'font) (set-options-font s-expr options))
((equal (first s-expr) 'name) (set-options-name s-expr options))
((equal (first s-expr) 'ignore-singlemind-messages) (set-options-ignore-singlemind-messages s-expr options))
)
)
(defun set-options-tiles (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-tiles options) (second s-expr)))
(defun set-options-font (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-font options) (second s-expr)))
(defun set-options-name (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(loop for c across (second s-expr)
with str = ""
when (and (or (find (string-downcase (string c)) *char-list* :test #'string=)
(char= c #\Space)
(char= c #\-))
(< (length str) *max-player-name-length*))
do
(setf str (format nil "~A~A" str (string c)))
finally (setf (options-player-name options) str))
)
(defun set-options-ignore-singlemind-messages (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-ignore-singlemind-messages options) (second s-expr)))
(defun create-options-file-string (options)
(let ((str (create-string)))
(format str ";; FONT: Changes the size of text font~%;; Format (font <font type>)~%;; <font type> can be (without quotes) \"font-6x13\" or \"font-8x13\"~A~%" (new-line))
(format str "(font ~A)~A~%~A~%" (string-downcase (string (options-font options))) (new-line) (new-line))
(format str ";; NAME: Sets the default name of the player~%;; Format (name \"<player name>\"). Only alphabetical ASCII characters, spaces and minuses are allowed in names.~A~%" (new-line))
(format str "(name \"~A\")~A~%~A~%" (options-player-name options) (new-line) (new-line))
(format str ";; IGNORE-SINGLEMIND-MESSAGES: Defines if the player will see messages that are available through angel's 'singlemind' ability.~%;; Format (ignore-singlemind-messages <value>). <value> can be t (show messages) or nil (do not show messages).~A~%" (new-line))
(format str "(ignore-singlemind-messages \"~A\")~A~%~A~%" (options-ignore-singlemind-messages options) (new-line) (new-line))
str))
| null | https://raw.githubusercontent.com/gwathlobal/CotD/d01ef486cc1d3b21d2ad670ebdb443e957290aa2/src/options.lisp | lisp | 'large - use small tiles
'small - use large tiles
'font-6x13 - use small font
'font-8x13 - use large font
default name of the player
if the singlemind messages shall be hidden from the player
| (in-package :cotd)
(defstruct options
)
(defun read-options (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(unless (typep s-expr 'list)
(return-from read-options nil))
(cond
((equal (first s-expr) 'tiles) (set-options-tiles s-expr options))
((equal (first s-expr) 'font) (set-options-font s-expr options))
((equal (first s-expr) 'name) (set-options-name s-expr options))
((equal (first s-expr) 'ignore-singlemind-messages) (set-options-ignore-singlemind-messages s-expr options))
)
)
(defun set-options-tiles (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-tiles options) (second s-expr)))
(defun set-options-font (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-font options) (second s-expr)))
(defun set-options-name (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(loop for c across (second s-expr)
with str = ""
when (and (or (find (string-downcase (string c)) *char-list* :test #'string=)
(char= c #\Space)
(char= c #\-))
(< (length str) *max-player-name-length*))
do
(setf str (format nil "~A~A" str (string c)))
finally (setf (options-player-name options) str))
)
(defun set-options-ignore-singlemind-messages (s-expr options)
(log:info "S-EXPR = ~A" s-expr)
(setf (options-ignore-singlemind-messages options) (second s-expr)))
(defun create-options-file-string (options)
(let ((str (create-string)))
(format str ";; FONT: Changes the size of text font~%;; Format (font <font type>)~%;; <font type> can be (without quotes) \"font-6x13\" or \"font-8x13\"~A~%" (new-line))
(format str "(font ~A)~A~%~A~%" (string-downcase (string (options-font options))) (new-line) (new-line))
(format str ";; NAME: Sets the default name of the player~%;; Format (name \"<player name>\"). Only alphabetical ASCII characters, spaces and minuses are allowed in names.~A~%" (new-line))
(format str "(name \"~A\")~A~%~A~%" (options-player-name options) (new-line) (new-line))
(format str ";; IGNORE-SINGLEMIND-MESSAGES: Defines if the player will see messages that are available through angel's 'singlemind' ability.~%;; Format (ignore-singlemind-messages <value>). <value> can be t (show messages) or nil (do not show messages).~A~%" (new-line))
(format str "(ignore-singlemind-messages \"~A\")~A~%~A~%" (options-ignore-singlemind-messages options) (new-line) (new-line))
str))
|
70ffcdcb57d2993096badb20689273987908c29f98aac3a0caace6efb0d9acbc | fyquah/hardcaml_zprize | test_controller.ml | open! Core
open Hardcaml
open Hardcaml_waveterm
module Config = struct
let num_windows = 4
let affine_point_bits = 16
let pipeline_depth = 8
let log_stall_fifo_depth = 2
end
module Scalar_config = struct
let window_size_bits = 8
end
module Controller = Pippenger.Controller.Make (Config) (Scalar_config)
module Sim = Cyclesim.With_interface (Controller.I) (Controller.O)
module I_rules = Display_rules.With_interface (Controller.I)
module O_rules = Display_rules.With_interface (Controller.O)
let ( <-. ) a b = a := Bits.of_int ~width:(Bits.width !a) b
let scalars = [| [| 1; 2; 3; 4 |]; [| 5; 2; 1; 3 |]; [| 1; 3; 3; 5 |] |]
let%expect_test "" =
let sim =
Sim.create
~config:Cyclesim.Config.trace_all
(Controller.create ~build_mode:Simulation (Scope.create ~flatten_design:true ()))
in
let waves, sim = Waveform.create sim in
let inputs = Cyclesim.inputs sim in
inputs.clear := Bits.vdd;
Cyclesim.cycle sim;
inputs.clear := Bits.gnd;
inputs.start := Bits.vdd;
Cyclesim.cycle sim;
inputs.start := Bits.gnd;
for i = 0 to 2 do
inputs.scalar_valid := Bits.vdd;
for window = 0 to Config.num_windows - 1 do
inputs.scalar.(window).scalar <-. scalars.(i).(window);
Cyclesim.cycle sim;
Cyclesim.cycle sim
done;
inputs.scalar_valid := Bits.gnd
done;
Waveform.print
~display_width:130
~display_height:60
~wave_width:1
~start_cycle:0
~display_rules:
(List.concat
[ I_rules.default ()
; O_rules.default ()
; [ Display_rule.port_name_is "STATE" ~wave_format:(Index Controller.State.names)
; Display_rule.default
]
])
waves;
[%expect
{|
┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────────────────────────────────────────────────┐
│clock ││┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ │
│ ││ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─│
│clear ││────┐ │
│ ││ └─────────────────────────────────────────────────────────────────────────────────────────────────── │
│start ││ ┌───┐ │
│ ││────┘ └─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┬───────────────────────────────┬───────────────────────────────┬─────────────────────────────── │
│scalar_scalar0 ││ 00 │01 │05 │01 │
│ ││────────┴───────────────────────────────┴───────────────────────────────┴─────────────────────────────── │
│scalar_negative0 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────┬───────────────────────────────────────────────────────────────┬─────────────────────── │
│scalar_scalar1 ││ 00 │02 │03 │
│ ││────────────────┴───────────────────────────────────────────────────────────────┴─────────────────────── │
│scalar_negative1 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────────────┬───────────────────────────────┬───────────────────────────────┬─────────────── │
│scalar_scalar2 ││ 00 │03 │01 │03 │
│ ││────────────────────────┴───────────────────────────────┴───────────────────────────────┴─────────────── │
│scalar_negative2 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────────────────────┬───────────────────────────────┬───────────────────────────────┬─────── │
│scalar_scalar3 ││ 00 │04 │03 │05 │
│ ││────────────────────────────────┴───────────────────────────────┴───────────────────────────────┴─────── │
│scalar_negative3 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│scalar_valid ││ ┌─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┘ │
│last_scalar ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│affine_point ││ 0000 │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│done_ ││────────┐ │
│ ││ └─────────────────────────────────────────────────────────────────────────────────────────────── │
│scalar_read ││ ┌───┐ ┌───┐ ┌─── │
│ ││────────────────────────────────────┘ └───────────────────────────┘ └───────────────────────────┘ │
│ ││────────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────── │
│window ││ 0 │1 │2 │3 │0 │1 │2 │3 │0 │1 │2 │3 │
│ ││────────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────── │
│ ││────────┬───────┬───────────────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────── │
│bucket_scalar ││ 00 │01 │00 │05 │02 │03 │04 │01 │02 │01 │03 │
│ ││────────┴───────┴───────────────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────── │
│bucket_negative ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│adder_affine_point││ 0000 │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│bubble ││ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ ││────────────────────┘ └───┘ └───┘ └───────────────────────────────────┘ └───┘ └─────────────── │
│execute ││ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌─── │
│ ││────────────┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ │
│ ││────────┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬─── │
│STATE ││ - │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │
│ ││────────┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴─── │
│exec_scalar ││ ┌─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┘ │
│exec_stalled ││ │
└──────────────────┘└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ |}]
;;
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/pippenger/test/test_controller.ml | ocaml | open! Core
open Hardcaml
open Hardcaml_waveterm
module Config = struct
let num_windows = 4
let affine_point_bits = 16
let pipeline_depth = 8
let log_stall_fifo_depth = 2
end
module Scalar_config = struct
let window_size_bits = 8
end
module Controller = Pippenger.Controller.Make (Config) (Scalar_config)
module Sim = Cyclesim.With_interface (Controller.I) (Controller.O)
module I_rules = Display_rules.With_interface (Controller.I)
module O_rules = Display_rules.With_interface (Controller.O)
let ( <-. ) a b = a := Bits.of_int ~width:(Bits.width !a) b
let scalars = [| [| 1; 2; 3; 4 |]; [| 5; 2; 1; 3 |]; [| 1; 3; 3; 5 |] |]
let%expect_test "" =
let sim =
Sim.create
~config:Cyclesim.Config.trace_all
(Controller.create ~build_mode:Simulation (Scope.create ~flatten_design:true ()))
in
let waves, sim = Waveform.create sim in
let inputs = Cyclesim.inputs sim in
inputs.clear := Bits.vdd;
Cyclesim.cycle sim;
inputs.clear := Bits.gnd;
inputs.start := Bits.vdd;
Cyclesim.cycle sim;
inputs.start := Bits.gnd;
for i = 0 to 2 do
inputs.scalar_valid := Bits.vdd;
for window = 0 to Config.num_windows - 1 do
inputs.scalar.(window).scalar <-. scalars.(i).(window);
Cyclesim.cycle sim;
Cyclesim.cycle sim
done;
inputs.scalar_valid := Bits.gnd
done;
Waveform.print
~display_width:130
~display_height:60
~wave_width:1
~start_cycle:0
~display_rules:
(List.concat
[ I_rules.default ()
; O_rules.default ()
; [ Display_rule.port_name_is "STATE" ~wave_format:(Index Controller.State.names)
; Display_rule.default
]
])
waves;
[%expect
{|
┌Signals───────────┐┌Waves───────────────────────────────────────────────────────────────────────────────────────────────────────┐
│clock ││┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐ │
│ ││ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─┘ └─│
│clear ││────┐ │
│ ││ └─────────────────────────────────────────────────────────────────────────────────────────────────── │
│start ││ ┌───┐ │
│ ││────┘ └─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┬───────────────────────────────┬───────────────────────────────┬─────────────────────────────── │
│scalar_scalar0 ││ 00 │01 │05 │01 │
│ ││────────┴───────────────────────────────┴───────────────────────────────┴─────────────────────────────── │
│scalar_negative0 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────┬───────────────────────────────────────────────────────────────┬─────────────────────── │
│scalar_scalar1 ││ 00 │02 │03 │
│ ││────────────────┴───────────────────────────────────────────────────────────────┴─────────────────────── │
│scalar_negative1 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────────────┬───────────────────────────────┬───────────────────────────────┬─────────────── │
│scalar_scalar2 ││ 00 │03 │01 │03 │
│ ││────────────────────────┴───────────────────────────────┴───────────────────────────────┴─────────────── │
│scalar_negative2 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────────────────────────────┬───────────────────────────────┬───────────────────────────────┬─────── │
│scalar_scalar3 ││ 00 │04 │03 │05 │
│ ││────────────────────────────────┴───────────────────────────────┴───────────────────────────────┴─────── │
│scalar_negative3 ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│scalar_valid ││ ┌─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┘ │
│last_scalar ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│affine_point ││ 0000 │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│done_ ││────────┐ │
│ ││ └─────────────────────────────────────────────────────────────────────────────────────────────── │
│scalar_read ││ ┌───┐ ┌───┐ ┌─── │
│ ││────────────────────────────────────┘ └───────────────────────────┘ └───────────────────────────┘ │
│ ││────────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────── │
│window ││ 0 │1 │2 │3 │0 │1 │2 │3 │0 │1 │2 │3 │
│ ││────────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────── │
│ ││────────┬───────┬───────────────────────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬─────── │
│bucket_scalar ││ 00 │01 │00 │05 │02 │03 │04 │01 │02 │01 │03 │
│ ││────────┴───────┴───────────────────────┴───────┴───────┴───────┴───────┴───────┴───────┴───────┴─────── │
│bucket_negative ││ │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│adder_affine_point││ 0000 │
│ ││──────────────────────────────────────────────────────────────────────────────────────────────────────── │
│bubble ││ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ ││────────────────────┘ └───┘ └───┘ └───────────────────────────────────┘ └───┘ └─────────────── │
│execute ││ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌─── │
│ ││────────────┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ │
│ ││────────┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬─── │
│STATE ││ - │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │M │E+ │W+ │E+ │W+ │E+ │W+ │E+ │
│ ││────────┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴─── │
│exec_scalar ││ ┌─────────────────────────────────────────────────────────────────────────────────────────────── │
│ ││────────┘ │
│exec_stalled ││ │
└──────────────────┘└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ |}]
;;
|
|
6eb9a64c3ffb319af73e4e58401acbfbc6bebf83fc93b74577603b8183493a46 | AccelerationNet/function-cache | capacity.lisp | (in-package :function-cache)
(defclass cache-capacity-mixin ()
((capacity
:accessor capacity :initarg :capacity :initform nil
:documentation "The maximum number of objects cached, when we hit this we
will reduce the number of cached entries by reduce-by-ratio")
(reduce-by-ratio
:accessor reduce-by-ratio :initarg :reduce-by-ratio :initform .2
:documentation "Remove the oldest reduce-by-ratio entries (eg: .2 or 20%)")))
(defun number-to-remove (cache)
(ceiling (* (capacity cache) (reduce-by-ratio cache))))
(defmethod at-cache-capacity? ((cache cache-capacity-mixin))
(and (capacity cache)
(>= (cached-results-count cache) (capacity cache))))
(defmethod (setf get-cached-value) :before (new (cache cache-capacity-mixin) cache-key)
(when (at-cache-capacity? cache)
(reduce-cached-set cache (number-to-remove cache))))
| null | https://raw.githubusercontent.com/AccelerationNet/function-cache/6a5ada401e57da2c8abf046f582029926e61fce8/src/capacity.lisp | lisp | (in-package :function-cache)
(defclass cache-capacity-mixin ()
((capacity
:accessor capacity :initarg :capacity :initform nil
:documentation "The maximum number of objects cached, when we hit this we
will reduce the number of cached entries by reduce-by-ratio")
(reduce-by-ratio
:accessor reduce-by-ratio :initarg :reduce-by-ratio :initform .2
:documentation "Remove the oldest reduce-by-ratio entries (eg: .2 or 20%)")))
(defun number-to-remove (cache)
(ceiling (* (capacity cache) (reduce-by-ratio cache))))
(defmethod at-cache-capacity? ((cache cache-capacity-mixin))
(and (capacity cache)
(>= (cached-results-count cache) (capacity cache))))
(defmethod (setf get-cached-value) :before (new (cache cache-capacity-mixin) cache-key)
(when (at-cache-capacity? cache)
(reduce-cached-set cache (number-to-remove cache))))
|
|
0954e32fd6c22595801708bd12f4f3f43e72165ae33c64d1beaf94b08313799a | c-cube/trustee | serve.ml | open Trustee_opentheory
module Log = Trustee_core.Log
module OT = Trustee_opentheory
open OT.Common_
let top_wrap_ req f =
try f()
with
| Error.E e ->
H.Response.make_string @@
Error (404, Fmt.asprintf "internal error: %a" Error.pp e)
let mk_page ~title:title_ bod : Html.elt =
let open Html in
let bod =
div [cls "navbar"] [
ul[cls "navbar-nav"][
li[cls "nav-item"][ a [A.href "/"] [txt "home"]];
]
]
:: bod
in
html [] [
head [] [
title [] [txt title_];
meta [A.charset "utf-8"];
link [A.href "/static/bootstrap.css"; A.rel "stylesheet"];
link [A.href "/static/main.css"; A.rel "stylesheet"];
script [A.src "/static/htmx.js"] [];
];
body [] [
div[cls "container"] bod
];
]
let reply_page ~title req h =
let headers = ["content-encoding", "utf-8"] in
let res =
if H.Headers.contains "hx-request" (H.Request.headers req) then (
(* fragment *)
Html.(to_string @@ div[cls"container"]h)
) else (
Html.to_string_top @@ mk_page ~title h
)
in
H.Response.make_string ~headers @@ Ok res
type state = {
server: H.t;
st: St.t;
}
let home_txt =
Html.[
p[][txt "Welcome to Trustee!"];
p[][
txt
{|Trustee is a HOL kernel implemented in OCaml, with a few unusual design choices,
such as the pervasive use of hashconsing, explicit type application,
and de Bruijn indices.|}
];
p[][
a[A.href "-cube/trustee"][txt "see on github."];
];
p[][
txt
{| This website shows a proof-checker for |};
a[A.href "/"][txt "opentheory"];
txt {| using Trustee. This doubles as a test suite and gives an idea of
how performant the tool is.|};
];
]
let h_root (self:state) : unit =
H.add_route_handler self.server H.Route.(return) @@ fun req ->
let@ () = top_wrap_ req in
let open Html in
let res =
let {OT.Idx.thy_by_name; articles; errors; _ } = self.st.idx in
[
h2[][txt "Trustee"];
div[] home_txt;
a[A.href "/stats"][txt "context statistics"];
h2[][ txt "theories"];
ul'[A.class_ "list-group"] [
sub_l (
thy_by_name
|> Str_tbl.to_list
|> List.sort CCOrd.(map fst string)
|> List.map
(fun (name,_th) ->
li [A.class_ "list-group-item"] [
a [A.href (spf "/thy/%s" (H.Util.percent_encode name))] [txt name];
]
)
)
]
]
in
reply_page ~title:"opentheory" req res
let h_thy (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "thy" @/ string_urlencoded @/ return) @@ fun thy_name req ->
let@ () = top_wrap_ req in
let thy = Idx.find_thy self.st.idx thy_name in
let res =
let open Html in
[
div[cls "container"][
h3[][txtf "Theory %s" thy_name];
Thy_file.to_html thy;
div [
"hx-trigger", "load";
"hx-get", (spf "/eval/%s" @@ H.Util.percent_encode thy_name);
"hx-swap", "innerHtml"] [
span[cls "htmx-indicator"; A.id "ind"][
txt "[evaluating…]";
]
];
]
]
in
reply_page ~title:(spf "theory %s" thy_name) req res
let h_art (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "art" @/ string_urlencoded @/ return) @@ fun art req ->
let@ () = top_wrap_ req in
let art_file =
let@ () = St.with_lock self.st.lock in
Idx.find_article self.st.idx art in
let content = CCIO.with_in art_file CCIO.read_all in
let res = Html.[
a[A.href ""][txt "reference documentation"];
h3[] [ txtf "Article %s" art ];
p[][txtf "path: %S" art_file];
details [][
summary[][txtf "%d bytes" (String.length content)];
pre[] [txt content]
]
]
in
reply_page ~title:(spf "article %s" art) req res
let h_eval (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "eval" @/ string_urlencoded @/ return) @@ fun thy_name req ->
let@ () = top_wrap_ req in
let res =
(* need lock around ctx/eval *)
let@ () = St.with_lock self.st.lock in
Eval.eval_theory self.st.eval thy_name
in
let config =
let thy =
let@ () = St.with_lock self.st.lock in
Idx.find_thy self.st.idx thy_name in
let open_namespaces =
thy.Thy_file.meta
|> List.filter_map (fun (mk,v) ->
if mk="show" then Some (Util.unquote_str v ^ ".") else None)
in
Log.debugf 2 (fun k->k"open namespaces: [%s]" (String.concat "; " open_namespaces));
Render.Config.make ~open_namespaces ()
in
let open Html in
begin match res with
| Ok (th,ei) ->
let res = [
h3[] [txt "Evaluation information"];
Eval.eval_info_to_html ei;
Render.theory_to_html ~config th;
] in
reply_page ~title:(spf "eval %s" thy_name) req res
| Error err ->
let msg = Fmt.asprintf "%a" Error.pp err in
H.Response.make_string (Error(500, msg))
end
let h_hash_item (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "h" @/ string @/ return) @@ fun h req ->
let@ () = top_wrap_ req in
let h = Chash.of_string_exn h in
let res =
(* need lock around ctx/eval *)
let@ () = St.with_lock self.st.lock in
Chash.Tbl.find_opt self.st.idx.Idx.by_hash h
in
let r = match res with
| Some r -> r
| None -> Error.failf (fun k->k"hash not found: %a" Chash.pp h)
in
let config = Render.Config.make ~open_all_namespaces:true () in
let open Html in
let kind, res = match r with
| Idx.H_const c ->
"constant", [
h3[] [txtf "constant %a" K.Const.pp c];
pre[][Render.const_to_html ~config c];
h4[] [txt "Definition"];
Render.const_def_to_html ~config self.st.ctx c;
]
| Idx.H_expr e ->
"expression", [
pre[][Render.expr_to_html ~config e]
]
| Idx.H_thm thm ->
"theorem", [
h3[] [txt "theorem"];
Render.thm_to_html ~config thm;
h3[] [txt "proof"];
Render.proof_to_html ~config thm;
]
in
reply_page ~title:(spf "%s %s" kind @@ Chash.to_string h) req res
let h_stats self : unit =
H.add_route_handler self.server
H.Route.(exact "stats" @/ return) @@ fun req ->
let@ () = top_wrap_ req in
let res =
(* need lock around ctx/eval *)
let@ () = St.with_lock self.st.lock in
let n_exprs = K.Ctx.n_exprs self.st.ctx in
let n_theories = List.length self.st.idx.Idx.theories in
let n_hashes = Chash.Tbl.length self.st.idx.Idx.by_hash in
Html.(
table[cls "table table-striped table-sm"][
tbody[][
tr[][
td[][txt "number of exprs"];
td[][txtf "%d" n_exprs];
];
tr[][
td[][txt "number of theories"];
td[][txtf "%d" n_theories];
];
tr[][
td[][txt "number of objects indexed by their hash"];
td[][txtf "%d" n_hashes];
];
]
]
)
in
reply_page ~title:"/stats" req [res]
let serve st ~port : unit =
let server = H.create ~port () in
let state = {server; st } in
h_root state;
h_thy state;
h_art state;
h_eval state;
h_hash_item state;
h_stats state;
H.Dir.add_vfs server
~config:(H.Dir.config ~dir_behavior:H.Dir.Index_or_lists ())
~vfs:Static.vfs ~prefix:"static";
Printf.printf "listen on :%d/\n%!" port;
match H.run server with
| Ok () -> ()
| Error e -> raise e
| null | https://raw.githubusercontent.com/c-cube/trustee/397841b8ff813255f5643fef43a7187e81db21f5/src/opentheory/tool/serve.ml | ocaml | fragment
need lock around ctx/eval
need lock around ctx/eval
need lock around ctx/eval | open Trustee_opentheory
module Log = Trustee_core.Log
module OT = Trustee_opentheory
open OT.Common_
let top_wrap_ req f =
try f()
with
| Error.E e ->
H.Response.make_string @@
Error (404, Fmt.asprintf "internal error: %a" Error.pp e)
let mk_page ~title:title_ bod : Html.elt =
let open Html in
let bod =
div [cls "navbar"] [
ul[cls "navbar-nav"][
li[cls "nav-item"][ a [A.href "/"] [txt "home"]];
]
]
:: bod
in
html [] [
head [] [
title [] [txt title_];
meta [A.charset "utf-8"];
link [A.href "/static/bootstrap.css"; A.rel "stylesheet"];
link [A.href "/static/main.css"; A.rel "stylesheet"];
script [A.src "/static/htmx.js"] [];
];
body [] [
div[cls "container"] bod
];
]
let reply_page ~title req h =
let headers = ["content-encoding", "utf-8"] in
let res =
if H.Headers.contains "hx-request" (H.Request.headers req) then (
Html.(to_string @@ div[cls"container"]h)
) else (
Html.to_string_top @@ mk_page ~title h
)
in
H.Response.make_string ~headers @@ Ok res
type state = {
server: H.t;
st: St.t;
}
let home_txt =
Html.[
p[][txt "Welcome to Trustee!"];
p[][
txt
{|Trustee is a HOL kernel implemented in OCaml, with a few unusual design choices,
such as the pervasive use of hashconsing, explicit type application,
and de Bruijn indices.|}
];
p[][
a[A.href "-cube/trustee"][txt "see on github."];
];
p[][
txt
{| This website shows a proof-checker for |};
a[A.href "/"][txt "opentheory"];
txt {| using Trustee. This doubles as a test suite and gives an idea of
how performant the tool is.|};
];
]
let h_root (self:state) : unit =
H.add_route_handler self.server H.Route.(return) @@ fun req ->
let@ () = top_wrap_ req in
let open Html in
let res =
let {OT.Idx.thy_by_name; articles; errors; _ } = self.st.idx in
[
h2[][txt "Trustee"];
div[] home_txt;
a[A.href "/stats"][txt "context statistics"];
h2[][ txt "theories"];
ul'[A.class_ "list-group"] [
sub_l (
thy_by_name
|> Str_tbl.to_list
|> List.sort CCOrd.(map fst string)
|> List.map
(fun (name,_th) ->
li [A.class_ "list-group-item"] [
a [A.href (spf "/thy/%s" (H.Util.percent_encode name))] [txt name];
]
)
)
]
]
in
reply_page ~title:"opentheory" req res
let h_thy (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "thy" @/ string_urlencoded @/ return) @@ fun thy_name req ->
let@ () = top_wrap_ req in
let thy = Idx.find_thy self.st.idx thy_name in
let res =
let open Html in
[
div[cls "container"][
h3[][txtf "Theory %s" thy_name];
Thy_file.to_html thy;
div [
"hx-trigger", "load";
"hx-get", (spf "/eval/%s" @@ H.Util.percent_encode thy_name);
"hx-swap", "innerHtml"] [
span[cls "htmx-indicator"; A.id "ind"][
txt "[evaluating…]";
]
];
]
]
in
reply_page ~title:(spf "theory %s" thy_name) req res
let h_art (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "art" @/ string_urlencoded @/ return) @@ fun art req ->
let@ () = top_wrap_ req in
let art_file =
let@ () = St.with_lock self.st.lock in
Idx.find_article self.st.idx art in
let content = CCIO.with_in art_file CCIO.read_all in
let res = Html.[
a[A.href ""][txt "reference documentation"];
h3[] [ txtf "Article %s" art ];
p[][txtf "path: %S" art_file];
details [][
summary[][txtf "%d bytes" (String.length content)];
pre[] [txt content]
]
]
in
reply_page ~title:(spf "article %s" art) req res
let h_eval (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "eval" @/ string_urlencoded @/ return) @@ fun thy_name req ->
let@ () = top_wrap_ req in
let res =
let@ () = St.with_lock self.st.lock in
Eval.eval_theory self.st.eval thy_name
in
let config =
let thy =
let@ () = St.with_lock self.st.lock in
Idx.find_thy self.st.idx thy_name in
let open_namespaces =
thy.Thy_file.meta
|> List.filter_map (fun (mk,v) ->
if mk="show" then Some (Util.unquote_str v ^ ".") else None)
in
Log.debugf 2 (fun k->k"open namespaces: [%s]" (String.concat "; " open_namespaces));
Render.Config.make ~open_namespaces ()
in
let open Html in
begin match res with
| Ok (th,ei) ->
let res = [
h3[] [txt "Evaluation information"];
Eval.eval_info_to_html ei;
Render.theory_to_html ~config th;
] in
reply_page ~title:(spf "eval %s" thy_name) req res
| Error err ->
let msg = Fmt.asprintf "%a" Error.pp err in
H.Response.make_string (Error(500, msg))
end
let h_hash_item (self:state) : unit =
H.add_route_handler self.server
H.Route.(exact "h" @/ string @/ return) @@ fun h req ->
let@ () = top_wrap_ req in
let h = Chash.of_string_exn h in
let res =
let@ () = St.with_lock self.st.lock in
Chash.Tbl.find_opt self.st.idx.Idx.by_hash h
in
let r = match res with
| Some r -> r
| None -> Error.failf (fun k->k"hash not found: %a" Chash.pp h)
in
let config = Render.Config.make ~open_all_namespaces:true () in
let open Html in
let kind, res = match r with
| Idx.H_const c ->
"constant", [
h3[] [txtf "constant %a" K.Const.pp c];
pre[][Render.const_to_html ~config c];
h4[] [txt "Definition"];
Render.const_def_to_html ~config self.st.ctx c;
]
| Idx.H_expr e ->
"expression", [
pre[][Render.expr_to_html ~config e]
]
| Idx.H_thm thm ->
"theorem", [
h3[] [txt "theorem"];
Render.thm_to_html ~config thm;
h3[] [txt "proof"];
Render.proof_to_html ~config thm;
]
in
reply_page ~title:(spf "%s %s" kind @@ Chash.to_string h) req res
let h_stats self : unit =
H.add_route_handler self.server
H.Route.(exact "stats" @/ return) @@ fun req ->
let@ () = top_wrap_ req in
let res =
let@ () = St.with_lock self.st.lock in
let n_exprs = K.Ctx.n_exprs self.st.ctx in
let n_theories = List.length self.st.idx.Idx.theories in
let n_hashes = Chash.Tbl.length self.st.idx.Idx.by_hash in
Html.(
table[cls "table table-striped table-sm"][
tbody[][
tr[][
td[][txt "number of exprs"];
td[][txtf "%d" n_exprs];
];
tr[][
td[][txt "number of theories"];
td[][txtf "%d" n_theories];
];
tr[][
td[][txt "number of objects indexed by their hash"];
td[][txtf "%d" n_hashes];
];
]
]
)
in
reply_page ~title:"/stats" req [res]
let serve st ~port : unit =
let server = H.create ~port () in
let state = {server; st } in
h_root state;
h_thy state;
h_art state;
h_eval state;
h_hash_item state;
h_stats state;
H.Dir.add_vfs server
~config:(H.Dir.config ~dir_behavior:H.Dir.Index_or_lists ())
~vfs:Static.vfs ~prefix:"static";
Printf.printf "listen on :%d/\n%!" port;
match H.run server with
| Ok () -> ()
| Error e -> raise e
|
25a2e50096e5babd91af5bad01ad66cdde7bb3f72ac9f29444bfc709a4be436e | timbod7/haskell-chart | Test17.hs | module Test17 where
import Graphics.Rendering.Chart
import Data.Colour
import Data.Colour.Names
import Control.Lens
import Data.Default.Class
import Data.Time.LocalTime
import System.Random
import ExampleStocks
import Utils
-- demonstrate Candles
chart :: Double -> Renderable (LayoutPick LocalTime Double Double)
chart lwidth = layoutLRToRenderable layout
where
layout = layoutlr_title .~"Stock Prices"
$ layoutlr_background .~ solidFillStyle (opaque white)
$ layoutlr_left_axis_visibility . axis_show_ticks .~ False
$ layoutlr_plots .~ [ Right (toPlot msftArea)
, Right (toPlot msftLine)
, Right (toPlot msftCandle)
, Left (toPlot aaplArea)
, Left (toPlot aaplLine)
, Left (toPlot aaplCandle) ]
$ layoutlr_foreground .~ opaque black
$ def
aaplLine = plot_lines_style .~ lineStyle 2 green
$ plot_lines_values .~ [[ (d, cl)
| (d,(lo,op,cl,hi)) <- pricesAAPL]]
$ plot_lines_title .~ "AAPL closing"
$ def
msftLine = plot_lines_style .~ lineStyle 2 purple
$ plot_lines_values .~ [[ (d, cl)
| (d,(lo,op,cl,hi)) <- pricesMSFT]]
$ plot_lines_title .~ "MSFT closing"
$ def
aaplArea = plot_fillbetween_style .~ solidFillStyle (withOpacity green 0.4)
$ plot_fillbetween_values .~ [ (d, (lo,hi))
| (d,(lo,op,cl,hi)) <- pricesAAPL]
$ plot_fillbetween_title .~ "AAPL spread"
$ def
msftArea = plot_fillbetween_style .~ solidFillStyle (withOpacity purple 0.4)
$ plot_fillbetween_values .~ [ (d, (lo,hi))
| (d,(lo,op,cl,hi)) <- pricesMSFT]
$ plot_fillbetween_title .~ "MSFT spread"
$ def
aaplCandle = plot_candle_line_style .~ lineStyle 1 blue
$ plot_candle_fill .~ True
$ plot_candle_tick_length .~ 0
$ plot_candle_width .~ 2
$ plot_candle_values .~ [ Candle d lo op 0 cl hi
| (d,(lo,op,cl,hi)) <- pricesAAPL]
$ plot_candle_title .~ "AAPL candle"
$ def
msftCandle = plot_candle_line_style .~ lineStyle 1 red
$ plot_candle_fill .~ True
$ plot_candle_rise_fill_style .~ solidFillStyle (opaque pink)
$ plot_candle_fall_fill_style .~ solidFillStyle (opaque red)
$ plot_candle_tick_length .~ 0
$ plot_candle_width .~ 2
$ plot_candle_values .~ [ Candle d lo op 0 cl hi
| (d,(lo,op,cl,hi)) <- pricesMSFT]
$ plot_candle_title .~ "MSFT candle"
$ def
lineStyle n colour = line_width .~ n * lwidth
$ line_color .~ opaque colour
$ def ^. plot_lines_style
main = main ' " test17 " ( chart 0.25 )
| null | https://raw.githubusercontent.com/timbod7/haskell-chart/8c5a823652ea1b4ec2adbced4a92a8161065ead6/chart-tests/tests/Test17.hs | haskell | demonstrate Candles | module Test17 where
import Graphics.Rendering.Chart
import Data.Colour
import Data.Colour.Names
import Control.Lens
import Data.Default.Class
import Data.Time.LocalTime
import System.Random
import ExampleStocks
import Utils
chart :: Double -> Renderable (LayoutPick LocalTime Double Double)
chart lwidth = layoutLRToRenderable layout
where
layout = layoutlr_title .~"Stock Prices"
$ layoutlr_background .~ solidFillStyle (opaque white)
$ layoutlr_left_axis_visibility . axis_show_ticks .~ False
$ layoutlr_plots .~ [ Right (toPlot msftArea)
, Right (toPlot msftLine)
, Right (toPlot msftCandle)
, Left (toPlot aaplArea)
, Left (toPlot aaplLine)
, Left (toPlot aaplCandle) ]
$ layoutlr_foreground .~ opaque black
$ def
aaplLine = plot_lines_style .~ lineStyle 2 green
$ plot_lines_values .~ [[ (d, cl)
| (d,(lo,op,cl,hi)) <- pricesAAPL]]
$ plot_lines_title .~ "AAPL closing"
$ def
msftLine = plot_lines_style .~ lineStyle 2 purple
$ plot_lines_values .~ [[ (d, cl)
| (d,(lo,op,cl,hi)) <- pricesMSFT]]
$ plot_lines_title .~ "MSFT closing"
$ def
aaplArea = plot_fillbetween_style .~ solidFillStyle (withOpacity green 0.4)
$ plot_fillbetween_values .~ [ (d, (lo,hi))
| (d,(lo,op,cl,hi)) <- pricesAAPL]
$ plot_fillbetween_title .~ "AAPL spread"
$ def
msftArea = plot_fillbetween_style .~ solidFillStyle (withOpacity purple 0.4)
$ plot_fillbetween_values .~ [ (d, (lo,hi))
| (d,(lo,op,cl,hi)) <- pricesMSFT]
$ plot_fillbetween_title .~ "MSFT spread"
$ def
aaplCandle = plot_candle_line_style .~ lineStyle 1 blue
$ plot_candle_fill .~ True
$ plot_candle_tick_length .~ 0
$ plot_candle_width .~ 2
$ plot_candle_values .~ [ Candle d lo op 0 cl hi
| (d,(lo,op,cl,hi)) <- pricesAAPL]
$ plot_candle_title .~ "AAPL candle"
$ def
msftCandle = plot_candle_line_style .~ lineStyle 1 red
$ plot_candle_fill .~ True
$ plot_candle_rise_fill_style .~ solidFillStyle (opaque pink)
$ plot_candle_fall_fill_style .~ solidFillStyle (opaque red)
$ plot_candle_tick_length .~ 0
$ plot_candle_width .~ 2
$ plot_candle_values .~ [ Candle d lo op 0 cl hi
| (d,(lo,op,cl,hi)) <- pricesMSFT]
$ plot_candle_title .~ "MSFT candle"
$ def
lineStyle n colour = line_width .~ n * lwidth
$ line_color .~ opaque colour
$ def ^. plot_lines_style
main = main ' " test17 " ( chart 0.25 )
|
4f4e2a98b838f47069b23de0d3e582542ae3ad1b9ef17d0f4e88d207637b55e9 | qkrgud55/ocamlmulti | genlex.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. *)
(* *)
(***********************************************************************)
$ I d : genlex.mli 12210 2012 - 03 - 08 19:52:03Z doligez $
* A generic lexical analyzer .
This module implements a simple ` ` standard '' lexical analyzer , presented
as a function from character streams to token streams . It implements
roughly the lexical conventions of OCaml , but is parameterized by the
set of keywords of your language .
Example : a lexer suitable for a desk calculator is obtained by
{ [ let lexer = make_lexer [ " + " ; " -";"*";"/";"let";"= " ; " ( " ; " ) " ] ] }
The associated parser would be a function from [ token stream ]
to , for instance , [ int ] , and would have rules such as :
{ [
let parse_expr = parser
[ < ' Int n > ] - > n
| [ < ' Kwd " ( " ; n = parse_expr ; ' Kwd " ) " > ] - > n
| [ < n1 = parse_expr ; n2 = parse_remainder n1 > ] - > n2
and parse_remainder n1 = parser
[ < ' Kwd " + " ; n2 = parse_expr > ] - > n1+n2
| ...
] }
One should notice that the use of the [ parser ] keyword and associated
notation for streams are only available through extensions . This
means that one has to preprocess its sources { i by using the
[ " -pp " ] command - line switch of the compilers .
This module implements a simple ``standard'' lexical analyzer, presented
as a function from character streams to token streams. It implements
roughly the lexical conventions of OCaml, but is parameterized by the
set of keywords of your language.
Example: a lexer suitable for a desk calculator is obtained by
{[ let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"] ]}
The associated parser would be a function from [token stream]
to, for instance, [int], and would have rules such as:
{[
let parse_expr = parser
[< 'Int n >] -> n
| [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
| [< n1 = parse_expr; n2 = parse_remainder n1 >] -> n2
and parse_remainder n1 = parser
[< 'Kwd "+"; n2 = parse_expr >] -> n1+n2
| ...
]}
One should notice that the use of the [parser] keyword and associated
notation for streams are only available through camlp4 extensions. This
means that one has to preprocess its sources {i e. g.} by using the
["-pp"] command-line switch of the compilers.
*)
* The type of tokens . The lexical classes are : [ Int ] and [ Float ]
for integer and floating - point numbers ; [ String ] for
string literals , enclosed in double quotes ; [ ] for
character literals , enclosed in single quotes ; [ Ident ] for
identifiers ( either sequences of letters , digits , underscores
and quotes , or sequences of ` ` operator characters '' such as
[ + ] , [ * ] , etc ) ; and [ Kwd ] for keywords ( either identifiers or
single ` ` special characters '' such as [ ( ] , [ } ] , etc ) .
for integer and floating-point numbers; [String] for
string literals, enclosed in double quotes; [Char] for
character literals, enclosed in single quotes; [Ident] for
identifiers (either sequences of letters, digits, underscores
and quotes, or sequences of ``operator characters'' such as
[+], [*], etc); and [Kwd] for keywords (either identifiers or
single ``special characters'' such as [(], [}], etc). *)
type token =
Kwd of string
| Ident of string
| Int of int
| Float of float
| String of string
| Char of char
val make_lexer : string list -> char Stream.t -> token Stream.t
* Construct the lexer function . The first argument is the list of
keywords . An identifier [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and as [ Ident s ] otherwise .
A special character [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and cause a lexical error ( exception
[ Parse_error ] ) otherwise . Blanks and newlines are skipped .
Comments delimited by [ ( * ] and [
keywords. An identifier [s] is returned as [Kwd s] if [s]
belongs to this list, and as [Ident s] otherwise.
A special character [s] is returned as [Kwd s] if [s]
belongs to this list, and cause a lexical error (exception
[Parse_error]) otherwise. Blanks and newlines are skipped.
Comments delimited by [(*] and [*)] are skipped as well,
and can be nested. *)
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/stdlib_r/genlex.mli | ocaml | *********************************************************************
OCaml
the special exception on linking described in file ../LICENSE.
*********************************************************************
] and [ | , 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
$ I d : genlex.mli 12210 2012 - 03 - 08 19:52:03Z doligez $
* A generic lexical analyzer .
This module implements a simple ` ` standard '' lexical analyzer , presented
as a function from character streams to token streams . It implements
roughly the lexical conventions of OCaml , but is parameterized by the
set of keywords of your language .
Example : a lexer suitable for a desk calculator is obtained by
{ [ let lexer = make_lexer [ " + " ; " -";"*";"/";"let";"= " ; " ( " ; " ) " ] ] }
The associated parser would be a function from [ token stream ]
to , for instance , [ int ] , and would have rules such as :
{ [
let parse_expr = parser
[ < ' Int n > ] - > n
| [ < ' Kwd " ( " ; n = parse_expr ; ' Kwd " ) " > ] - > n
| [ < n1 = parse_expr ; n2 = parse_remainder n1 > ] - > n2
and parse_remainder n1 = parser
[ < ' Kwd " + " ; n2 = parse_expr > ] - > n1+n2
| ...
] }
One should notice that the use of the [ parser ] keyword and associated
notation for streams are only available through extensions . This
means that one has to preprocess its sources { i by using the
[ " -pp " ] command - line switch of the compilers .
This module implements a simple ``standard'' lexical analyzer, presented
as a function from character streams to token streams. It implements
roughly the lexical conventions of OCaml, but is parameterized by the
set of keywords of your language.
Example: a lexer suitable for a desk calculator is obtained by
{[ let lexer = make_lexer ["+";"-";"*";"/";"let";"="; "("; ")"] ]}
The associated parser would be a function from [token stream]
to, for instance, [int], and would have rules such as:
{[
let parse_expr = parser
[< 'Int n >] -> n
| [< 'Kwd "("; n = parse_expr; 'Kwd ")" >] -> n
| [< n1 = parse_expr; n2 = parse_remainder n1 >] -> n2
and parse_remainder n1 = parser
[< 'Kwd "+"; n2 = parse_expr >] -> n1+n2
| ...
]}
One should notice that the use of the [parser] keyword and associated
notation for streams are only available through camlp4 extensions. This
means that one has to preprocess its sources {i e. g.} by using the
["-pp"] command-line switch of the compilers.
*)
* The type of tokens . The lexical classes are : [ Int ] and [ Float ]
for integer and floating - point numbers ; [ String ] for
string literals , enclosed in double quotes ; [ ] for
character literals , enclosed in single quotes ; [ Ident ] for
identifiers ( either sequences of letters , digits , underscores
and quotes , or sequences of ` ` operator characters '' such as
[ + ] , [ * ] , etc ) ; and [ Kwd ] for keywords ( either identifiers or
single ` ` special characters '' such as [ ( ] , [ } ] , etc ) .
for integer and floating-point numbers; [String] for
string literals, enclosed in double quotes; [Char] for
character literals, enclosed in single quotes; [Ident] for
identifiers (either sequences of letters, digits, underscores
and quotes, or sequences of ``operator characters'' such as
[+], [*], etc); and [Kwd] for keywords (either identifiers or
single ``special characters'' such as [(], [}], etc). *)
type token =
Kwd of string
| Ident of string
| Int of int
| Float of float
| String of string
| Char of char
val make_lexer : string list -> char Stream.t -> token Stream.t
* Construct the lexer function . The first argument is the list of
keywords . An identifier [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and as [ Ident s ] otherwise .
A special character [ s ] is returned as [ Kwd s ] if [ s ]
belongs to this list , and cause a lexical error ( exception
[ Parse_error ] ) otherwise . Blanks and newlines are skipped .
Comments delimited by [ ( * ] and [
keywords. An identifier [s] is returned as [Kwd s] if [s]
belongs to this list, and as [Ident s] otherwise.
A special character [s] is returned as [Kwd s] if [s]
belongs to this list, and cause a lexical error (exception
[Parse_error]) otherwise. Blanks and newlines are skipped.
and can be nested. *)
|
87b43d13943219e0750e8c0c8be46154233cdc54d291aced3a6bd97cc2b6ad4d | kaoskorobase/hsc3-server | sine-grains.hs | import Control.Concurrent.MVar
import Control.Monad (void, when)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Sound.SC3.UGen
import Sound.SC3.Server.State.Monad
import Sound.SC3.Server.State.Monad.Command
-- You need the hsc3-server-internal package in order to use the internal server
--import Sound.SC3.Server.Monad.Process.Internal (withDefaultInternal)
import Sound.SC3.Server.State.Monad.Process (withDefaultSynth)
import Sound.OSC (pauseThread, pauseThreadUntil)
import qualified Sound.OSC as OSC
import System.Posix.Signals (installHandler, keyboardSignal, Handler(Catch))
import System.Random
-- Simple sine grain synthdef with frequency and amplitude controls and an ASR envelope.
sine :: UGen
sine = out 0 $ pan2 x (sinOsc KR 1 0 * 0.6) 1
where x = sinOsc AR (control KR "freq" 440) 0
* control KR "amp" 1
* envGen KR (control KR "gate" 1) 1 0 1 RemoveSynth (envASR 0.02 1 0.1 EnvLin)
| Once a second ask for the server status and print it .
statusLoop :: Server ()
statusLoop = do
statusM >>= liftIO . print
pauseThread 1
statusLoop
-- | Latency imposed on packets sent to the server.
latency :: Double
latency = 0.03
-- | Random sine grain generator loop.
grainLoop :: MVar a -> SynthDef -> Double -> Double -> Double -> Server ()
grainLoop quit synthDef delta sustain t = do
Get a random frequency between 100 and 800 Hz
f <- liftIO $ randomRIO (100,800)
Get a random amplitude between 0.1 and 0.3
a <- liftIO $ randomRIO (0.1,0.3)
-- Get the root node
r <- rootNode
Create a synth of the sine grain SynthDef with the random freqyency and amplitude from above
Schedule the synth for execution in ' latency ' seconds in order to avoid jitter
synth <- (t + latency) `exec` s_new synthDef AddToTail r [("freq", f), ("amp", a)]
Fork a thread for releasing the synth after ' sustain ' seconds
fork $ do
-- Calculate the time at which to release the synth and pause
let t' = t + sustain
pauseThreadUntil t'
-- Release the synth, taking latency into account
(t' + latency) `exec` s_release 0 synth
-- Calculate the time for the next iteration and pause
let t' = t + delta
pauseThreadUntil t'
-- Check whether to exit the loop and recurse
b <- liftIO $ isEmptyMVar quit
when b $ grainLoop quit synthDef delta sustain t'
newBreakHandler :: IO (MVar ())
newBreakHandler = do
quit <- newEmptyMVar
void $ installHandler keyboardSignal
(Catch $ putStrLn "Quitting..." >> putMVar quit ())
Nothing
return quit
main :: IO ()
main = do
-- Install keyboard break handler
quit <- newBreakHandler
-- Run an scsynth process
-- You need the hsc3-server-internal package in order to use the internal server
-- withDefaultInternal $ do
withDefaultSynth $ do
Create a new SynthDef
sd <- exec_ $ d_recv "hsc3-server:sine" sine
-- Fork the status display loop
fork statusLoop
-- Enter the grain loop
grainLoop quit sd 0.03 0.06 =<< liftIO OSC.time
takeMVar quit
| null | https://raw.githubusercontent.com/kaoskorobase/hsc3-server/7e87e59619a23d44367c98cfdb21ca263a3aa8f9/examples/sine-grains.hs | haskell | You need the hsc3-server-internal package in order to use the internal server
import Sound.SC3.Server.Monad.Process.Internal (withDefaultInternal)
Simple sine grain synthdef with frequency and amplitude controls and an ASR envelope.
| Latency imposed on packets sent to the server.
| Random sine grain generator loop.
Get the root node
Calculate the time at which to release the synth and pause
Release the synth, taking latency into account
Calculate the time for the next iteration and pause
Check whether to exit the loop and recurse
Install keyboard break handler
Run an scsynth process
You need the hsc3-server-internal package in order to use the internal server
withDefaultInternal $ do
Fork the status display loop
Enter the grain loop | import Control.Concurrent.MVar
import Control.Monad (void, when)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Sound.SC3.UGen
import Sound.SC3.Server.State.Monad
import Sound.SC3.Server.State.Monad.Command
import Sound.SC3.Server.State.Monad.Process (withDefaultSynth)
import Sound.OSC (pauseThread, pauseThreadUntil)
import qualified Sound.OSC as OSC
import System.Posix.Signals (installHandler, keyboardSignal, Handler(Catch))
import System.Random
sine :: UGen
sine = out 0 $ pan2 x (sinOsc KR 1 0 * 0.6) 1
where x = sinOsc AR (control KR "freq" 440) 0
* control KR "amp" 1
* envGen KR (control KR "gate" 1) 1 0 1 RemoveSynth (envASR 0.02 1 0.1 EnvLin)
| Once a second ask for the server status and print it .
statusLoop :: Server ()
statusLoop = do
statusM >>= liftIO . print
pauseThread 1
statusLoop
latency :: Double
latency = 0.03
grainLoop :: MVar a -> SynthDef -> Double -> Double -> Double -> Server ()
grainLoop quit synthDef delta sustain t = do
Get a random frequency between 100 and 800 Hz
f <- liftIO $ randomRIO (100,800)
Get a random amplitude between 0.1 and 0.3
a <- liftIO $ randomRIO (0.1,0.3)
r <- rootNode
Create a synth of the sine grain SynthDef with the random freqyency and amplitude from above
Schedule the synth for execution in ' latency ' seconds in order to avoid jitter
synth <- (t + latency) `exec` s_new synthDef AddToTail r [("freq", f), ("amp", a)]
Fork a thread for releasing the synth after ' sustain ' seconds
fork $ do
let t' = t + sustain
pauseThreadUntil t'
(t' + latency) `exec` s_release 0 synth
let t' = t + delta
pauseThreadUntil t'
b <- liftIO $ isEmptyMVar quit
when b $ grainLoop quit synthDef delta sustain t'
newBreakHandler :: IO (MVar ())
newBreakHandler = do
quit <- newEmptyMVar
void $ installHandler keyboardSignal
(Catch $ putStrLn "Quitting..." >> putMVar quit ())
Nothing
return quit
main :: IO ()
main = do
quit <- newBreakHandler
withDefaultSynth $ do
Create a new SynthDef
sd <- exec_ $ d_recv "hsc3-server:sine" sine
fork statusLoop
grainLoop quit sd 0.03 0.06 =<< liftIO OSC.time
takeMVar quit
|
8a6690a4e95118b49388c5ec9660b6dd4691a52ff18217a79a1f68b23cb55b2d | lisp/de.setf.utility | modpackage.lisp | -*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.utility.implementation ; -*-
This file is part of the ' de.setf.utility ' Common Lisp library .
;;; It defines package operators with provisions for side-effects on exxisting packages.
Copyright 2003 , 2009 , 2010 [ ) All Rights Reserved
;;; 'de.setf.utility' is free software: you can redistribute it and/or modify
it under the terms of version 3 of the GNU Lesser General Public License as published by
the Free Software Foundation .
;;;
;;; 'de.setf.utility' 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.
;;;
A copy of the GNU Lesser General Public License should be included with ' de.setf.utility , as ` lgpl.txt ` .
;;; If not, see the GNU [site](/).
;;;
;;; content : several package operators to extend and/or standardize defpackage
;;;
;;; modpackage (package-designator &rest options)
;;; A macro to define or modify the designated package. The options include operations with
;;; side-effects on existing packages.
;;;
ensure - package ( designator & key if - exists if - does - not - exist )
;;; modify a ackage's existence to create, load, delete based its curent existence and the
;;; existence arguments
;;;
;;; modify-package (package &rest options)
;;; function implementation for the modpackage macro.
;;;
;;; In particular,
;;; with defined behavior for repeated operations
;;;
;;; as a special-case, this file defines the implementation package and the utility package.
it should be loaded as the first of the utility source files , as they require the implementation package
;;; to exist and use its package definition operator to extend the interface package.
;;;
20030328 neither openmcl nor allegro5 . * support package documentation
20030412 corrected : export - only , : export - from order to preceed other : export- * options
20030416 correct load - package to look first for a binary file ( still without regard to write date )
20030416 and added optional separate package file
20030419 observe exisiting accessibles for : import - from and : export - to , but not : export - from and : export - through
20030419 signal error / cerror for : shadowing - inport - from shadowing - inport - to
20030419 stable - sort for operation ordering , with changes to precedence predicate to return nil for self reference
20030419 explicit : use nil argument to make - package in ensure - package
;;; 20030901 :ensure method to modify-package;
;;; 20030901 replaced package-search-path* with a single *package-host-name* to avoid problems with host-free logical pathnames
20030901 optional package file is < designator>-package rather than < designator>/package to allow arbitrary content
20030901 in subdirectories
20031212.jaa changed package op order to : export - from : export - only since the import must happen first
20040106.jaa exported * package - host - name * ; added package as load - package designator
20050525.janderson single - case symbol names
20090303.janderson unified utility packages ; import modpackage into cl - user
20100203.janderson unified with asdf for loading
20100210.janderson initial package definitions ( this file and pathnames ) in one place
(in-package :de.setf.utility.implementation)
(eval-when (:execute :load-toplevel :compile-toplevel)
(import '(modpackage) :common-lisp-user)
(defparameter *package-operations*
'(:purge :clear :ensure
:like :shadow :shadowing-import-from :use-only :use
:import-only :import-from :intern-only :intern
:export-from :export-only :unexport :export :alias :nicknames
:shadowing-import-to :use-by :export-through :version)))
(defmacro defvarconstant (name value &optional documentation)
(let ((name-var (gensym)))
`(defconstant ,name
(let ((,name-var ,value))
(if (boundp ',name)
(progn (assert (equalp (symbol-value ',name) ,name-var) ()
"Previous value for constant ~a not equal to new binding: ~s."
',name ,name-var)
(symbol-value ',name))
,name-var))
,@(when documentation (list documentation)))))
(defparameter *package-host-name* "library"
"Used by functions ensure-package and load-package.
The *package-host-name* variable should be bound to a logical host name which
designates translations which comprise the possible locations of loadable package implementations.")
(defparameter *binary-type* (pathname-type (compile-file-pathname "file.LISP")))
(define-condition package-not-found (#+(and mcl digitool) ccl::no-such-package warning)
((package :initform nil)
(name :initform nil :initarg :name)
(pathname :initform nil :initarg :pathname))
(:report (lambda (condition stream)
(with-slots (name pathname) condition
(format stream "package not found: ~a~@[ in pathname: ~s~]." name pathname)))))
(defun intern-symbol-name (datum in-package)
(etypecase datum
(string )
((and symbol (not null)) (setf datum (string datum))))
(intern datum in-package))
(defun find-symbol-name (datum in-package)
(etypecase datum
(string )
((and symbol (not null)) (setf datum (string datum))))
(or (find-symbol datum in-package) (error "symbol not found: ~s ~s" datum in-package)))
(defun call-with-symbol-names (function designators)
(if (listp designators)
(let* ((length (length designators))
(names (make-list length)))
(declare (fixnum length) (dynamic-extent names))
(flet ((string-first (symbols designators)
(setf (first symbols) (string (first designators)))))
(declare (dynamic-extent #'string-first))
(mapl #'string-first names designators)
(funcall function names)))
(funcall function (string designators)))
(values))
(defun call-with-interned-symbols (function designators in-package)
(if (listp designators)
(let* ((length (length designators))
(symbols (make-list length)))
(declare (fixnum length) (dynamic-extent symbols))
(flet ((intern-first (symbols designators)
(setf (first symbols) (intern-symbol-name (first designators) in-package))))
(declare (dynamic-extent #'intern-first))
(mapl #'intern-first symbols designators)
(funcall function symbols)))
(funcall function (intern-symbol-name designators in-package)))
in-package)
(defun call-with-found-symbols (function designators in-package)
(if (listp designators)
(let* ((length (length designators))
(symbols (make-list length)))
(declare (fixnum length) (dynamic-extent symbols))
(flet ((find-first (symbols designators)
(setf (first symbols) (find-symbol-name (first designators) in-package))))
(declare (dynamic-extent #'find-first))
(mapl #'find-first symbols designators)
(funcall function symbols)))
(funcall function (find-symbol-name designators in-package))))
(defun string-match-p (string pattern)
#+ccl(ccl::%component-match-p string pattern)
#-ccl(error "no definition available for string-match-p: ~s: ~s" string pattern))
(defun find-packages (wildname &key (if-does-not-exist nil))
(or (remove-if (complement #'(lambda (package)
(flet ((test-name (name) (string-match-p name wildname)))
(or (test-name (package-name package))
(dolist (nickname (package-nicknames package))
(when (test-name nickname) (return t)))))))
(list-all-packages) :key #'package-name)
(ecase if-does-not-exist
((nil) nil)
(:error (error 'package-not-found :name wildname :pathname nil)))))
(defgeneric modify-package-operation (package operation arguments)
(:method ((package t) (operation t) (arguments t))
(modify-package-operation (ensure-package package :if-does-not-exist :error) operation arguments))
(:method ((package package) (operation t) (symbol t))
(modify-package-operation package operation (list symbol)))
(:method ((package package) (operation t) (symbols list))
(no-applicable-method #'modify-package-operation package operation symbols))
(:method ((package package) (operation (eql :clear)) (arguments t))
(unuse-package (package-use-list package) package)
(dolist (using-package (package-used-by-list package)) (unuse-package package using-package))
(do-all-symbols (symbol package) (unintern symbol package)))
(:method ((package package) (operation (eql :ensure)) (arguments cons))
(dolist (to-ensure arguments)
(ensure-package to-ensure :if-does-not-exist :load)))
(:method ((package package) (operation (eql :like)) (arguments cons))
(modify-package-operation package :like (first arguments))
(when (rest arguments)
(apply #'modify-package package (rest arguments))))
(:method ((package package) (operation (eql :like)) (prototype t))
(modify-package-operation package :like (ensure-package prototype :if-does-not-exist :error)))
(:method ((package package) (operation (eql :like)) (prototype package))
(modify-package-operation package :clear nil)
(when (package-shadowing-symbols prototype)
(shadowing-import (package-shadowing-symbols prototype) package))
(dolist (using-package (package-used-by-list prototype)) (use-package package using-package))
(dolist (used-package (package-use-list prototype)) (use-package used-package package))
(with-package-iterator (next-symbol prototype :internal :external)
(loop (multiple-value-bind (more-p symbol accessibility) (next-symbol)
(unless more-p (return))
(ecase accessibility
(:external (import symbol package) (export symbol package))
(:internal (import symbol package)))))))
(:method ((package package) (operation (eql :alias)) (arguments list))
(flet ((do-alias (names)
(unless (listp names) (setf names (list names)))
(rename-package package (package-name package) (union names (package-nicknames package) :test #'string=))))
(declare (dynamic-extent #'do-alias))
(call-with-symbol-names #'do-alias arguments)))
(:method ((package package) (operation (eql :nicknames)) (nicknames list))
(rename-package package (package-name package) (mapcar #'string nicknames)))
(:method ((package package) (operation (eql :export-only)) (symbols list))
(flet ((do-export (symbols) (export symbols package)))
(declare (dynamic-extent #'do-export))
(do-external-symbols (symbol package)
(unless (find symbol symbols :test #'string=) (unexport symbol package)))
(when symbols
(call-with-interned-symbols #'do-export symbols package))))
(:method ((package package) (operation (eql :export)) (symbols list))
(flet ((do-export (symbols) (export symbols package)))
(declare (dynamic-extent #'do-export))
(call-with-interned-symbols #'do-export symbols package)))
(:method ((package package) (operation (eql :unexport)) (symbols list))
(flet ((do-unexport (symbols) (unexport symbols package)))
(declare (dynamic-extent #'do-unexport))
(call-with-interned-symbols #'do-unexport symbols package)))
(:method ((package package) (operation (eql :intern)) (symbols list))
(call-with-interned-symbols #'identity symbols package))
(:method ((package package) (operation (eql :intern-only)) (symbols list))
(with-package-iterator (next-symbol package :internal)
(loop (multiple-value-bind (more-p symbol) (next-symbol)
(unless more-p (return))
(unless (or (find symbol symbols :test #'string=)
(find symbol (package-shadowing-symbols package)))
(unintern symbol package))))
(when symbols
(call-with-interned-symbols #'identity symbols package))))
(:method ((package package) (operation (eql :import-from)) (source-and-symbols list))
(flet ((do-import (symbol) (import symbol package)))
(declare (dynamic-extent #'do-import))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-found-symbols #'do-import symbols source-package)
(do-external-symbols (symbol source-package)
(unless (find symbol (package-shadowing-symbols package) :test #'string=)
(do-import symbol)))))))
(:method ((package package) (operation (eql :import-only)) (source-and-symbols list))
(with-package-iterator (next-symbol package :internal)
(loop (multiple-value-bind (more-p symbol) (next-symbol)
(unless more-p (return))
(unless (eq (symbol-package symbol) package)
(unintern symbol package))))
(when source-and-symbols
(modify-package-operation package :import-from source-and-symbols))))
(:method ((package package) (operation (eql :shadow)) (symbols list))
(flet ((do-shadow (symbols) (shadow symbols package)))
(declare (dynamic-extent #'do-shadow))
(when symbols
(call-with-interned-symbols #'do-shadow symbols package))))
(:method ((package package) (operation (eql :shadowing-import-from)) (source-and-symbols list))
(labels ((do-shadowing-import (symbol &aux accessible)
(if (setf accessible (find-symbol (string symbol) package))
(if (eq accessible symbol)
(unless (find symbol (package-shadowing-symbols package))
(shadowing-import symbol package))
(if (eq (symbol-package accessible) package)
(error "symbol already present in package: ~s: ~s: ~s" symbol accessible package)
(progn (cerror "allow new symbol to shadow accessible symbol: ~s: ~s."
(make-condition 'package-error :package package)
symbol accessible)
(shadowing-import symbol package))))
(shadowing-import symbol package)))
(do-shadowing-import-list (symbols) (dolist (symbol symbols) (do-shadowing-import symbol))))
(declare (dynamic-extent #'do-shadowing-import-list #'do-shadowing-import))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-interned-symbols #'do-shadowing-import-list symbols source-package)
(do-external-symbols (symbol source-package)
(do-shadowing-import symbol))))))
(:method ((package package) (operation (eql :shadowing-import-to)) (destination-and-symbols list))
(let ((destination-package (first destination-and-symbols))
(symbols (rest destination-and-symbols)))
(labels ((do-shadowing-import (symbol &aux accessible)
(if (setf accessible (find-symbol (string symbol) destination-package))
(if (eq accessible symbol)
(unless (find symbol (package-shadowing-symbols destination-package))
(shadowing-import symbol destination-package))
(if (eq (symbol-package accessible) destination-package)
(error "symbol already present in package: ~s: ~s: ~s" symbol accessible destination-package)
(progn (cerror "allow new symbol to shadow accessible symbol: ~s: ~s."
(make-condition 'package-error :package destination-package)
symbol accessible)
(shadowing-import symbol destination-package))))
(shadowing-import symbol destination-package)))
(do-shadowing-import-list (symbols) (dolist (symbol symbols) (do-shadowing-import symbol))))
(declare (dynamic-extent #'do-shadowing-import-list #'do-shadowing-import))
(if symbols
(call-with-interned-symbols #'do-shadowing-import-list symbols package)
(do-external-symbols (symbol package)
(do-shadowing-import symbol))))))
(:method ((package package) (operation (eql :export-from)) (source-and-symbols list))
"Export symbols originating in the given package: (origin . designators)
If no symbols are specified, then export all external symbols."
(flet ((do-import-export (symbol) (import symbol package) (export symbol package)))
(declare (dynamic-extent #'do-import-export))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-interned-symbols #'do-import-export symbols source-package)
;; do all and don't allow for shadowing
(do-external-symbols (symbol source-package) (do-import-export symbol))))))
(:method ((package package) (operation (eql :export-through)) (destination-and-symbols list))
(let ((destination-package (ensure-package (first destination-and-symbols) :if-does-not-exist :error))
(symbols (rest destination-and-symbols)))
;; the symbol may be present in the other package or may be new
(if symbols
(flet ((do-export-export (symbol) (export symbol package)
(import symbol destination-package)
(export symbol destination-package)))
(declare (dynamic-extent #'do-export-export))
(dolist (symbol symbols)
(when (setf symbol (find-symbol (string symbol) destination-package))
(import symbol package)))
(call-with-interned-symbols #'do-export-export symbols package))
;; do all and don't allow for shadowing
(do-external-symbols (symbol package)
(import symbol destination-package) (export symbol destination-package)))))
(:method ((package package) (operation (eql :use-only)) (packages list))
(let ((packages-used (package-use-list package)))
(when packages-used (unuse-package packages-used package)))
(use-package packages package))
(:method ((package package) (operation (eql :use)) (packages list))
(when packages (use-package packages package)))
(:method ((package package) (operation (eql :use-by)) (packages list))
(dolist (other-package packages) (use-package package other-package)))
(:method ((package package) (operation (eql :version)) (version cons))
(modify-package-operation package operation (first version)))
(:method ((package package) (operation (eql :version)) (version t))
(setf (package-version package) version))
(:method ((package package) (operation (eql :documentation)) (documentation cons))
#-(or (and allegro allegro-version>= (not (version>= 6 0))) clisp)
(setf (documentation package t) (first documentation))
documentation)
(:method ((package package) (operation (eql :documentation)) (documentation t))
#-(or (and allegro allegro-version>= (not (version>= 6 0))) clisp)
(setf (documentation package t) documentation)
documentation)
(:method ((package package) (operation (eql :purge)) (argument t))
(dolist (using-package (package-used-by-list package))
(unuse-package package using-package))
(dolist (importing-package (list-all-packages))
(with-package-iterator (next-symbol importing-package :internal :external)
(loop (multiple-value-bind (more-p symbol access) (next-symbol)
(unless more-p (return))
(when (eq (symbol-package symbol) package)
(multiple-value-bind (again-symbol access) (find-symbol (symbol-name symbol) package)
(when (eq access :external) (unexport again-symbol package)))
(unintern symbol package)
(when (eq access :external)
(unexport symbol importing-package))
(unintern symbol importing-package)
(import symbol importing-package)
(when (eq access :external)
(export symbol importing-package)))))))
(when argument (delete-package package))))
(defgeneric modify-package-operation-preceeds-p (operation1 operation2)
(:method :before ((op1 (eql :purge)) (op2 t)) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op2 t) (op1 (eql :purge))) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op1 (eql :clear)) (op2 t)) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op2 t) (op1 (eql :clear))) (error "package operation permitted alone only: ~s." op1))
(:method ((op1 t) (op2 t)) (member op2 (rest (member op1 *package-operations*)))))
#|
(sort '(:documentation :version :export-only :export-from :export-from :export-from :export-from :export )
#'modify-package-operation-preceeds-p)
|#
(defgeneric modify-package (package &rest options)
(:method ((package t) &rest args)
(apply #'modify-package (ensure-package package :if-does-not-exist :error) args))
(:method ((package string) &rest args)
(if (wild-pathname-p package)
(apply #'modify-package (find-packages package :if-does-not-exist :error) args)
(call-next-method)))
(:method ((packages list) &rest args)
(dolist (package packages)
(apply #'modify-package package args)))
(:method ((package package) &rest options)
(unless (evenp (length options))
(error "illegal option list: ~s." options))
(do ((key (pop options) (pop options))
(arguments (pop options) (pop options)))
((null key))
(modify-package-operation package key arguments))
package))
(defmacro modPackage (name-and-args &rest options)
"modify a package as specified. the options include those of defpackage.
additional specifications support inter-package operations.
if the package exists, it is destructively modified."
(let ((package-form `(ensure-package ,(string (if (consp name-and-args) (first name-and-args) name-and-args))
,@(when (consp name-and-args) (rest name-and-args)))))
(labels ((check-modpackage-option (option)
(destructuring-bind (operation . arguments) option
(unless (compute-applicable-methods #'modify-package-operation (list *package* operation arguments))
(error "illegal option: ~s not supported by ~s." (first option) #'modify-package-operation))
(case operation
(:like
`(:like '(,(string (first arguments))
,@(apply #'append
(stable-sort (mapcar #'check-modpackage-option (rest arguments))
#'modify-package-operation-preceeds-p
:key #'first)))))
(t
(list operation
(when arguments (list 'quote (mapcar #'string arguments)))))))))
`(eval-when (:execute :load-toplevel :compile-toplevel)
(modify-package ,package-form ,@(apply #'append
(stable-sort (mapcar #'check-modpackage-option options)
#'modify-package-operation-preceeds-p
:key #'first)))))))
#+(and mcl digitool)
(pushnew '(modPackage . 1) *fred-special-indent-alist* :key #'first)
#+source-analysis
(de.setf.utility.documentation:defSourceForm (modPackage :class de.setf.utility.documentation:package-source :category package))
(defgeneric package-pathname (designator)
(:documentation
"used to transform a designator for a package location into a logical pathname - minus the file type.")
# \. designator ) ) ) )
(:method ((pathname pathname)) pathname)
(:method ((package package)) (package-pathname (package-name package)))
(:method ((designator symbol)) (package-pathname (string-downcase (symbol-name designator)))))
(defgeneric pathname-package-name (pathname)
(:method ((pathname pathname))
(format nil "~{~a.~}~@[~a~]"
(rest (pathname-directory pathname)) (pathname-name pathname))))
(defgeneric load-package (designator)
(:method ((designator package))
(load-package (package-name designator)))
#+asdf
(:method ((designator symbol))
(asdf:operate 'asdf:load-op designator))
#+asdf
(:method ((designator string))
(asdf:operate 'asdf:load-op designator))
#-asdf
(:method ((designator t))
(load-package (package-pathname designator)))
#-asdf
(:method ((designator pathname))
"iterate over registerd hosts; merge the imputed pathname with the host and, where a binary or source file is found, load that file and return the pathname. where a file is found, alos look for an optional, separate, package definition file."
(let ((package-pathname (make-pathname :name (concatenate 'string (pathname-name designator) "-PACKAGE")
:defaults designator))
(truename nil)
(package-truename nil))
there should be a base file . if there is an additional package file , load it first
(unless (setf truename (or (probe-file (make-pathname :type *binary-type* :defaults designator))
;; heuristic to deal with case-specific logical pathnames in linux
(probe-file (string-downcase (namestring (make-pathname :type *binary-type* :defaults designator))))
(probe-file (make-pathname :type "LISP" :defaults designator))
(probe-file (string-downcase (namestring (make-pathname :type "LISP" :defaults designator))))))
(error 'package-not-found
:name (pathname-package-name designator) :pathname designator))
(when (setf package-truename (or (probe-file (make-pathname :type *binary-type* :defaults package-pathname))
(probe-file (string-downcase (namestring (make-pathname :type *binary-type* :defaults package-pathname))))
(probe-file (string-downcase (namestring (make-pathname :type "LISP" :defaults package-pathname))))
(probe-file (make-pathname :type "LISP" :defaults package-pathname))))
(load package-truename))
(load truename)
;; compare explicitly to avoid case problems
(or (let ((test-name (pathname-package-name designator)))
(dolist (package (list-all-packages))
(when (or (string-equal test-name (package-name package))
(dolist (nickname (package-nicknames package))
(when (string-equal test-name nickname) (return package))))
(return package))))
(error 'package-not-found
:name (pathname-package-name designator) :pathname truename)))))
(defgeneric edit-package (designator)
(:method ((designator t))
(edit-package (find-package designator)))
(:method ((package package))
;; perform indirectly in case the operators are not loaded
(asdf:operate 'asdf::edit-op (package-name package))))
(defgeneric ensure-package (designator &key if-does-not-exist)
(:method ((package package) &key &allow-other-keys) package)
(:method ((name symbol) &rest args)
(declare (dynamic-extent args))
(apply #'ensure-package (string name) args))
(:method ((name string) &key (if-does-not-exist :create) (if-exists t))
(let ((package (find-package name)))
(if package
(ecase if-exists
((t) package)
(:supersede
(ecase if-does-not-exist
(:create (delete-package package)
(make-package name :use nil))
(:load (load-package name))))
(:error (error "package exists: ~s" package)))
(ecase if-does-not-exist
(:load (load-package name))
(:error (error 'package-not-found :name name :pathname nil))
(:create (make-package name :use nil)))))))
;;
;;
;;
(defun purge-package (package &optional (delete-p t))
"dissolve all dependancies upon the package and delete it. where it is used by another package, unuse it.
where a symbol has been imported, if it is still present in the argument package. move it to the importing package."
(modify-package-operation package :purge delete-p))
(defun clean-package (package &aux (count 0))
"remove any uninterned symbols from the package"
(setf package (find-package package))
(with-package-iterator (next-symbol package :external :internal)
(loop (multiple-value-bind (next-p symbol accessibility) (next-symbol)
(unless next-p (return))
(unless (symbol-package symbol)
(when (eq :external accessibility)
(unexport symbol package))
(unintern symbol package)
(incf count))))
(values package count)))
;;
;;
;;
(defmacro check-feature (feature)
"ensure that a compiled file is loaded in the same environemnt in which it was compiled."
(if (find feature *features*)
`(unless (find ,feature *features* :test #'string-equal)
(warn "compile-time feature missing upon load: ~s: ~s." ',feature *load-pathname*))
`(when (find ,feature *features* :test #'string-equal)
(warn "compile-time non-feature present upon load: ~s: ~s." ',feature *load-pathname*))))
(defparameter *package-version-indicator-name* (string '#:*PACKAGE-VERSION*))
(defun package-version (&optional (designator *package*) &aux version-indicator package)
"if provided a package designator, returns the values of the version identifier in that package. if provided the value t, returns a plist of package names and version values."
(if (eq designator t)
(remove nil (mapcar #'(lambda (package)
(multiple-value-bind (version package)
(package-version package)
(when version
(cons (package-name package) version))))
(list-all-packages)))
(if (setf package (find-package designator))
(values (when (and (setf version-indicator (find-symbol *package-version-indicator-name* package))
(boundp version-indicator))
(symbol-value version-indicator))
package)
nil)))
(defun (setf package-version) (version designator &aux version-indicator package)
(setf package (find-package designator))
(assert (packagep package))
(setf version-indicator (intern *package-version-indicator-name* package))
(setf (symbol-value version-indicator) version))
(provide :de.setf.utility.package)
( trace ( setf package - version ) )
:de.setf.utility
| null | https://raw.githubusercontent.com/lisp/de.setf.utility/782cd79d99ebf40deeed60c492be9873bbe42a15/modpackage.lisp | lisp | Syntax : ansi - common - lisp ; Base : 10 ; Package : de.setf.utility.implementation ; -*-
It defines package operators with provisions for side-effects on exxisting packages.
'de.setf.utility' is free software: you can redistribute it and/or modify
'de.setf.utility' 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.
If not, see the GNU [site](/).
content : several package operators to extend and/or standardize defpackage
modpackage (package-designator &rest options)
A macro to define or modify the designated package. The options include operations with
side-effects on existing packages.
modify a ackage's existence to create, load, delete based its curent existence and the
existence arguments
modify-package (package &rest options)
function implementation for the modpackage macro.
In particular,
with defined behavior for repeated operations
as a special-case, this file defines the implementation package and the utility package.
to exist and use its package definition operator to extend the interface package.
20030901 :ensure method to modify-package;
20030901 replaced package-search-path* with a single *package-host-name* to avoid problems with host-free logical pathnames
added package as load - package designator
import modpackage into cl - user
do all and don't allow for shadowing
the symbol may be present in the other package or may be new
do all and don't allow for shadowing
(sort '(:documentation :version :export-only :export-from :export-from :export-from :export-from :export )
#'modify-package-operation-preceeds-p)
heuristic to deal with case-specific logical pathnames in linux
compare explicitly to avoid case problems
perform indirectly in case the operators are not loaded
|
This file is part of the ' de.setf.utility ' Common Lisp library .
Copyright 2003 , 2009 , 2010 [ ) All Rights Reserved
it under the terms of version 3 of the GNU Lesser General Public License as published by
the Free Software Foundation .
A copy of the GNU Lesser General Public License should be included with ' de.setf.utility , as ` lgpl.txt ` .
ensure - package ( designator & key if - exists if - does - not - exist )
it should be loaded as the first of the utility source files , as they require the implementation package
20030328 neither openmcl nor allegro5 . * support package documentation
20030412 corrected : export - only , : export - from order to preceed other : export- * options
20030416 correct load - package to look first for a binary file ( still without regard to write date )
20030416 and added optional separate package file
20030419 observe exisiting accessibles for : import - from and : export - to , but not : export - from and : export - through
20030419 signal error / cerror for : shadowing - inport - from shadowing - inport - to
20030419 stable - sort for operation ordering , with changes to precedence predicate to return nil for self reference
20030419 explicit : use nil argument to make - package in ensure - package
20030901 optional package file is < designator>-package rather than < designator>/package to allow arbitrary content
20030901 in subdirectories
20031212.jaa changed package op order to : export - from : export - only since the import must happen first
20050525.janderson single - case symbol names
20100203.janderson unified with asdf for loading
20100210.janderson initial package definitions ( this file and pathnames ) in one place
(in-package :de.setf.utility.implementation)
(eval-when (:execute :load-toplevel :compile-toplevel)
(import '(modpackage) :common-lisp-user)
(defparameter *package-operations*
'(:purge :clear :ensure
:like :shadow :shadowing-import-from :use-only :use
:import-only :import-from :intern-only :intern
:export-from :export-only :unexport :export :alias :nicknames
:shadowing-import-to :use-by :export-through :version)))
(defmacro defvarconstant (name value &optional documentation)
(let ((name-var (gensym)))
`(defconstant ,name
(let ((,name-var ,value))
(if (boundp ',name)
(progn (assert (equalp (symbol-value ',name) ,name-var) ()
"Previous value for constant ~a not equal to new binding: ~s."
',name ,name-var)
(symbol-value ',name))
,name-var))
,@(when documentation (list documentation)))))
(defparameter *package-host-name* "library"
"Used by functions ensure-package and load-package.
The *package-host-name* variable should be bound to a logical host name which
designates translations which comprise the possible locations of loadable package implementations.")
(defparameter *binary-type* (pathname-type (compile-file-pathname "file.LISP")))
(define-condition package-not-found (#+(and mcl digitool) ccl::no-such-package warning)
((package :initform nil)
(name :initform nil :initarg :name)
(pathname :initform nil :initarg :pathname))
(:report (lambda (condition stream)
(with-slots (name pathname) condition
(format stream "package not found: ~a~@[ in pathname: ~s~]." name pathname)))))
(defun intern-symbol-name (datum in-package)
(etypecase datum
(string )
((and symbol (not null)) (setf datum (string datum))))
(intern datum in-package))
(defun find-symbol-name (datum in-package)
(etypecase datum
(string )
((and symbol (not null)) (setf datum (string datum))))
(or (find-symbol datum in-package) (error "symbol not found: ~s ~s" datum in-package)))
(defun call-with-symbol-names (function designators)
(if (listp designators)
(let* ((length (length designators))
(names (make-list length)))
(declare (fixnum length) (dynamic-extent names))
(flet ((string-first (symbols designators)
(setf (first symbols) (string (first designators)))))
(declare (dynamic-extent #'string-first))
(mapl #'string-first names designators)
(funcall function names)))
(funcall function (string designators)))
(values))
(defun call-with-interned-symbols (function designators in-package)
(if (listp designators)
(let* ((length (length designators))
(symbols (make-list length)))
(declare (fixnum length) (dynamic-extent symbols))
(flet ((intern-first (symbols designators)
(setf (first symbols) (intern-symbol-name (first designators) in-package))))
(declare (dynamic-extent #'intern-first))
(mapl #'intern-first symbols designators)
(funcall function symbols)))
(funcall function (intern-symbol-name designators in-package)))
in-package)
(defun call-with-found-symbols (function designators in-package)
(if (listp designators)
(let* ((length (length designators))
(symbols (make-list length)))
(declare (fixnum length) (dynamic-extent symbols))
(flet ((find-first (symbols designators)
(setf (first symbols) (find-symbol-name (first designators) in-package))))
(declare (dynamic-extent #'find-first))
(mapl #'find-first symbols designators)
(funcall function symbols)))
(funcall function (find-symbol-name designators in-package))))
(defun string-match-p (string pattern)
#+ccl(ccl::%component-match-p string pattern)
#-ccl(error "no definition available for string-match-p: ~s: ~s" string pattern))
(defun find-packages (wildname &key (if-does-not-exist nil))
(or (remove-if (complement #'(lambda (package)
(flet ((test-name (name) (string-match-p name wildname)))
(or (test-name (package-name package))
(dolist (nickname (package-nicknames package))
(when (test-name nickname) (return t)))))))
(list-all-packages) :key #'package-name)
(ecase if-does-not-exist
((nil) nil)
(:error (error 'package-not-found :name wildname :pathname nil)))))
(defgeneric modify-package-operation (package operation arguments)
(:method ((package t) (operation t) (arguments t))
(modify-package-operation (ensure-package package :if-does-not-exist :error) operation arguments))
(:method ((package package) (operation t) (symbol t))
(modify-package-operation package operation (list symbol)))
(:method ((package package) (operation t) (symbols list))
(no-applicable-method #'modify-package-operation package operation symbols))
(:method ((package package) (operation (eql :clear)) (arguments t))
(unuse-package (package-use-list package) package)
(dolist (using-package (package-used-by-list package)) (unuse-package package using-package))
(do-all-symbols (symbol package) (unintern symbol package)))
(:method ((package package) (operation (eql :ensure)) (arguments cons))
(dolist (to-ensure arguments)
(ensure-package to-ensure :if-does-not-exist :load)))
(:method ((package package) (operation (eql :like)) (arguments cons))
(modify-package-operation package :like (first arguments))
(when (rest arguments)
(apply #'modify-package package (rest arguments))))
(:method ((package package) (operation (eql :like)) (prototype t))
(modify-package-operation package :like (ensure-package prototype :if-does-not-exist :error)))
(:method ((package package) (operation (eql :like)) (prototype package))
(modify-package-operation package :clear nil)
(when (package-shadowing-symbols prototype)
(shadowing-import (package-shadowing-symbols prototype) package))
(dolist (using-package (package-used-by-list prototype)) (use-package package using-package))
(dolist (used-package (package-use-list prototype)) (use-package used-package package))
(with-package-iterator (next-symbol prototype :internal :external)
(loop (multiple-value-bind (more-p symbol accessibility) (next-symbol)
(unless more-p (return))
(ecase accessibility
(:external (import symbol package) (export symbol package))
(:internal (import symbol package)))))))
(:method ((package package) (operation (eql :alias)) (arguments list))
(flet ((do-alias (names)
(unless (listp names) (setf names (list names)))
(rename-package package (package-name package) (union names (package-nicknames package) :test #'string=))))
(declare (dynamic-extent #'do-alias))
(call-with-symbol-names #'do-alias arguments)))
(:method ((package package) (operation (eql :nicknames)) (nicknames list))
(rename-package package (package-name package) (mapcar #'string nicknames)))
(:method ((package package) (operation (eql :export-only)) (symbols list))
(flet ((do-export (symbols) (export symbols package)))
(declare (dynamic-extent #'do-export))
(do-external-symbols (symbol package)
(unless (find symbol symbols :test #'string=) (unexport symbol package)))
(when symbols
(call-with-interned-symbols #'do-export symbols package))))
(:method ((package package) (operation (eql :export)) (symbols list))
(flet ((do-export (symbols) (export symbols package)))
(declare (dynamic-extent #'do-export))
(call-with-interned-symbols #'do-export symbols package)))
(:method ((package package) (operation (eql :unexport)) (symbols list))
(flet ((do-unexport (symbols) (unexport symbols package)))
(declare (dynamic-extent #'do-unexport))
(call-with-interned-symbols #'do-unexport symbols package)))
(:method ((package package) (operation (eql :intern)) (symbols list))
(call-with-interned-symbols #'identity symbols package))
(:method ((package package) (operation (eql :intern-only)) (symbols list))
(with-package-iterator (next-symbol package :internal)
(loop (multiple-value-bind (more-p symbol) (next-symbol)
(unless more-p (return))
(unless (or (find symbol symbols :test #'string=)
(find symbol (package-shadowing-symbols package)))
(unintern symbol package))))
(when symbols
(call-with-interned-symbols #'identity symbols package))))
(:method ((package package) (operation (eql :import-from)) (source-and-symbols list))
(flet ((do-import (symbol) (import symbol package)))
(declare (dynamic-extent #'do-import))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-found-symbols #'do-import symbols source-package)
(do-external-symbols (symbol source-package)
(unless (find symbol (package-shadowing-symbols package) :test #'string=)
(do-import symbol)))))))
(:method ((package package) (operation (eql :import-only)) (source-and-symbols list))
(with-package-iterator (next-symbol package :internal)
(loop (multiple-value-bind (more-p symbol) (next-symbol)
(unless more-p (return))
(unless (eq (symbol-package symbol) package)
(unintern symbol package))))
(when source-and-symbols
(modify-package-operation package :import-from source-and-symbols))))
(:method ((package package) (operation (eql :shadow)) (symbols list))
(flet ((do-shadow (symbols) (shadow symbols package)))
(declare (dynamic-extent #'do-shadow))
(when symbols
(call-with-interned-symbols #'do-shadow symbols package))))
(:method ((package package) (operation (eql :shadowing-import-from)) (source-and-symbols list))
(labels ((do-shadowing-import (symbol &aux accessible)
(if (setf accessible (find-symbol (string symbol) package))
(if (eq accessible symbol)
(unless (find symbol (package-shadowing-symbols package))
(shadowing-import symbol package))
(if (eq (symbol-package accessible) package)
(error "symbol already present in package: ~s: ~s: ~s" symbol accessible package)
(progn (cerror "allow new symbol to shadow accessible symbol: ~s: ~s."
(make-condition 'package-error :package package)
symbol accessible)
(shadowing-import symbol package))))
(shadowing-import symbol package)))
(do-shadowing-import-list (symbols) (dolist (symbol symbols) (do-shadowing-import symbol))))
(declare (dynamic-extent #'do-shadowing-import-list #'do-shadowing-import))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-interned-symbols #'do-shadowing-import-list symbols source-package)
(do-external-symbols (symbol source-package)
(do-shadowing-import symbol))))))
(:method ((package package) (operation (eql :shadowing-import-to)) (destination-and-symbols list))
(let ((destination-package (first destination-and-symbols))
(symbols (rest destination-and-symbols)))
(labels ((do-shadowing-import (symbol &aux accessible)
(if (setf accessible (find-symbol (string symbol) destination-package))
(if (eq accessible symbol)
(unless (find symbol (package-shadowing-symbols destination-package))
(shadowing-import symbol destination-package))
(if (eq (symbol-package accessible) destination-package)
(error "symbol already present in package: ~s: ~s: ~s" symbol accessible destination-package)
(progn (cerror "allow new symbol to shadow accessible symbol: ~s: ~s."
(make-condition 'package-error :package destination-package)
symbol accessible)
(shadowing-import symbol destination-package))))
(shadowing-import symbol destination-package)))
(do-shadowing-import-list (symbols) (dolist (symbol symbols) (do-shadowing-import symbol))))
(declare (dynamic-extent #'do-shadowing-import-list #'do-shadowing-import))
(if symbols
(call-with-interned-symbols #'do-shadowing-import-list symbols package)
(do-external-symbols (symbol package)
(do-shadowing-import symbol))))))
(:method ((package package) (operation (eql :export-from)) (source-and-symbols list))
"Export symbols originating in the given package: (origin . designators)
If no symbols are specified, then export all external symbols."
(flet ((do-import-export (symbol) (import symbol package) (export symbol package)))
(declare (dynamic-extent #'do-import-export))
(let ((source-package (first source-and-symbols))
(symbols (rest source-and-symbols)))
(if symbols
(call-with-interned-symbols #'do-import-export symbols source-package)
(do-external-symbols (symbol source-package) (do-import-export symbol))))))
(:method ((package package) (operation (eql :export-through)) (destination-and-symbols list))
(let ((destination-package (ensure-package (first destination-and-symbols) :if-does-not-exist :error))
(symbols (rest destination-and-symbols)))
(if symbols
(flet ((do-export-export (symbol) (export symbol package)
(import symbol destination-package)
(export symbol destination-package)))
(declare (dynamic-extent #'do-export-export))
(dolist (symbol symbols)
(when (setf symbol (find-symbol (string symbol) destination-package))
(import symbol package)))
(call-with-interned-symbols #'do-export-export symbols package))
(do-external-symbols (symbol package)
(import symbol destination-package) (export symbol destination-package)))))
(:method ((package package) (operation (eql :use-only)) (packages list))
(let ((packages-used (package-use-list package)))
(when packages-used (unuse-package packages-used package)))
(use-package packages package))
(:method ((package package) (operation (eql :use)) (packages list))
(when packages (use-package packages package)))
(:method ((package package) (operation (eql :use-by)) (packages list))
(dolist (other-package packages) (use-package package other-package)))
(:method ((package package) (operation (eql :version)) (version cons))
(modify-package-operation package operation (first version)))
(:method ((package package) (operation (eql :version)) (version t))
(setf (package-version package) version))
(:method ((package package) (operation (eql :documentation)) (documentation cons))
#-(or (and allegro allegro-version>= (not (version>= 6 0))) clisp)
(setf (documentation package t) (first documentation))
documentation)
(:method ((package package) (operation (eql :documentation)) (documentation t))
#-(or (and allegro allegro-version>= (not (version>= 6 0))) clisp)
(setf (documentation package t) documentation)
documentation)
(:method ((package package) (operation (eql :purge)) (argument t))
(dolist (using-package (package-used-by-list package))
(unuse-package package using-package))
(dolist (importing-package (list-all-packages))
(with-package-iterator (next-symbol importing-package :internal :external)
(loop (multiple-value-bind (more-p symbol access) (next-symbol)
(unless more-p (return))
(when (eq (symbol-package symbol) package)
(multiple-value-bind (again-symbol access) (find-symbol (symbol-name symbol) package)
(when (eq access :external) (unexport again-symbol package)))
(unintern symbol package)
(when (eq access :external)
(unexport symbol importing-package))
(unintern symbol importing-package)
(import symbol importing-package)
(when (eq access :external)
(export symbol importing-package)))))))
(when argument (delete-package package))))
(defgeneric modify-package-operation-preceeds-p (operation1 operation2)
(:method :before ((op1 (eql :purge)) (op2 t)) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op2 t) (op1 (eql :purge))) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op1 (eql :clear)) (op2 t)) (error "package operation permitted alone only: ~s." op1))
(:method :before ((op2 t) (op1 (eql :clear))) (error "package operation permitted alone only: ~s." op1))
(:method ((op1 t) (op2 t)) (member op2 (rest (member op1 *package-operations*)))))
(defgeneric modify-package (package &rest options)
(:method ((package t) &rest args)
(apply #'modify-package (ensure-package package :if-does-not-exist :error) args))
(:method ((package string) &rest args)
(if (wild-pathname-p package)
(apply #'modify-package (find-packages package :if-does-not-exist :error) args)
(call-next-method)))
(:method ((packages list) &rest args)
(dolist (package packages)
(apply #'modify-package package args)))
(:method ((package package) &rest options)
(unless (evenp (length options))
(error "illegal option list: ~s." options))
(do ((key (pop options) (pop options))
(arguments (pop options) (pop options)))
((null key))
(modify-package-operation package key arguments))
package))
(defmacro modPackage (name-and-args &rest options)
"modify a package as specified. the options include those of defpackage.
additional specifications support inter-package operations.
if the package exists, it is destructively modified."
(let ((package-form `(ensure-package ,(string (if (consp name-and-args) (first name-and-args) name-and-args))
,@(when (consp name-and-args) (rest name-and-args)))))
(labels ((check-modpackage-option (option)
(destructuring-bind (operation . arguments) option
(unless (compute-applicable-methods #'modify-package-operation (list *package* operation arguments))
(error "illegal option: ~s not supported by ~s." (first option) #'modify-package-operation))
(case operation
(:like
`(:like '(,(string (first arguments))
,@(apply #'append
(stable-sort (mapcar #'check-modpackage-option (rest arguments))
#'modify-package-operation-preceeds-p
:key #'first)))))
(t
(list operation
(when arguments (list 'quote (mapcar #'string arguments)))))))))
`(eval-when (:execute :load-toplevel :compile-toplevel)
(modify-package ,package-form ,@(apply #'append
(stable-sort (mapcar #'check-modpackage-option options)
#'modify-package-operation-preceeds-p
:key #'first)))))))
#+(and mcl digitool)
(pushnew '(modPackage . 1) *fred-special-indent-alist* :key #'first)
#+source-analysis
(de.setf.utility.documentation:defSourceForm (modPackage :class de.setf.utility.documentation:package-source :category package))
(defgeneric package-pathname (designator)
(:documentation
"used to transform a designator for a package location into a logical pathname - minus the file type.")
# \. designator ) ) ) )
(:method ((pathname pathname)) pathname)
(:method ((package package)) (package-pathname (package-name package)))
(:method ((designator symbol)) (package-pathname (string-downcase (symbol-name designator)))))
(defgeneric pathname-package-name (pathname)
(:method ((pathname pathname))
(format nil "~{~a.~}~@[~a~]"
(rest (pathname-directory pathname)) (pathname-name pathname))))
(defgeneric load-package (designator)
(:method ((designator package))
(load-package (package-name designator)))
#+asdf
(:method ((designator symbol))
(asdf:operate 'asdf:load-op designator))
#+asdf
(:method ((designator string))
(asdf:operate 'asdf:load-op designator))
#-asdf
(:method ((designator t))
(load-package (package-pathname designator)))
#-asdf
(:method ((designator pathname))
"iterate over registerd hosts; merge the imputed pathname with the host and, where a binary or source file is found, load that file and return the pathname. where a file is found, alos look for an optional, separate, package definition file."
(let ((package-pathname (make-pathname :name (concatenate 'string (pathname-name designator) "-PACKAGE")
:defaults designator))
(truename nil)
(package-truename nil))
there should be a base file . if there is an additional package file , load it first
(unless (setf truename (or (probe-file (make-pathname :type *binary-type* :defaults designator))
(probe-file (string-downcase (namestring (make-pathname :type *binary-type* :defaults designator))))
(probe-file (make-pathname :type "LISP" :defaults designator))
(probe-file (string-downcase (namestring (make-pathname :type "LISP" :defaults designator))))))
(error 'package-not-found
:name (pathname-package-name designator) :pathname designator))
(when (setf package-truename (or (probe-file (make-pathname :type *binary-type* :defaults package-pathname))
(probe-file (string-downcase (namestring (make-pathname :type *binary-type* :defaults package-pathname))))
(probe-file (string-downcase (namestring (make-pathname :type "LISP" :defaults package-pathname))))
(probe-file (make-pathname :type "LISP" :defaults package-pathname))))
(load package-truename))
(load truename)
(or (let ((test-name (pathname-package-name designator)))
(dolist (package (list-all-packages))
(when (or (string-equal test-name (package-name package))
(dolist (nickname (package-nicknames package))
(when (string-equal test-name nickname) (return package))))
(return package))))
(error 'package-not-found
:name (pathname-package-name designator) :pathname truename)))))
(defgeneric edit-package (designator)
(:method ((designator t))
(edit-package (find-package designator)))
(:method ((package package))
(asdf:operate 'asdf::edit-op (package-name package))))
(defgeneric ensure-package (designator &key if-does-not-exist)
(:method ((package package) &key &allow-other-keys) package)
(:method ((name symbol) &rest args)
(declare (dynamic-extent args))
(apply #'ensure-package (string name) args))
(:method ((name string) &key (if-does-not-exist :create) (if-exists t))
(let ((package (find-package name)))
(if package
(ecase if-exists
((t) package)
(:supersede
(ecase if-does-not-exist
(:create (delete-package package)
(make-package name :use nil))
(:load (load-package name))))
(:error (error "package exists: ~s" package)))
(ecase if-does-not-exist
(:load (load-package name))
(:error (error 'package-not-found :name name :pathname nil))
(:create (make-package name :use nil)))))))
(defun purge-package (package &optional (delete-p t))
"dissolve all dependancies upon the package and delete it. where it is used by another package, unuse it.
where a symbol has been imported, if it is still present in the argument package. move it to the importing package."
(modify-package-operation package :purge delete-p))
(defun clean-package (package &aux (count 0))
"remove any uninterned symbols from the package"
(setf package (find-package package))
(with-package-iterator (next-symbol package :external :internal)
(loop (multiple-value-bind (next-p symbol accessibility) (next-symbol)
(unless next-p (return))
(unless (symbol-package symbol)
(when (eq :external accessibility)
(unexport symbol package))
(unintern symbol package)
(incf count))))
(values package count)))
(defmacro check-feature (feature)
"ensure that a compiled file is loaded in the same environemnt in which it was compiled."
(if (find feature *features*)
`(unless (find ,feature *features* :test #'string-equal)
(warn "compile-time feature missing upon load: ~s: ~s." ',feature *load-pathname*))
`(when (find ,feature *features* :test #'string-equal)
(warn "compile-time non-feature present upon load: ~s: ~s." ',feature *load-pathname*))))
(defparameter *package-version-indicator-name* (string '#:*PACKAGE-VERSION*))
(defun package-version (&optional (designator *package*) &aux version-indicator package)
"if provided a package designator, returns the values of the version identifier in that package. if provided the value t, returns a plist of package names and version values."
(if (eq designator t)
(remove nil (mapcar #'(lambda (package)
(multiple-value-bind (version package)
(package-version package)
(when version
(cons (package-name package) version))))
(list-all-packages)))
(if (setf package (find-package designator))
(values (when (and (setf version-indicator (find-symbol *package-version-indicator-name* package))
(boundp version-indicator))
(symbol-value version-indicator))
package)
nil)))
(defun (setf package-version) (version designator &aux version-indicator package)
(setf package (find-package designator))
(assert (packagep package))
(setf version-indicator (intern *package-version-indicator-name* package))
(setf (symbol-value version-indicator) version))
(provide :de.setf.utility.package)
( trace ( setf package - version ) )
:de.setf.utility
|
9ab95016435f596dd6e745720fa789356e5d17076cecfb886b3fccc60ab295f2 | VisionsGlobalEmpowerment/webchange | views.cljs | (ns webchange.admin.pages.create-activity.views
(:require
[re-frame.core :as re-frame]
[webchange.admin.widgets.page.views :as page]
[webchange.ui.index :as ui]
[webchange.admin.pages.create-activity.state :as state]
[webchange.utils.languages :refer [language-options]]))
(defn- activity-categories
[]
(let [categories @(re-frame/subscribe [::state/categories])
selected @(re-frame/subscribe [::state/selected-category])]
[:div.activity-categories
(for [category categories]
[:div {:class-name (ui/get-class-name {"activity-category" true
"selected" (= (:id category) (:id selected))})
:on-click #(re-frame/dispatch [::state/select-category (:id category)])}
[:div.activity-category-header
[:div (:name category)]
[ui/icon {:icon "caret-right"}]]
[:div.activity-category-description
(:description category)]])]))
(defn- template-list
[]
(let [templates @(re-frame/subscribe [::state/templates])
selected @(re-frame/subscribe [::state/selected-template])]
(if (empty? templates)
[:div.empty-list "Please choose an activity category on the left"]
[:div.template-list
(for [template templates]
[:div.template-wrapper
[:div {:class-name (ui/get-class-name {"template" true})
:on-click #(re-frame/dispatch [::state/select-template (:name template)])}
[:div {:class-name (ui/get-class-name {"preview-wrapper" true
"selected" (= (:name template) (:name selected))})}
[ui/image {:class-name (ui/get-class-name {"preview" true})
:src (or (:preview template) "/images/admin/create_activity/preview_placeholder.png")}]]
[:div.template-name
(:name template)]
[:div.template-description
(:description template)]]
(when (= (:name template) (:name selected))
[ui/icon {:class-name "selected-icon"
:icon "check"}])])])))
(defn- select-page
[]
(let [selected-template-name @(re-frame/subscribe [::state/selected-template-name])
confirm-selection #(re-frame/dispatch [::state/confirm-selection])]
[page/page {:class-name "page--create-activity"}
[page/header {:title "Create Activity"
:icon "games"
:icon-color "blue-2"
:class-name "page--create-activity--header"}]
[page/content {:title "Choose a Template"
:icon "check"
:class-name "page--create-activity--content"}
[template-list]]
[page/side-bar {:title "Activity Categories"
:icon "info"
:class-name "page--create-activity--side-bar"}
[activity-categories]]
(when selected-template-name
[page/footer
[:div.footer-text [:strong "Activity Choice:"] selected-template-name]
[ui/button {:class-name "footer-button-confirm"
:icon "arrow-right"
:on-click confirm-selection}
"Next"]])]))
(defn- activity-form
[]
(let [activity-name-value @(re-frame/subscribe [::state/activity-name])
language-value @(re-frame/subscribe [::state/language])
handle-change-name #(re-frame/dispatch [::state/change-name %])
handle-change-lang #(re-frame/dispatch [::state/change-lang %])]
[:div.activity-form
[ui/input {:label "Activity Name"
:value activity-name-value
:required? true
:on-change handle-change-name}]
[:div.note
[ui/icon {:icon "info"}]
[:div "Name Your Activity - This will be shown in your library and in the course table"]]
[ui/select {:label "Select Language"
:value language-value
:required? true
:options language-options
:on-change handle-change-lang}]]))
(defn- template-info
[]
(let [template @(re-frame/subscribe [::state/selected-template])]
[:div {:class-name (ui/get-class-name {"template-info" true})}
[:div {:class-name (ui/get-class-name {"preview-wrapper" true})}
[ui/image {:class-name (ui/get-class-name {"preview" true})
:src (or (:preview template) "/images/admin/create_activity/preview_placeholder.png")}]]
[:div.template-name
(:name template)]
[:div.template-description
(:description template)]]))
(defn- form-page
[]
(let [selected-category @(re-frame/subscribe [::state/selected-category])
selected-template @(re-frame/subscribe [::state/selected-template])
handle-build #(re-frame/dispatch [::state/build])
handle-back #(re-frame/dispatch [::state/back])]
[page/page {:class-name "page--create-activity"}
[page/header {:title "Create Activity"
:icon "games"
:icon-color "blue-2"
:class-name "page--create-activity--header"}]
[page/content {:title "Edit"
:icon "edit"
:class-name "page--create-activity--content"}
[activity-form]]
[page/side-bar {:title (:name selected-category)
:icon "info"
:class-name "page--create-activity--side-bar"}
[template-info]]
[page/footer
[ui/button {:class-name "footer-button-back"
:color "blue-1"
:on-click handle-back}
"Back"]
[ui/button {:class-name "footer-button-confirm"
:on-click handle-build}
"Save & Build"]]]))
(defn page
[props]
(re-frame/dispatch [::state/init])
(fn []
(let [selected-template-name @(re-frame/subscribe [::state/selected-template-name])
selection-confirmed @(re-frame/subscribe [::state/selection-confirmed])
confirm-selection #(re-frame/dispatch [::state/confirm-selection])]
(if selection-confirmed
[form-page]
[select-page]))))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/481ff7a527c15d2d1365cbe35f044cf3736c82e7/src/cljs/webchange/admin/pages/create_activity/views.cljs | clojure | (ns webchange.admin.pages.create-activity.views
(:require
[re-frame.core :as re-frame]
[webchange.admin.widgets.page.views :as page]
[webchange.ui.index :as ui]
[webchange.admin.pages.create-activity.state :as state]
[webchange.utils.languages :refer [language-options]]))
(defn- activity-categories
[]
(let [categories @(re-frame/subscribe [::state/categories])
selected @(re-frame/subscribe [::state/selected-category])]
[:div.activity-categories
(for [category categories]
[:div {:class-name (ui/get-class-name {"activity-category" true
"selected" (= (:id category) (:id selected))})
:on-click #(re-frame/dispatch [::state/select-category (:id category)])}
[:div.activity-category-header
[:div (:name category)]
[ui/icon {:icon "caret-right"}]]
[:div.activity-category-description
(:description category)]])]))
(defn- template-list
[]
(let [templates @(re-frame/subscribe [::state/templates])
selected @(re-frame/subscribe [::state/selected-template])]
(if (empty? templates)
[:div.empty-list "Please choose an activity category on the left"]
[:div.template-list
(for [template templates]
[:div.template-wrapper
[:div {:class-name (ui/get-class-name {"template" true})
:on-click #(re-frame/dispatch [::state/select-template (:name template)])}
[:div {:class-name (ui/get-class-name {"preview-wrapper" true
"selected" (= (:name template) (:name selected))})}
[ui/image {:class-name (ui/get-class-name {"preview" true})
:src (or (:preview template) "/images/admin/create_activity/preview_placeholder.png")}]]
[:div.template-name
(:name template)]
[:div.template-description
(:description template)]]
(when (= (:name template) (:name selected))
[ui/icon {:class-name "selected-icon"
:icon "check"}])])])))
(defn- select-page
[]
(let [selected-template-name @(re-frame/subscribe [::state/selected-template-name])
confirm-selection #(re-frame/dispatch [::state/confirm-selection])]
[page/page {:class-name "page--create-activity"}
[page/header {:title "Create Activity"
:icon "games"
:icon-color "blue-2"
:class-name "page--create-activity--header"}]
[page/content {:title "Choose a Template"
:icon "check"
:class-name "page--create-activity--content"}
[template-list]]
[page/side-bar {:title "Activity Categories"
:icon "info"
:class-name "page--create-activity--side-bar"}
[activity-categories]]
(when selected-template-name
[page/footer
[:div.footer-text [:strong "Activity Choice:"] selected-template-name]
[ui/button {:class-name "footer-button-confirm"
:icon "arrow-right"
:on-click confirm-selection}
"Next"]])]))
(defn- activity-form
[]
(let [activity-name-value @(re-frame/subscribe [::state/activity-name])
language-value @(re-frame/subscribe [::state/language])
handle-change-name #(re-frame/dispatch [::state/change-name %])
handle-change-lang #(re-frame/dispatch [::state/change-lang %])]
[:div.activity-form
[ui/input {:label "Activity Name"
:value activity-name-value
:required? true
:on-change handle-change-name}]
[:div.note
[ui/icon {:icon "info"}]
[:div "Name Your Activity - This will be shown in your library and in the course table"]]
[ui/select {:label "Select Language"
:value language-value
:required? true
:options language-options
:on-change handle-change-lang}]]))
(defn- template-info
[]
(let [template @(re-frame/subscribe [::state/selected-template])]
[:div {:class-name (ui/get-class-name {"template-info" true})}
[:div {:class-name (ui/get-class-name {"preview-wrapper" true})}
[ui/image {:class-name (ui/get-class-name {"preview" true})
:src (or (:preview template) "/images/admin/create_activity/preview_placeholder.png")}]]
[:div.template-name
(:name template)]
[:div.template-description
(:description template)]]))
(defn- form-page
[]
(let [selected-category @(re-frame/subscribe [::state/selected-category])
selected-template @(re-frame/subscribe [::state/selected-template])
handle-build #(re-frame/dispatch [::state/build])
handle-back #(re-frame/dispatch [::state/back])]
[page/page {:class-name "page--create-activity"}
[page/header {:title "Create Activity"
:icon "games"
:icon-color "blue-2"
:class-name "page--create-activity--header"}]
[page/content {:title "Edit"
:icon "edit"
:class-name "page--create-activity--content"}
[activity-form]]
[page/side-bar {:title (:name selected-category)
:icon "info"
:class-name "page--create-activity--side-bar"}
[template-info]]
[page/footer
[ui/button {:class-name "footer-button-back"
:color "blue-1"
:on-click handle-back}
"Back"]
[ui/button {:class-name "footer-button-confirm"
:on-click handle-build}
"Save & Build"]]]))
(defn page
[props]
(re-frame/dispatch [::state/init])
(fn []
(let [selected-template-name @(re-frame/subscribe [::state/selected-template-name])
selection-confirmed @(re-frame/subscribe [::state/selection-confirmed])
confirm-selection #(re-frame/dispatch [::state/confirm-selection])]
(if selection-confirmed
[form-page]
[select-page]))))
|
|
b4bdd0addef319e0c9394da8d6826def35e185cfb94bf5a56d9978b09a8316db | ghc/packages-Cabal | MyBenchModule.hs | module MyBenchModule where
main :: IO ()
main = error ""
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/AutogenModules/SrcDist/MyBenchModule.hs | haskell | module MyBenchModule where
main :: IO ()
main = error ""
|
|
9a099145ae1fb7545c69af524f46799d795209d7d4d62ea3df5d4d1d9da792bd | ptal/AbSolute | infer.ml | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 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
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 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
Lesser General Public License for more details. *)
open Core
open Core.Types
open Lang.Ast
open Lang.Rewritting
open Lang.Pretty_print
open Tast
open Aast
open Ad_type
type inferred_type =
| CannotType of string
| Typed of ad_uid list
type iformula = inferred_type aformula
type iqformula = inferred_type aqformula
let uids_of' = function
| CannotType _ -> []
| Typed uids -> uids
let uids_of (ty,_) = uids_of' ty
let merge_ity ty1 ty2 =
match ty1, ty2 with
| CannotType msg1, CannotType msg2 -> CannotType (
msg1 ^ (if msg1 = "" || msg2 = "" then "" else "\n") ^ msg2)
| CannotType msg, Typed []
| Typed [], CannotType msg -> CannotType msg
| Typed uids, CannotType _ | CannotType _, Typed uids -> Typed uids
| Typed uids1, Typed uids2 -> Typed (List.sort_uniq compare (uids1@uids2))
let is_uid_in uid tf = List.mem uid (uids_of tf)
let is_uid_in2 uid tf1 tf2 = is_uid_in uid tf1 && is_uid_in uid tf2
let rec formula_to_iformula f =
let tf = match f with
| FVar v -> AFVar v
| Cmp c -> ACmp c
| Equiv(f1, f2) -> AEquiv(formula_to_iformula f1, formula_to_iformula f2)
| Imply(f1, f2) -> AImply(formula_to_iformula f1, formula_to_iformula f2)
| And(f1, f2) -> AAnd(formula_to_iformula f1, formula_to_iformula f2)
| Or(f1, f2) -> AOr(formula_to_iformula f1, formula_to_iformula f2)
| Not f1 -> ANot (formula_to_iformula f1)
in
(Typed [], tf)
let rec qformula_to_iqformula = function
| QFFormula f -> AQFFormula (formula_to_iformula f)
| Exists(v, ty, qf) -> AExists (v, ty, Typed [], qformula_to_iqformula qf)
module Inference =
struct
module Var2UID = Map.Make(struct type t=vname let compare=compare end)
type var_env = (ad_uid list) Var2UID.t
type t = {
trace: bool;
* ` true ` if we want to trace the reason why we can not type a formula .
If ` false ` , all strings ` s ` in ` CannotType s ` will be empty .
This is mostly an optimization to avoid constructing error messages ( which can be quite long ) when the formula is typable .
If `false`, all strings `s` in `CannotType s` will be empty.
This is mostly an optimization to avoid constructing error messages (which can be quite long) when the formula is typable. *)
debug: bool;
(** If set to `true`, we have a trace of the typing process.
It is useful to debug the inference process. *)
indent: int;
(** Useful for clear debugging messages. *)
venv: var_env; (** Variable environment mapping a variable name to its supported abstract domains. *)
adty: ad_ty; (** The abstract domain type, we try to infer a type for a formula matching this type. *)
ad_env: ad_ty UID2Adty.t;
}
let init adty trace =
{trace; debug=false; indent=0; venv = Var2UID.empty; adty; ad_env = (build_adenv adty)}
(* Debugging facilities. *)
let rec make_indent = function
| 0 -> ""
| x -> " " ^ (make_indent (x-1))
let indent typer = { typer with indent=(typer.indent+2) }
let debug typer make_msg =
if typer.debug then
(Printf.printf "%s%s\n" (make_indent typer.indent) (make_msg ());
flush_all ())
else ()
let string_of_adtys adtys =
let rec aux = function
| [] -> ""
| x::l -> (string_of_adty x) ^ (if l <> [] then " ; " else "") ^ (aux l)
in
if List.length adtys = 1 then aux adtys
else "[" ^ (aux adtys) ^ "]"
let string_of_ity typer = function
| CannotType msg -> "Error(" ^ msg ^ ")"
| Typed ad_uids ->
string_of_adtys (List.map (fun x -> UID2Adty.find x typer.ad_env) ad_uids)
let debug_adty typer make_msg adty =
if typer.debug then
Printf.printf "%s%s %s\n" (make_indent typer.indent) (make_msg ()) (string_of_adty adty)
else ()
let debug_ty typer term ty =
if typer.debug then
Printf.printf "%s%s:%s\n" (make_indent typer.indent)
(term ()) (string_of_ity typer ty)
else ()
(* Inference errors. *)
let gen_err typer uid f =
CannotType
(if typer.trace then
"[" ^ (string_of_type typer.ad_env uid) ^ "] " ^ f ()
else
"")
let variable_not_in_dom_err typer uid v =
gen_err typer uid (fun () -> "Variable `" ^ v ^ "` does not belong to the abstract domain.")
let variable_not_in_subdom_err typer uid sub_uid v =
gen_err typer uid (fun () -> "Variable `" ^ v ^ "` does not belong to the sub-domain `"
^ (ad_name typer.ad_env sub_uid) ^ "`.\n"
^ "Note that this domain do not represent variables by itself but relies on the sub-domain.")
let not_a_constraint_err typer uid ad_name_adj ad_name =
gen_err typer uid (fun () ->
("The constraint is not a " ^ ad_name_adj ^ " constraint, so we cannot add it into " ^ ad_name ^ "."))
let not_a_box_constraint_err typer uid = not_a_constraint_err typer uid "box" "box"
let not_an_octagonal_constraint_err typer uid = not_a_constraint_err typer uid "octagonal" "octagon"
let ground_dom_does_not_handle_logic_connector_err typer uid =
gen_err typer uid (fun () -> "Ground abstract domain does not support logic connectors other than conjunction.")
let no_domain_support_this_variable_err typer uid v ty =
gen_err typer uid (fun () -> "The variable `" ^ v ^ "` (type `" ^ (string_of_ty ty) ^ "`) is not supported in any abstract domain.")
let sat_does_not_support_term_err typer uid =
gen_err typer uid (fun () -> "SAT domain does not support term, only Boolean formulas are supported.")
let direct_product_no_subdomain_err typer uid msg =
gen_err typer uid (fun () -> "The formula is not supported in any of the sub-domain of the direct product because:\n"
^ (Tools.indent msg))
let logic_completion_subdomain_failed_on_term_err typer uid =
gen_err typer uid (fun () -> "Logic completion delegates the term typing to its sub-domain, but it could not type this term.")
let no_var_mgad_err v adtys =
raise (Wrong_modelling(
"Variable `" ^ v ^ "` must be interpreted in several abstract elements, but there is not a most general one.\n"
^ "For instance, if a variable exists in two abstract elements, e.g. Box and Oct, we must have a type Box X Oct that takes care of mapping this variable in both domains.\n"
^ "Note that some abstract domains such as projection-based product take care of synchronizing the variables of both domains.\n"
^ " Candidate abstract domains: " ^ (string_of_adtys adtys)
))
let create_typing_error msg tf =
let cannot_type_formula msg f =
"Cannot type the following formula: `" ^ (string_of_aformula (CannotType msg, f)) ^ "` because:\n"
^ (Tools.indent msg) in
let rec aux msg f =
match f with
| AFVar v -> "Cannot type of the variable `" ^ v ^ "` because:\n"
^ (Tools.indent msg)
| ACmp c -> "Cannot type the following constraint: `" ^ (string_of_constraint c) ^ "` because:\n"
^ (Tools.indent msg)
| AAnd (tf1, tf2)
| AOr (tf1,tf2)
| AImply (tf1,tf2)
| AEquiv (tf1,tf2) ->
(match tf1, tf2 with
| ((CannotType msg, f1), _) -> aux msg f1
| (_, (CannotType msg, f2)) -> aux msg f2
| _ -> cannot_type_formula msg f)
| ANot (CannotType msg, tf1) -> aux msg tf1
| ANot _ -> cannot_type_formula msg f
in aux msg (snd tf)
(* I. Inference of the variables types. *)
let interval_can_represent_var vardom_ty ty =
let is_integer = function
| Interval Z | Interval_mix -> true
| Interval_oc _ | Interval _ -> false (* Open-close interval only makes sense with float or rational. *) in
let is_rational = function
| Interval_oc Q | Interval Q -> true
NOTE : Interval_mix is implemented with floating point number for the real part .
let is_float = function
| Interval_oc F | Interval_mix | Interval F -> true
| _ -> false in
let is_real x = is_rational x || is_float x in
match ty with
| Concrete Int -> is_integer vardom_ty
| Concrete Real -> is_real vardom_ty
| Abstract Bool -> is_integer vardom_ty
| Abstract (Machine Z) -> is_integer vardom_ty
| Abstract (Machine Q) -> is_rational vardom_ty
| Abstract (Machine F) -> is_float vardom_ty
| Abstract VUnit -> false
| Abstract (BDD _) -> false
let compatible_ty ty vty =
match ty with
| Concrete Int -> vty = Z
| Concrete Real -> vty = F || vty = Q
| Abstract (Machine ty) -> vty = ty
| Abstract Bool -> vty = Z
| Abstract _ -> false
(* For now, no vardom support hole in their domains. *)
let is_vardom_support_neq = function
| Interval _ | Interval_oc _ | Interval_mix -> false
let rec infer_var ty adty =
let is_boolean = function
| Abstract Bool -> true
| _ -> false in
match adty with
| (uid, Box vardom_ty) when interval_can_represent_var vardom_ty ty -> [uid]
| (uid, Octagon vty) when compatible_ty ty vty -> [uid]
| (uid, SAT) when is_boolean ty -> [uid]
| (_, Delayed_product _) -> failwith "Delayed_product type inference is not yet implemented."
| (_, Direct_product adtys) -> List.flatten (List.map (infer_var ty) adtys)
| (_, Logic_completion adty) -> infer_var ty adty
| _ -> []
let build_venv typer tf =
let rec aux = function
| AQFFormula _ -> Var2UID.empty
| AExists(v, _, Typed uids, tf) -> Var2UID.add v uids (aux tf)
| _ -> failwith "build_venv: `check_var_ty` should be called before."
in
{typer with venv=(aux tf)}
let rec check_type_var = function
| AQFFormula _ -> ()
| AExists(_,_,CannotType msg,_) ->
raise (Wrong_modelling msg)
| AExists(_,_,Typed [],_) ->
failwith "Empty list of UIDs: we should either give a type to the variable, or `CannotType`."
| AExists(_,_,_,tf) -> check_type_var tf
let infer_vars_ty typer tf =
debug typer (fun () -> "I. Typing of the variables\n");
let rec aux typer = function
| (AQFFormula _) as tf -> tf
| AExists (v, ty, Typed [], tf) ->
let tf = aux typer tf in
let uids = List.sort_uniq compare (infer_var ty typer.adty) in
let res =
if List.length uids > 0 then Typed uids
else no_domain_support_this_variable_err typer 0 v ty
in
debug_ty typer (fun () -> v) res;
AExists (v, ty, res, tf)
| AExists (v,_,_,_) -> failwith
("infer_vars_ty: Existential connector of `" ^ v ^ "` is partly typed, which is not yet supported.")
in
let tf = aux typer tf in
check_type_var tf;
let typer = build_venv typer tf in
(typer, tf)
(* II. Inference of the constraints types. *)
let belong typer uid v =
let uids = Var2UID.find v typer.venv in
List.exists (fun u -> u = uid) uids
let bool_var_infer typer v uid =
if Var2UID.mem v typer.venv then
Typed [uid]
else
variable_not_in_dom_err typer uid v
let ground_dom_infer typer uid term_infer tf =
let rec aux typer (ty, f) =
let (ty', f) =
match f with
| AFVar v -> merge_ity ty (bool_var_infer typer v uid), f
| ACmp c -> (term_infer c, f)
For conjunction , we type ` TAnd ` only if the inferred type is the same in both formula .
| AAnd (tf1, tf2) ->
let tf1, tf2 = aux typer tf1, aux typer tf2 in
if is_uid_in2 uid tf1 tf2 then
(merge_ity ty (Typed [uid]), AAnd(tf1,tf2))
else
(ty, AAnd(tf1,tf2))
| AOr (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AOr(tf1, tf2))
| AImply (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AImply(tf1, tf2))
| AEquiv (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1, tf2))
| ANot tf1 -> (ground_dom_does_not_handle_logic_connector_err typer uid, ANot (aux typer tf1)) in
let tf = (merge_ity ty ty', f) in
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and binary_aux typer tf1 tf2 make =
let tf1, tf2 = aux typer tf1, aux typer tf2 in
(ground_dom_does_not_handle_logic_connector_err typer uid, make tf1 tf2) in
aux typer tf
let fully_defined_over typer uid c =
let vars = vars_of_bconstraint c in
List.find_opt (fun v -> not (belong typer uid v)) vars
let box_infer typer box_uid vardom tf =
let is_box_constraint ((_, op, _) as c) =
let vars = vars_of_bconstraint c in
if List.length vars = 1 then
match op with
| NEQ -> is_vardom_support_neq vardom
| _ -> true
else
false in
let term_infer c =
if is_box_constraint c then
match fully_defined_over typer box_uid c with
| None -> Typed [box_uid]
| Some v -> variable_not_in_dom_err typer box_uid v
else
not_a_box_constraint_err typer box_uid
in ground_dom_infer typer box_uid term_infer tf
let octagon_infer typer oct_uid tf =
let rec is_octagonal_term = function
| Funcall(_, exprs) -> List.length (List.flatten (List.map get_vars_expr exprs)) = 0
| Unary(NEG, e) -> is_octagonal_term e
| Binary(e1,ADD,e2) | Binary(e1,SUB,e2) -> is_octagonal_term e1 && is_octagonal_term e2
| Var _ | Cst _ -> true
| _ -> false
in
let is_octagonal_constraint ((e1, op, e2) as c) =
let vars = vars_of_bconstraint c in
if List.length vars >= 1 && List.length vars <= 2 then
match op with
| NEQ -> false
| _ -> is_octagonal_term e1 && is_octagonal_term e2
else
false
in
let term_infer c =
if is_octagonal_constraint c then
match fully_defined_over typer oct_uid c with
| None -> Typed [oct_uid]
| Some v -> variable_not_in_dom_err typer oct_uid v
else
not_an_octagonal_constraint_err typer oct_uid
in ground_dom_infer typer oct_uid term_infer tf
let generic_formula_infer typer uid tf literal term =
let rec aux ((ty, f) as tf) =
let tf = match f with
| AFVar v -> merge_ity ty (literal v tf), AFVar v
| ACmp c -> merge_ity ty (term c tf), ACmp c
| AEquiv(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1,tf2))
| AImply(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AImply(tf1,tf2))
| AAnd(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AAnd(tf1,tf2))
| AOr(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AOr(tf1,tf2))
| ANot tf ->
let tf = aux tf in
if is_uid_in uid tf then
(merge_ity ty (Typed [uid]), ANot tf)
else
(ty, ANot tf)
in
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and binary_aux ty tf1 tf2 make =
let tf1, tf2 = aux tf1, aux tf2 in
let f = make tf1 tf2 in
if is_uid_in2 uid tf1 tf2 then
(merge_ity ty (Typed [uid]), f)
else
(ty, f)
in
aux tf
let sat_infer typer sat_uid tf =
generic_formula_infer typer sat_uid tf
(fun v _ -> bool_var_infer typer v sat_uid)
(fun _ _ -> sat_does_not_support_term_err typer sat_uid)
let rec infer_constraints_ty typer tf (uid, adty) =
debug_adty typer (fun () -> "Typing of `" ^ (string_of_aformula tf) ^ "` with abstract domain") (uid, adty);
let typer = indent typer in
match adty with
| Box vardom -> box_infer typer uid vardom tf
| Octagon _ -> octagon_infer typer uid tf
| SAT -> sat_infer typer uid tf
| Delayed_product _ -> failwith "Delayed_product type inference is not yet implemented."
| Direct_product adtys -> direct_product_infer typer uid tf adtys
| Logic_completion adty -> logic_completion_infer typer uid tf adty
| Propagator_completion adty -> propagator_completion_infer typer uid tf adty
and direct_product_infer typer dp_uid tf adtys =
(* (1) Attempt to give a type to the formula `tf` in every component individually. *)
let tf = List.fold_left (infer_constraints_ty typer) tf adtys in
let adtys_uids = List.map fst adtys in
( 2 ) The next step is to give the type ` dp_uid ` to formulas of the form ` f1 : t1 /\ f2 : t2 ` if are in the product , and t1 ! = t2 .
let rec aux (ty, f) =
match f with
| AAnd(tf1,tf2) ->
let tf1, tf2 = aux tf1, aux tf2 in
let f = AAnd(tf1, tf2) in
let uids1, uids2 = uids_of tf1, uids_of tf2 in
let ty' =
if is_uid_in2 dp_uid tf1 tf2 then
Typed [dp_uid]
else
let u1 = Tools.intersect adtys_uids uids1 in
let u2 = Tools.intersect adtys_uids uids2 in
let common = Tools.intersect u1 u2 in
(* The sub-formulas tf1 and tf2 can be interpreted in different sub-domains of the product. *)
if List.length u1 > 0 && List.length u2 > 0 then
Typed (dp_uid::common)
else
CannotType ("Direct product could not type a conjunction c1 /\\ c2 because " ^
(match List.length u1, List.length u2 with
| 0, 0 -> "none of the sub-formula could be treated in any sub-domain."
| x, 0 when x > 0 -> "c2 could not be treated in any sub-domain"
| 0, x when x > 0 -> "c1 could not be treated in any sub-domain"
| _ -> failwith "unreachable"))
in
(merge_ity ty ty'), f
| _ ->
If there exists one sub - domain that can handle this formula , then the direct product can handle it .
However , we do not assign ` dp_uid ` to this formula , if we did , it means we want this formula to be treated in every domain of the product ( redundant information ) .
Redundant constraints might be interesting to explore , but this is for future work ( at least the typing framework already support it ) .
However, we do not assign `dp_uid` to this formula, if we did, it means we want this formula to be treated in every domain of the product (redundant information).
Redundant constraints might be interesting to explore, but this is for future work (at least the typing framework already support it). *)
ty,f
in
match aux tf with
| CannotType msg, f -> direct_product_no_subdomain_err typer dp_uid msg, f
| tf ->
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and logic_completion_infer typer lc_uid tf adty =
let tf = infer_constraints_ty (indent typer) tf adty in
(* Whenever this term is typed in the sub-domain of the completion, the completion can handle it too. *)
let lc_term _ tf =
match fst tf with
| Typed _ when is_mgad adty (uids_of tf) -> Typed [lc_uid]
| _ -> logic_completion_subdomain_failed_on_term_err typer lc_uid
in
generic_formula_infer typer lc_uid tf lc_term lc_term
and propagator_completion_infer typer pc_uid tf adty =
let tf = infer_constraints_ty (indent typer) tf adty in
let term_infer c =
match fully_defined_over typer (fst adty) c with
| None -> Typed [pc_uid]
| Some v -> variable_not_in_subdom_err typer pc_uid (fst adty) v
in ground_dom_infer typer pc_uid term_infer tf
let infer_constraints_ty_or_fail typer tf =
debug typer (fun () -> "\nII. Typing of the sub-formulas & constraints.\n");
map_tqf (fun tqf ->
We first try to type the formula without tracing the errors .
let typer = {typer with trace=false} in
let tqf = infer_constraints_ty typer tqf typer.adty in
match fst tqf with
| CannotType _ ->
debug typer (fun () -> "Typing of the formula failed, so we now create the error message and trace the typing process.");
let typer = {typer with trace=true; debug=false} in
let tqf = infer_constraints_ty typer tqf typer.adty in
(match fst tqf with
| CannotType msg -> raise (Wrong_modelling (create_typing_error msg tqf))
| Typed _ -> failwith "CannotType with trace=false, and Typed with trace=true, `trace` should not impact typing.")
| Typed _ -> tqf
) tf
(* III. Variable's type restriction. *)
module VarConsCounter = Map.Make(struct type t=vname * ad_uid let compare=compare end)
let build_var_cons_map tf uids_of =
let rec aux vcm tf =
let add_unary v vcm uid =
VarConsCounter.update (v,uid) (fun x ->
match x with
| Some (u,n) -> Some (u+1,n)
| None -> Some(1,0)) vcm in
let add_nary c vcm uid =
let vars = vars_of_bconstraint c in
if List.length vars = 1 then
add_unary (List.hd vars) vcm uid
else
List.fold_left (fun vcm v ->
VarConsCounter.update (v,uid) (fun x ->
match x with
| Some (u,n) -> Some (u,n+1)
| None -> Some(0,1)) vcm) vcm vars in
match tf with
| ty, AFVar v -> List.fold_left (add_unary v) vcm (uids_of ty)
| ty, ACmp c -> List.fold_left (add_nary c) vcm (uids_of ty)
| _, AEquiv(tf1,tf2) | _, AImply(tf1,tf2) | _, AAnd(tf1,tf2) | _, AOr(tf1,tf2) ->
aux (aux vcm tf1) tf2
| _, ANot tf -> aux vcm tf
in aux VarConsCounter.empty tf
let find_in_vcm v uid vcm =
try
VarConsCounter.find (v,uid) vcm
If Not_found , it means that the variable does not appear with this UID in any constraint .
with Not_found -> (0,0)
let restrict_unary_var_dom typer uids =
let is_octagon uid =
match UID2Adty.find uid typer.ad_env with
| _, Octagon _ -> true
| _ -> false in
let rec remove_octagon = function
| [] -> []
| x::l when is_octagon x -> l
| x::l -> x::(remove_octagon l) in
if List.length uids > 1 then remove_octagon uids else uids
let rec extract_formula = function
| AQFFormula tqf -> tqf
| AExists (_,_,_,tqf) -> extract_formula tqf
let restrict_variable_ty typer tf =
debug typer (fun () -> "\nIII. Restrict variables' types\n");
let tqf = extract_formula tf in
let vcm = build_var_cons_map tqf uids_of' in
let rec aux = function
| AQFFormula tqf -> AQFFormula tqf
| AExists (v,ty,Typed uids,tqf) ->
let nary = List.filter
(fun uid -> snd (find_in_vcm v uid vcm) > 0)
uids in
let uids =
if (List.length nary) > 0 then nary
else restrict_unary_var_dom typer uids in
debug_ty typer (fun () -> v) (Typed uids);
AExists (v,ty,Typed uids,aux tqf)
| AExists (_,_,CannotType _,_) -> failwith "restrict_variable_ty: Reached a CannotType, but should be checked before in `check_type_var`."
in
let tf = aux tf in
let typer = build_venv typer tf in
(typer, tf)
(* V. Instantiation of the formula type. *)
(* This function is applied after `instantiate_formula_ty`, therefore the constraints' types have already been instantiated.
Since we instantiate the variable with its most general abstract domain, the constraints stay well-typed. *)
let instantiate_var_ty typer vcm vname uids =
let useful_uids = List.filter
(fun uid ->
let u,n = find_in_vcm vname uid vcm in
u > 0 || n > 0) uids in
(* In case the variable does not occur in any constraint, we keep the list of UIDs. *)
let useful_uids = if List.length useful_uids = 0 then uids else useful_uids in
let adtys = List.map (fun uid -> UID2Adty.find uid typer.ad_env) useful_uids in
match select_mgad adtys with
| None -> no_var_mgad_err vname adtys
| Some adty -> fst adty
let sort_most_specialized typer uids =
We want the list to be sorted with the most specialized first ( so we rank it " smaller " in the compare function ) .
let compare_specialization ty1 ty2 =
if ty1 = ty2 then 0
else
match is_more_specialized ty1 ty2 with
| True -> -1
| False -> 1
| Unknown -> 0 (* Unrelated domains are considered equal here. *)
in
let adtys = List.map (fun uid -> UID2Adty.find uid typer.ad_env) uids in
if adtys = [] then failwith "Type uids should not be empty (should be checked in `infer_constraints_ty_or_fail`)";
let adtys = List.stable_sort compare_specialization adtys in
List.map fst adtys
let most_specialized typer uids = List.hd (sort_most_specialized typer uids)
* From a sorted list of UIDS available , pick the first one that is a MGAD w.r.t . the UIDs in the provided list .
let first_supporting typer need_to_support_uids uids_available =
let rec aux = function
| [] -> failwith "Could not find an abstract domain supporting sub-formula, this should be checked in `infer_constraints_ty_or_fail`."
| uid::l ->
let adty = UID2Adty.find uid typer.ad_env in
if is_mgad adty need_to_support_uids then uid
else aux l
in aux uids_available
let instantiate_formula_ty typer tf =
let rec aux tf =
let (uid,f) = match tf with
| Typed uids, AFVar v ->
let var_uids = Var2UID.find v typer.venv in
let uids = Tools.intersect uids var_uids in
(most_specialized typer uids, AFVar v)
| Typed uids, ACmp c ->
We only keep the UID , its abstract element is fully defined over the variables of the constraint .
Due to ` restrict_variable_ty ` we must perform this filtering .
Due to `restrict_variable_ty` we must perform this filtering. *)
let uids = List.filter
(fun uid ->
List.for_all
(fun v ->
let adty = UID2Adty.find uid typer.ad_env in
List.exists
(fun u -> subtype (UID2Adty.find u typer.ad_env) adty)
(Var2UID.find v typer.venv))
(vars_of_bconstraint c))
uids in
(most_specialized typer uids, ACmp c)
| Typed uids, AAnd (tf1, tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AAnd(tf1, tf2))
| Typed uids, AOr (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AOr(tf1, tf2))
| Typed uids, AImply (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AImply(tf1, tf2))
| Typed uids, AEquiv (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1, tf2))
| Typed uids, ANot tf ->
let (uid1, tf1) = aux tf in
let sorted_uids = sort_most_specialized typer uids in
(first_supporting typer [uid1] sorted_uids, ANot (uid1,tf1))
| _ -> failwith "instantiate_formula_ty: Formula should all be typed after the call to `infer_constraints_ty_or_fail`."
in
(* debug_ty typer (fun () -> string_of_aformula tf) (fst tf); *)
debug_ty typer (fun () -> string_of_aformula tf) (Typed [uid]);
(uid,f)
and binary_aux uids tf1 tf2 make =
let (uid1, tf1), (uid2, tf2) = aux tf1, aux tf2 in
let sorted_uids = sort_most_specialized typer uids in
(first_supporting typer [uid1; uid2] sorted_uids, make (uid1,tf1) (uid2,tf2))
in
aux tf
let instantiate_qformula_ty typer tf =
debug typer (fun () -> "\nIV. Instantiate the type of formula\n");
let rec aux = function
| AQFFormula tqf ->
let tqf = instantiate_formula_ty typer tqf in
AQFFormula tqf, build_var_cons_map tqf (fun uid -> [uid])
| AExists (vname,ty,Typed uids,tf) ->
let tf, vcm = aux tf in
let uid = instantiate_var_ty typer vcm vname uids in
AExists (vname, ty, uid, tf), vcm
| AExists (_,_,CannotType msg, _) -> raise (Wrong_modelling msg)
in fst (aux tf)
end
let make_tqformula tf =
let rec aux' = function
| uid, AFVar v -> (uid, TFVar v)
| uid, ACmp c -> (uid, TCmp c)
| uid, AAnd (tf1, tf2) -> (uid, TAnd(aux' tf1, aux' tf2))
| uid, AOr (tf1,tf2) -> (uid, TOr(aux' tf1, aux' tf2))
| uid, AImply (tf1,tf2) -> (uid, TImply(aux' tf1, aux' tf2))
| uid, AEquiv (tf1,tf2) -> (uid, TEquiv(aux' tf1, aux' tf2))
| uid, ANot tf -> (uid, TNot (aux' tf)) in
let rec aux = function
| AQFFormula tqf -> TQFFormula (aux' tqf)
| AExists (name, ty, uid, tf) ->
TExists ({name; ty; uid}, aux tf)
in aux tf
let infer_type adty f =
let open Inference in
let tf = qformula_to_iqformula f in
let typer = init adty true in
let (typer, tf) = infer_vars_ty typer tf in
let tf = infer_constraints_ty_or_fail typer tf in
let (typer, tf) = restrict_variable_ty typer tf in
let tf = instantiate_qformula_ty typer tf in
debug typer (fun () -> "\nFormula successfully typed.\n");
make_tqformula tf
| null | https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/lang/typing/infer.ml | ocaml | * If set to `true`, we have a trace of the typing process.
It is useful to debug the inference process.
* Useful for clear debugging messages.
* Variable environment mapping a variable name to its supported abstract domains.
* The abstract domain type, we try to infer a type for a formula matching this type.
Debugging facilities.
Inference errors.
I. Inference of the variables types.
Open-close interval only makes sense with float or rational.
For now, no vardom support hole in their domains.
II. Inference of the constraints types.
(1) Attempt to give a type to the formula `tf` in every component individually.
The sub-formulas tf1 and tf2 can be interpreted in different sub-domains of the product.
Whenever this term is typed in the sub-domain of the completion, the completion can handle it too.
III. Variable's type restriction.
V. Instantiation of the formula type.
This function is applied after `instantiate_formula_ty`, therefore the constraints' types have already been instantiated.
Since we instantiate the variable with its most general abstract domain, the constraints stay well-typed.
In case the variable does not occur in any constraint, we keep the list of UIDs.
Unrelated domains are considered equal here.
debug_ty typer (fun () -> string_of_aformula tf) (fst tf); | Copyright 2019
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation ; either
version 3 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
Lesser General Public License for more details .
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 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
Lesser General Public License for more details. *)
open Core
open Core.Types
open Lang.Ast
open Lang.Rewritting
open Lang.Pretty_print
open Tast
open Aast
open Ad_type
type inferred_type =
| CannotType of string
| Typed of ad_uid list
type iformula = inferred_type aformula
type iqformula = inferred_type aqformula
let uids_of' = function
| CannotType _ -> []
| Typed uids -> uids
let uids_of (ty,_) = uids_of' ty
let merge_ity ty1 ty2 =
match ty1, ty2 with
| CannotType msg1, CannotType msg2 -> CannotType (
msg1 ^ (if msg1 = "" || msg2 = "" then "" else "\n") ^ msg2)
| CannotType msg, Typed []
| Typed [], CannotType msg -> CannotType msg
| Typed uids, CannotType _ | CannotType _, Typed uids -> Typed uids
| Typed uids1, Typed uids2 -> Typed (List.sort_uniq compare (uids1@uids2))
let is_uid_in uid tf = List.mem uid (uids_of tf)
let is_uid_in2 uid tf1 tf2 = is_uid_in uid tf1 && is_uid_in uid tf2
let rec formula_to_iformula f =
let tf = match f with
| FVar v -> AFVar v
| Cmp c -> ACmp c
| Equiv(f1, f2) -> AEquiv(formula_to_iformula f1, formula_to_iformula f2)
| Imply(f1, f2) -> AImply(formula_to_iformula f1, formula_to_iformula f2)
| And(f1, f2) -> AAnd(formula_to_iformula f1, formula_to_iformula f2)
| Or(f1, f2) -> AOr(formula_to_iformula f1, formula_to_iformula f2)
| Not f1 -> ANot (formula_to_iformula f1)
in
(Typed [], tf)
let rec qformula_to_iqformula = function
| QFFormula f -> AQFFormula (formula_to_iformula f)
| Exists(v, ty, qf) -> AExists (v, ty, Typed [], qformula_to_iqformula qf)
module Inference =
struct
module Var2UID = Map.Make(struct type t=vname let compare=compare end)
type var_env = (ad_uid list) Var2UID.t
type t = {
trace: bool;
* ` true ` if we want to trace the reason why we can not type a formula .
If ` false ` , all strings ` s ` in ` CannotType s ` will be empty .
This is mostly an optimization to avoid constructing error messages ( which can be quite long ) when the formula is typable .
If `false`, all strings `s` in `CannotType s` will be empty.
This is mostly an optimization to avoid constructing error messages (which can be quite long) when the formula is typable. *)
debug: bool;
indent: int;
ad_env: ad_ty UID2Adty.t;
}
let init adty trace =
{trace; debug=false; indent=0; venv = Var2UID.empty; adty; ad_env = (build_adenv adty)}
let rec make_indent = function
| 0 -> ""
| x -> " " ^ (make_indent (x-1))
let indent typer = { typer with indent=(typer.indent+2) }
let debug typer make_msg =
if typer.debug then
(Printf.printf "%s%s\n" (make_indent typer.indent) (make_msg ());
flush_all ())
else ()
let string_of_adtys adtys =
let rec aux = function
| [] -> ""
| x::l -> (string_of_adty x) ^ (if l <> [] then " ; " else "") ^ (aux l)
in
if List.length adtys = 1 then aux adtys
else "[" ^ (aux adtys) ^ "]"
let string_of_ity typer = function
| CannotType msg -> "Error(" ^ msg ^ ")"
| Typed ad_uids ->
string_of_adtys (List.map (fun x -> UID2Adty.find x typer.ad_env) ad_uids)
let debug_adty typer make_msg adty =
if typer.debug then
Printf.printf "%s%s %s\n" (make_indent typer.indent) (make_msg ()) (string_of_adty adty)
else ()
let debug_ty typer term ty =
if typer.debug then
Printf.printf "%s%s:%s\n" (make_indent typer.indent)
(term ()) (string_of_ity typer ty)
else ()
let gen_err typer uid f =
CannotType
(if typer.trace then
"[" ^ (string_of_type typer.ad_env uid) ^ "] " ^ f ()
else
"")
let variable_not_in_dom_err typer uid v =
gen_err typer uid (fun () -> "Variable `" ^ v ^ "` does not belong to the abstract domain.")
let variable_not_in_subdom_err typer uid sub_uid v =
gen_err typer uid (fun () -> "Variable `" ^ v ^ "` does not belong to the sub-domain `"
^ (ad_name typer.ad_env sub_uid) ^ "`.\n"
^ "Note that this domain do not represent variables by itself but relies on the sub-domain.")
let not_a_constraint_err typer uid ad_name_adj ad_name =
gen_err typer uid (fun () ->
("The constraint is not a " ^ ad_name_adj ^ " constraint, so we cannot add it into " ^ ad_name ^ "."))
let not_a_box_constraint_err typer uid = not_a_constraint_err typer uid "box" "box"
let not_an_octagonal_constraint_err typer uid = not_a_constraint_err typer uid "octagonal" "octagon"
let ground_dom_does_not_handle_logic_connector_err typer uid =
gen_err typer uid (fun () -> "Ground abstract domain does not support logic connectors other than conjunction.")
let no_domain_support_this_variable_err typer uid v ty =
gen_err typer uid (fun () -> "The variable `" ^ v ^ "` (type `" ^ (string_of_ty ty) ^ "`) is not supported in any abstract domain.")
let sat_does_not_support_term_err typer uid =
gen_err typer uid (fun () -> "SAT domain does not support term, only Boolean formulas are supported.")
let direct_product_no_subdomain_err typer uid msg =
gen_err typer uid (fun () -> "The formula is not supported in any of the sub-domain of the direct product because:\n"
^ (Tools.indent msg))
let logic_completion_subdomain_failed_on_term_err typer uid =
gen_err typer uid (fun () -> "Logic completion delegates the term typing to its sub-domain, but it could not type this term.")
let no_var_mgad_err v adtys =
raise (Wrong_modelling(
"Variable `" ^ v ^ "` must be interpreted in several abstract elements, but there is not a most general one.\n"
^ "For instance, if a variable exists in two abstract elements, e.g. Box and Oct, we must have a type Box X Oct that takes care of mapping this variable in both domains.\n"
^ "Note that some abstract domains such as projection-based product take care of synchronizing the variables of both domains.\n"
^ " Candidate abstract domains: " ^ (string_of_adtys adtys)
))
let create_typing_error msg tf =
let cannot_type_formula msg f =
"Cannot type the following formula: `" ^ (string_of_aformula (CannotType msg, f)) ^ "` because:\n"
^ (Tools.indent msg) in
let rec aux msg f =
match f with
| AFVar v -> "Cannot type of the variable `" ^ v ^ "` because:\n"
^ (Tools.indent msg)
| ACmp c -> "Cannot type the following constraint: `" ^ (string_of_constraint c) ^ "` because:\n"
^ (Tools.indent msg)
| AAnd (tf1, tf2)
| AOr (tf1,tf2)
| AImply (tf1,tf2)
| AEquiv (tf1,tf2) ->
(match tf1, tf2 with
| ((CannotType msg, f1), _) -> aux msg f1
| (_, (CannotType msg, f2)) -> aux msg f2
| _ -> cannot_type_formula msg f)
| ANot (CannotType msg, tf1) -> aux msg tf1
| ANot _ -> cannot_type_formula msg f
in aux msg (snd tf)
let interval_can_represent_var vardom_ty ty =
let is_integer = function
| Interval Z | Interval_mix -> true
let is_rational = function
| Interval_oc Q | Interval Q -> true
NOTE : Interval_mix is implemented with floating point number for the real part .
let is_float = function
| Interval_oc F | Interval_mix | Interval F -> true
| _ -> false in
let is_real x = is_rational x || is_float x in
match ty with
| Concrete Int -> is_integer vardom_ty
| Concrete Real -> is_real vardom_ty
| Abstract Bool -> is_integer vardom_ty
| Abstract (Machine Z) -> is_integer vardom_ty
| Abstract (Machine Q) -> is_rational vardom_ty
| Abstract (Machine F) -> is_float vardom_ty
| Abstract VUnit -> false
| Abstract (BDD _) -> false
let compatible_ty ty vty =
match ty with
| Concrete Int -> vty = Z
| Concrete Real -> vty = F || vty = Q
| Abstract (Machine ty) -> vty = ty
| Abstract Bool -> vty = Z
| Abstract _ -> false
let is_vardom_support_neq = function
| Interval _ | Interval_oc _ | Interval_mix -> false
let rec infer_var ty adty =
let is_boolean = function
| Abstract Bool -> true
| _ -> false in
match adty with
| (uid, Box vardom_ty) when interval_can_represent_var vardom_ty ty -> [uid]
| (uid, Octagon vty) when compatible_ty ty vty -> [uid]
| (uid, SAT) when is_boolean ty -> [uid]
| (_, Delayed_product _) -> failwith "Delayed_product type inference is not yet implemented."
| (_, Direct_product adtys) -> List.flatten (List.map (infer_var ty) adtys)
| (_, Logic_completion adty) -> infer_var ty adty
| _ -> []
let build_venv typer tf =
let rec aux = function
| AQFFormula _ -> Var2UID.empty
| AExists(v, _, Typed uids, tf) -> Var2UID.add v uids (aux tf)
| _ -> failwith "build_venv: `check_var_ty` should be called before."
in
{typer with venv=(aux tf)}
let rec check_type_var = function
| AQFFormula _ -> ()
| AExists(_,_,CannotType msg,_) ->
raise (Wrong_modelling msg)
| AExists(_,_,Typed [],_) ->
failwith "Empty list of UIDs: we should either give a type to the variable, or `CannotType`."
| AExists(_,_,_,tf) -> check_type_var tf
let infer_vars_ty typer tf =
debug typer (fun () -> "I. Typing of the variables\n");
let rec aux typer = function
| (AQFFormula _) as tf -> tf
| AExists (v, ty, Typed [], tf) ->
let tf = aux typer tf in
let uids = List.sort_uniq compare (infer_var ty typer.adty) in
let res =
if List.length uids > 0 then Typed uids
else no_domain_support_this_variable_err typer 0 v ty
in
debug_ty typer (fun () -> v) res;
AExists (v, ty, res, tf)
| AExists (v,_,_,_) -> failwith
("infer_vars_ty: Existential connector of `" ^ v ^ "` is partly typed, which is not yet supported.")
in
let tf = aux typer tf in
check_type_var tf;
let typer = build_venv typer tf in
(typer, tf)
let belong typer uid v =
let uids = Var2UID.find v typer.venv in
List.exists (fun u -> u = uid) uids
let bool_var_infer typer v uid =
if Var2UID.mem v typer.venv then
Typed [uid]
else
variable_not_in_dom_err typer uid v
let ground_dom_infer typer uid term_infer tf =
let rec aux typer (ty, f) =
let (ty', f) =
match f with
| AFVar v -> merge_ity ty (bool_var_infer typer v uid), f
| ACmp c -> (term_infer c, f)
For conjunction , we type ` TAnd ` only if the inferred type is the same in both formula .
| AAnd (tf1, tf2) ->
let tf1, tf2 = aux typer tf1, aux typer tf2 in
if is_uid_in2 uid tf1 tf2 then
(merge_ity ty (Typed [uid]), AAnd(tf1,tf2))
else
(ty, AAnd(tf1,tf2))
| AOr (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AOr(tf1, tf2))
| AImply (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AImply(tf1, tf2))
| AEquiv (tf1,tf2) -> binary_aux typer tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1, tf2))
| ANot tf1 -> (ground_dom_does_not_handle_logic_connector_err typer uid, ANot (aux typer tf1)) in
let tf = (merge_ity ty ty', f) in
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and binary_aux typer tf1 tf2 make =
let tf1, tf2 = aux typer tf1, aux typer tf2 in
(ground_dom_does_not_handle_logic_connector_err typer uid, make tf1 tf2) in
aux typer tf
let fully_defined_over typer uid c =
let vars = vars_of_bconstraint c in
List.find_opt (fun v -> not (belong typer uid v)) vars
let box_infer typer box_uid vardom tf =
let is_box_constraint ((_, op, _) as c) =
let vars = vars_of_bconstraint c in
if List.length vars = 1 then
match op with
| NEQ -> is_vardom_support_neq vardom
| _ -> true
else
false in
let term_infer c =
if is_box_constraint c then
match fully_defined_over typer box_uid c with
| None -> Typed [box_uid]
| Some v -> variable_not_in_dom_err typer box_uid v
else
not_a_box_constraint_err typer box_uid
in ground_dom_infer typer box_uid term_infer tf
let octagon_infer typer oct_uid tf =
let rec is_octagonal_term = function
| Funcall(_, exprs) -> List.length (List.flatten (List.map get_vars_expr exprs)) = 0
| Unary(NEG, e) -> is_octagonal_term e
| Binary(e1,ADD,e2) | Binary(e1,SUB,e2) -> is_octagonal_term e1 && is_octagonal_term e2
| Var _ | Cst _ -> true
| _ -> false
in
let is_octagonal_constraint ((e1, op, e2) as c) =
let vars = vars_of_bconstraint c in
if List.length vars >= 1 && List.length vars <= 2 then
match op with
| NEQ -> false
| _ -> is_octagonal_term e1 && is_octagonal_term e2
else
false
in
let term_infer c =
if is_octagonal_constraint c then
match fully_defined_over typer oct_uid c with
| None -> Typed [oct_uid]
| Some v -> variable_not_in_dom_err typer oct_uid v
else
not_an_octagonal_constraint_err typer oct_uid
in ground_dom_infer typer oct_uid term_infer tf
let generic_formula_infer typer uid tf literal term =
let rec aux ((ty, f) as tf) =
let tf = match f with
| AFVar v -> merge_ity ty (literal v tf), AFVar v
| ACmp c -> merge_ity ty (term c tf), ACmp c
| AEquiv(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1,tf2))
| AImply(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AImply(tf1,tf2))
| AAnd(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AAnd(tf1,tf2))
| AOr(tf1,tf2) -> binary_aux ty tf1 tf2 (fun tf1 tf2 -> AOr(tf1,tf2))
| ANot tf ->
let tf = aux tf in
if is_uid_in uid tf then
(merge_ity ty (Typed [uid]), ANot tf)
else
(ty, ANot tf)
in
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and binary_aux ty tf1 tf2 make =
let tf1, tf2 = aux tf1, aux tf2 in
let f = make tf1 tf2 in
if is_uid_in2 uid tf1 tf2 then
(merge_ity ty (Typed [uid]), f)
else
(ty, f)
in
aux tf
let sat_infer typer sat_uid tf =
generic_formula_infer typer sat_uid tf
(fun v _ -> bool_var_infer typer v sat_uid)
(fun _ _ -> sat_does_not_support_term_err typer sat_uid)
let rec infer_constraints_ty typer tf (uid, adty) =
debug_adty typer (fun () -> "Typing of `" ^ (string_of_aformula tf) ^ "` with abstract domain") (uid, adty);
let typer = indent typer in
match adty with
| Box vardom -> box_infer typer uid vardom tf
| Octagon _ -> octagon_infer typer uid tf
| SAT -> sat_infer typer uid tf
| Delayed_product _ -> failwith "Delayed_product type inference is not yet implemented."
| Direct_product adtys -> direct_product_infer typer uid tf adtys
| Logic_completion adty -> logic_completion_infer typer uid tf adty
| Propagator_completion adty -> propagator_completion_infer typer uid tf adty
and direct_product_infer typer dp_uid tf adtys =
let tf = List.fold_left (infer_constraints_ty typer) tf adtys in
let adtys_uids = List.map fst adtys in
( 2 ) The next step is to give the type ` dp_uid ` to formulas of the form ` f1 : t1 /\ f2 : t2 ` if are in the product , and t1 ! = t2 .
let rec aux (ty, f) =
match f with
| AAnd(tf1,tf2) ->
let tf1, tf2 = aux tf1, aux tf2 in
let f = AAnd(tf1, tf2) in
let uids1, uids2 = uids_of tf1, uids_of tf2 in
let ty' =
if is_uid_in2 dp_uid tf1 tf2 then
Typed [dp_uid]
else
let u1 = Tools.intersect adtys_uids uids1 in
let u2 = Tools.intersect adtys_uids uids2 in
let common = Tools.intersect u1 u2 in
if List.length u1 > 0 && List.length u2 > 0 then
Typed (dp_uid::common)
else
CannotType ("Direct product could not type a conjunction c1 /\\ c2 because " ^
(match List.length u1, List.length u2 with
| 0, 0 -> "none of the sub-formula could be treated in any sub-domain."
| x, 0 when x > 0 -> "c2 could not be treated in any sub-domain"
| 0, x when x > 0 -> "c1 could not be treated in any sub-domain"
| _ -> failwith "unreachable"))
in
(merge_ity ty ty'), f
| _ ->
If there exists one sub - domain that can handle this formula , then the direct product can handle it .
However , we do not assign ` dp_uid ` to this formula , if we did , it means we want this formula to be treated in every domain of the product ( redundant information ) .
Redundant constraints might be interesting to explore , but this is for future work ( at least the typing framework already support it ) .
However, we do not assign `dp_uid` to this formula, if we did, it means we want this formula to be treated in every domain of the product (redundant information).
Redundant constraints might be interesting to explore, but this is for future work (at least the typing framework already support it). *)
ty,f
in
match aux tf with
| CannotType msg, f -> direct_product_no_subdomain_err typer dp_uid msg, f
| tf ->
let _ = debug_ty typer (fun () -> string_of_aformula tf) (fst tf) in
tf
and logic_completion_infer typer lc_uid tf adty =
let tf = infer_constraints_ty (indent typer) tf adty in
let lc_term _ tf =
match fst tf with
| Typed _ when is_mgad adty (uids_of tf) -> Typed [lc_uid]
| _ -> logic_completion_subdomain_failed_on_term_err typer lc_uid
in
generic_formula_infer typer lc_uid tf lc_term lc_term
and propagator_completion_infer typer pc_uid tf adty =
let tf = infer_constraints_ty (indent typer) tf adty in
let term_infer c =
match fully_defined_over typer (fst adty) c with
| None -> Typed [pc_uid]
| Some v -> variable_not_in_subdom_err typer pc_uid (fst adty) v
in ground_dom_infer typer pc_uid term_infer tf
let infer_constraints_ty_or_fail typer tf =
debug typer (fun () -> "\nII. Typing of the sub-formulas & constraints.\n");
map_tqf (fun tqf ->
We first try to type the formula without tracing the errors .
let typer = {typer with trace=false} in
let tqf = infer_constraints_ty typer tqf typer.adty in
match fst tqf with
| CannotType _ ->
debug typer (fun () -> "Typing of the formula failed, so we now create the error message and trace the typing process.");
let typer = {typer with trace=true; debug=false} in
let tqf = infer_constraints_ty typer tqf typer.adty in
(match fst tqf with
| CannotType msg -> raise (Wrong_modelling (create_typing_error msg tqf))
| Typed _ -> failwith "CannotType with trace=false, and Typed with trace=true, `trace` should not impact typing.")
| Typed _ -> tqf
) tf
module VarConsCounter = Map.Make(struct type t=vname * ad_uid let compare=compare end)
let build_var_cons_map tf uids_of =
let rec aux vcm tf =
let add_unary v vcm uid =
VarConsCounter.update (v,uid) (fun x ->
match x with
| Some (u,n) -> Some (u+1,n)
| None -> Some(1,0)) vcm in
let add_nary c vcm uid =
let vars = vars_of_bconstraint c in
if List.length vars = 1 then
add_unary (List.hd vars) vcm uid
else
List.fold_left (fun vcm v ->
VarConsCounter.update (v,uid) (fun x ->
match x with
| Some (u,n) -> Some (u,n+1)
| None -> Some(0,1)) vcm) vcm vars in
match tf with
| ty, AFVar v -> List.fold_left (add_unary v) vcm (uids_of ty)
| ty, ACmp c -> List.fold_left (add_nary c) vcm (uids_of ty)
| _, AEquiv(tf1,tf2) | _, AImply(tf1,tf2) | _, AAnd(tf1,tf2) | _, AOr(tf1,tf2) ->
aux (aux vcm tf1) tf2
| _, ANot tf -> aux vcm tf
in aux VarConsCounter.empty tf
let find_in_vcm v uid vcm =
try
VarConsCounter.find (v,uid) vcm
If Not_found , it means that the variable does not appear with this UID in any constraint .
with Not_found -> (0,0)
let restrict_unary_var_dom typer uids =
let is_octagon uid =
match UID2Adty.find uid typer.ad_env with
| _, Octagon _ -> true
| _ -> false in
let rec remove_octagon = function
| [] -> []
| x::l when is_octagon x -> l
| x::l -> x::(remove_octagon l) in
if List.length uids > 1 then remove_octagon uids else uids
let rec extract_formula = function
| AQFFormula tqf -> tqf
| AExists (_,_,_,tqf) -> extract_formula tqf
let restrict_variable_ty typer tf =
debug typer (fun () -> "\nIII. Restrict variables' types\n");
let tqf = extract_formula tf in
let vcm = build_var_cons_map tqf uids_of' in
let rec aux = function
| AQFFormula tqf -> AQFFormula tqf
| AExists (v,ty,Typed uids,tqf) ->
let nary = List.filter
(fun uid -> snd (find_in_vcm v uid vcm) > 0)
uids in
let uids =
if (List.length nary) > 0 then nary
else restrict_unary_var_dom typer uids in
debug_ty typer (fun () -> v) (Typed uids);
AExists (v,ty,Typed uids,aux tqf)
| AExists (_,_,CannotType _,_) -> failwith "restrict_variable_ty: Reached a CannotType, but should be checked before in `check_type_var`."
in
let tf = aux tf in
let typer = build_venv typer tf in
(typer, tf)
let instantiate_var_ty typer vcm vname uids =
let useful_uids = List.filter
(fun uid ->
let u,n = find_in_vcm vname uid vcm in
u > 0 || n > 0) uids in
let useful_uids = if List.length useful_uids = 0 then uids else useful_uids in
let adtys = List.map (fun uid -> UID2Adty.find uid typer.ad_env) useful_uids in
match select_mgad adtys with
| None -> no_var_mgad_err vname adtys
| Some adty -> fst adty
let sort_most_specialized typer uids =
We want the list to be sorted with the most specialized first ( so we rank it " smaller " in the compare function ) .
let compare_specialization ty1 ty2 =
if ty1 = ty2 then 0
else
match is_more_specialized ty1 ty2 with
| True -> -1
| False -> 1
in
let adtys = List.map (fun uid -> UID2Adty.find uid typer.ad_env) uids in
if adtys = [] then failwith "Type uids should not be empty (should be checked in `infer_constraints_ty_or_fail`)";
let adtys = List.stable_sort compare_specialization adtys in
List.map fst adtys
let most_specialized typer uids = List.hd (sort_most_specialized typer uids)
* From a sorted list of UIDS available , pick the first one that is a MGAD w.r.t . the UIDs in the provided list .
let first_supporting typer need_to_support_uids uids_available =
let rec aux = function
| [] -> failwith "Could not find an abstract domain supporting sub-formula, this should be checked in `infer_constraints_ty_or_fail`."
| uid::l ->
let adty = UID2Adty.find uid typer.ad_env in
if is_mgad adty need_to_support_uids then uid
else aux l
in aux uids_available
let instantiate_formula_ty typer tf =
let rec aux tf =
let (uid,f) = match tf with
| Typed uids, AFVar v ->
let var_uids = Var2UID.find v typer.venv in
let uids = Tools.intersect uids var_uids in
(most_specialized typer uids, AFVar v)
| Typed uids, ACmp c ->
We only keep the UID , its abstract element is fully defined over the variables of the constraint .
Due to ` restrict_variable_ty ` we must perform this filtering .
Due to `restrict_variable_ty` we must perform this filtering. *)
let uids = List.filter
(fun uid ->
List.for_all
(fun v ->
let adty = UID2Adty.find uid typer.ad_env in
List.exists
(fun u -> subtype (UID2Adty.find u typer.ad_env) adty)
(Var2UID.find v typer.venv))
(vars_of_bconstraint c))
uids in
(most_specialized typer uids, ACmp c)
| Typed uids, AAnd (tf1, tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AAnd(tf1, tf2))
| Typed uids, AOr (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AOr(tf1, tf2))
| Typed uids, AImply (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AImply(tf1, tf2))
| Typed uids, AEquiv (tf1,tf2) -> binary_aux uids tf1 tf2 (fun tf1 tf2 -> AEquiv(tf1, tf2))
| Typed uids, ANot tf ->
let (uid1, tf1) = aux tf in
let sorted_uids = sort_most_specialized typer uids in
(first_supporting typer [uid1] sorted_uids, ANot (uid1,tf1))
| _ -> failwith "instantiate_formula_ty: Formula should all be typed after the call to `infer_constraints_ty_or_fail`."
in
debug_ty typer (fun () -> string_of_aformula tf) (Typed [uid]);
(uid,f)
and binary_aux uids tf1 tf2 make =
let (uid1, tf1), (uid2, tf2) = aux tf1, aux tf2 in
let sorted_uids = sort_most_specialized typer uids in
(first_supporting typer [uid1; uid2] sorted_uids, make (uid1,tf1) (uid2,tf2))
in
aux tf
let instantiate_qformula_ty typer tf =
debug typer (fun () -> "\nIV. Instantiate the type of formula\n");
let rec aux = function
| AQFFormula tqf ->
let tqf = instantiate_formula_ty typer tqf in
AQFFormula tqf, build_var_cons_map tqf (fun uid -> [uid])
| AExists (vname,ty,Typed uids,tf) ->
let tf, vcm = aux tf in
let uid = instantiate_var_ty typer vcm vname uids in
AExists (vname, ty, uid, tf), vcm
| AExists (_,_,CannotType msg, _) -> raise (Wrong_modelling msg)
in fst (aux tf)
end
let make_tqformula tf =
let rec aux' = function
| uid, AFVar v -> (uid, TFVar v)
| uid, ACmp c -> (uid, TCmp c)
| uid, AAnd (tf1, tf2) -> (uid, TAnd(aux' tf1, aux' tf2))
| uid, AOr (tf1,tf2) -> (uid, TOr(aux' tf1, aux' tf2))
| uid, AImply (tf1,tf2) -> (uid, TImply(aux' tf1, aux' tf2))
| uid, AEquiv (tf1,tf2) -> (uid, TEquiv(aux' tf1, aux' tf2))
| uid, ANot tf -> (uid, TNot (aux' tf)) in
let rec aux = function
| AQFFormula tqf -> TQFFormula (aux' tqf)
| AExists (name, ty, uid, tf) ->
TExists ({name; ty; uid}, aux tf)
in aux tf
let infer_type adty f =
let open Inference in
let tf = qformula_to_iqformula f in
let typer = init adty true in
let (typer, tf) = infer_vars_ty typer tf in
let tf = infer_constraints_ty_or_fail typer tf in
let (typer, tf) = restrict_variable_ty typer tf in
let tf = instantiate_qformula_ty typer tf in
debug typer (fun () -> "\nFormula successfully typed.\n");
make_tqformula tf
|
7c1b850f8907ddac7b12949b8645ce81e9db7c070da6dc883293898bb86ebd65 | discus-lang/salt | Name.hs |
module Salt.Core.Exp.Name
( Annot
, Name (..), Text, IsString(..)
, Bind (..)
, Bound (..), pattern Bound)
where
import Data.Text (Text)
import Data.String
import Data.Typeable
import qualified Data.Text as T
---------------------------------------------------------------------------------------------------
-- | The usual constraints on expression annotations.
allows us to throw exceptions that mention them .
type Annot a = (Show a, Typeable a)
---------------------------------------------------------------------------------------------------
-- | Names of things.
data Name
= Name Text
deriving (Show, Eq, Ord)
instance IsString Name where
fromString str = Name $ T.pack str
---------------------------------------------------------------------------------------------------
-- | Binding occurence of variable.
data Bind
-- | Named binder.
= BindName Name
-- | Non-binding binder.
-- This behaves like a binder where the name is not mentioned
-- anywhere else in the program.
| BindNone
deriving (Show, Eq, Ord)
instance IsString Bind where
fromString str = BindName $ Name $ T.pack str
---------------------------------------------------------------------------------------------------
-- | Bound occurrence of variable.
data Bound
= BoundWith Name Integer
deriving (Show, Eq, Ord)
pattern Bound n = BoundWith n 0
instance IsString Bound where
fromString str = Bound $ Name $ T.pack str
| null | https://raw.githubusercontent.com/discus-lang/salt/33c14414ac7e238fdbd8161971b8b8ac67fff569/src/salt/Salt/Core/Exp/Name.hs | haskell | -------------------------------------------------------------------------------------------------
| The usual constraints on expression annotations.
-------------------------------------------------------------------------------------------------
| Names of things.
-------------------------------------------------------------------------------------------------
| Binding occurence of variable.
| Named binder.
| Non-binding binder.
This behaves like a binder where the name is not mentioned
anywhere else in the program.
-------------------------------------------------------------------------------------------------
| Bound occurrence of variable. |
module Salt.Core.Exp.Name
( Annot
, Name (..), Text, IsString(..)
, Bind (..)
, Bound (..), pattern Bound)
where
import Data.Text (Text)
import Data.String
import Data.Typeable
import qualified Data.Text as T
allows us to throw exceptions that mention them .
type Annot a = (Show a, Typeable a)
data Name
= Name Text
deriving (Show, Eq, Ord)
instance IsString Name where
fromString str = Name $ T.pack str
data Bind
= BindName Name
| BindNone
deriving (Show, Eq, Ord)
instance IsString Bind where
fromString str = BindName $ Name $ T.pack str
data Bound
= BoundWith Name Integer
deriving (Show, Eq, Ord)
pattern Bound n = BoundWith n 0
instance IsString Bound where
fromString str = Bound $ Name $ T.pack str
|
ef7d508c0991d53c8de820842f189b504d4cc74aa38d193c96189214161ffb58 | apibot-org/apibot | auth.clj | (ns apibot.auth
(:require
[apibot.config :as config])
(:import
[com.auth0.jwt.algorithms Algorithm]
[com.auth0.jwt JWT JWTVerifier]
[com.auth0.jwt.interfaces RSAKeyProvider]
[com.auth0.jwk UrlJwkProvider Jwk]
[java.security.interfaces RSAPublicKey]))
(defn ^RSAKeyProvider jwt-key-provider
[]
(let [provider (new UrlJwkProvider "/")]
(reify RSAKeyProvider
(getPrivateKey [this] nil)
(getPrivateKeyId [this] nil)
(getPublicKeyById [this key-id]
(let [^Jwk jwk (.get provider key-id)
^RSAPublicKey pubKey (.getPublicKey jwk)]
pubKey)))))
(defn ^JWTVerifier create-verifier
"Create a new JWTVerifier which can be used to verify tokens
by calling (.verify verifier).
Throws JWTVerificationException if verification fails."
([^RSAKeyProvider this]
(-> this
(Algorithm/RSA256)
(JWT/require)
(.withIssuer "/")
(.withAudience (into-array String [(config/auth0-audience)]))
(.build)))
([]
(-> (jwt-key-provider) create-verifier)))
| null | https://raw.githubusercontent.com/apibot-org/apibot/26c77c688980549a8deceeeb39f01108be016435/src/clj/apibot/auth.clj | clojure | (ns apibot.auth
(:require
[apibot.config :as config])
(:import
[com.auth0.jwt.algorithms Algorithm]
[com.auth0.jwt JWT JWTVerifier]
[com.auth0.jwt.interfaces RSAKeyProvider]
[com.auth0.jwk UrlJwkProvider Jwk]
[java.security.interfaces RSAPublicKey]))
(defn ^RSAKeyProvider jwt-key-provider
[]
(let [provider (new UrlJwkProvider "/")]
(reify RSAKeyProvider
(getPrivateKey [this] nil)
(getPrivateKeyId [this] nil)
(getPublicKeyById [this key-id]
(let [^Jwk jwk (.get provider key-id)
^RSAPublicKey pubKey (.getPublicKey jwk)]
pubKey)))))
(defn ^JWTVerifier create-verifier
"Create a new JWTVerifier which can be used to verify tokens
by calling (.verify verifier).
Throws JWTVerificationException if verification fails."
([^RSAKeyProvider this]
(-> this
(Algorithm/RSA256)
(JWT/require)
(.withIssuer "/")
(.withAudience (into-array String [(config/auth0-audience)]))
(.build)))
([]
(-> (jwt-key-provider) create-verifier)))
|
|
a19c2e5fff32b9dad7da5c582ba248c1535ac4c54a46a7ccc903e89a14c2a491 | cxphoe/SICP-solutions | analyze.rkt | (load "expression.rkt")
;; make a copy of the original apply in the scheme
(define apply-in-underlying-scheme apply)
;; evaluator for amb
(define (ambeval exp env succeed fail)
((analyze exp) env succeed fail))
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((amb? exp) (analyze-amb exp))
((assignment? exp) (analyze-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((require? exp) (analyze-require exp))
((if-fail? exp) (analyze-if-fail exp))
((and? exp) (analyze (and->if exp)))
((or? exp) (analyze (or->if exp)))
((do? exp) (analyze (do->if exp)))
((while? exp) (analyze (while->combination exp)))
((lambda? exp) (analyze-lambda exp))
((let? exp) (analyze (let->combination exp)))
((begin? exp) (analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(define (analyze-self-evaluating exp)
(lambda (env succeed fail)
(succeed exp fail)))
(define (analyze-quoted exp)
(let ((qval (text-of-quotation exp)))
(lambda (env succeed fail)
(succeed qval fail))))
(define (analyze-variable exp)
(lambda (env succeed fail)
(succeed (lookup-variable-value exp env) fail)))
(define (analyze-assignment exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
;; success continuation
(lambda (val fail2)
(let ((old-value
(lookup-variable-value var env)))
(set-variable-value! var val env)
(succeed 'ok
(lambda ()
(set-variable-value! var
olf-value
env)
(fail2)))))
;; failure continuation
fail))))
(define (analyze-definition exp)
(let ((var (definition-variable exp))
(vproc (analyze (definition-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(define-variable! var val env)
(succeed 'ok fail2))
fail))))
(define (analyze-if exp)
(let ((pproc (analyze (if-predicate exp)))
(cproc (analyze (if-consequent exp)))
(aproc (analyze (if-alternative exp))))
(lambda (env succeed fail)
(pproc env
;; success continuation for evaluating the predicate
;; to obtain pred-value
(lambda (pred-value fail2)
(if (true? pred-value)
(cproc env succeed fail2)
(aproc env succeed fail2)))
;; failure continuation for evaluating the predicate
fail))))
(define (analyze-lambda exp)
(let ((vars (lambda-parameters exp))
(bproc (analyze-sequence (lambda-body exp))))
(lambda (env succeed fail)
(succeed (make-procedure vars bproc env) fail))))
(define (analyze-sequence exps)
(define (sequentially proc1 proc2)
(lambda (env succeed fail)
(proc1 env
success continuation for calling
(lambda (proc1-value fail2)
(proc2 env succeed fail2))
failure continuation for calling
fail)))
(define (loop first-proc rest-procs)
(if (null? rest-procs)
first-proc
(loop (sequentially first-proc (car rest-procs))
(cdr rest-procs))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence -- ANALYZE"))
(loop (car procs) (cdr procs))))
(define (analyze-application exp)
(let ((fproc (analyze (operator exp)))
(aprocs (map analyze (operands exp))))
(lambda (env succeed fail)
(fproc env
(lambda (proc fail2)
(get-args aprocs
env
(lambda (args fail3)
(execute-application
proc args succeed fail3))
fail2))
fail))))
(define (get-args aprocs env succeed fail)
(if (null? aprocs)
(succeed '() fail)
((car aprocs) env
;; success continuation for this aproc
(lambda (arg fail2)
(get-args (cdr aprocs)
env
;; success cintinuation for recursive
;; call to get-args
(lambda (args fail3)
(succeed (cons arg args)
fail3))
fail2))
fail)))
(define (execute-application proc args succeed fail)
(cond ((primitive-procedure? proc)
(succeed (apply-primitive-procedure proc args)
fail))
((compound-procedure? proc)
((procedure-body proc)
(extend-environment (procedure-parameters proc)
args
(procedure-environment proc))
succeed
fail))
(else
(error
"Unknown procedure type -- EXECUTE-APPLICATION"
proc))))
(define (analyze-amb exp)
(let ((cprocs (map analyze (amb-choices exp))))
(lambda (env succeed fail)
(define (try-next choices)
(if (null? choices)
(fail)
((car choices) env
succeed
(lambda ()
(try-next (cdr choices))))))
(try-next cprocs))))
( load " 4.50.rkt " )
(load "4.52.rkt")
(load "4.54.rkt") | null | https://raw.githubusercontent.com/cxphoe/SICP-solutions/d35bb688db0320f6efb3b3bde1a14ce21da319bd/Chapter%204-Metalinguistic%20Abstraction/3.Non-deterministic%20Computation/analyze.rkt | racket | make a copy of the original apply in the scheme
evaluator for amb
success continuation
failure continuation
success continuation for evaluating the predicate
to obtain pred-value
failure continuation for evaluating the predicate
success continuation for this aproc
success cintinuation for recursive
call to get-args | (load "expression.rkt")
(define apply-in-underlying-scheme apply)
(define (ambeval exp env succeed fail)
((analyze exp) env succeed fail))
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((amb? exp) (analyze-amb exp))
((assignment? exp) (analyze-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((require? exp) (analyze-require exp))
((if-fail? exp) (analyze-if-fail exp))
((and? exp) (analyze (and->if exp)))
((or? exp) (analyze (or->if exp)))
((do? exp) (analyze (do->if exp)))
((while? exp) (analyze (while->combination exp)))
((lambda? exp) (analyze-lambda exp))
((let? exp) (analyze (let->combination exp)))
((begin? exp) (analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(define (analyze-self-evaluating exp)
(lambda (env succeed fail)
(succeed exp fail)))
(define (analyze-quoted exp)
(let ((qval (text-of-quotation exp)))
(lambda (env succeed fail)
(succeed qval fail))))
(define (analyze-variable exp)
(lambda (env succeed fail)
(succeed (lookup-variable-value exp env) fail)))
(define (analyze-assignment exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(let ((old-value
(lookup-variable-value var env)))
(set-variable-value! var val env)
(succeed 'ok
(lambda ()
(set-variable-value! var
olf-value
env)
(fail2)))))
fail))))
(define (analyze-definition exp)
(let ((var (definition-variable exp))
(vproc (analyze (definition-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(define-variable! var val env)
(succeed 'ok fail2))
fail))))
(define (analyze-if exp)
(let ((pproc (analyze (if-predicate exp)))
(cproc (analyze (if-consequent exp)))
(aproc (analyze (if-alternative exp))))
(lambda (env succeed fail)
(pproc env
(lambda (pred-value fail2)
(if (true? pred-value)
(cproc env succeed fail2)
(aproc env succeed fail2)))
fail))))
(define (analyze-lambda exp)
(let ((vars (lambda-parameters exp))
(bproc (analyze-sequence (lambda-body exp))))
(lambda (env succeed fail)
(succeed (make-procedure vars bproc env) fail))))
(define (analyze-sequence exps)
(define (sequentially proc1 proc2)
(lambda (env succeed fail)
(proc1 env
success continuation for calling
(lambda (proc1-value fail2)
(proc2 env succeed fail2))
failure continuation for calling
fail)))
(define (loop first-proc rest-procs)
(if (null? rest-procs)
first-proc
(loop (sequentially first-proc (car rest-procs))
(cdr rest-procs))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence -- ANALYZE"))
(loop (car procs) (cdr procs))))
(define (analyze-application exp)
(let ((fproc (analyze (operator exp)))
(aprocs (map analyze (operands exp))))
(lambda (env succeed fail)
(fproc env
(lambda (proc fail2)
(get-args aprocs
env
(lambda (args fail3)
(execute-application
proc args succeed fail3))
fail2))
fail))))
(define (get-args aprocs env succeed fail)
(if (null? aprocs)
(succeed '() fail)
((car aprocs) env
(lambda (arg fail2)
(get-args (cdr aprocs)
env
(lambda (args fail3)
(succeed (cons arg args)
fail3))
fail2))
fail)))
(define (execute-application proc args succeed fail)
(cond ((primitive-procedure? proc)
(succeed (apply-primitive-procedure proc args)
fail))
((compound-procedure? proc)
((procedure-body proc)
(extend-environment (procedure-parameters proc)
args
(procedure-environment proc))
succeed
fail))
(else
(error
"Unknown procedure type -- EXECUTE-APPLICATION"
proc))))
(define (analyze-amb exp)
(let ((cprocs (map analyze (amb-choices exp))))
(lambda (env succeed fail)
(define (try-next choices)
(if (null? choices)
(fail)
((car choices) env
succeed
(lambda ()
(try-next (cdr choices))))))
(try-next cprocs))))
( load " 4.50.rkt " )
(load "4.52.rkt")
(load "4.54.rkt") |
bc56601015c920617480482af1bc1a3974c58b4c02ef8e064ff53132035ae900 | hjwylde/werewolf | Orphan.hs | |
Module : Game . Werewolf . Command . Orphan
Description : Orphan commands .
Copyright : ( c ) , 2016
License : :
Orphan commands .
Module : Game.Werewolf.Command.Orphan
Description : Orphan commands.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Orphan commands.
-}
module Game.Werewolf.Command.Orphan (
-- * Commands
chooseCommand,
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Extra
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Message.Error
import Game.Werewolf.Util
chooseCommand :: Text -> Text -> Command
chooseCommand callerName targetName = Command $ do
validatePlayer callerName callerName
unlessM (isPlayerOrphan callerName) $ throwError [playerCannotDoThatMessage callerName]
unlessM isOrphansTurn $ throwError [playerCannotDoThatRightNowMessage callerName]
when (callerName == targetName) $ throwError [playerCannotChooseSelfMessage callerName]
validatePlayer callerName targetName
roleModel .= Just targetName
| null | https://raw.githubusercontent.com/hjwylde/werewolf/d22a941120a282127fc3e2db52e7c86b5d238344/app/Game/Werewolf/Command/Orphan.hs | haskell | * Commands | |
Module : Game . Werewolf . Command . Orphan
Description : Orphan commands .
Copyright : ( c ) , 2016
License : :
Orphan commands .
Module : Game.Werewolf.Command.Orphan
Description : Orphan commands.
Copyright : (c) Henry J. Wylde, 2016
License : BSD3
Maintainer :
Orphan commands.
-}
module Game.Werewolf.Command.Orphan (
chooseCommand,
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Extra
import Data.Text (Text)
import Game.Werewolf
import Game.Werewolf.Command
import Game.Werewolf.Message.Error
import Game.Werewolf.Util
chooseCommand :: Text -> Text -> Command
chooseCommand callerName targetName = Command $ do
validatePlayer callerName callerName
unlessM (isPlayerOrphan callerName) $ throwError [playerCannotDoThatMessage callerName]
unlessM isOrphansTurn $ throwError [playerCannotDoThatRightNowMessage callerName]
when (callerName == targetName) $ throwError [playerCannotChooseSelfMessage callerName]
validatePlayer callerName targetName
roleModel .= Just targetName
|
5d42e7a11f9dcca106c177e551391de37bd5d4a273dd1cc5582427f9b7dd3e3e | roehst/tapl-implementations | core.ml | open Format
open Syntax
open Support.Error
open Support.Pervasive
(* ------------------------ EVALUATION ------------------------ *)
exception NoRuleApplies
let rec isnumericval ctx t = match t with
TmZero(_) -> true
| TmSucc(_,t1) -> isnumericval ctx t1
| _ -> false
let rec isval ctx t = match t with
TmTrue(_) -> true
| TmFalse(_) -> true
| TmString _ -> true
| TmUnit(_) -> true
| TmFloat _ -> true
| t when isnumericval ctx t -> true
| TmAbs(_,_,_,_) -> true
| TmRecord(_,fields) -> List.for_all (fun (l,ti) -> isval ctx ti) fields
| _ -> false
let rec eval1 ctx t = match t with
TmApp(fi,TmAbs(_,x,tyT11,t12),v2) when isval ctx v2 ->
termSubstTop v2 t12
| TmApp(fi,v1,t2) when isval ctx v1 ->
let t2' = eval1 ctx t2 in
TmApp(fi, v1, t2')
| TmApp(fi,t1,t2) ->
let t1' = eval1 ctx t1 in
TmApp(fi, t1', t2)
| TmIf(_,TmTrue(_),t2,t3) ->
t2
| TmIf(_,TmFalse(_),t2,t3) ->
t3
| TmIf(fi,t1,t2,t3) ->
let t1' = eval1 ctx t1 in
TmIf(fi, t1', t2, t3)
| TmRecord(fi,fields) ->
let rec evalafield l = match l with
[] -> raise NoRuleApplies
| (l,vi)::rest when isval ctx vi ->
let rest' = evalafield rest in
(l,vi)::rest'
| (l,ti)::rest ->
let ti' = eval1 ctx ti in
(l, ti')::rest
in let fields' = evalafield fields in
TmRecord(fi, fields')
| TmProj(fi, (TmRecord(_, fields) as v1), l) when isval ctx v1 ->
(try List.assoc l fields
with Not_found -> raise NoRuleApplies)
| TmProj(fi, t1, l) ->
let t1' = eval1 ctx t1 in
TmProj(fi, t1', l)
| TmLet(fi,x,v1,t2) when isval ctx v1 ->
termSubstTop v1 t2
| TmLet(fi,x,t1,t2) ->
let t1' = eval1 ctx t1 in
TmLet(fi, x, t1', t2)
| TmFix(fi,v1) as t when isval ctx v1 ->
(match v1 with
TmAbs(_,_,_,t12) -> termSubstTop t t12
| _ -> raise NoRuleApplies)
| TmFix(fi,t1) ->
let t1' = eval1 ctx t1
in TmFix(fi,t1')
| TmVar(fi,n,_) ->
(match getbinding fi ctx n with
TmAbbBind(t,_) -> t
| _ -> raise NoRuleApplies)
| TmAscribe(fi,v1,tyT) when isval ctx v1 ->
v1
| TmAscribe(fi,t1,tyT) ->
let t1' = eval1 ctx t1 in
TmAscribe(fi,t1',tyT)
| TmTimesfloat(fi,TmFloat(_,f1),TmFloat(_,f2)) ->
TmFloat(fi, f1 *. f2)
| TmTimesfloat(fi,(TmFloat(_,f1) as t1),t2) ->
let t2' = eval1 ctx t2 in
TmTimesfloat(fi,t1,t2')
| TmTimesfloat(fi,t1,t2) ->
let t1' = eval1 ctx t1 in
TmTimesfloat(fi,t1',t2)
| TmSucc(fi,t1) ->
let t1' = eval1 ctx t1 in
TmSucc(fi, t1')
| TmPred(_,TmZero(_)) ->
TmZero(dummyinfo)
| TmPred(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
nv1
| TmPred(fi,t1) ->
let t1' = eval1 ctx t1 in
TmPred(fi, t1')
| TmIsZero(_,TmZero(_)) ->
TmTrue(dummyinfo)
| TmIsZero(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
TmFalse(dummyinfo)
| TmIsZero(fi,t1) ->
let t1' = eval1 ctx t1 in
TmIsZero(fi, t1')
| _ ->
raise NoRuleApplies
let rec eval ctx t =
try let t' = eval1 ctx t
in eval ctx t'
with NoRuleApplies -> t
(* ------------------------ SUBTYPING ------------------------ *)
let evalbinding ctx b = match b with
TmAbbBind(t,tyT) ->
let t' = eval ctx t in
TmAbbBind(t',tyT)
| bind -> bind
let istyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT) -> true
| _ -> false
let gettyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT) -> tyT
| _ -> raise NoRuleApplies
let rec computety ctx tyT = match tyT with
TyVar(i,_) when istyabb ctx i -> gettyabb ctx i
| _ -> raise NoRuleApplies
let rec simplifyty ctx tyT =
try
let tyT' = computety ctx tyT in
simplifyty ctx tyT'
with NoRuleApplies -> tyT
let rec tyeqv ctx tyS tyT =
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| (TyString,TyString) -> true
| (TyTop,TyTop) -> true
| (TyUnit,TyUnit) -> true
| (TyId(b1),TyId(b2)) -> b1=b2
| (TyFloat,TyFloat) -> true
| (TyVar(i,_), _) when istyabb ctx i ->
tyeqv ctx (gettyabb ctx i) tyT
| (_, TyVar(i,_)) when istyabb ctx i ->
tyeqv ctx tyS (gettyabb ctx i)
| (TyVar(i,_),TyVar(j,_)) -> i=j
| (TyBool,TyBool) -> true
| (TyNat,TyNat) -> true
| (TyRecord(fields1),TyRecord(fields2)) ->
List.length fields1 = List.length fields2
&&
List.for_all
(fun (li2,tyTi2) ->
try let (tyTi1) = List.assoc li2 fields1 in
tyeqv ctx tyTi1 tyTi2
with Not_found -> false)
fields2
| _ -> false
let rec subtype ctx tyS tyT =
tyeqv ctx tyS tyT ||
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(_,TyTop) ->
true
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(subtype ctx tyT1 tyS1) && (subtype ctx tyS2 tyT2)
| (TyRecord(fS), TyRecord(fT)) ->
List.for_all
(fun (li,tyTi) ->
try let tySi = List.assoc li fS in
subtype ctx tySi tyTi
with Not_found -> false)
fT
| (_,_) ->
false
let rec join ctx tyS tyT =
if subtype ctx tyS tyT then tyT else
if subtype ctx tyT tyS then tyS else
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyRecord(fS), TyRecord(fT)) ->
let labelsS = List.map (fun (li,_) -> li) fS in
let labelsT = List.map (fun (li,_) -> li) fT in
let commonLabels =
List.find_all (fun l -> List.mem l labelsT) labelsS in
let commonFields =
List.map (fun li ->
let tySi = List.assoc li fS in
let tyTi = List.assoc li fT in
(li, join ctx tySi tyTi))
commonLabels in
TyRecord(commonFields)
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(try TyArr(meet ctx tyS1 tyT1, join ctx tyS2 tyT2)
with Not_found -> TyTop)
| _ ->
TyTop
and meet ctx tyS tyT =
if subtype ctx tyS tyT then tyS else
if subtype ctx tyT tyS then tyT else
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyRecord(fS), TyRecord(fT)) ->
let labelsS = List.map (fun (li,_) -> li) fS in
let labelsT = List.map (fun (li,_) -> li) fT in
let allLabels =
List.append
labelsS
(List.find_all
(fun l -> not (List.mem l labelsS)) labelsT) in
let allFields =
List.map (fun li ->
if List.mem li allLabels then
let tySi = List.assoc li fS in
let tyTi = List.assoc li fT in
(li, meet ctx tySi tyTi)
else if List.mem li labelsS then
(li, List.assoc li fS)
else
(li, List.assoc li fT))
allLabels in
TyRecord(allFields)
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
TyArr(join ctx tyS1 tyT1, meet ctx tyS2 tyT2)
| _ ->
raise Not_found
(* ------------------------ TYPING ------------------------ *)
let rec typeof ctx t =
match t with
TmInert(fi,tyT) ->
tyT
| TmVar(fi,i,_) -> getTypeFromContext fi ctx i
| TmAbs(fi,x,tyT1,t2) ->
let ctx' = addbinding ctx x (VarBind(tyT1)) in
let tyT2 = typeof ctx' t2 in
TyArr(tyT1, typeShift (-1) tyT2)
| TmApp(fi,t1,t2) ->
let tyT1 = typeof ctx t1 in
let tyT2 = typeof ctx t2 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if subtype ctx tyT2 tyT11 then tyT12
else error fi "parameter type mismatch"
| _ -> error fi "arrow type expected")
| TmTrue(fi) ->
TyBool
| TmFalse(fi) ->
TyBool
| TmIf(fi,t1,t2,t3) ->
if subtype ctx (typeof ctx t1) TyBool then
join ctx (typeof ctx t2) (typeof ctx t3)
else error fi "guard of conditional not a boolean"
| TmRecord(fi, fields) ->
let fieldtys =
List.map (fun (li,ti) -> (li, typeof ctx ti)) fields in
TyRecord(fieldtys)
| TmProj(fi, t1, l) ->
(match simplifyty ctx (typeof ctx t1) with
TyRecord(fieldtys) ->
(try List.assoc l fieldtys
with Not_found -> error fi ("label "^l^" not found"))
| _ -> error fi "Expected record type")
| TmLet(fi,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
let ctx' = addbinding ctx x (VarBind(tyT1)) in
typeShift (-1) (typeof ctx' t2)
| TmFix(fi, t1) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if subtype ctx tyT12 tyT11 then tyT12
else error fi "result of body not compatible with domain"
| _ -> error fi "arrow type expected")
| TmString _ -> TyString
| TmUnit(fi) -> TyUnit
| TmAscribe(fi,t1,tyT) ->
if subtype ctx (typeof ctx t1) tyT then
tyT
else
error fi "body of as-term does not have the expected type"
| TmFloat _ -> TyFloat
| TmTimesfloat(fi,t1,t2) ->
if subtype ctx (typeof ctx t1) TyFloat
&& subtype ctx (typeof ctx t2) TyFloat then TyFloat
else error fi "argument of timesfloat is not a number"
| TmZero(fi) ->
TyNat
| TmSucc(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of succ is not a number"
| TmPred(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of pred is not a number"
| TmIsZero(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyBool
else error fi "argument of iszero is not a number"
| null | https://raw.githubusercontent.com/roehst/tapl-implementations/23c0dc505a8c0b0a797201a7e4e3e5b939dd8fdb/fullsub/core.ml | ocaml | ------------------------ EVALUATION ------------------------
------------------------ SUBTYPING ------------------------
------------------------ TYPING ------------------------ | open Format
open Syntax
open Support.Error
open Support.Pervasive
exception NoRuleApplies
let rec isnumericval ctx t = match t with
TmZero(_) -> true
| TmSucc(_,t1) -> isnumericval ctx t1
| _ -> false
let rec isval ctx t = match t with
TmTrue(_) -> true
| TmFalse(_) -> true
| TmString _ -> true
| TmUnit(_) -> true
| TmFloat _ -> true
| t when isnumericval ctx t -> true
| TmAbs(_,_,_,_) -> true
| TmRecord(_,fields) -> List.for_all (fun (l,ti) -> isval ctx ti) fields
| _ -> false
let rec eval1 ctx t = match t with
TmApp(fi,TmAbs(_,x,tyT11,t12),v2) when isval ctx v2 ->
termSubstTop v2 t12
| TmApp(fi,v1,t2) when isval ctx v1 ->
let t2' = eval1 ctx t2 in
TmApp(fi, v1, t2')
| TmApp(fi,t1,t2) ->
let t1' = eval1 ctx t1 in
TmApp(fi, t1', t2)
| TmIf(_,TmTrue(_),t2,t3) ->
t2
| TmIf(_,TmFalse(_),t2,t3) ->
t3
| TmIf(fi,t1,t2,t3) ->
let t1' = eval1 ctx t1 in
TmIf(fi, t1', t2, t3)
| TmRecord(fi,fields) ->
let rec evalafield l = match l with
[] -> raise NoRuleApplies
| (l,vi)::rest when isval ctx vi ->
let rest' = evalafield rest in
(l,vi)::rest'
| (l,ti)::rest ->
let ti' = eval1 ctx ti in
(l, ti')::rest
in let fields' = evalafield fields in
TmRecord(fi, fields')
| TmProj(fi, (TmRecord(_, fields) as v1), l) when isval ctx v1 ->
(try List.assoc l fields
with Not_found -> raise NoRuleApplies)
| TmProj(fi, t1, l) ->
let t1' = eval1 ctx t1 in
TmProj(fi, t1', l)
| TmLet(fi,x,v1,t2) when isval ctx v1 ->
termSubstTop v1 t2
| TmLet(fi,x,t1,t2) ->
let t1' = eval1 ctx t1 in
TmLet(fi, x, t1', t2)
| TmFix(fi,v1) as t when isval ctx v1 ->
(match v1 with
TmAbs(_,_,_,t12) -> termSubstTop t t12
| _ -> raise NoRuleApplies)
| TmFix(fi,t1) ->
let t1' = eval1 ctx t1
in TmFix(fi,t1')
| TmVar(fi,n,_) ->
(match getbinding fi ctx n with
TmAbbBind(t,_) -> t
| _ -> raise NoRuleApplies)
| TmAscribe(fi,v1,tyT) when isval ctx v1 ->
v1
| TmAscribe(fi,t1,tyT) ->
let t1' = eval1 ctx t1 in
TmAscribe(fi,t1',tyT)
| TmTimesfloat(fi,TmFloat(_,f1),TmFloat(_,f2)) ->
TmFloat(fi, f1 *. f2)
| TmTimesfloat(fi,(TmFloat(_,f1) as t1),t2) ->
let t2' = eval1 ctx t2 in
TmTimesfloat(fi,t1,t2')
| TmTimesfloat(fi,t1,t2) ->
let t1' = eval1 ctx t1 in
TmTimesfloat(fi,t1',t2)
| TmSucc(fi,t1) ->
let t1' = eval1 ctx t1 in
TmSucc(fi, t1')
| TmPred(_,TmZero(_)) ->
TmZero(dummyinfo)
| TmPred(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
nv1
| TmPred(fi,t1) ->
let t1' = eval1 ctx t1 in
TmPred(fi, t1')
| TmIsZero(_,TmZero(_)) ->
TmTrue(dummyinfo)
| TmIsZero(_,TmSucc(_,nv1)) when (isnumericval ctx nv1) ->
TmFalse(dummyinfo)
| TmIsZero(fi,t1) ->
let t1' = eval1 ctx t1 in
TmIsZero(fi, t1')
| _ ->
raise NoRuleApplies
let rec eval ctx t =
try let t' = eval1 ctx t
in eval ctx t'
with NoRuleApplies -> t
let evalbinding ctx b = match b with
TmAbbBind(t,tyT) ->
let t' = eval ctx t in
TmAbbBind(t',tyT)
| bind -> bind
let istyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT) -> true
| _ -> false
let gettyabb ctx i =
match getbinding dummyinfo ctx i with
TyAbbBind(tyT) -> tyT
| _ -> raise NoRuleApplies
let rec computety ctx tyT = match tyT with
TyVar(i,_) when istyabb ctx i -> gettyabb ctx i
| _ -> raise NoRuleApplies
let rec simplifyty ctx tyT =
try
let tyT' = computety ctx tyT in
simplifyty ctx tyT'
with NoRuleApplies -> tyT
let rec tyeqv ctx tyS tyT =
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(tyeqv ctx tyS1 tyT1) && (tyeqv ctx tyS2 tyT2)
| (TyString,TyString) -> true
| (TyTop,TyTop) -> true
| (TyUnit,TyUnit) -> true
| (TyId(b1),TyId(b2)) -> b1=b2
| (TyFloat,TyFloat) -> true
| (TyVar(i,_), _) when istyabb ctx i ->
tyeqv ctx (gettyabb ctx i) tyT
| (_, TyVar(i,_)) when istyabb ctx i ->
tyeqv ctx tyS (gettyabb ctx i)
| (TyVar(i,_),TyVar(j,_)) -> i=j
| (TyBool,TyBool) -> true
| (TyNat,TyNat) -> true
| (TyRecord(fields1),TyRecord(fields2)) ->
List.length fields1 = List.length fields2
&&
List.for_all
(fun (li2,tyTi2) ->
try let (tyTi1) = List.assoc li2 fields1 in
tyeqv ctx tyTi1 tyTi2
with Not_found -> false)
fields2
| _ -> false
let rec subtype ctx tyS tyT =
tyeqv ctx tyS tyT ||
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(_,TyTop) ->
true
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(subtype ctx tyT1 tyS1) && (subtype ctx tyS2 tyT2)
| (TyRecord(fS), TyRecord(fT)) ->
List.for_all
(fun (li,tyTi) ->
try let tySi = List.assoc li fS in
subtype ctx tySi tyTi
with Not_found -> false)
fT
| (_,_) ->
false
let rec join ctx tyS tyT =
if subtype ctx tyS tyT then tyT else
if subtype ctx tyT tyS then tyS else
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyRecord(fS), TyRecord(fT)) ->
let labelsS = List.map (fun (li,_) -> li) fS in
let labelsT = List.map (fun (li,_) -> li) fT in
let commonLabels =
List.find_all (fun l -> List.mem l labelsT) labelsS in
let commonFields =
List.map (fun li ->
let tySi = List.assoc li fS in
let tyTi = List.assoc li fT in
(li, join ctx tySi tyTi))
commonLabels in
TyRecord(commonFields)
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
(try TyArr(meet ctx tyS1 tyT1, join ctx tyS2 tyT2)
with Not_found -> TyTop)
| _ ->
TyTop
and meet ctx tyS tyT =
if subtype ctx tyS tyT then tyS else
if subtype ctx tyT tyS then tyT else
let tyS = simplifyty ctx tyS in
let tyT = simplifyty ctx tyT in
match (tyS,tyT) with
(TyRecord(fS), TyRecord(fT)) ->
let labelsS = List.map (fun (li,_) -> li) fS in
let labelsT = List.map (fun (li,_) -> li) fT in
let allLabels =
List.append
labelsS
(List.find_all
(fun l -> not (List.mem l labelsS)) labelsT) in
let allFields =
List.map (fun li ->
if List.mem li allLabels then
let tySi = List.assoc li fS in
let tyTi = List.assoc li fT in
(li, meet ctx tySi tyTi)
else if List.mem li labelsS then
(li, List.assoc li fS)
else
(li, List.assoc li fT))
allLabels in
TyRecord(allFields)
| (TyArr(tyS1,tyS2),TyArr(tyT1,tyT2)) ->
TyArr(join ctx tyS1 tyT1, meet ctx tyS2 tyT2)
| _ ->
raise Not_found
let rec typeof ctx t =
match t with
TmInert(fi,tyT) ->
tyT
| TmVar(fi,i,_) -> getTypeFromContext fi ctx i
| TmAbs(fi,x,tyT1,t2) ->
let ctx' = addbinding ctx x (VarBind(tyT1)) in
let tyT2 = typeof ctx' t2 in
TyArr(tyT1, typeShift (-1) tyT2)
| TmApp(fi,t1,t2) ->
let tyT1 = typeof ctx t1 in
let tyT2 = typeof ctx t2 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if subtype ctx tyT2 tyT11 then tyT12
else error fi "parameter type mismatch"
| _ -> error fi "arrow type expected")
| TmTrue(fi) ->
TyBool
| TmFalse(fi) ->
TyBool
| TmIf(fi,t1,t2,t3) ->
if subtype ctx (typeof ctx t1) TyBool then
join ctx (typeof ctx t2) (typeof ctx t3)
else error fi "guard of conditional not a boolean"
| TmRecord(fi, fields) ->
let fieldtys =
List.map (fun (li,ti) -> (li, typeof ctx ti)) fields in
TyRecord(fieldtys)
| TmProj(fi, t1, l) ->
(match simplifyty ctx (typeof ctx t1) with
TyRecord(fieldtys) ->
(try List.assoc l fieldtys
with Not_found -> error fi ("label "^l^" not found"))
| _ -> error fi "Expected record type")
| TmLet(fi,x,t1,t2) ->
let tyT1 = typeof ctx t1 in
let ctx' = addbinding ctx x (VarBind(tyT1)) in
typeShift (-1) (typeof ctx' t2)
| TmFix(fi, t1) ->
let tyT1 = typeof ctx t1 in
(match simplifyty ctx tyT1 with
TyArr(tyT11,tyT12) ->
if subtype ctx tyT12 tyT11 then tyT12
else error fi "result of body not compatible with domain"
| _ -> error fi "arrow type expected")
| TmString _ -> TyString
| TmUnit(fi) -> TyUnit
| TmAscribe(fi,t1,tyT) ->
if subtype ctx (typeof ctx t1) tyT then
tyT
else
error fi "body of as-term does not have the expected type"
| TmFloat _ -> TyFloat
| TmTimesfloat(fi,t1,t2) ->
if subtype ctx (typeof ctx t1) TyFloat
&& subtype ctx (typeof ctx t2) TyFloat then TyFloat
else error fi "argument of timesfloat is not a number"
| TmZero(fi) ->
TyNat
| TmSucc(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of succ is not a number"
| TmPred(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyNat
else error fi "argument of pred is not a number"
| TmIsZero(fi,t1) ->
if subtype ctx (typeof ctx t1) TyNat then TyBool
else error fi "argument of iszero is not a number"
|
ad547f23f5cd338147af574ae2394bbedbf2929794c279b8a0915a0dcfe69884 | byorgey/AoC | 05.hs | # LANGUAGE RecordWildCards #
import Control.Arrow
import Data.List
import Data.Maybe
import Numeric
main = interact $
lines >>> map readSeat >>> applyAll [solveA, solveB] >>> map show >>> unlines
type Seat = (Int,Int)
seatID :: Seat -> Int
seatID (r,c) = r * 8 + c
readSeat :: String -> Seat
readSeat = splitAt 7 >>> (readBin "FB" *** readBin "LR")
readBin :: [Char] -> String -> Int
readBin bits = readInt 2 (`elem` bits) (\c -> fromJust (findIndex (==c) bits)) >>> head >>> fst
solveA, solveB :: [Seat] -> Int
solveA = map seatID >>> maximum
solveB = map seatID >>> sort >>> (zip <*> tail) >>>
find (uncurry subtract >>> (==2)) >>> fromJust >>> fst >>> succ
applyAll fs x = map ($x) fs
| null | https://raw.githubusercontent.com/byorgey/AoC/30eb51eb41af9ca86b05de598a3a96d25bd428e3/2020/05/05.hs | haskell | # LANGUAGE RecordWildCards #
import Control.Arrow
import Data.List
import Data.Maybe
import Numeric
main = interact $
lines >>> map readSeat >>> applyAll [solveA, solveB] >>> map show >>> unlines
type Seat = (Int,Int)
seatID :: Seat -> Int
seatID (r,c) = r * 8 + c
readSeat :: String -> Seat
readSeat = splitAt 7 >>> (readBin "FB" *** readBin "LR")
readBin :: [Char] -> String -> Int
readBin bits = readInt 2 (`elem` bits) (\c -> fromJust (findIndex (==c) bits)) >>> head >>> fst
solveA, solveB :: [Seat] -> Int
solveA = map seatID >>> maximum
solveB = map seatID >>> sort >>> (zip <*> tail) >>>
find (uncurry subtract >>> (==2)) >>> fromJust >>> fst >>> succ
applyAll fs x = map ($x) fs
|
|
161b44243d5b1358e7fb1bc9a2417449431e6b3761ae0605e4e3c18ab99aad42 | mstksg/inCode | Entry.hs | {-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Blog.View.Entry where
import Blog.Types
import Blog.Util
import Blog.Util.Tag
import Blog.View
import Blog.View.Social
import Control.Monad
import Data.List
import Data.Maybe
import Data.String
import System.FilePath
import Text.Blaze.Html5 ((!))
import qualified Data.Text as T
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.Pandoc.Definition as P
data EntryInfo = EI
{ eiEntry :: !Entry
, eiTags :: ![Tag]
, eiPrevEntry :: !(Maybe Entry)
, eiNextEntry :: !(Maybe Entry)
, eiSignoff :: !P.Pandoc
}
deriving (Show)
viewEntry
:: (?config :: Config)
=> EntryInfo
-> H.Html
viewEntry EI{..} = H.div ! A.class_ "entry-section unit span-grid" ! mainSection $ do
H.article ! A.class_ "tile article" $ do
H.header $ do
unless isPosted $
H.div ! A.class_ "unposted-banner" $
"Unposted entry"
H.h1 ! A.id "title" $
H.toHtml $ entryTitle eiEntry
H.p ! A.class_ "entry-info" $ do
"by " :: H.Html
H.a ! A.class_ "author" ! A.href (H.textValue aboutUrl) $
H.toHtml $ authorName (confAuthorInfo ?config)
forM_ (entryPostTime eiEntry) $ \t -> do
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
H.time
! A.datetime (H.textValue (T.pack (renderDatetimeTime t)))
! A.pubdate ""
! A.class_ "pubdate"
$ H.toHtml (renderFriendlyTime t)
H.p $ do
H.span ! A.class_ "source-info" $ do
forM_ (renderSourceUrl (T.pack (entrySourceFile eiEntry))) $ \u -> do
H.a
! A.class_ "source-link"
! A.href (H.textValue u)
$ "Source"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
let entryMd = entryCanonical eiEntry -<.> "md"
defMdLink = renderRenderUrl $ T.pack entryMd
altMdLink = fromString $ renderUrl' entryMd
H.a
! A.class_ "source-link"
! A.href (maybe altMdLink H.textValue defMdLink)
$ "Markdown"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text) -- shining bright like a diams ~
H.a
! A.class_ "source-link"
! A.href (fromString (renderUrl' (entryCanonical eiEntry -<.> "tex")))
$ "LaTeX"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
"Posted in " :: H.Html
categoryList (filterTags CategoryTag eiTags)
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
H.a ! A.class_ "comment-link" ! A.href "#disqus_thread" $ "Comments"
H.hr
H.aside ! A.class_ "contents-container" $ do
H.h5 ! A.id "contents-header" $
"Contents"
H.div ! A.id "toc" $ mempty
H.div ! A.class_ "main-content copy-content" $
copyToHtml (entryContents eiEntry)
H.footer $ do
unless (entryNoSignoff eiEntry) $ do
H.hr
copySection Nothing (copyToHtml eiSignoff)
H.ul ! A.class_ "entry-series" $
mapM_ seriesLi (filterTags SeriesTag eiTags)
H.ul ! A.class_ "tag-list" $
mapM_ tagLi eiTags
viewSocialShare
nextPrevUrl eiPrevEntry eiNextEntry
H.div ! A.class_ "post-entry" $
H.div ! A.class_ "tile" $ do
H.div ! A.id "disqus_thread" $ mempty
H.script ! A.type_ "text/javascript" $
H.toHtml $
T.unlines
[ "var disqus_config = function () {"
, " this.page.url = '" <> renderUrl (T.pack $ entryCanonical eiEntry) <> "';"
, flip foldMap (entryIdentifier eiEntry) $ \i ->
" this.page.identifier = '" <> i <> "';"
, "};"
, "(function() {"
, " var d = document, s = d.createElement('script');"
, " s.src = '//" <> devDisqus (confDeveloperAPIs ?config) <> ".disqus.com/embed.js';"
, " s.setAttribute('data-timestamp', +new Date());"
, " (d.head || d.body).appendChild(s);"
, "})();"
]
H.noscript $ do
"Please enable JavaScript to view the " :: H.Html
H.a ! A.href "" $
"comments powered by Disqus." :: H.Html
H.br
H.a ! A.href "" ! A.class_ "dsq-brlink" $ do
"Comments powered by " :: H.Html
H.span ! A.class_ "logo-disqus" $
"Disqus" :: H.Html
where
aboutUrl = renderUrl "/"
isPosted = maybe False ( < = eiNow ) ( entryPostTime eiEntry )
isPosted = isJust $ entryPostTime eiEntry
nextPrevUrl
:: (?config :: Config)
=> Maybe Entry
-> Maybe Entry
-> H.Html
nextPrevUrl prevEntry nextEntry =
H.nav ! A.class_ "next-prev-links" $
H.ul $ do
forM_ prevEntry $ \Entry{..} ->
H.li ! A.class_ "prev-entry-link" $ do
H.preEscapedToHtml ("← " :: T.Text)
H.a ! A.href (fromString (renderUrl' entryCanonical)) $
H.toHtml entryTitle
" (Previous)" :: H.Html
forM_ nextEntry $ \Entry{..} ->
H.li ! A.class_ "next-entry-link" $ do
"(Next) " :: H.Html
H.a ! A.href (fromString (renderUrl' entryCanonical)) $
H.toHtml entryTitle
H.preEscapedToHtml (" →" :: T.Text)
categoryList
:: (?config :: Config)
=> [Tag]
-> H.Html
categoryList = sequence_
. intersperse ", "
. map (tagLink (T.unpack . tagLabel))
seriesLi
:: (?config :: Config)
=> Tag
-> H.Html
seriesLi t = H.li $
H.div $ do
"This entry is a part of a series called " :: H.Html
H.b $
H.toHtml $ "\"" <> tagLabel t <> "\""
". Find the rest of the entries in this series at its " :: H.Html
tagLink (const " series history") t
"." :: H.Html
| null | https://raw.githubusercontent.com/mstksg/inCode/e1f80a3dfd83eaa2b817dc922fd7f331cd1ece8a/src/Blog/View/Entry.hs | haskell | # LANGUAGE ImplicitParams #
# LANGUAGE OverloadedStrings #
shining bright like a diams ~ | # LANGUAGE RecordWildCards #
module Blog.View.Entry where
import Blog.Types
import Blog.Util
import Blog.Util.Tag
import Blog.View
import Blog.View.Social
import Control.Monad
import Data.List
import Data.Maybe
import Data.String
import System.FilePath
import Text.Blaze.Html5 ((!))
import qualified Data.Text as T
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.Pandoc.Definition as P
data EntryInfo = EI
{ eiEntry :: !Entry
, eiTags :: ![Tag]
, eiPrevEntry :: !(Maybe Entry)
, eiNextEntry :: !(Maybe Entry)
, eiSignoff :: !P.Pandoc
}
deriving (Show)
viewEntry
:: (?config :: Config)
=> EntryInfo
-> H.Html
viewEntry EI{..} = H.div ! A.class_ "entry-section unit span-grid" ! mainSection $ do
H.article ! A.class_ "tile article" $ do
H.header $ do
unless isPosted $
H.div ! A.class_ "unposted-banner" $
"Unposted entry"
H.h1 ! A.id "title" $
H.toHtml $ entryTitle eiEntry
H.p ! A.class_ "entry-info" $ do
"by " :: H.Html
H.a ! A.class_ "author" ! A.href (H.textValue aboutUrl) $
H.toHtml $ authorName (confAuthorInfo ?config)
forM_ (entryPostTime eiEntry) $ \t -> do
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
H.time
! A.datetime (H.textValue (T.pack (renderDatetimeTime t)))
! A.pubdate ""
! A.class_ "pubdate"
$ H.toHtml (renderFriendlyTime t)
H.p $ do
H.span ! A.class_ "source-info" $ do
forM_ (renderSourceUrl (T.pack (entrySourceFile eiEntry))) $ \u -> do
H.a
! A.class_ "source-link"
! A.href (H.textValue u)
$ "Source"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
let entryMd = entryCanonical eiEntry -<.> "md"
defMdLink = renderRenderUrl $ T.pack entryMd
altMdLink = fromString $ renderUrl' entryMd
H.a
! A.class_ "source-link"
! A.href (maybe altMdLink H.textValue defMdLink)
$ "Markdown"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
H.a
! A.class_ "source-link"
! A.href (fromString (renderUrl' (entryCanonical eiEntry -<.> "tex")))
$ "LaTeX"
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
"Posted in " :: H.Html
categoryList (filterTags CategoryTag eiTags)
H.span ! A.class_ "info-separator" $
H.preEscapedToHtml
(" ♦ " :: T.Text)
H.a ! A.class_ "comment-link" ! A.href "#disqus_thread" $ "Comments"
H.hr
H.aside ! A.class_ "contents-container" $ do
H.h5 ! A.id "contents-header" $
"Contents"
H.div ! A.id "toc" $ mempty
H.div ! A.class_ "main-content copy-content" $
copyToHtml (entryContents eiEntry)
H.footer $ do
unless (entryNoSignoff eiEntry) $ do
H.hr
copySection Nothing (copyToHtml eiSignoff)
H.ul ! A.class_ "entry-series" $
mapM_ seriesLi (filterTags SeriesTag eiTags)
H.ul ! A.class_ "tag-list" $
mapM_ tagLi eiTags
viewSocialShare
nextPrevUrl eiPrevEntry eiNextEntry
H.div ! A.class_ "post-entry" $
H.div ! A.class_ "tile" $ do
H.div ! A.id "disqus_thread" $ mempty
H.script ! A.type_ "text/javascript" $
H.toHtml $
T.unlines
[ "var disqus_config = function () {"
, " this.page.url = '" <> renderUrl (T.pack $ entryCanonical eiEntry) <> "';"
, flip foldMap (entryIdentifier eiEntry) $ \i ->
" this.page.identifier = '" <> i <> "';"
, "};"
, "(function() {"
, " var d = document, s = d.createElement('script');"
, " s.src = '//" <> devDisqus (confDeveloperAPIs ?config) <> ".disqus.com/embed.js';"
, " s.setAttribute('data-timestamp', +new Date());"
, " (d.head || d.body).appendChild(s);"
, "})();"
]
H.noscript $ do
"Please enable JavaScript to view the " :: H.Html
H.a ! A.href "" $
"comments powered by Disqus." :: H.Html
H.br
H.a ! A.href "" ! A.class_ "dsq-brlink" $ do
"Comments powered by " :: H.Html
H.span ! A.class_ "logo-disqus" $
"Disqus" :: H.Html
where
aboutUrl = renderUrl "/"
isPosted = maybe False ( < = eiNow ) ( entryPostTime eiEntry )
isPosted = isJust $ entryPostTime eiEntry
nextPrevUrl
:: (?config :: Config)
=> Maybe Entry
-> Maybe Entry
-> H.Html
nextPrevUrl prevEntry nextEntry =
H.nav ! A.class_ "next-prev-links" $
H.ul $ do
forM_ prevEntry $ \Entry{..} ->
H.li ! A.class_ "prev-entry-link" $ do
H.preEscapedToHtml ("← " :: T.Text)
H.a ! A.href (fromString (renderUrl' entryCanonical)) $
H.toHtml entryTitle
" (Previous)" :: H.Html
forM_ nextEntry $ \Entry{..} ->
H.li ! A.class_ "next-entry-link" $ do
"(Next) " :: H.Html
H.a ! A.href (fromString (renderUrl' entryCanonical)) $
H.toHtml entryTitle
H.preEscapedToHtml (" →" :: T.Text)
categoryList
:: (?config :: Config)
=> [Tag]
-> H.Html
categoryList = sequence_
. intersperse ", "
. map (tagLink (T.unpack . tagLabel))
seriesLi
:: (?config :: Config)
=> Tag
-> H.Html
seriesLi t = H.li $
H.div $ do
"This entry is a part of a series called " :: H.Html
H.b $
H.toHtml $ "\"" <> tagLabel t <> "\""
". Find the rest of the entries in this series at its " :: H.Html
tagLink (const " series history") t
"." :: H.Html
|
a4581cc756d4b9ba41fd359f96a01d940cc1bee42a065965d7d91d1df63f26cc | DerekCuevas/interview-cake-clj | core.clj | (ns find-in-ordered-set.core
(:gen-class))
(def ^:private gt? (comp pos? compare))
(def ^:private eq? (comp zero? compare))
(defn- midpoint [start end]
(-> (- end start)
(/ 2)
int
(+ start)))
(defn binary-search
"O(lgn) - returns index of item in sorted vector, -1 if not found."
[arr item]
(loop [start 0
end (count arr)]
(let [mid (midpoint start end)
mid-item (get arr mid)]
(cond
(eq? mid-item item) mid
(<= (- end start) 1) -1
(gt? mid-item item) (recur start mid)
:else (recur mid end)))))
| null | https://raw.githubusercontent.com/DerekCuevas/interview-cake-clj/f17d3239bb30bcc17ced473f055a9859f9d1fb8d/find-in-ordered-set/src/find_in_ordered_set/core.clj | clojure | (ns find-in-ordered-set.core
(:gen-class))
(def ^:private gt? (comp pos? compare))
(def ^:private eq? (comp zero? compare))
(defn- midpoint [start end]
(-> (- end start)
(/ 2)
int
(+ start)))
(defn binary-search
"O(lgn) - returns index of item in sorted vector, -1 if not found."
[arr item]
(loop [start 0
end (count arr)]
(let [mid (midpoint start end)
mid-item (get arr mid)]
(cond
(eq? mid-item item) mid
(<= (- end start) 1) -1
(gt? mid-item item) (recur start mid)
:else (recur mid end)))))
|
|
a49d4adcf55ab612df4786d1e5f93524481d0918e19b6df8ef183dafe693eab6 | brendanhay/amazonka | RegexPatternSetReferenceStatement.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
-- Module : Amazonka.WAFV2.Types.RegexPatternSetReferenceStatement
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Amazonka.WAFV2.Types.RegexPatternSetReferenceStatement where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import Amazonka.WAFV2.Types.FieldToMatch
import Amazonka.WAFV2.Types.TextTransformation
-- | A rule statement used to search web request components for matches with
-- regular expressions. To use this, create a RegexPatternSet that
specifies the expressions that you want to detect , then use the ARN of
-- that set in this statement. A web request matches the pattern set rule
-- statement if the request component matches any of the patterns in the
set . To create a regex pattern set , see CreateRegexPatternSet .
--
-- Each regex pattern set rule statement references a regex pattern set.
-- You create and maintain the set independent of your rules. This allows
-- you to use the single set in multiple rules. When you update the
referenced set , WAF automatically updates all rules that reference it .
--
-- /See:/ 'newRegexPatternSetReferenceStatement' smart constructor.
data RegexPatternSetReferenceStatement = RegexPatternSetReferenceStatement'
| The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
-- statement references.
arn :: Prelude.Text,
| The part of the web request that you want WAF to inspect .
fieldToMatch :: FieldToMatch,
-- | Text transformations eliminate some of the unusual formatting that
-- attackers use in web requests in an effort to bypass detection. If you
specify one or more transformations in a rule statement , WAF performs
-- all transformations on the content of the request component identified
-- by @FieldToMatch@, starting from the lowest priority setting, before
-- inspecting the content for a match.
textTransformations :: Prelude.NonEmpty TextTransformation
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'RegexPatternSetReferenceStatement' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' arn ' , ' regexPatternSetReferenceStatement_arn ' - The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
-- statement references.
--
' fieldToMatch ' , ' regexPatternSetReferenceStatement_fieldToMatch ' - The part of the web request that you want WAF to inspect .
--
-- 'textTransformations', 'regexPatternSetReferenceStatement_textTransformations' - Text transformations eliminate some of the unusual formatting that
-- attackers use in web requests in an effort to bypass detection. If you
specify one or more transformations in a rule statement , WAF performs
-- all transformations on the content of the request component identified
-- by @FieldToMatch@, starting from the lowest priority setting, before
-- inspecting the content for a match.
newRegexPatternSetReferenceStatement ::
-- | 'arn'
Prelude.Text ->
-- | 'fieldToMatch'
FieldToMatch ->
| ' '
Prelude.NonEmpty TextTransformation ->
RegexPatternSetReferenceStatement
newRegexPatternSetReferenceStatement
pARN_
pFieldToMatch_
pTextTransformations_ =
RegexPatternSetReferenceStatement'
{ arn = pARN_,
fieldToMatch = pFieldToMatch_,
textTransformations =
Lens.coerced
Lens.# pTextTransformations_
}
| The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
-- statement references.
regexPatternSetReferenceStatement_arn :: Lens.Lens' RegexPatternSetReferenceStatement Prelude.Text
regexPatternSetReferenceStatement_arn = Lens.lens (\RegexPatternSetReferenceStatement' {arn} -> arn) (\s@RegexPatternSetReferenceStatement' {} a -> s {arn = a} :: RegexPatternSetReferenceStatement)
| The part of the web request that you want WAF to inspect .
regexPatternSetReferenceStatement_fieldToMatch :: Lens.Lens' RegexPatternSetReferenceStatement FieldToMatch
regexPatternSetReferenceStatement_fieldToMatch = Lens.lens (\RegexPatternSetReferenceStatement' {fieldToMatch} -> fieldToMatch) (\s@RegexPatternSetReferenceStatement' {} a -> s {fieldToMatch = a} :: RegexPatternSetReferenceStatement)
-- | Text transformations eliminate some of the unusual formatting that
-- attackers use in web requests in an effort to bypass detection. If you
specify one or more transformations in a rule statement , WAF performs
-- all transformations on the content of the request component identified
-- by @FieldToMatch@, starting from the lowest priority setting, before
-- inspecting the content for a match.
regexPatternSetReferenceStatement_textTransformations :: Lens.Lens' RegexPatternSetReferenceStatement (Prelude.NonEmpty TextTransformation)
regexPatternSetReferenceStatement_textTransformations = Lens.lens (\RegexPatternSetReferenceStatement' {textTransformations} -> textTransformations) (\s@RegexPatternSetReferenceStatement' {} a -> s {textTransformations = a} :: RegexPatternSetReferenceStatement) Prelude.. Lens.coerced
instance
Data.FromJSON
RegexPatternSetReferenceStatement
where
parseJSON =
Data.withObject
"RegexPatternSetReferenceStatement"
( \x ->
RegexPatternSetReferenceStatement'
Prelude.<$> (x Data..: "ARN")
Prelude.<*> (x Data..: "FieldToMatch")
Prelude.<*> (x Data..: "TextTransformations")
)
instance
Prelude.Hashable
RegexPatternSetReferenceStatement
where
hashWithSalt
_salt
RegexPatternSetReferenceStatement' {..} =
_salt `Prelude.hashWithSalt` arn
`Prelude.hashWithSalt` fieldToMatch
`Prelude.hashWithSalt` textTransformations
instance
Prelude.NFData
RegexPatternSetReferenceStatement
where
rnf RegexPatternSetReferenceStatement' {..} =
Prelude.rnf arn
`Prelude.seq` Prelude.rnf fieldToMatch
`Prelude.seq` Prelude.rnf textTransformations
instance
Data.ToJSON
RegexPatternSetReferenceStatement
where
toJSON RegexPatternSetReferenceStatement' {..} =
Data.object
( Prelude.catMaybes
[ Prelude.Just ("ARN" Data..= arn),
Prelude.Just ("FieldToMatch" Data..= fieldToMatch),
Prelude.Just
("TextTransformations" Data..= textTransformations)
]
)
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-wafv2/gen/Amazonka/WAFV2/Types/RegexPatternSetReferenceStatement.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Module : Amazonka.WAFV2.Types.RegexPatternSetReferenceStatement
Stability : auto-generated
| A rule statement used to search web request components for matches with
regular expressions. To use this, create a RegexPatternSet that
that set in this statement. A web request matches the pattern set rule
statement if the request component matches any of the patterns in the
Each regex pattern set rule statement references a regex pattern set.
You create and maintain the set independent of your rules. This allows
you to use the single set in multiple rules. When you update the
/See:/ 'newRegexPatternSetReferenceStatement' smart constructor.
statement references.
| Text transformations eliminate some of the unusual formatting that
attackers use in web requests in an effort to bypass detection. If you
all transformations on the content of the request component identified
by @FieldToMatch@, starting from the lowest priority setting, before
inspecting the content for a match.
|
Create a value of 'RegexPatternSetReferenceStatement' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
statement references.
'textTransformations', 'regexPatternSetReferenceStatement_textTransformations' - Text transformations eliminate some of the unusual formatting that
attackers use in web requests in an effort to bypass detection. If you
all transformations on the content of the request component identified
by @FieldToMatch@, starting from the lowest priority setting, before
inspecting the content for a match.
| 'arn'
| 'fieldToMatch'
statement references.
| Text transformations eliminate some of the unusual formatting that
attackers use in web requests in an effort to bypass detection. If you
all transformations on the content of the request component identified
by @FieldToMatch@, starting from the lowest priority setting, before
inspecting the content for a match. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Amazonka.WAFV2.Types.RegexPatternSetReferenceStatement where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import Amazonka.WAFV2.Types.FieldToMatch
import Amazonka.WAFV2.Types.TextTransformation
specifies the expressions that you want to detect , then use the ARN of
set . To create a regex pattern set , see CreateRegexPatternSet .
referenced set , WAF automatically updates all rules that reference it .
data RegexPatternSetReferenceStatement = RegexPatternSetReferenceStatement'
| The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
arn :: Prelude.Text,
| The part of the web request that you want WAF to inspect .
fieldToMatch :: FieldToMatch,
specify one or more transformations in a rule statement , WAF performs
textTransformations :: Prelude.NonEmpty TextTransformation
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' arn ' , ' regexPatternSetReferenceStatement_arn ' - The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
' fieldToMatch ' , ' regexPatternSetReferenceStatement_fieldToMatch ' - The part of the web request that you want WAF to inspect .
specify one or more transformations in a rule statement , WAF performs
newRegexPatternSetReferenceStatement ::
Prelude.Text ->
FieldToMatch ->
| ' '
Prelude.NonEmpty TextTransformation ->
RegexPatternSetReferenceStatement
newRegexPatternSetReferenceStatement
pARN_
pFieldToMatch_
pTextTransformations_ =
RegexPatternSetReferenceStatement'
{ arn = pARN_,
fieldToMatch = pFieldToMatch_,
textTransformations =
Lens.coerced
Lens.# pTextTransformations_
}
| The Amazon Resource Name ( ARN ) of the RegexPatternSet that this
regexPatternSetReferenceStatement_arn :: Lens.Lens' RegexPatternSetReferenceStatement Prelude.Text
regexPatternSetReferenceStatement_arn = Lens.lens (\RegexPatternSetReferenceStatement' {arn} -> arn) (\s@RegexPatternSetReferenceStatement' {} a -> s {arn = a} :: RegexPatternSetReferenceStatement)
| The part of the web request that you want WAF to inspect .
regexPatternSetReferenceStatement_fieldToMatch :: Lens.Lens' RegexPatternSetReferenceStatement FieldToMatch
regexPatternSetReferenceStatement_fieldToMatch = Lens.lens (\RegexPatternSetReferenceStatement' {fieldToMatch} -> fieldToMatch) (\s@RegexPatternSetReferenceStatement' {} a -> s {fieldToMatch = a} :: RegexPatternSetReferenceStatement)
specify one or more transformations in a rule statement , WAF performs
regexPatternSetReferenceStatement_textTransformations :: Lens.Lens' RegexPatternSetReferenceStatement (Prelude.NonEmpty TextTransformation)
regexPatternSetReferenceStatement_textTransformations = Lens.lens (\RegexPatternSetReferenceStatement' {textTransformations} -> textTransformations) (\s@RegexPatternSetReferenceStatement' {} a -> s {textTransformations = a} :: RegexPatternSetReferenceStatement) Prelude.. Lens.coerced
instance
Data.FromJSON
RegexPatternSetReferenceStatement
where
parseJSON =
Data.withObject
"RegexPatternSetReferenceStatement"
( \x ->
RegexPatternSetReferenceStatement'
Prelude.<$> (x Data..: "ARN")
Prelude.<*> (x Data..: "FieldToMatch")
Prelude.<*> (x Data..: "TextTransformations")
)
instance
Prelude.Hashable
RegexPatternSetReferenceStatement
where
hashWithSalt
_salt
RegexPatternSetReferenceStatement' {..} =
_salt `Prelude.hashWithSalt` arn
`Prelude.hashWithSalt` fieldToMatch
`Prelude.hashWithSalt` textTransformations
instance
Prelude.NFData
RegexPatternSetReferenceStatement
where
rnf RegexPatternSetReferenceStatement' {..} =
Prelude.rnf arn
`Prelude.seq` Prelude.rnf fieldToMatch
`Prelude.seq` Prelude.rnf textTransformations
instance
Data.ToJSON
RegexPatternSetReferenceStatement
where
toJSON RegexPatternSetReferenceStatement' {..} =
Data.object
( Prelude.catMaybes
[ Prelude.Just ("ARN" Data..= arn),
Prelude.Just ("FieldToMatch" Data..= fieldToMatch),
Prelude.Just
("TextTransformations" Data..= textTransformations)
]
)
|
512908b3ebeb0604781652d1ba08c7b6a3c31807f630fb14e3d2fb60db126051 | vonzhou/LearnYouHaskellForGreatGood | myaction2.hs |
main = do
a <- (++) <$> getLine <*> getLine
putStrLn $ "The two lines concatenated turned out to be:" ++ a
| null | https://raw.githubusercontent.com/vonzhou/LearnYouHaskellForGreatGood/439d848deac53ef6da6df433078b7f1dcf54d18d/chapter11/myaction2.hs | haskell |
main = do
a <- (++) <$> getLine <*> getLine
putStrLn $ "The two lines concatenated turned out to be:" ++ a
|
|
00f79c1769f8b448e0ec3156fc6ecb11e66ac223270d9145b94776f2d339cb60 | kupl/FixML | sub69.ml |
type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff : aexp * string -> aexp
= fun (exp, var) -> match exp with
Const c -> Const 0
| Var s -> if s = var then Const 1 else Const 0
| Power (s, n) -> begin
if s <> var then Const 0
else match n with
1 -> Times [Const 1]
| _ -> Times [Const n; Power (s, n-1)]
end
| Times l -> begin
match l with
| hd::tl -> Sum [Times (diff (hd, var)::tl); Times [hd; diff (Times tl, var)]]
end | null | https://raw.githubusercontent.com/kupl/FixML/0a032a733d68cd8ccc8b1034d2908cd43b241fce/benchmarks/differentiate/diff1/submissions/sub69.ml | ocaml |
type aexp =
| Const of int
| Var of string
| Power of string * int
| Times of aexp list
| Sum of aexp list
let rec diff : aexp * string -> aexp
= fun (exp, var) -> match exp with
Const c -> Const 0
| Var s -> if s = var then Const 1 else Const 0
| Power (s, n) -> begin
if s <> var then Const 0
else match n with
1 -> Times [Const 1]
| _ -> Times [Const n; Power (s, n-1)]
end
| Times l -> begin
match l with
| hd::tl -> Sum [Times (diff (hd, var)::tl); Times [hd; diff (Times tl, var)]]
end |
|
db8d940e00833301bae31f9851e799af51a4ef7c0d84e83206e0c14b0ae97d2e | karimarttila/clojure | state.cljs | (ns simplefrontend.state
(:require [re-frame.core :as re-frame]))
;; Subscriptions
(re-frame/reg-sub
::current-route
(fn [db]
(:current-route db)))
(re-frame/reg-sub
::jwt
(fn [db]
(:jwt db)))
(re-frame/reg-sub
::debug
(fn [db]
(:debug db)))
| null | https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/webstore-demo/re-frame-demo/src/cljs/simplefrontend/state.cljs | clojure | Subscriptions | (ns simplefrontend.state
(:require [re-frame.core :as re-frame]))
(re-frame/reg-sub
::current-route
(fn [db]
(:current-route db)))
(re-frame/reg-sub
::jwt
(fn [db]
(:jwt db)))
(re-frame/reg-sub
::debug
(fn [db]
(:debug db)))
|
f0033215d5300cf8d3d51766679913aa5af23b733226ea5712b466acff51f336 | ont-app/igraph-vocabulary | macros.clj | (ns ont-app.igraph-vocabulary.macros
(:require
[ont-app.igraph.core :as igraph :refer [normal-form]]
[ont-app.igraph-vocabulary.io :as ig-io]
)
)
(defmacro graph-source
"Returns the contents of `edn-source` read in with updated ns metadata.
NOTE: typical usage is to embed contents of an ontology into clj(c/s) code."
[edn-source]
(normal-form (ig-io/read-graph-from-source edn-source)))
| null | https://raw.githubusercontent.com/ont-app/igraph-vocabulary/e044ae713318b9ad0820dd1e1f782abb746beb08/src/ont_app/igraph_vocabulary/macros.clj | clojure | (ns ont-app.igraph-vocabulary.macros
(:require
[ont-app.igraph.core :as igraph :refer [normal-form]]
[ont-app.igraph-vocabulary.io :as ig-io]
)
)
(defmacro graph-source
"Returns the contents of `edn-source` read in with updated ns metadata.
NOTE: typical usage is to embed contents of an ontology into clj(c/s) code."
[edn-source]
(normal-form (ig-io/read-graph-from-source edn-source)))
|
|
c51203047b1095720a6201d4fac1da7bd80d3b186f5cb4f1b7dde03cc1f0393a | jaredponn/Fly-Plane-Fly | Buttons.hs | {-# LANGUAGE BangPatterns #-}
module Buttons where
import Control.Monad.State.Lazy
import Control.Monad.Reader
import Linear.V2
import SDL
import Aabb
import GuiTransforms
import GameVars
data ButtonAttr = ButtonAttr { rect :: {-# UNPACK #-} !(Rectangle Float)
, aabb :: {-# UNPACK #-} !Aabb
, texture :: Texture}
type Button m = ReaderT (ButtonAttr) m ()
-- buttonEffectFromMouse takes an action and the current input and will apply that function if the mouse is over the button and clicking it
buttonEffectFromMouse :: Monad m => m () -- action to modify the game
-> Input -- current input of the game
-> Button m
buttonEffectFromMouse f input = do
let mousepos = (\(V2 a b) -> (SDL.P (V2 (fromIntegral a) (fromIntegral b)))) . _mousePos $ input
mousepress = _mousePress input
btnattr <- ask
if pointHitTest mousepos (aabb btnattr) && mousepress
then lift f
else return ()
{- FUNCTIONS TO CREATE BUTTONS -}
createButtonAttrFromAabb :: Aabb -> Texture -> ButtonAttr
createButtonAttrFromAabb !naabb !ntexture = ButtonAttr { rect = aabbToRectangle naabb
, aabb = naabb
, texture = ntexture}
createButtonAttrFromRectangle :: Rectangle Float -> Texture -> ButtonAttr
createButtonAttrFromRectangle !nrect !ntexture = ButtonAttr { rect = nrect
, aabb = rectangleToAabb nrect
, texture = ntexture}
createCenteredButtonAttr :: (GuiTransforms m) => V2 Float -- lengths. Width, height
-> Texture
-> m ButtonAttr
createCenteredButtonAttr !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 0)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
yCenterButtonAttr >=> xCenterButtonAttr $ tmpbtnattr
createXCenteredButtonAttr :: (GuiTransforms m) => Float -- y position
-> V2 Float -- lengths. Width, height
-> Texture
-> m ButtonAttr
createXCenteredButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
xCenterButtonAttr tmpbtnattr
createLeftEdgeAlignedButtonAttr :: (GuiTransforms m) => Float -- y position
-> V2 Float -- lengths. Width, height
-> Texture
-> m ButtonAttr
createLeftEdgeAlignedButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
alignToLeftEdgeButtonAttr tmpbtnattr
createRightEdgeAlignedButtonAttr :: (GuiTransforms m) => Float -- y position
-> V2 Float -- lengths. Width, height
-> Texture
-> m ButtonAttr
createRightEdgeAlignedButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
alignToRightEdgeButtonAttr tmpbtnattr
{- TRANSFORMS TO BUTTON ATTRIBUTES -}
xCenterButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
xCenterButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- xCenterRectangle rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle' }
yCenterButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
yCenterButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- yCenterRectangle rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToLeftEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToLeftEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToLeftEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToRightEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToRightEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToRightEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToBottomEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToBottomEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToBottomEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
translateButtonAttr :: V2 Float -> ButtonAttr -> ButtonAttr
translateButtonAttr !ntranslation !btnattr = let nrect = GuiTransforms.translate ntranslation $ rect btnattr
in btnattr { rect = nrect
, aabb = rectangleToAabb nrect}
| null | https://raw.githubusercontent.com/jaredponn/Fly-Plane-Fly/8e250f29216f2f75dac2dd0235a2b0243d601620/src/Buttons.hs | haskell | # LANGUAGE BangPatterns #
# UNPACK #
# UNPACK #
buttonEffectFromMouse takes an action and the current input and will apply that function if the mouse is over the button and clicking it
action to modify the game
current input of the game
FUNCTIONS TO CREATE BUTTONS
lengths. Width, height
y position
lengths. Width, height
y position
lengths. Width, height
y position
lengths. Width, height
TRANSFORMS TO BUTTON ATTRIBUTES | module Buttons where
import Control.Monad.State.Lazy
import Control.Monad.Reader
import Linear.V2
import SDL
import Aabb
import GuiTransforms
import GameVars
, texture :: Texture}
type Button m = ReaderT (ButtonAttr) m ()
-> Button m
buttonEffectFromMouse f input = do
let mousepos = (\(V2 a b) -> (SDL.P (V2 (fromIntegral a) (fromIntegral b)))) . _mousePos $ input
mousepress = _mousePress input
btnattr <- ask
if pointHitTest mousepos (aabb btnattr) && mousepress
then lift f
else return ()
createButtonAttrFromAabb :: Aabb -> Texture -> ButtonAttr
createButtonAttrFromAabb !naabb !ntexture = ButtonAttr { rect = aabbToRectangle naabb
, aabb = naabb
, texture = ntexture}
createButtonAttrFromRectangle :: Rectangle Float -> Texture -> ButtonAttr
createButtonAttrFromRectangle !nrect !ntexture = ButtonAttr { rect = nrect
, aabb = rectangleToAabb nrect
, texture = ntexture}
-> Texture
-> m ButtonAttr
createCenteredButtonAttr !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 0)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
yCenterButtonAttr >=> xCenterButtonAttr $ tmpbtnattr
-> Texture
-> m ButtonAttr
createXCenteredButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
xCenterButtonAttr tmpbtnattr
-> Texture
-> m ButtonAttr
createLeftEdgeAlignedButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
alignToLeftEdgeButtonAttr tmpbtnattr
-> Texture
-> m ButtonAttr
createRightEdgeAlignedButtonAttr !ypos !lengths !ntexture = do
let tmpbtnattr = ButtonAttr { rect = Rectangle (P (V2 0 ypos)) lengths
, aabb = Aabb (P (V2 0 0)) (P (V2 0 0))
, texture = ntexture}
alignToRightEdgeButtonAttr tmpbtnattr
xCenterButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
xCenterButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- xCenterRectangle rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle' }
yCenterButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
yCenterButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- yCenterRectangle rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToLeftEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToLeftEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToLeftEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToRightEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToRightEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToRightEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
alignToBottomEdgeButtonAttr :: (GuiTransforms m ) => ButtonAttr -> m ButtonAttr
alignToBottomEdgeButtonAttr !btnattr = do
let rectangle = rect btnattr
rectangle' <- alignToBottomEdge rectangle
return btnattr { rect = rectangle'
, aabb = rectangleToAabb rectangle'}
translateButtonAttr :: V2 Float -> ButtonAttr -> ButtonAttr
translateButtonAttr !ntranslation !btnattr = let nrect = GuiTransforms.translate ntranslation $ rect btnattr
in btnattr { rect = nrect
, aabb = rectangleToAabb nrect}
|
accd8f9625dfdeea377fa566b705d305ccfa88208648e1e9ac9c9ad40f8c649b | vraid/earthgen | util.rkt | #lang racket
(require "util/vector-util.rkt")
(provide (all-from-out
"util/vector-util.rkt"))
| null | https://raw.githubusercontent.com/vraid/earthgen/208ac834c02208ddc16a31aa9e7ff7f91c18e046/package/vraid/util.rkt | racket | #lang racket
(require "util/vector-util.rkt")
(provide (all-from-out
"util/vector-util.rkt"))
|
|
eaa5580d3025cc9515209211409bf6026bb1ab313232e7069b3142edbe1e6a2c | dinosaure/overlap | test_runes.ml | #!/usr/bin/env ocaml
#use "topfind" ;;
#require "astring" ;;
#require "fpath" ;;
#require "bos" ;;
open Rresult
let is_opt x = String.length x > 1 && x.[0] = '-'
let parse_opt_arg x =
let l = String.length x in
if x.[1] <> '-'
then
if l = 2 then x, None
else String.sub x 0 2, Some (String.sub x 2 (l - 2))
else
try
let i = String.index x '=' in
String.sub x 0 i, Some (String.sub x (i + 1) (l - i - 1))
with Not_found -> x, None
type arg =
| Path of Fpath.t
| Library of [ `Abs of Fpath.t | `Rel of Fpath.t | `Name of string ]
let parse_lL_value name value = match name with
| "-L" ->
( match Fpath.of_string value with
| Ok v when Fpath.is_dir_path v && Sys.is_directory value -> R.ok (Path v)
| Ok v when Sys.is_directory value -> R.ok (Path (Fpath.to_dir_path v))
| Ok v -> R.error_msgf "Directory <%a> does not exist" Fpath.pp v
| Error err -> Error err )
| "-l" ->
( match Astring.String.cut ~sep:":" value with
| Some ("", path) ->
( match Fpath.of_string path with
| Ok v when Fpath.is_abs v && Sys.file_exists path -> Ok (Library (`Abs v))
| Ok v when Fpath.is_rel v -> Ok (Library (`Rel v))
| Ok v -> R.error_msgf "Library <%a> does not exist" Fpath.pp v
| Error err -> Error err )
| Some (_, _) -> R.error_msgf "Invalid <namespec> %S" value
| None ->
( match Fpath.of_string value with
| Ok v when Fpath.is_file_path v && Fpath.filename v = value -> Ok (Library (`Name value))
| Ok v -> R.error_msgf "Invalid library name <%a>" Fpath.pp v
| Error err -> Error err ) )
| _ -> Fmt.failwith "Invalid argument name %S" name
let parse_lL_args args =
let rec go lL_args = function
| [] | "--" :: _ -> R.ok (List.rev lL_args)
| x :: args ->
if not (is_opt x)
then go lL_args args
else
let name, value = parse_opt_arg x in
match name with
| "-L" | "-l" ->
( match value with
| Some value -> parse_lL_value name value >>= fun v -> go (v :: lL_args) args
| None -> match args with
| [] -> R.error_msgf "%s must have a value." name
| value :: args ->
if is_opt value
then R.error_msgf "%s must have a value." name
else parse_lL_value name value >>= fun v -> go (v :: lL_args) args )
| _ -> go lL_args args in
go [] args
let is_path = function Path _ -> true | Library _ -> false
let prj_path = function Path x -> x | _ -> assert false
let prj_libraries = function Library x -> x | _ -> assert false
let libraries_exist args =
let paths, libraries = List.partition is_path args in
let paths = List.map prj_path paths in
let libraries = List.map prj_libraries libraries in
let rec go = function
| [] -> R.ok ()
| `Rel library :: libraries ->
let rec check = function
| [] -> R.error_msgf "Library <:%a> does not exist." Fpath.pp library
| p0 :: ps ->
let path = Fpath.(p0 // library) in
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> check ps in
check paths
| `Name library :: libraries ->
let lib = Fmt.strf "lib%s.a" library in
let rec check = function
| [] -> R.error_msgf "Library lib%s.a does not exist." library
| p0 :: ps ->
let path = Fpath.(p0 / lib) in
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> check ps in
check paths
| `Abs path :: libraries ->
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> R.error_msgf "Library <%a> does not exist." Fpath.pp path in
go libraries
let exists lib =
let open Bos in
let command = Cmd.(v "ocamlfind" % "query" % lib) in
OS.Cmd.run_out command |> OS.Cmd.out_null
>>= function
| ((), (_, `Exited 0)) -> R.ok true
| _ -> R.ok false
let query target lib =
let open Bos in
let format = Fmt.strf "-L%%d %%(%s_linkopts)" target in
let command = Cmd.(v "ocamlfind" % "query" % "-format" % format % lib) in
OS.Cmd.run_out command |> OS.Cmd.out_lines
>>= (function (output, (_, `Exited 0)) -> R.ok output
| _ -> R.error_msgf "<ocamlfind> does not properly exit.")
>>| String.concat " "
>>| Astring.String.cuts ~sep:" " ~empty:false
let run () =
( exists "mirage-xen-posix" >>= function
| true -> query "xen" "bigarray-overlap" >>= parse_lL_args >>= libraries_exist
| false -> R.ok () ) >>= fun () ->
( exists "ocaml-freestanding" >>= function
| true -> query "freestanding" "bigarray-overlap" >>= parse_lL_args >>= libraries_exist
| false -> R.ok () ) >>= fun () ->
R.ok ()
let exit_success = 0
let exit_failure = 1
let () = match run () with
| Ok () -> exit exit_success
| Error (`Msg err) -> Fmt.epr "%s\n%!" err ; exit exit_failure
| null | https://raw.githubusercontent.com/dinosaure/overlap/dc09b26e904d3d8ecdd28fa4efb144d81ffa3df9/test/test_runes.ml | ocaml | #!/usr/bin/env ocaml
#use "topfind" ;;
#require "astring" ;;
#require "fpath" ;;
#require "bos" ;;
open Rresult
let is_opt x = String.length x > 1 && x.[0] = '-'
let parse_opt_arg x =
let l = String.length x in
if x.[1] <> '-'
then
if l = 2 then x, None
else String.sub x 0 2, Some (String.sub x 2 (l - 2))
else
try
let i = String.index x '=' in
String.sub x 0 i, Some (String.sub x (i + 1) (l - i - 1))
with Not_found -> x, None
type arg =
| Path of Fpath.t
| Library of [ `Abs of Fpath.t | `Rel of Fpath.t | `Name of string ]
let parse_lL_value name value = match name with
| "-L" ->
( match Fpath.of_string value with
| Ok v when Fpath.is_dir_path v && Sys.is_directory value -> R.ok (Path v)
| Ok v when Sys.is_directory value -> R.ok (Path (Fpath.to_dir_path v))
| Ok v -> R.error_msgf "Directory <%a> does not exist" Fpath.pp v
| Error err -> Error err )
| "-l" ->
( match Astring.String.cut ~sep:":" value with
| Some ("", path) ->
( match Fpath.of_string path with
| Ok v when Fpath.is_abs v && Sys.file_exists path -> Ok (Library (`Abs v))
| Ok v when Fpath.is_rel v -> Ok (Library (`Rel v))
| Ok v -> R.error_msgf "Library <%a> does not exist" Fpath.pp v
| Error err -> Error err )
| Some (_, _) -> R.error_msgf "Invalid <namespec> %S" value
| None ->
( match Fpath.of_string value with
| Ok v when Fpath.is_file_path v && Fpath.filename v = value -> Ok (Library (`Name value))
| Ok v -> R.error_msgf "Invalid library name <%a>" Fpath.pp v
| Error err -> Error err ) )
| _ -> Fmt.failwith "Invalid argument name %S" name
let parse_lL_args args =
let rec go lL_args = function
| [] | "--" :: _ -> R.ok (List.rev lL_args)
| x :: args ->
if not (is_opt x)
then go lL_args args
else
let name, value = parse_opt_arg x in
match name with
| "-L" | "-l" ->
( match value with
| Some value -> parse_lL_value name value >>= fun v -> go (v :: lL_args) args
| None -> match args with
| [] -> R.error_msgf "%s must have a value." name
| value :: args ->
if is_opt value
then R.error_msgf "%s must have a value." name
else parse_lL_value name value >>= fun v -> go (v :: lL_args) args )
| _ -> go lL_args args in
go [] args
let is_path = function Path _ -> true | Library _ -> false
let prj_path = function Path x -> x | _ -> assert false
let prj_libraries = function Library x -> x | _ -> assert false
let libraries_exist args =
let paths, libraries = List.partition is_path args in
let paths = List.map prj_path paths in
let libraries = List.map prj_libraries libraries in
let rec go = function
| [] -> R.ok ()
| `Rel library :: libraries ->
let rec check = function
| [] -> R.error_msgf "Library <:%a> does not exist." Fpath.pp library
| p0 :: ps ->
let path = Fpath.(p0 // library) in
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> check ps in
check paths
| `Name library :: libraries ->
let lib = Fmt.strf "lib%s.a" library in
let rec check = function
| [] -> R.error_msgf "Library lib%s.a does not exist." library
| p0 :: ps ->
let path = Fpath.(p0 / lib) in
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> check ps in
check paths
| `Abs path :: libraries ->
Bos.OS.Path.exists path >>= function
| true -> go libraries
| false -> R.error_msgf "Library <%a> does not exist." Fpath.pp path in
go libraries
let exists lib =
let open Bos in
let command = Cmd.(v "ocamlfind" % "query" % lib) in
OS.Cmd.run_out command |> OS.Cmd.out_null
>>= function
| ((), (_, `Exited 0)) -> R.ok true
| _ -> R.ok false
let query target lib =
let open Bos in
let format = Fmt.strf "-L%%d %%(%s_linkopts)" target in
let command = Cmd.(v "ocamlfind" % "query" % "-format" % format % lib) in
OS.Cmd.run_out command |> OS.Cmd.out_lines
>>= (function (output, (_, `Exited 0)) -> R.ok output
| _ -> R.error_msgf "<ocamlfind> does not properly exit.")
>>| String.concat " "
>>| Astring.String.cuts ~sep:" " ~empty:false
let run () =
( exists "mirage-xen-posix" >>= function
| true -> query "xen" "bigarray-overlap" >>= parse_lL_args >>= libraries_exist
| false -> R.ok () ) >>= fun () ->
( exists "ocaml-freestanding" >>= function
| true -> query "freestanding" "bigarray-overlap" >>= parse_lL_args >>= libraries_exist
| false -> R.ok () ) >>= fun () ->
R.ok ()
let exit_success = 0
let exit_failure = 1
let () = match run () with
| Ok () -> exit exit_success
| Error (`Msg err) -> Fmt.epr "%s\n%!" err ; exit exit_failure
|
|
6330413b15c0993408b1a7f3bfd2e19bbb18bda67d6567d4853766a4b63e5543 | mathematical-systems/clml | dlasy2.lisp | ;;; Compiled by f2cl version:
( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ "
" $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 "
" $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ "
" $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ "
" $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ "
" $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " )
Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 )
;;;
;;; Options: ((:prune-labels nil) (:auto-save t)
;;; (:relaxed-array-decls t) (:coerce-assigns :as-needed)
;;; (:array-type ':array) (:array-slicing t)
;;; (:declare-common nil) (:float-format double-float))
(in-package "LAPACK")
(let* ((zero 0.0) (one 1.0) (two 2.0) (half 0.5) (eight 8.0))
(declare (type (double-float 0.0 0.0) zero)
(type (double-float 1.0 1.0) one) (type (double-float 2.0 2.0) two)
(type (double-float 0.5 0.5) half)
(type (double-float 8.0 8.0) eight)
(ignorable zero one two half eight))
(let ((locu12
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(3 4 1 2)))
(locl21
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(2 1 4 3)))
(locu22
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(4 3 2 1)))
(xswpiv
(make-array 4
:element-type 't
:initial-contents '(nil nil t t)))
(bswpiv
(make-array 4
:element-type 't
:initial-contents '(nil t nil t))))
(declare (type (array f2cl-lib:integer4 (4)) locu12 locl21 locu22)
(type (array f2cl-lib:logical (4)) xswpiv bswpiv))
(defun dlasy2
(ltranl ltranr isgn n1 n2 tl ldtl tr ldtr b ldb$ scale x ldx
xnorm info)
(declare (type (double-float) xnorm scale)
(type (array double-float (*)) x b tr tl)
(type f2cl-lib:logical ltranr ltranl)
(type (f2cl-lib:integer4) info ldx ldb$ ldtr ldtl n2 n1 isgn))
(f2cl-lib:with-multi-array-data ((tl double-float tl-%data%
tl-%offset%)
(tr double-float tr-%data%
tr-%offset%)
(b double-float b-%data%
b-%offset%)
(x double-float x-%data%
x-%offset%))
(prog ((btmp (make-array 4 :element-type 'double-float))
(t16 (make-array 16 :element-type 'double-float))
(tmp (make-array 4 :element-type 'double-float))
(x2 (make-array 2 :element-type 'double-float))
(jpiv (make-array 4 :element-type 'f2cl-lib:integer4))
(bet 0.0) (eps 0.0) (gam 0.0) (l21 0.0) (sgn 0.0)
(smin 0.0) (smlnum 0.0) (tau1 0.0) (temp 0.0) (u11 0.0)
(u12 0.0) (u22 0.0) (xmax 0.0) (i 0) (ip 0) (ipiv 0)
(ipsv 0) (j 0) (jp 0) (jpsv 0) (k 0) (bswap nil)
(xswap nil))
(declare
(type (double-float) bet eps gam l21 sgn smin smlnum
tau1 temp u11 u12 u22 xmax)
(type (array double-float (16)) t16)
(type (array f2cl-lib:integer4 (4)) jpiv)
(type (array double-float (2)) x2)
(type f2cl-lib:logical bswap xswap)
(type (array double-float (4)) btmp tmp)
(type (f2cl-lib:integer4) i ip ipiv ipsv j jp jpsv k))
(setf info 0)
(if (or (= n1 0) (= n2 0)) (go end_label))
(setf eps (dlamch "P"))
(setf smlnum (/ (dlamch "S") eps))
(setf sgn
(coerce (the f2cl-lib:integer4 isgn)
'double-float))
(setf k (f2cl-lib:int-sub (f2cl-lib:int-add n1 n1 n2) 2))
(f2cl-lib:computed-goto (label10 label20 label30 label50)
k)
label10 (setf tau1
(+ (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl) (1 *)) tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf bet (abs tau1))
(cond ((<= bet smlnum)
(setf tau1 smlnum)
(setf bet smlnum)
(setf info 1)))
(setf scale one)
(setf gam
(abs (f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%)))
(if (> (* smlnum gam) bet) (setf scale (/ one gam)))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(/ (* (f2cl-lib:fref b-%data% (1 1)
((1 ldb$) (1 *)) b-%offset%)
scale)
tau1))
(setf xnorm
(abs (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)))
(go end_label)
label20 (setf smin
(max (* eps
(max (abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 2)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 2)
((1 ldtr)
(1 *))
tr-%offset%))))
smlnum))
(setf (f2cl-lib:fref tmp (1) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref tmp (4) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranr
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%))))
(t
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (1 2) ((1 ldb$) (1 *))
b-%offset%))
(go label40)
label30 (setf smin
(max (* eps
(max (abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 2)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 2)
((1 ldtl)
(1 *))
tl-%offset%))))
smlnum))
(setf (f2cl-lib:fref tmp (1) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref tmp (4) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranl
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%)))
(t
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (2 1) ((1 ldb$) (1 *))
b-%offset%))
label40 (setf ipiv (idamax 4 tmp 1))
(setf u11 (f2cl-lib:fref tmp (ipiv) ((1 4))))
(cond ((<= (abs u11) smin)
(setf info 1)
(setf u11 smin)))
(setf u12
(f2cl-lib:fref tmp
((f2cl-lib:fref locu12 (ipiv)
((1 4))))
((1 4))))
(setf l21
(/ (f2cl-lib:fref tmp
((f2cl-lib:fref locl21 (ipiv)
((1 4))))
((1 4)))
u11))
(setf u22
(- (f2cl-lib:fref tmp
((f2cl-lib:fref locu22 (ipiv)
((1 4))))
((1 4)))
(* u12 l21)))
(setf xswap (f2cl-lib:fref xswpiv (ipiv) ((1 4))))
(setf bswap (f2cl-lib:fref bswpiv (ipiv) ((1 4))))
(cond ((<= (abs u22) smin)
(setf info 1)
(setf u22 smin)))
(cond (bswap
(setf temp (f2cl-lib:fref btmp (2) ((1 4))))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(- (f2cl-lib:fref btmp (1) ((1 4)))
(* l21 temp)))
(setf (f2cl-lib:fref btmp (1) ((1 4))) temp))
(t
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(- (f2cl-lib:fref btmp (2) ((1 4)))
(* l21
(f2cl-lib:fref btmp (1) ((1 4))))))))
(setf scale one)
(cond ((or (> (* two smlnum
(abs (f2cl-lib:fref btmp (2) ((1 4)))))
(abs u22))
(> (* two smlnum
(abs (f2cl-lib:fref btmp (1) ((1 4)))))
(abs u11)))
(setf scale
(/ half
(max (abs (f2cl-lib:fref btmp (1)
((1 4))))
(abs (f2cl-lib:fref btmp (2)
((1 4)))))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(* (f2cl-lib:fref btmp (1) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(* (f2cl-lib:fref btmp (2) ((1 4)))
scale))))
(setf (f2cl-lib:fref x2 (2) ((1 2)))
(/ (f2cl-lib:fref btmp (2) ((1 4))) u22))
(setf (f2cl-lib:fref x2 (1) ((1 2)))
(- (/ (f2cl-lib:fref btmp (1) ((1 4))) u11)
(* (/ u12 u11) (f2cl-lib:fref x2 (2) ((1 2))))))
(cond (xswap
(setf temp (f2cl-lib:fref x2 (2) ((1 2))))
(setf (f2cl-lib:fref x2 (2) ((1 2)))
(f2cl-lib:fref x2 (1) ((1 2))))
(setf (f2cl-lib:fref x2 (1) ((1 2))) temp)))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref x2 (1) ((1 2))))
(cond ((= n1 1)
(setf (f2cl-lib:fref x-%data% (1 2)
((1 ldx) (1 *)) x-%offset%)
(f2cl-lib:fref x2 (2) ((1 2))))
(setf xnorm
(+ (abs (f2cl-lib:fref x-%data% (1 1)
((1 ldx) (1 *))
x-%offset%))
(abs (f2cl-lib:fref x-%data% (1 2)
((1 ldx) (1 *))
x-%offset%)))))
(t
(setf (f2cl-lib:fref x-%data% (2 1)
((1 ldx) (1 *)) x-%offset%)
(f2cl-lib:fref x2 (2) ((1 2))))
(setf xnorm
(max (abs (f2cl-lib:fref x-%data% (1 1)
((1 ldx) (1 *))
x-%offset%))
(abs (f2cl-lib:fref x-%data% (2 1)
((1 ldx) (1 *))
x-%offset%))))))
(go end_label)
label50 (setf smin
(max (abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(setf smin
(max smin
(abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 2)
((1 ldtl) (1 *))
tl-%offset%))))
(setf smin (max (* eps smin) smlnum))
(setf (f2cl-lib:fref btmp (1) ((1 4))) zero)
(dcopy 16 btmp 0 t16 1)
(setf (f2cl-lib:fref t16 (1 1) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (2 2) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (3 3) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (4 4) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranl
(setf (f2cl-lib:fref t16 (1 2) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (2 1) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (3 4) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (4 3) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%)))
(t
(setf (f2cl-lib:fref t16 (1 2) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (2 1) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (3 4) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (4 3) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))))
(cond (ltranr
(setf (f2cl-lib:fref t16 (1 3) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (2 4) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (3 1) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (4 2) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%))))
(t
(setf (f2cl-lib:fref t16 (1 3) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (2 4) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (3 1) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (4 2) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (2 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (3) ((1 4)))
(f2cl-lib:fref b-%data% (1 2) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (4) ((1 4)))
(f2cl-lib:fref b-%data% (2 2) ((1 ldb$) (1 *))
b-%offset%))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 3) nil)
(tagbody
(setf xmax zero)
(f2cl-lib:fdo (ip i
(f2cl-lib:int-add ip 1))
((> ip 4) nil)
(tagbody
(f2cl-lib:fdo (jp i
(f2cl-lib:int-add jp
1))
((> jp
4)
nil)
(tagbody
(cond ((>= (abs (f2cl-lib:fref t16
(ip
jp)
((1
4)
(1
4))))
xmax)
(setf xmax
(abs (f2cl-lib:fref t16
(ip
jp)
((1
4)
(1
4)))))
(setf ipsv
ip)
(setf jpsv
jp)))
label60))
label70))
(cond ((/= ipsv i)
(dswap 4
(f2cl-lib:array-slice t16
double-float
(ipsv 1)
((1 4)
(1 4)))
4
(f2cl-lib:array-slice t16
double-float
(i 1)
((1 4)
(1 4)))
4)
(setf temp
(f2cl-lib:fref btmp (i)
((1 4))))
(setf (f2cl-lib:fref btmp (i)
((1 4)))
(f2cl-lib:fref btmp (ipsv)
((1 4))))
(setf (f2cl-lib:fref btmp (ipsv)
((1 4)))
temp)))
(if (/= jpsv i)
(dswap 4
(f2cl-lib:array-slice t16
double-float
(1 jpsv)
((1 4)
(1 4)))
1
(f2cl-lib:array-slice t16
double-float
(1 i)
((1 4)
(1 4)))
1))
(setf (f2cl-lib:fref jpiv (i) ((1 4)))
jpsv)
(cond ((< (abs (f2cl-lib:fref t16 (i i)
((1 4)
(1 4))))
smin)
(setf info 1)
(setf (f2cl-lib:fref t16 (i i)
((1 4)
(1 4)))
smin)))
(f2cl-lib:fdo (j (f2cl-lib:int-add i 1)
(f2cl-lib:int-add j 1))
((> j 4) nil)
(tagbody
(setf (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(/ (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref t16
(i
i)
((1
4)
(1
4)))))
(setf (f2cl-lib:fref btmp
(j)
((1
4)))
(- (f2cl-lib:fref btmp
(j)
((1
4)))
(* (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref btmp
(i)
((1
4))))))
(f2cl-lib:fdo (k
(f2cl-lib:int-add i
1)
(f2cl-lib:int-add k
1))
((> k
4)
nil)
(tagbody
(setf (f2cl-lib:fref t16
(j
k)
((1
4)
(1
4)))
(- (f2cl-lib:fref t16
(j
k)
((1
4)
(1
4)))
(* (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref t16
(i
k)
((1
4)
(1
4))))))
label80))
label90))
label100))
(if (< (abs (f2cl-lib:fref t16 (4 4) ((1 4) (1 4))))
smin)
(setf (f2cl-lib:fref t16 (4 4) ((1 4) (1 4))) smin))
(setf scale one)
(cond ((or (> (* eight smlnum
(abs (f2cl-lib:fref btmp (1) ((1 4)))))
(abs (f2cl-lib:fref t16 (1 1)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (2) ((1 4)))))
(abs (f2cl-lib:fref t16 (2 2)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (3) ((1 4)))))
(abs (f2cl-lib:fref t16 (3 3)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (4) ((1 4)))))
(abs (f2cl-lib:fref t16 (4 4)
((1 4) (1 4))))))
(setf scale
(/ (/ one eight)
(max (abs (f2cl-lib:fref btmp (1)
((1 4))))
(abs (f2cl-lib:fref btmp (2)
((1 4))))
(abs (f2cl-lib:fref btmp (3)
((1 4))))
(abs (f2cl-lib:fref btmp (4)
((1 4)))))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(* (f2cl-lib:fref btmp (1) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(* (f2cl-lib:fref btmp (2) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (3) ((1 4)))
(* (f2cl-lib:fref btmp (3) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (4) ((1 4)))
(* (f2cl-lib:fref btmp (4) ((1 4)))
scale))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 4) nil)
(tagbody
(setf k (f2cl-lib:int-sub 5 i))
(setf temp
(/ one
(f2cl-lib:fref t16 (k k)
((1 4)
(1 4)))))
(setf (f2cl-lib:fref tmp (k) ((1 4)))
(* (f2cl-lib:fref btmp (k)
((1 4)))
temp))
(f2cl-lib:fdo (j (f2cl-lib:int-add k 1)
(f2cl-lib:int-add j 1))
((> j 4) nil)
(tagbody
(setf (f2cl-lib:fref tmp
(k)
((1
4)))
(- (f2cl-lib:fref tmp
(k)
((1
4)))
(* temp
(f2cl-lib:fref t16
(k
j)
((1
4)
(1
4)))
(f2cl-lib:fref tmp
(j)
((1
4))))))
label110))
label120))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 3) nil)
(tagbody
(cond ((/= (f2cl-lib:fref jpiv
((f2cl-lib:int-add 4
(f2cl-lib:int-sub i)))
((1 4)))
(f2cl-lib:int-add 4
(f2cl-lib:int-sub i)))
(setf temp
(f2cl-lib:fref tmp
((f2cl-lib:int-sub 4
i))
((1 4))))
(setf (f2cl-lib:fref tmp
((f2cl-lib:int-sub 4
i))
((1 4)))
(f2cl-lib:fref tmp
((f2cl-lib:fref jpiv
((f2cl-lib:int-sub 4
i))
((1
4))))
((1 4))))
(setf (f2cl-lib:fref tmp
((f2cl-lib:fref jpiv
((f2cl-lib:int-sub 4
i))
((1
4))))
((1 4)))
temp)))
label130))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (1) ((1 4))))
(setf (f2cl-lib:fref x-%data% (2 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (2) ((1 4))))
(setf (f2cl-lib:fref x-%data% (1 2) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (3) ((1 4))))
(setf (f2cl-lib:fref x-%data% (2 2) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (4) ((1 4))))
(setf xnorm
(max (+ (abs (f2cl-lib:fref tmp (1) ((1 4))))
(abs (f2cl-lib:fref tmp (3) ((1 4)))))
(+ (abs (f2cl-lib:fref tmp (2) ((1 4))))
(abs (f2cl-lib:fref tmp (4) ((1 4)))))))
(go end_label)
end_label (return (values nil nil nil nil nil nil nil nil nil
nil nil scale nil nil xnorm
info)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasy2
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo :arg-types '(fortran-to-lisp::logical
fortran-to-lisp::logical
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(double-float)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(double-float)
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil
fortran-to-lisp::scale nil nil
fortran-to-lisp::xnorm
fortran-to-lisp::info)
:calls '(fortran-to-lisp::dswap fortran-to-lisp::dcopy
fortran-to-lisp::idamax fortran-to-lisp::dlamch))))
| null | https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/lapack/dlasy2.lisp | lisp | Compiled by f2cl version:
Options: ((:prune-labels nil) (:auto-save t)
(:relaxed-array-decls t) (:coerce-assigns :as-needed)
(:array-type ':array) (:array-slicing t)
(:declare-common nil) (:float-format double-float)) | ( " $ I d : f2cl1.l , v 1.209 2008/09/11 14:59:55 rtoy Exp $ "
" $ I d : f2cl2.l , v 1.37 2008/02/22 22:19:33 "
" $ I d : f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Rel $ "
" $ I d : f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Rel $ "
" $ I d : f2cl5.l , v 1.197 2008/09/11 15:03:25 rtoy Exp $ "
" $ I d : f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ "
" $ I d : macros.l , v 1.106 2008/09/15 15:27:36 " )
Using Lisp International Allegro CL Enterprise Edition 8.1 [ 64 - bit Linux ( x86 - 64 ) ] ( Oct 7 , 2008 17:13 )
(in-package "LAPACK")
(let* ((zero 0.0) (one 1.0) (two 2.0) (half 0.5) (eight 8.0))
(declare (type (double-float 0.0 0.0) zero)
(type (double-float 1.0 1.0) one) (type (double-float 2.0 2.0) two)
(type (double-float 0.5 0.5) half)
(type (double-float 8.0 8.0) eight)
(ignorable zero one two half eight))
(let ((locu12
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(3 4 1 2)))
(locl21
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(2 1 4 3)))
(locu22
(make-array 4
:element-type 'f2cl-lib:integer4
:initial-contents '(4 3 2 1)))
(xswpiv
(make-array 4
:element-type 't
:initial-contents '(nil nil t t)))
(bswpiv
(make-array 4
:element-type 't
:initial-contents '(nil t nil t))))
(declare (type (array f2cl-lib:integer4 (4)) locu12 locl21 locu22)
(type (array f2cl-lib:logical (4)) xswpiv bswpiv))
(defun dlasy2
(ltranl ltranr isgn n1 n2 tl ldtl tr ldtr b ldb$ scale x ldx
xnorm info)
(declare (type (double-float) xnorm scale)
(type (array double-float (*)) x b tr tl)
(type f2cl-lib:logical ltranr ltranl)
(type (f2cl-lib:integer4) info ldx ldb$ ldtr ldtl n2 n1 isgn))
(f2cl-lib:with-multi-array-data ((tl double-float tl-%data%
tl-%offset%)
(tr double-float tr-%data%
tr-%offset%)
(b double-float b-%data%
b-%offset%)
(x double-float x-%data%
x-%offset%))
(prog ((btmp (make-array 4 :element-type 'double-float))
(t16 (make-array 16 :element-type 'double-float))
(tmp (make-array 4 :element-type 'double-float))
(x2 (make-array 2 :element-type 'double-float))
(jpiv (make-array 4 :element-type 'f2cl-lib:integer4))
(bet 0.0) (eps 0.0) (gam 0.0) (l21 0.0) (sgn 0.0)
(smin 0.0) (smlnum 0.0) (tau1 0.0) (temp 0.0) (u11 0.0)
(u12 0.0) (u22 0.0) (xmax 0.0) (i 0) (ip 0) (ipiv 0)
(ipsv 0) (j 0) (jp 0) (jpsv 0) (k 0) (bswap nil)
(xswap nil))
(declare
(type (double-float) bet eps gam l21 sgn smin smlnum
tau1 temp u11 u12 u22 xmax)
(type (array double-float (16)) t16)
(type (array f2cl-lib:integer4 (4)) jpiv)
(type (array double-float (2)) x2)
(type f2cl-lib:logical bswap xswap)
(type (array double-float (4)) btmp tmp)
(type (f2cl-lib:integer4) i ip ipiv ipsv j jp jpsv k))
(setf info 0)
(if (or (= n1 0) (= n2 0)) (go end_label))
(setf eps (dlamch "P"))
(setf smlnum (/ (dlamch "S") eps))
(setf sgn
(coerce (the f2cl-lib:integer4 isgn)
'double-float))
(setf k (f2cl-lib:int-sub (f2cl-lib:int-add n1 n1 n2) 2))
(f2cl-lib:computed-goto (label10 label20 label30 label50)
k)
label10 (setf tau1
(+ (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl) (1 *)) tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf bet (abs tau1))
(cond ((<= bet smlnum)
(setf tau1 smlnum)
(setf bet smlnum)
(setf info 1)))
(setf scale one)
(setf gam
(abs (f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%)))
(if (> (* smlnum gam) bet) (setf scale (/ one gam)))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(/ (* (f2cl-lib:fref b-%data% (1 1)
((1 ldb$) (1 *)) b-%offset%)
scale)
tau1))
(setf xnorm
(abs (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)))
(go end_label)
label20 (setf smin
(max (* eps
(max (abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 2)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 2)
((1 ldtr)
(1 *))
tr-%offset%))))
smlnum))
(setf (f2cl-lib:fref tmp (1) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref tmp (4) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranr
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%))))
(t
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (1 2) ((1 ldb$) (1 *))
b-%offset%))
(go label40)
label30 (setf smin
(max (* eps
(max (abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr)
(1 *))
tr-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 2)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 1)
((1 ldtl)
(1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 2)
((1 ldtl)
(1 *))
tl-%offset%))))
smlnum))
(setf (f2cl-lib:fref tmp (1) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref tmp (4) ((1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranl
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%)))
(t
(setf (f2cl-lib:fref tmp (2) ((1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref tmp (3) ((1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (2 1) ((1 ldb$) (1 *))
b-%offset%))
label40 (setf ipiv (idamax 4 tmp 1))
(setf u11 (f2cl-lib:fref tmp (ipiv) ((1 4))))
(cond ((<= (abs u11) smin)
(setf info 1)
(setf u11 smin)))
(setf u12
(f2cl-lib:fref tmp
((f2cl-lib:fref locu12 (ipiv)
((1 4))))
((1 4))))
(setf l21
(/ (f2cl-lib:fref tmp
((f2cl-lib:fref locl21 (ipiv)
((1 4))))
((1 4)))
u11))
(setf u22
(- (f2cl-lib:fref tmp
((f2cl-lib:fref locu22 (ipiv)
((1 4))))
((1 4)))
(* u12 l21)))
(setf xswap (f2cl-lib:fref xswpiv (ipiv) ((1 4))))
(setf bswap (f2cl-lib:fref bswpiv (ipiv) ((1 4))))
(cond ((<= (abs u22) smin)
(setf info 1)
(setf u22 smin)))
(cond (bswap
(setf temp (f2cl-lib:fref btmp (2) ((1 4))))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(- (f2cl-lib:fref btmp (1) ((1 4)))
(* l21 temp)))
(setf (f2cl-lib:fref btmp (1) ((1 4))) temp))
(t
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(- (f2cl-lib:fref btmp (2) ((1 4)))
(* l21
(f2cl-lib:fref btmp (1) ((1 4))))))))
(setf scale one)
(cond ((or (> (* two smlnum
(abs (f2cl-lib:fref btmp (2) ((1 4)))))
(abs u22))
(> (* two smlnum
(abs (f2cl-lib:fref btmp (1) ((1 4)))))
(abs u11)))
(setf scale
(/ half
(max (abs (f2cl-lib:fref btmp (1)
((1 4))))
(abs (f2cl-lib:fref btmp (2)
((1 4)))))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(* (f2cl-lib:fref btmp (1) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(* (f2cl-lib:fref btmp (2) ((1 4)))
scale))))
(setf (f2cl-lib:fref x2 (2) ((1 2)))
(/ (f2cl-lib:fref btmp (2) ((1 4))) u22))
(setf (f2cl-lib:fref x2 (1) ((1 2)))
(- (/ (f2cl-lib:fref btmp (1) ((1 4))) u11)
(* (/ u12 u11) (f2cl-lib:fref x2 (2) ((1 2))))))
(cond (xswap
(setf temp (f2cl-lib:fref x2 (2) ((1 2))))
(setf (f2cl-lib:fref x2 (2) ((1 2)))
(f2cl-lib:fref x2 (1) ((1 2))))
(setf (f2cl-lib:fref x2 (1) ((1 2))) temp)))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref x2 (1) ((1 2))))
(cond ((= n1 1)
(setf (f2cl-lib:fref x-%data% (1 2)
((1 ldx) (1 *)) x-%offset%)
(f2cl-lib:fref x2 (2) ((1 2))))
(setf xnorm
(+ (abs (f2cl-lib:fref x-%data% (1 1)
((1 ldx) (1 *))
x-%offset%))
(abs (f2cl-lib:fref x-%data% (1 2)
((1 ldx) (1 *))
x-%offset%)))))
(t
(setf (f2cl-lib:fref x-%data% (2 1)
((1 ldx) (1 *)) x-%offset%)
(f2cl-lib:fref x2 (2) ((1 2))))
(setf xnorm
(max (abs (f2cl-lib:fref x-%data% (1 1)
((1 ldx) (1 *))
x-%offset%))
(abs (f2cl-lib:fref x-%data% (2 1)
((1 ldx) (1 *))
x-%offset%))))))
(go end_label)
label50 (setf smin
(max (abs (f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%))
(abs (f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(setf smin
(max smin
(abs (f2cl-lib:fref tl-%data% (1 1)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(abs (f2cl-lib:fref tl-%data% (2 2)
((1 ldtl) (1 *))
tl-%offset%))))
(setf smin (max (* eps smin) smlnum))
(setf (f2cl-lib:fref btmp (1) ((1 4))) zero)
(dcopy 16 btmp 0 t16 1)
(setf (f2cl-lib:fref t16 (1 1) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (2 2) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (1 1)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (3 3) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (1 1) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(setf (f2cl-lib:fref t16 (4 4) ((1 4) (1 4)))
(+ (f2cl-lib:fref tl-%data% (2 2) ((1 ldtl) (1 *))
tl-%offset%)
(* sgn
(f2cl-lib:fref tr-%data% (2 2)
((1 ldtr) (1 *))
tr-%offset%))))
(cond (ltranl
(setf (f2cl-lib:fref t16 (1 2) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (2 1) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (3 4) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (4 3) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%)))
(t
(setf (f2cl-lib:fref t16 (1 2) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (2 1) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (3 4) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (1 2)
((1 ldtl) (1 *))
tl-%offset%))
(setf (f2cl-lib:fref t16 (4 3) ((1 4) (1 4)))
(f2cl-lib:fref tl-%data% (2 1)
((1 ldtl) (1 *))
tl-%offset%))))
(cond (ltranr
(setf (f2cl-lib:fref t16 (1 3) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (2 4) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (3 1) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (4 2) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%))))
(t
(setf (f2cl-lib:fref t16 (1 3) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (2 4) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (2 1)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (3 1) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))
(setf (f2cl-lib:fref t16 (4 2) ((1 4) (1 4)))
(* sgn
(f2cl-lib:fref tr-%data% (1 2)
((1 ldtr) (1 *))
tr-%offset%)))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(f2cl-lib:fref b-%data% (1 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(f2cl-lib:fref b-%data% (2 1) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (3) ((1 4)))
(f2cl-lib:fref b-%data% (1 2) ((1 ldb$) (1 *))
b-%offset%))
(setf (f2cl-lib:fref btmp (4) ((1 4)))
(f2cl-lib:fref b-%data% (2 2) ((1 ldb$) (1 *))
b-%offset%))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 3) nil)
(tagbody
(setf xmax zero)
(f2cl-lib:fdo (ip i
(f2cl-lib:int-add ip 1))
((> ip 4) nil)
(tagbody
(f2cl-lib:fdo (jp i
(f2cl-lib:int-add jp
1))
((> jp
4)
nil)
(tagbody
(cond ((>= (abs (f2cl-lib:fref t16
(ip
jp)
((1
4)
(1
4))))
xmax)
(setf xmax
(abs (f2cl-lib:fref t16
(ip
jp)
((1
4)
(1
4)))))
(setf ipsv
ip)
(setf jpsv
jp)))
label60))
label70))
(cond ((/= ipsv i)
(dswap 4
(f2cl-lib:array-slice t16
double-float
(ipsv 1)
((1 4)
(1 4)))
4
(f2cl-lib:array-slice t16
double-float
(i 1)
((1 4)
(1 4)))
4)
(setf temp
(f2cl-lib:fref btmp (i)
((1 4))))
(setf (f2cl-lib:fref btmp (i)
((1 4)))
(f2cl-lib:fref btmp (ipsv)
((1 4))))
(setf (f2cl-lib:fref btmp (ipsv)
((1 4)))
temp)))
(if (/= jpsv i)
(dswap 4
(f2cl-lib:array-slice t16
double-float
(1 jpsv)
((1 4)
(1 4)))
1
(f2cl-lib:array-slice t16
double-float
(1 i)
((1 4)
(1 4)))
1))
(setf (f2cl-lib:fref jpiv (i) ((1 4)))
jpsv)
(cond ((< (abs (f2cl-lib:fref t16 (i i)
((1 4)
(1 4))))
smin)
(setf info 1)
(setf (f2cl-lib:fref t16 (i i)
((1 4)
(1 4)))
smin)))
(f2cl-lib:fdo (j (f2cl-lib:int-add i 1)
(f2cl-lib:int-add j 1))
((> j 4) nil)
(tagbody
(setf (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(/ (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref t16
(i
i)
((1
4)
(1
4)))))
(setf (f2cl-lib:fref btmp
(j)
((1
4)))
(- (f2cl-lib:fref btmp
(j)
((1
4)))
(* (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref btmp
(i)
((1
4))))))
(f2cl-lib:fdo (k
(f2cl-lib:int-add i
1)
(f2cl-lib:int-add k
1))
((> k
4)
nil)
(tagbody
(setf (f2cl-lib:fref t16
(j
k)
((1
4)
(1
4)))
(- (f2cl-lib:fref t16
(j
k)
((1
4)
(1
4)))
(* (f2cl-lib:fref t16
(j
i)
((1
4)
(1
4)))
(f2cl-lib:fref t16
(i
k)
((1
4)
(1
4))))))
label80))
label90))
label100))
(if (< (abs (f2cl-lib:fref t16 (4 4) ((1 4) (1 4))))
smin)
(setf (f2cl-lib:fref t16 (4 4) ((1 4) (1 4))) smin))
(setf scale one)
(cond ((or (> (* eight smlnum
(abs (f2cl-lib:fref btmp (1) ((1 4)))))
(abs (f2cl-lib:fref t16 (1 1)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (2) ((1 4)))))
(abs (f2cl-lib:fref t16 (2 2)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (3) ((1 4)))))
(abs (f2cl-lib:fref t16 (3 3)
((1 4) (1 4)))))
(> (* eight smlnum
(abs (f2cl-lib:fref btmp (4) ((1 4)))))
(abs (f2cl-lib:fref t16 (4 4)
((1 4) (1 4))))))
(setf scale
(/ (/ one eight)
(max (abs (f2cl-lib:fref btmp (1)
((1 4))))
(abs (f2cl-lib:fref btmp (2)
((1 4))))
(abs (f2cl-lib:fref btmp (3)
((1 4))))
(abs (f2cl-lib:fref btmp (4)
((1 4)))))))
(setf (f2cl-lib:fref btmp (1) ((1 4)))
(* (f2cl-lib:fref btmp (1) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (2) ((1 4)))
(* (f2cl-lib:fref btmp (2) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (3) ((1 4)))
(* (f2cl-lib:fref btmp (3) ((1 4))) scale))
(setf (f2cl-lib:fref btmp (4) ((1 4)))
(* (f2cl-lib:fref btmp (4) ((1 4)))
scale))))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 4) nil)
(tagbody
(setf k (f2cl-lib:int-sub 5 i))
(setf temp
(/ one
(f2cl-lib:fref t16 (k k)
((1 4)
(1 4)))))
(setf (f2cl-lib:fref tmp (k) ((1 4)))
(* (f2cl-lib:fref btmp (k)
((1 4)))
temp))
(f2cl-lib:fdo (j (f2cl-lib:int-add k 1)
(f2cl-lib:int-add j 1))
((> j 4) nil)
(tagbody
(setf (f2cl-lib:fref tmp
(k)
((1
4)))
(- (f2cl-lib:fref tmp
(k)
((1
4)))
(* temp
(f2cl-lib:fref t16
(k
j)
((1
4)
(1
4)))
(f2cl-lib:fref tmp
(j)
((1
4))))))
label110))
label120))
(f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i 3) nil)
(tagbody
(cond ((/= (f2cl-lib:fref jpiv
((f2cl-lib:int-add 4
(f2cl-lib:int-sub i)))
((1 4)))
(f2cl-lib:int-add 4
(f2cl-lib:int-sub i)))
(setf temp
(f2cl-lib:fref tmp
((f2cl-lib:int-sub 4
i))
((1 4))))
(setf (f2cl-lib:fref tmp
((f2cl-lib:int-sub 4
i))
((1 4)))
(f2cl-lib:fref tmp
((f2cl-lib:fref jpiv
((f2cl-lib:int-sub 4
i))
((1
4))))
((1 4))))
(setf (f2cl-lib:fref tmp
((f2cl-lib:fref jpiv
((f2cl-lib:int-sub 4
i))
((1
4))))
((1 4)))
temp)))
label130))
(setf (f2cl-lib:fref x-%data% (1 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (1) ((1 4))))
(setf (f2cl-lib:fref x-%data% (2 1) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (2) ((1 4))))
(setf (f2cl-lib:fref x-%data% (1 2) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (3) ((1 4))))
(setf (f2cl-lib:fref x-%data% (2 2) ((1 ldx) (1 *))
x-%offset%)
(f2cl-lib:fref tmp (4) ((1 4))))
(setf xnorm
(max (+ (abs (f2cl-lib:fref tmp (1) ((1 4))))
(abs (f2cl-lib:fref tmp (3) ((1 4)))))
(+ (abs (f2cl-lib:fref tmp (2) ((1 4))))
(abs (f2cl-lib:fref tmp (4) ((1 4)))))))
(go end_label)
end_label (return (values nil nil nil nil nil nil nil nil nil
nil nil scale nil nil xnorm
info)))))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::dlasy2
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo :arg-types '(fortran-to-lisp::logical
fortran-to-lisp::logical
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(double-float)
(array
double-float
(*))
(fortran-to-lisp::integer4)
(double-float)
(fortran-to-lisp::integer4))
:return-values '(nil nil nil nil nil nil nil nil nil nil nil
fortran-to-lisp::scale nil nil
fortran-to-lisp::xnorm
fortran-to-lisp::info)
:calls '(fortran-to-lisp::dswap fortran-to-lisp::dcopy
fortran-to-lisp::idamax fortran-to-lisp::dlamch))))
|
013b219187515591d05d8e71be06c0e6fe024e190830a548499e2b67c7edb20e | rodo/tsung-gis | slippymap.erl |
%
% @doc OpenStreetMap slippy map tile numbers
%
@author < >
% []
%
2013,2014 Rodolphe Quiedeville
%
< a href=" / wiki / Slippy_map_tilenames"> / wiki / Slippy_map_tilenames</a >
-module(slippymap).
-export([deg2num/3]).
-export([num2deg/3,num2bbox/3]).
-export([tmstowms/1]).
-export([tile2lat/2,tile2lon/2]).
@doc Convert list_url DynVar to list of coord
%
%
tmstowms({_Pid, DynVars})->
Urls = lists:map(fun(Url)->
[Z, X, Y] = url_split(Url),
num2bbox(X, Y, Z)
end,
last_block(DynVars)),
lists:usort(Urls).
last_block(DynVars)->
case ts_dynvars:lookup(list_url, DynVars) of
{ok, Block} -> Block;
false -> ""
end.
% @doc convert geometric coordinate to tile numbers
%
@spec deg2num(Lat::float ( ) , : : float ( ) , Zoom::integer ( ) ) - > { integer ( ) , integer ( ) }
%
deg2num(Lat,Lon,Zoom)->
X = math:pow(2, Zoom) * ((Lon + 180) / 360),
Sec = 1 / math:cos(deg2rad(Lat)),
R = math:log(math:tan(deg2rad(Lat)) + Sec) / math:pi(),
Y = math:pow(2, Zoom) * (1 - R) / 2,
{round(X), round(Y)}.
% @doc convert tile numbers to geometric coordinate
%
% Return a tuple : {longitude, latitude}
%
( ) , Y::integer ( ) , Zoom::integer ( ) ) - > { float ( ) , float ( ) }
%
num2deg(X,Y,Zoom)->
{tile2lon(X, Zoom), tile2lat(Y, Zoom)}.
deg2rad(C)->
C * math:pi() / 180.
% @doc convert tile numbers to bouding box
%
%
num2bbox(X,Y,Zoom)->
North = tile2lat(Y, Zoom),
South = tile2lat(Y + 1, Zoom),
West = tile2lon(X, Zoom),
East = tile2lon(X + 1, Zoom),
{West, South, East, North}.
tile2lat(Y, Z)->
% double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
% return Math.toDegrees(Math.atan(Math.sinh(n)));) ->
N = math:pi() - ( 2.0 * math:pi() * Y) / math:pow(2, Z),
LatRad = math:atan(math:sinh(N)),
[Lat] = io_lib:format("~.8f", [LatRad * 180 / math:pi()]),
list_to_float(Lat).
tile2lon(X, Z)->
% double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
% return Math.toDegrees(Math.atan(Math.sinh(n)));) ->
N = math:pow(2, Z),
[Lon] = io_lib:format("~.8f", [X / N * 360 - 180]),
list_to_float(Lon).
%
%
%
%% Split the url
%%
%% @doc return an array with [Z, X, Y]
url_split(Url)->
lists:map(fun(X) ->
{Int, _} = string:to_integer(X),
Int
end,
split(Url)).
split(Url)->
Elmts = string:tokens(Url, "/"),
case length(Elmts) of
3 -> T=Elmts;
_ -> [_|T] = Elmts
end,
T.
| null | https://raw.githubusercontent.com/rodo/tsung-gis/d6fc43e5c21d7d12f703cf0766dcd0900ab1d6bc/src/slippymap.erl | erlang |
@doc OpenStreetMap slippy map tile numbers
[]
@doc convert geometric coordinate to tile numbers
@doc convert tile numbers to geometric coordinate
Return a tuple : {longitude, latitude}
@doc convert tile numbers to bouding box
double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
return Math.toDegrees(Math.atan(Math.sinh(n)));) ->
double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z);
return Math.toDegrees(Math.atan(Math.sinh(n)));) ->
Split the url
@doc return an array with [Z, X, Y] |
@author < >
2013,2014 Rodolphe Quiedeville
< a href=" / wiki / Slippy_map_tilenames"> / wiki / Slippy_map_tilenames</a >
-module(slippymap).
-export([deg2num/3]).
-export([num2deg/3,num2bbox/3]).
-export([tmstowms/1]).
-export([tile2lat/2,tile2lon/2]).
@doc Convert list_url DynVar to list of coord
tmstowms({_Pid, DynVars})->
Urls = lists:map(fun(Url)->
[Z, X, Y] = url_split(Url),
num2bbox(X, Y, Z)
end,
last_block(DynVars)),
lists:usort(Urls).
last_block(DynVars)->
case ts_dynvars:lookup(list_url, DynVars) of
{ok, Block} -> Block;
false -> ""
end.
@spec deg2num(Lat::float ( ) , : : float ( ) , Zoom::integer ( ) ) - > { integer ( ) , integer ( ) }
deg2num(Lat,Lon,Zoom)->
X = math:pow(2, Zoom) * ((Lon + 180) / 360),
Sec = 1 / math:cos(deg2rad(Lat)),
R = math:log(math:tan(deg2rad(Lat)) + Sec) / math:pi(),
Y = math:pow(2, Zoom) * (1 - R) / 2,
{round(X), round(Y)}.
( ) , Y::integer ( ) , Zoom::integer ( ) ) - > { float ( ) , float ( ) }
num2deg(X,Y,Zoom)->
{tile2lon(X, Zoom), tile2lat(Y, Zoom)}.
deg2rad(C)->
C * math:pi() / 180.
num2bbox(X,Y,Zoom)->
North = tile2lat(Y, Zoom),
South = tile2lat(Y + 1, Zoom),
West = tile2lon(X, Zoom),
East = tile2lon(X + 1, Zoom),
{West, South, East, North}.
tile2lat(Y, Z)->
N = math:pi() - ( 2.0 * math:pi() * Y) / math:pow(2, Z),
LatRad = math:atan(math:sinh(N)),
[Lat] = io_lib:format("~.8f", [LatRad * 180 / math:pi()]),
list_to_float(Lat).
tile2lon(X, Z)->
N = math:pow(2, Z),
[Lon] = io_lib:format("~.8f", [X / N * 360 - 180]),
list_to_float(Lon).
url_split(Url)->
lists:map(fun(X) ->
{Int, _} = string:to_integer(X),
Int
end,
split(Url)).
split(Url)->
Elmts = string:tokens(Url, "/"),
case length(Elmts) of
3 -> T=Elmts;
_ -> [_|T] = Elmts
end,
T.
|
ee03acdd89df5033c8d252e7d660a4be4541b377953e00e123bb40b6860cdcf7 | finnishtransportagency/harja | valikatselmukset.clj | (ns harja.palvelin.palvelut.kulut.valikatselmukset
(:require
[com.stuartsierra.component :as component]
[slingshot.slingshot :refer [throw+ try+]]
[taoensso.timbre :as log]
[specql.core :refer [columns]]
[harja.domain.kulut.valikatselmus :as valikatselmus]
[harja.domain.muokkaustiedot :as muokkaustiedot]
[harja.domain.oikeudet :as oikeudet]
[harja.domain.urakka :as urakka]
[harja.kyselyt.urakat :as q-urakat]
[harja.kyselyt.valikatselmus :as valikatselmus-q]
[harja.kyselyt.urakat :as urakat-q]
[harja.kyselyt.budjettisuunnittelu :as budjettisuunnittelu-q]
[harja.kyselyt.konversio :as konv]
[harja.kyselyt.toteumat :as toteumat-q]
[harja.kyselyt.sanktiot :as sanktiot-q]
[harja.kyselyt.laatupoikkeamat :as laatupoikkeamat-q]
[harja.kyselyt.erilliskustannus-kyselyt :as erilliskustannus-kyselyt]
[harja.palvelin.palvelut.lupaus.lupaus-palvelu :as lupaus-palvelu]
[harja.palvelin.palvelut.laadunseuranta :as laadunseuranta-palvelu]
[harja.palvelin.palvelut.toteumat :as toteumat-palvelu]
[harja.palvelin.komponentit.http-palvelin :refer [julkaise-palvelu poista-palvelut]]
[harja.pvm :as pvm]
[harja.domain.roolit :as roolit]
[harja.domain.lupaus-domain :as lupaus-domain]
[clojure.java.jdbc :as jdbc]
[harja.tyokalut.yleiset :refer [round2]]))
Ensimmäinen veikkaus siitä , milloin tavoitehinnan oikaisuja .
Tarkentuu myöhemmin . Huomaa , että .
(defn oikaisujen-sallittu-aikavali
"Rakennetaan sallittu aikaväli valitun hoitokauden perusteella"
[valittu-hoitokausi]
(let [hoitokauden-alkuvuosi (pvm/vuosi (first valittu-hoitokausi))
sallittu-viimeinen-vuosi (pvm/vuosi (second valittu-hoitokausi))]
Kuukausi - indexit on pielessä , niin tuo vaikuttaa hassulta
{:alkupvm (pvm/luo-pvm hoitokauden-alkuvuosi 8 1)
:loppupvm (pvm/luo-pvm sallittu-viimeinen-vuosi 11 31)}))
(defn sallitussa-aikavalissa?
"Tarkistaa onko päätöksen tekohetki hoitokauden sisällä tai muutama kuukausi sen yli"
[valittu-hoitokausi nykyhetki]
(let [sallittu-aikavali (oikaisujen-sallittu-aikavali valittu-hoitokausi)]
(pvm/valissa? nykyhetki (:alkupvm sallittu-aikavali) (:loppupvm sallittu-aikavali))))
(defn heita-virhe [viesti] (throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti viesti}}))
(defn tarkista-aikavali
"Tarkistaa, ollaanko kutsuhetkellä (nyt) tavoitehinnan oikaisujen tai päätösten teon sallitussa aikavälissä, eli
Suomen aikavyöhykkeellä syyskuun 1. päivän ja joulukuun viimeisen päivän välissä valitun hoitokauden aikana. Muulloin heittää virheen."
[urakka toimenpide kayttaja valittu-hoitokausi]
(let [nykyhetki (pvm/nyt)
toimenpide-teksti (case toimenpide
:paatos "Urakan päätöksiä"
:tavoitehinnan-oikaisu "Tavoitehinnan oikaisuja")
urakka-aktiivinen? (pvm/valissa? (pvm/nyt) (:alkupvm urakka) (:loppupvm urakka))
sallittu-aikavali (oikaisujen-sallittu-aikavali valittu-hoitokausi)
sallitussa-aikavalissa? (sallitussa-aikavalissa? valittu-hoitokausi nykyhetki)
jvh? (roolit/jvh? kayttaja)
MH urakoissa on pakko sallia muutokset vuosille 2019 ja 2020 , koska päätöksiä ei ole vuoden 2021 syksyä
näille urakoille tehdä , johtuen päätösten myöhäisestä valmistumisesta . 2023 vuoteen muutokset
;; sallimalla aikavälitarkistus.
viimeinen-poikkeusaika (pvm/->pvm "31.12.2022")
poikkeusvuosi? (and
(pvm/sama-tai-ennen? (pvm/nyt) viimeinen-poikkeusaika)
(lupaus-domain/urakka-19-20? urakka))]
(when-not (or jvh? urakka-aktiivinen? poikkeusvuosi?) (heita-virhe (str toimenpide-teksti " ei voi käsitellä urakka-ajan ulkopuolella")))
(when-not (or jvh? sallitussa-aikavalissa? poikkeusvuosi?)
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti (str toimenpide-teksti " saa käsitellä ainoastaan sallitulla aikavälillä.")}}))))
(defn tarkista-valikatselmusten-urakkatyyppi [urakka toimenpide]
(let [toimenpide-teksti (case toimenpide
:paatos "Urakan päätöksiä"
:tavoitehinnan-oikaisu "Tavoitehinnan oikaisuja"
:kattohinnan-oikaisu "Kattohinnan oikaisuja")]
(when-not (= "teiden-hoito" (:tyyppi urakka))
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti (str toimenpide-teksti " saa tehdä ainoastaan teiden hoitourakoille")}}))))
(defn tarkista-ei-siirtoa-viimeisena-vuotena [tiedot urakka]
(let [siirto (::valikatselmus/siirto tiedot)
siirto? (and (some? siirto)
(pos? siirto))
viimeinen-vuosi? (= (pvm/vuosi (:loppupvm urakka)) (pvm/vuosi (pvm/nyt)))]
(when (and siirto? viimeinen-vuosi?) (heita-virhe "Kattohinnan ylitystä ei voi siirtää ensi vuodelle urakan viimeisenä vuotena"))))
(defn tarkista-ei-siirtoa-tavoitehinnan-ylityksessa [tiedot]
(let [siirto (::valikatselmus/siirto tiedot)
siirto? (and (some? siirto)
(< 0 siirto))]
(when siirto? (heita-virhe "Tavoitehinnan ylitystä ei voi siirtää ensi vuodelle"))))
(defn tarkista-maksun-miinusmerkki-alituksessa [tiedot]
(let [urakoitsijan-maksu (or (::valikatselmus/urakoitsijan-maksu tiedot) 0)]
(when (pos? urakoitsijan-maksu)
(heita-virhe "Tavoitehinnan alituksessa urakoitsijan maksun täytyy olla miinusmerkkinen tai nolla"))))
(defn tarkista-tavoitehinnan-ylitys [{::valikatselmus/keys [tilaajan-maksu urakoitsijan-maksu] :as tiedot} tavoitehinta kattohinta]
ylitys ei tiettyä osaa
_ (when-not (and (number? tavoitehinta) (number? tilaajan-maksu) (number? urakoitsijan-maksu))
(heita-virhe "Tavoitehinnan ylityspäätös vaatii tavoitehinnan, tilaajan-maksun ja urajoitsijan-maksun."))
Pyöristetään , tulevat frontilta liukulukuina ,
;; Esim.
( + 18970.6678707 44264.8916983 ) ; ; = > 63235.559569000005
ylityksen-maksimimaara (round2 8 (- kattohinta tavoitehinta))
maksujen-osuus (round2 8 (+ tilaajan-maksu urakoitsijan-maksu))]
(do
Urakoitsijan maksut ja 10 % tavoitehinnasta , koska muuten maksetaan ylityksiä
(when (> maksujen-osuus ylityksen-maksimimaara)
(heita-virhe "Maksujen osuus suurempi, kuin tavoitehinnan ja kattohinnan erotus."))
siirto
(tarkista-ei-siirtoa-tavoitehinnan-ylityksessa tiedot))))
(defn tarkista-lupausbonus
"Varmista, että annettu bonus täsmää lupauksista saatavaan bonukseen"
[db kayttaja tiedot]
(let [urakan-tiedot (first (urakat-q/hae-urakka db {:id (::urakka/id tiedot)}))
urakan-alkuvuosi (pvm/vuosi (:alkupvm urakan-tiedot))
hakuparametrit {:urakka-id (::urakka/id tiedot)
:urakan-alkuvuosi urakan-alkuvuosi
:nykyhetki (pvm/nyt)
:valittu-hoitokausi [(pvm/luo-pvm (::valikatselmus/hoitokauden-alkuvuosi tiedot) 9 1)
(pvm/luo-pvm (inc (::valikatselmus/hoitokauden-alkuvuosi tiedot)) 8 30)]}
vanha-mhu? (lupaus-domain/urakka-19-20? urakan-tiedot)
lupaustiedot (if vanha-mhu?
(lupaus-palvelu/hae-kuukausittaiset-pisteet-hoitokaudelle db kayttaja hakuparametrit)
(lupaus-palvelu/hae-urakan-lupaustiedot-hoitokaudelle db hakuparametrit))
tilaajan-maksu (bigdec (::valikatselmus/tilaajan-maksu tiedot))
laskettu-bonus (bigdec (or (get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :bonus]) 0M))]
(cond (and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupausbonus)
, että bonus on annettu , jotta voidaan
(get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :bonus])
Varmistetaan , että lupauksissa laskettu bonus täsmää päätöksen bonukseen
(= laskettu-bonus tilaajan-maksu))
true
(and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupausbonus)
, että tavoite on täytetty , eli nolla case , jotta voidaan
(get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :tavoite-taytetty])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec 0) tilaajan-maksu))
true
:else
(do
(log/warn "Lupausbonuksen tilaajan maksun summa ei täsmää lupauksissa lasketun bonuksen kanssa.
Laskettu bonus: " laskettu-bonus " tilaajan maksu: " tilaajan-maksu)
(heita-virhe "Lupausbonuksen tilaajan maksun summa ei täsmää lupauksissa lasketun bonuksen kanssa.")))))
(defn tarkista-lupaussanktio
"Varmista, että tuleva sanktio täsmää lupauksista saatavaan sanktioon"
[db kayttaja tiedot]
(let [urakan-tiedot (first (urakat-q/hae-urakka db {:id (::urakka/id tiedot)}))
urakan-alkuvuosi (pvm/vuosi (:alkupvm urakan-tiedot))
hakuparametrit {:urakka-id (::urakka/id tiedot)
:urakan-alkuvuosi urakan-alkuvuosi
:nykyhetki (pvm/nyt)
:valittu-hoitokausi [(pvm/luo-pvm (::valikatselmus/hoitokauden-alkuvuosi tiedot) 9 1)
(pvm/luo-pvm (inc (::valikatselmus/hoitokauden-alkuvuosi tiedot)) 8 30)]}
Lupauksia käsitellään täysin eri tavalla riippuen urakan alkuvuodesta
lupaukset (if (lupaus-domain/vuosi-19-20? urakan-alkuvuosi)
(lupaus-palvelu/hae-kuukausittaiset-pisteet-hoitokaudelle db kayttaja hakuparametrit)
(lupaus-palvelu/hae-urakan-lupaustiedot-hoitokaudelle db hakuparametrit))]
(cond (and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupaussanktio)
, että sanktio on annettu , jotta voidaan
(get-in lupaukset [:yhteenveto :bonus-tai-sanktio :sanktio])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec (get-in lupaukset [:yhteenveto :bonus-tai-sanktio :sanktio])) (bigdec (::valikatselmus/urakoitsijan-maksu tiedot))))
true
(and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupaussanktio)
, että tavoite on täytetty , eli nolla case , jotta voidaan
(get-in lupaukset [:yhteenveto :bonus-tai-sanktio :tavoite-taytetty])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec 0) (bigdec (::valikatselmus/urakoitsijan-maksu tiedot))))
true
:else
(heita-virhe "Lupaussanktion urakoitsijan maksun summa ei täsmää lupauksissa lasketun sanktion kanssa."))))
(defn- poista-urakan-paatokset [db urakka-id hoitokauden-alkuvuosi kayttaja]
(let [paatokset (valikatselmus-q/hae-urakan-paatokset-hoitovuodelle db urakka-id hoitokauden-alkuvuosi)]
(doseq [paatos paatokset]
(cond
(and
(= (::valikatselmus/tyyppi paatos) "lupaussanktio")
(not (nil? (::valikatselmus/sanktio-id paatos))))
(laadunseuranta-palvelu/poista-suorasanktio db kayttaja {:id (::valikatselmus/sanktio-id paatos) :urakka-id urakka-id})
(and
(= (::valikatselmus/tyyppi paatos) "lupausbonus")
(not (nil? (:erilliskustannus_id paatos))))
(toteumat-palvelu/poista-erilliskustannus db kayttaja
{:id (::valikatselmus/erilliskustannus-id paatos) :urakka-id urakka-id})))
(valikatselmus-q/poista-paatokset db hoitokauden-alkuvuosi (:id kayttaja))))
(defn tarkista-kattohinnan-ylitys [tiedot urakka]
(do
(tarkista-ei-siirtoa-viimeisena-vuotena tiedot urakka)))
(defn tarkista-maksun-maara-alituksessa [db tiedot urakka tavoitehinta hoitokauden-alkuvuosi]
(let [maksu (- (::valikatselmus/urakoitsijan-maksu tiedot))
viimeinen-hoitokausi? (= (pvm/vuosi (:loppupvm urakka)) (inc hoitokauden-alkuvuosi))
maksimi-tavoitepalkkio (* valikatselmus/+maksimi-tavoitepalkkio-prosentti+ tavoitehinta)]
(when (and (not viimeinen-hoitokausi?) (> maksu maksimi-tavoitepalkkio))
(heita-virhe "Urakoitsijalle maksettava summa ei saa ylittää 3% tavoitehinnasta"))))
(defn tarkista-tavoitehinnan-alitus [db tiedot urakka tavoitehinta hoitokauden-alkuvuosi]
(do
(tarkista-maksun-miinusmerkki-alituksessa tiedot)
(tarkista-maksun-maara-alituksessa db tiedot urakka tavoitehinta hoitokauden-alkuvuosi)))
(defn alkuvuosi->hoitokausi [urakka hoitokauden-alkuvuosi]
(let [urakan-aloitusvuosi (pvm/vuosi (:alkupvm urakka))]
(inc (- hoitokauden-alkuvuosi urakan-aloitusvuosi))))
Tavoitehinnan oikaisuja tehdään loppuvuodesta .
Nämä summataan tai vähennetään .
(defn tallenna-tavoitehinnan-oikaisu [db kayttaja tiedot]
(log/debug "tallenna-tavoitehinnan-oikaisu :: tiedot" (pr-str tiedot))
(let [urakka-id (::urakka/id tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi tiedot)
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do (oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))
tiedot (select-keys tiedot (columns ::valikatselmus/tavoitehinnan-oikaisu))
oikaisu-specql (merge tiedot {::urakka/id urakka-id
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (or (::muokkaustiedot/luotu tiedot) (pvm/nyt))
::muokkaustiedot/muokattu (pvm/nyt)
::valikatselmus/summa (bigdec (::valikatselmus/summa tiedot))
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi})]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(if (::valikatselmus/oikaisun-id tiedot)
(valikatselmus-q/paivita-oikaisu db oikaisu-specql)
(valikatselmus-q/tee-oikaisu db oikaisu-specql))))
(defn poista-tavoitehinnan-oikaisu [db kayttaja {::valikatselmus/keys [oikaisun-id] :as tiedot}]
{:pre [(number? oikaisun-id)]}
(log/debug "poista-tavoitehinnan-oikaisu :: tiedot" (pr-str tiedot))
(let [oikaisu (valikatselmus-q/hae-oikaisu db oikaisun-id)
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi oikaisu)
urakka-id (::urakka/id oikaisu)
urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do (oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/poista-oikaisu db tiedot)))
(defn hae-tavoitehintojen-oikaisut [db kayttaja tiedot]
(oikeudet/vaadi-lukuoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu kayttaja (::urakka/id tiedot))
(let [urakka-id (::urakka/id tiedot)]
(assert (number? urakka-id) "Virhe urakan ID:ssä.")
(valikatselmus-q/hae-oikaisut db tiedot)))
(defn oikaistu-tavoitehinta-vuodelle [db urakka-id hoitokauden-alkuvuosi]
(:tavoitehinta-oikaistu
(budjettisuunnittelu-q/budjettitavoite-vuodelle db urakka-id hoitokauden-alkuvuosi)))
(defn tarkista-kattohinta-suurempi-kuin-tavoitehinta [db urakka-id hoitokauden-alkuvuosi uusi-kattohinta]
(let [oikaistu-tavoitehinta (oikaistu-tavoitehinta-vuodelle db urakka-id hoitokauden-alkuvuosi)]
(when-not oikaistu-tavoitehinta
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti "Oikaistua tavoitehintaa ei ole saatavilla, joten uutta kattohintaa ei voida asettaa"}}))
(when-not (>= uusi-kattohinta oikaistu-tavoitehinta)
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti "Kattohinnan täytyy olla suurempi kuin tavoitehinta"}}))))
loppuvuodesta 2019 - 2020 alkaneille urakoille .
.
(defn tallenna-kattohinnan-oikaisu
[db kayttaja {urakka-id ::urakka/id
hoitokauden-alkuvuosi ::valikatselmus/hoitokauden-alkuvuosi
uusi-kattohinta ::valikatselmus/uusi-kattohinta
:as tiedot}]
{:pre [(number? urakka-id) (pos-int? hoitokauden-alkuvuosi) (number? uusi-kattohinta) (pos? uusi-kattohinta)]}
(log/debug "tallenna-kattohinnan-oikaisu :: tiedot" (pr-str tiedot))
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(jdbc/with-db-transaction [db db]
(let [urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :kattohinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi)
(tarkista-kattohinta-suurempi-kuin-tavoitehinta db urakka-id hoitokauden-alkuvuosi uusi-kattohinta))
vanha-rivi (valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi)
oikaisu-specql (merge
vanha-rivi
{::urakka/id urakka-id
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (pvm/nyt)
::muokkaustiedot/muokattu (pvm/nyt)
::valikatselmus/uusi-kattohinta (bigdec uusi-kattohinta)
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi})]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(if (::valikatselmus/kattohinnan-oikaisun-id oikaisu-specql)
(do (valikatselmus-q/paivita-kattohinnan-oikaisu db oikaisu-specql)
(valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi))
(valikatselmus-q/tee-kattohinnan-oikaisu db oikaisu-specql)))))
(defn poista-kattohinnan-oikaisu [db kayttaja {hoitokauden-alkuvuosi ::valikatselmus/hoitokauden-alkuvuosi urakka-id ::urakka/id :as tiedot}]
{:pre [(number? urakka-id) (pos-int? hoitokauden-alkuvuosi)]}
(log/debug "poista-kattohinnan-oikaisu :: tiedot" (pr-str tiedot))
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(jdbc/with-db-transaction [db db]
(let [urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/poista-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi))))
(defn hae-kattohintojen-oikaisut [db _kayttaja tiedot]
(let [urakka-id (::urakka/id tiedot)]
(assert (number? urakka-id) "Virhe urakan ID:ssä.")
(valikatselmus-q/hae-kattohinnan-oikaisut db tiedot)))
(defn tee-paatoksen-tiedot [tiedot kayttaja hoitokauden-alkuvuosi erilliskustannus_id sanktio_id]
(merge tiedot {::valikatselmus/tyyppi (name (::valikatselmus/tyyppi tiedot))
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi
::valikatselmus/siirto (bigdec (or (::valikatselmus/siirto tiedot) 0))
::valikatselmus/urakoitsijan-maksu (bigdec (or (::valikatselmus/urakoitsijan-maksu tiedot) 0))
::valikatselmus/tilaajan-maksu (bigdec (or (::valikatselmus/tilaajan-maksu tiedot) 0))
::valikatselmus/erilliskustannus-id erilliskustannus_id
::valikatselmus/sanktio-id sanktio_id
::muokkaustiedot/poistettu? false
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (or (::muokkaustiedot/luotu tiedot) (pvm/nyt))
::muokkaustiedot/muokattu (or (::muokkaustiedot/muokattu tiedot) (pvm/nyt))}))
(defn hae-urakan-paatokset [db kayttaja tiedot]
(oikeudet/vaadi-lukuoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
(::urakka/id tiedot))
(valikatselmus-q/hae-urakan-paatokset db tiedot))
(defn- lupauksen-indeksi
"Lupausbonukselle ja -sanktiolle lisätään indeksi urakan tiedoista, mikäli ne on MH-urakoita ja alkavat vuonna -19 tai -20"
[urakan-tiedot]
(if (and
(= "teiden-hoito" (:tyyppi urakan-tiedot))
(or
(= (-> urakan-tiedot :alkupvm pvm/vuosi) 2020)
(= (-> urakan-tiedot :alkupvm pvm/vuosi) 2019)))
(:indeksi urakan-tiedot)
nil))
(defn- tallenna-lupaussanktio [db paatoksen-tiedot kayttaja]
(when (= ::valikatselmus/lupaussanktio (::valikatselmus/tyyppi paatoksen-tiedot))
(let [urakka-id (::urakka/id paatoksen-tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
toimenpideinstanssi-id (valikatselmus-q/hae-urakan-bonuksen-toimenpideinstanssi-id db urakka-id)
perustelu (str "Urakoitsija sai " (::valikatselmus/lupaus-toteutuneet-pisteet paatoksen-tiedot)
" pistettä ja lupasi " (::valikatselmus/lupaus-luvatut-pisteet paatoksen-tiedot) " pistettä.")
kohdistuspvm (konv/sql-date (pvm/luo-pvm-dec-kk (inc (::valikatselmus/hoitokauden-alkuvuosi paatoksen-tiedot)) 9 15))
" alkuvuodesta , indeksejä ei välttämättä / sanktioissa . MHU urakoissa 2021 niitä ei sidota indeksiin "
indeksi (lupauksen-indeksi urakka)
laatupoikkeama {:tekijanimi (:nimi kayttaja)
:paatos {:paatos "sanktio", :kasittelyaika (pvm/nyt), :perustelu perustelu, :kasittelytapa :valikatselmus}
:kohde nil
:aika kohdistuspvm
:urakka urakka-id
:yllapitokohde nil}
lupaussanktiotyyppi (first (sanktiot-q/hae-sanktiotyypin-tiedot-koodilla db {:koodit 0}))
sanktio {:kasittelyaika (pvm/nyt)
:suorasanktio true,
:laji :lupaussanktio,
:summa (::valikatselmus/urakoitsijan-maksu paatoksen-tiedot),
:toimenpideinstanssi toimenpideinstanssi-id,
:perintapvm kohdistuspvm
Lupaussanktion tyyppiä ei
:tyyppi lupaussanktiotyyppi
:indeksi indeksi}
Tallennus palauttaa sanktio - id : n
uusin-sanktio-id (laadunseuranta-palvelu/tallenna-suorasanktio db kayttaja sanktio laatupoikkeama urakka-id [nil nil])]
uusin-sanktio-id)))
(defn- tallenna-lupausbonus
"Lupauspäätöstä tallennettaessa voidaan tallentaa myös lupausbonus"
[db paatoksen-tiedot kayttaja]
(when (= ::valikatselmus/lupausbonus (::valikatselmus/tyyppi paatoksen-tiedot))
(let [urakka-id (::urakka/id paatoksen-tiedot)
urakan-tiedot (first (urakat-q/hae-urakka db urakka-id))
indeksin-nimi (lupauksen-indeksi urakan-tiedot)
toimenpideinstanssi-id (valikatselmus-q/hae-urakan-bonuksen-toimenpideinstanssi-id db urakka-id)
sopimus-id (:id (first (urakat-q/hae-urakan-sopimukset db urakka-id)))
laskutuspvm (konv/sql-date (pvm/luo-pvm-dec-kk (inc (::valikatselmus/hoitokauden-alkuvuosi paatoksen-tiedot)) 9 15))
lisatiedot (str "Urakoitsija sai " (::valikatselmus/lupaus-toteutuneet-pisteet paatoksen-tiedot)
" pistettä ja lupasi " (::valikatselmus/lupaus-luvatut-pisteet paatoksen-tiedot) " pistettä.")
ek {:tyyppi "lupausbonus"
:urakka urakka-id
:sopimus sopimus-id
:toimenpideinstanssi toimenpideinstanssi-id
:pvm laskutuspvm
:rahasumma (::valikatselmus/tilaajan-maksu paatoksen-tiedot)
:indeksin_nimi indeksin-nimi
:lisatieto lisatiedot
:laskutuskuukausi laskutuspvm
:kasittelytapa "valikatselmus"
:luoja (:id kayttaja)}
bonus (toteumat-q/luo-erilliskustannus<! db ek)]
(:id bonus))))
(defn tee-paatos-urakalle [db kayttaja tiedot]
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
(::urakka/id tiedot))
(log/debug "tee-paatos-urakalle :: tiedot" (pr-str tiedot))
(let [urakka-id (::urakka/id tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi tiedot)
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :paatos)
#_ (tarkista-aikavali urakka :paatos kayttaja valittu-hoitokausi))
paatoksen-tyyppi (::valikatselmus/tyyppi tiedot)
tavoitehinta (valikatselmus-q/hae-oikaistu-tavoitehinta db {:urakka-id urakka-id
:hoitokauden-alkuvuosi hoitokauden-alkuvuosi})
kattohinta (valikatselmus-q/hae-oikaistu-kattohinta db {:urakka-id urakka-id
:hoitokauden-alkuvuosi hoitokauden-alkuvuosi})
erilliskustannus_id (tallenna-lupausbonus db tiedot kayttaja)
sanktio_id (tallenna-lupaussanktio db tiedot kayttaja)]
(case paatoksen-tyyppi
::valikatselmus/tavoitehinnan-ylitys (tarkista-tavoitehinnan-ylitys tiedot tavoitehinta kattohinta)
::valikatselmus/kattohinnan-ylitys (tarkista-kattohinnan-ylitys tiedot urakka)
::valikatselmus/tavoitehinnan-alitus (tarkista-tavoitehinnan-alitus db tiedot urakka tavoitehinta hoitokauden-alkuvuosi)
::valikatselmus/lupausbonus (tarkista-lupausbonus db kayttaja tiedot)
::valikatselmus/lupaussanktio (tarkista-lupaussanktio db kayttaja tiedot))
(valikatselmus-q/tee-paatos db (tee-paatoksen-tiedot tiedot kayttaja hoitokauden-alkuvuosi erilliskustannus_id sanktio_id))))
(defn poista-paatos [db kayttaja {::valikatselmus/keys [paatoksen-id] :as tiedot}]
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu kayttaja (::urakka/id tiedot))
(log/debug "poista-lupaus-paatos :: tiedot" (pr-str tiedot))
(if (number? paatoksen-id)
Poista mahdollinen lupausbonus / lupaussanktio
paatos (first (valikatselmus-q/hae-paatos db paatoksen-id))
urakka-id (:urakka-id paatos)
Poista joko lupaussanktio tai lupausbonus täsmää
_ (cond
(and
(= (:tyyppi paatos) "lupaussanktio")
(not (nil? (:sanktio_id paatos))))
(laadunseuranta-palvelu/poista-suorasanktio db kayttaja {:id (:sanktio_id paatos) :urakka-id urakka-id})
(and
(= (:tyyppi paatos) "lupausbonus")
(not (nil? (:erilliskustannus_id paatos))))
(toteumat-palvelu/poista-erilliskustannus db kayttaja
{:id (:erilliskustannus_id paatos) :urakka-id urakka-id}))
vastaus (valikatselmus-q/poista-paatos db paatoksen-id)]
vastaus)
(heita-virhe "Päätöksen id puuttuu!")))
(defrecord Valikatselmukset []
component/Lifecycle
(start [this]
(let [http (:http-palvelin this)
db (:db this)]
(julkaise-palvelu http :tallenna-tavoitehinnan-oikaisu
(fn [user tiedot]
(tallenna-tavoitehinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-tavoitehintojen-oikaisut
(fn [user tiedot]
(hae-tavoitehintojen-oikaisut db user tiedot)))
(julkaise-palvelu http :poista-tavoitehinnan-oikaisu
(fn [user tiedot]
(poista-tavoitehinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :tallenna-kattohinnan-oikaisu
(fn [user tiedot]
(tallenna-kattohinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-kattohintojen-oikaisut
(fn [user tiedot]
(hae-kattohintojen-oikaisut db user tiedot)))
(julkaise-palvelu http :poista-kattohinnan-oikaisu
(fn [user tiedot]
(poista-kattohinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-urakan-paatokset
(fn [user tiedot]
(hae-urakan-paatokset db user tiedot)))
(julkaise-palvelu http :tallenna-urakan-paatos
(fn [user tiedot]
(tee-paatos-urakalle db user tiedot)))
(julkaise-palvelu http :poista-paatos
(fn [user tiedot]
(poista-paatos db user tiedot)))
this))
(stop [this]
(poista-palvelut (:http-palvelin this)
:tallenna-tavoitehinnan-oikaisu
:hae-tavoitehintojen-oikaisut
:poista-tavoitehinnan-oikaisu
:tallenna-kattohinnan-oikaisu
:hae-kattohintojen-oikaisut
:poista-kattohinnan-oikaisu
:hae-urakan-paatokset
:tallenna-urakan-paatos
:poista-paatos)
this))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/e54f1e98af6dfaad959cc915c93f63619ba4c4ed/src/clj/harja/palvelin/palvelut/kulut/valikatselmukset.clj | clojure | sallimalla aikavälitarkistus.
Esim.
; = > 63235.559569000005 | (ns harja.palvelin.palvelut.kulut.valikatselmukset
(:require
[com.stuartsierra.component :as component]
[slingshot.slingshot :refer [throw+ try+]]
[taoensso.timbre :as log]
[specql.core :refer [columns]]
[harja.domain.kulut.valikatselmus :as valikatselmus]
[harja.domain.muokkaustiedot :as muokkaustiedot]
[harja.domain.oikeudet :as oikeudet]
[harja.domain.urakka :as urakka]
[harja.kyselyt.urakat :as q-urakat]
[harja.kyselyt.valikatselmus :as valikatselmus-q]
[harja.kyselyt.urakat :as urakat-q]
[harja.kyselyt.budjettisuunnittelu :as budjettisuunnittelu-q]
[harja.kyselyt.konversio :as konv]
[harja.kyselyt.toteumat :as toteumat-q]
[harja.kyselyt.sanktiot :as sanktiot-q]
[harja.kyselyt.laatupoikkeamat :as laatupoikkeamat-q]
[harja.kyselyt.erilliskustannus-kyselyt :as erilliskustannus-kyselyt]
[harja.palvelin.palvelut.lupaus.lupaus-palvelu :as lupaus-palvelu]
[harja.palvelin.palvelut.laadunseuranta :as laadunseuranta-palvelu]
[harja.palvelin.palvelut.toteumat :as toteumat-palvelu]
[harja.palvelin.komponentit.http-palvelin :refer [julkaise-palvelu poista-palvelut]]
[harja.pvm :as pvm]
[harja.domain.roolit :as roolit]
[harja.domain.lupaus-domain :as lupaus-domain]
[clojure.java.jdbc :as jdbc]
[harja.tyokalut.yleiset :refer [round2]]))
Ensimmäinen veikkaus siitä , milloin tavoitehinnan oikaisuja .
Tarkentuu myöhemmin . Huomaa , että .
(defn oikaisujen-sallittu-aikavali
"Rakennetaan sallittu aikaväli valitun hoitokauden perusteella"
[valittu-hoitokausi]
(let [hoitokauden-alkuvuosi (pvm/vuosi (first valittu-hoitokausi))
sallittu-viimeinen-vuosi (pvm/vuosi (second valittu-hoitokausi))]
Kuukausi - indexit on pielessä , niin tuo vaikuttaa hassulta
{:alkupvm (pvm/luo-pvm hoitokauden-alkuvuosi 8 1)
:loppupvm (pvm/luo-pvm sallittu-viimeinen-vuosi 11 31)}))
(defn sallitussa-aikavalissa?
"Tarkistaa onko päätöksen tekohetki hoitokauden sisällä tai muutama kuukausi sen yli"
[valittu-hoitokausi nykyhetki]
(let [sallittu-aikavali (oikaisujen-sallittu-aikavali valittu-hoitokausi)]
(pvm/valissa? nykyhetki (:alkupvm sallittu-aikavali) (:loppupvm sallittu-aikavali))))
(defn heita-virhe [viesti] (throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti viesti}}))
(defn tarkista-aikavali
"Tarkistaa, ollaanko kutsuhetkellä (nyt) tavoitehinnan oikaisujen tai päätösten teon sallitussa aikavälissä, eli
Suomen aikavyöhykkeellä syyskuun 1. päivän ja joulukuun viimeisen päivän välissä valitun hoitokauden aikana. Muulloin heittää virheen."
[urakka toimenpide kayttaja valittu-hoitokausi]
(let [nykyhetki (pvm/nyt)
toimenpide-teksti (case toimenpide
:paatos "Urakan päätöksiä"
:tavoitehinnan-oikaisu "Tavoitehinnan oikaisuja")
urakka-aktiivinen? (pvm/valissa? (pvm/nyt) (:alkupvm urakka) (:loppupvm urakka))
sallittu-aikavali (oikaisujen-sallittu-aikavali valittu-hoitokausi)
sallitussa-aikavalissa? (sallitussa-aikavalissa? valittu-hoitokausi nykyhetki)
jvh? (roolit/jvh? kayttaja)
MH urakoissa on pakko sallia muutokset vuosille 2019 ja 2020 , koska päätöksiä ei ole vuoden 2021 syksyä
näille urakoille tehdä , johtuen päätösten myöhäisestä valmistumisesta . 2023 vuoteen muutokset
viimeinen-poikkeusaika (pvm/->pvm "31.12.2022")
poikkeusvuosi? (and
(pvm/sama-tai-ennen? (pvm/nyt) viimeinen-poikkeusaika)
(lupaus-domain/urakka-19-20? urakka))]
(when-not (or jvh? urakka-aktiivinen? poikkeusvuosi?) (heita-virhe (str toimenpide-teksti " ei voi käsitellä urakka-ajan ulkopuolella")))
(when-not (or jvh? sallitussa-aikavalissa? poikkeusvuosi?)
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti (str toimenpide-teksti " saa käsitellä ainoastaan sallitulla aikavälillä.")}}))))
(defn tarkista-valikatselmusten-urakkatyyppi [urakka toimenpide]
(let [toimenpide-teksti (case toimenpide
:paatos "Urakan päätöksiä"
:tavoitehinnan-oikaisu "Tavoitehinnan oikaisuja"
:kattohinnan-oikaisu "Kattohinnan oikaisuja")]
(when-not (= "teiden-hoito" (:tyyppi urakka))
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti (str toimenpide-teksti " saa tehdä ainoastaan teiden hoitourakoille")}}))))
(defn tarkista-ei-siirtoa-viimeisena-vuotena [tiedot urakka]
(let [siirto (::valikatselmus/siirto tiedot)
siirto? (and (some? siirto)
(pos? siirto))
viimeinen-vuosi? (= (pvm/vuosi (:loppupvm urakka)) (pvm/vuosi (pvm/nyt)))]
(when (and siirto? viimeinen-vuosi?) (heita-virhe "Kattohinnan ylitystä ei voi siirtää ensi vuodelle urakan viimeisenä vuotena"))))
(defn tarkista-ei-siirtoa-tavoitehinnan-ylityksessa [tiedot]
(let [siirto (::valikatselmus/siirto tiedot)
siirto? (and (some? siirto)
(< 0 siirto))]
(when siirto? (heita-virhe "Tavoitehinnan ylitystä ei voi siirtää ensi vuodelle"))))
(defn tarkista-maksun-miinusmerkki-alituksessa [tiedot]
(let [urakoitsijan-maksu (or (::valikatselmus/urakoitsijan-maksu tiedot) 0)]
(when (pos? urakoitsijan-maksu)
(heita-virhe "Tavoitehinnan alituksessa urakoitsijan maksun täytyy olla miinusmerkkinen tai nolla"))))
(defn tarkista-tavoitehinnan-ylitys [{::valikatselmus/keys [tilaajan-maksu urakoitsijan-maksu] :as tiedot} tavoitehinta kattohinta]
ylitys ei tiettyä osaa
_ (when-not (and (number? tavoitehinta) (number? tilaajan-maksu) (number? urakoitsijan-maksu))
(heita-virhe "Tavoitehinnan ylityspäätös vaatii tavoitehinnan, tilaajan-maksun ja urajoitsijan-maksun."))
Pyöristetään , tulevat frontilta liukulukuina ,
ylityksen-maksimimaara (round2 8 (- kattohinta tavoitehinta))
maksujen-osuus (round2 8 (+ tilaajan-maksu urakoitsijan-maksu))]
(do
Urakoitsijan maksut ja 10 % tavoitehinnasta , koska muuten maksetaan ylityksiä
(when (> maksujen-osuus ylityksen-maksimimaara)
(heita-virhe "Maksujen osuus suurempi, kuin tavoitehinnan ja kattohinnan erotus."))
siirto
(tarkista-ei-siirtoa-tavoitehinnan-ylityksessa tiedot))))
(defn tarkista-lupausbonus
"Varmista, että annettu bonus täsmää lupauksista saatavaan bonukseen"
[db kayttaja tiedot]
(let [urakan-tiedot (first (urakat-q/hae-urakka db {:id (::urakka/id tiedot)}))
urakan-alkuvuosi (pvm/vuosi (:alkupvm urakan-tiedot))
hakuparametrit {:urakka-id (::urakka/id tiedot)
:urakan-alkuvuosi urakan-alkuvuosi
:nykyhetki (pvm/nyt)
:valittu-hoitokausi [(pvm/luo-pvm (::valikatselmus/hoitokauden-alkuvuosi tiedot) 9 1)
(pvm/luo-pvm (inc (::valikatselmus/hoitokauden-alkuvuosi tiedot)) 8 30)]}
vanha-mhu? (lupaus-domain/urakka-19-20? urakan-tiedot)
lupaustiedot (if vanha-mhu?
(lupaus-palvelu/hae-kuukausittaiset-pisteet-hoitokaudelle db kayttaja hakuparametrit)
(lupaus-palvelu/hae-urakan-lupaustiedot-hoitokaudelle db hakuparametrit))
tilaajan-maksu (bigdec (::valikatselmus/tilaajan-maksu tiedot))
laskettu-bonus (bigdec (or (get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :bonus]) 0M))]
(cond (and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupausbonus)
, että bonus on annettu , jotta voidaan
(get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :bonus])
Varmistetaan , että lupauksissa laskettu bonus täsmää päätöksen bonukseen
(= laskettu-bonus tilaajan-maksu))
true
(and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupausbonus)
, että tavoite on täytetty , eli nolla case , jotta voidaan
(get-in lupaustiedot [:yhteenveto :bonus-tai-sanktio :tavoite-taytetty])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec 0) tilaajan-maksu))
true
:else
(do
(log/warn "Lupausbonuksen tilaajan maksun summa ei täsmää lupauksissa lasketun bonuksen kanssa.
Laskettu bonus: " laskettu-bonus " tilaajan maksu: " tilaajan-maksu)
(heita-virhe "Lupausbonuksen tilaajan maksun summa ei täsmää lupauksissa lasketun bonuksen kanssa.")))))
(defn tarkista-lupaussanktio
"Varmista, että tuleva sanktio täsmää lupauksista saatavaan sanktioon"
[db kayttaja tiedot]
(let [urakan-tiedot (first (urakat-q/hae-urakka db {:id (::urakka/id tiedot)}))
urakan-alkuvuosi (pvm/vuosi (:alkupvm urakan-tiedot))
hakuparametrit {:urakka-id (::urakka/id tiedot)
:urakan-alkuvuosi urakan-alkuvuosi
:nykyhetki (pvm/nyt)
:valittu-hoitokausi [(pvm/luo-pvm (::valikatselmus/hoitokauden-alkuvuosi tiedot) 9 1)
(pvm/luo-pvm (inc (::valikatselmus/hoitokauden-alkuvuosi tiedot)) 8 30)]}
Lupauksia käsitellään täysin eri tavalla riippuen urakan alkuvuodesta
lupaukset (if (lupaus-domain/vuosi-19-20? urakan-alkuvuosi)
(lupaus-palvelu/hae-kuukausittaiset-pisteet-hoitokaudelle db kayttaja hakuparametrit)
(lupaus-palvelu/hae-urakan-lupaustiedot-hoitokaudelle db hakuparametrit))]
(cond (and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupaussanktio)
, että sanktio on annettu , jotta voidaan
(get-in lupaukset [:yhteenveto :bonus-tai-sanktio :sanktio])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec (get-in lupaukset [:yhteenveto :bonus-tai-sanktio :sanktio])) (bigdec (::valikatselmus/urakoitsijan-maksu tiedot))))
true
(and
Varmistetaan , että
(= (::valikatselmus/tyyppi tiedot) ::valikatselmus/lupaussanktio)
, että tavoite on täytetty , eli nolla case , jotta voidaan
(get-in lupaukset [:yhteenveto :bonus-tai-sanktio :tavoite-taytetty])
Varmistetaan , että lupauksissa laskettu sanktio
(= (bigdec 0) (bigdec (::valikatselmus/urakoitsijan-maksu tiedot))))
true
:else
(heita-virhe "Lupaussanktion urakoitsijan maksun summa ei täsmää lupauksissa lasketun sanktion kanssa."))))
(defn- poista-urakan-paatokset [db urakka-id hoitokauden-alkuvuosi kayttaja]
(let [paatokset (valikatselmus-q/hae-urakan-paatokset-hoitovuodelle db urakka-id hoitokauden-alkuvuosi)]
(doseq [paatos paatokset]
(cond
(and
(= (::valikatselmus/tyyppi paatos) "lupaussanktio")
(not (nil? (::valikatselmus/sanktio-id paatos))))
(laadunseuranta-palvelu/poista-suorasanktio db kayttaja {:id (::valikatselmus/sanktio-id paatos) :urakka-id urakka-id})
(and
(= (::valikatselmus/tyyppi paatos) "lupausbonus")
(not (nil? (:erilliskustannus_id paatos))))
(toteumat-palvelu/poista-erilliskustannus db kayttaja
{:id (::valikatselmus/erilliskustannus-id paatos) :urakka-id urakka-id})))
(valikatselmus-q/poista-paatokset db hoitokauden-alkuvuosi (:id kayttaja))))
(defn tarkista-kattohinnan-ylitys [tiedot urakka]
(do
(tarkista-ei-siirtoa-viimeisena-vuotena tiedot urakka)))
(defn tarkista-maksun-maara-alituksessa [db tiedot urakka tavoitehinta hoitokauden-alkuvuosi]
(let [maksu (- (::valikatselmus/urakoitsijan-maksu tiedot))
viimeinen-hoitokausi? (= (pvm/vuosi (:loppupvm urakka)) (inc hoitokauden-alkuvuosi))
maksimi-tavoitepalkkio (* valikatselmus/+maksimi-tavoitepalkkio-prosentti+ tavoitehinta)]
(when (and (not viimeinen-hoitokausi?) (> maksu maksimi-tavoitepalkkio))
(heita-virhe "Urakoitsijalle maksettava summa ei saa ylittää 3% tavoitehinnasta"))))
(defn tarkista-tavoitehinnan-alitus [db tiedot urakka tavoitehinta hoitokauden-alkuvuosi]
(do
(tarkista-maksun-miinusmerkki-alituksessa tiedot)
(tarkista-maksun-maara-alituksessa db tiedot urakka tavoitehinta hoitokauden-alkuvuosi)))
(defn alkuvuosi->hoitokausi [urakka hoitokauden-alkuvuosi]
(let [urakan-aloitusvuosi (pvm/vuosi (:alkupvm urakka))]
(inc (- hoitokauden-alkuvuosi urakan-aloitusvuosi))))
Tavoitehinnan oikaisuja tehdään loppuvuodesta .
Nämä summataan tai vähennetään .
(defn tallenna-tavoitehinnan-oikaisu [db kayttaja tiedot]
(log/debug "tallenna-tavoitehinnan-oikaisu :: tiedot" (pr-str tiedot))
(let [urakka-id (::urakka/id tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi tiedot)
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do (oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))
tiedot (select-keys tiedot (columns ::valikatselmus/tavoitehinnan-oikaisu))
oikaisu-specql (merge tiedot {::urakka/id urakka-id
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (or (::muokkaustiedot/luotu tiedot) (pvm/nyt))
::muokkaustiedot/muokattu (pvm/nyt)
::valikatselmus/summa (bigdec (::valikatselmus/summa tiedot))
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi})]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(if (::valikatselmus/oikaisun-id tiedot)
(valikatselmus-q/paivita-oikaisu db oikaisu-specql)
(valikatselmus-q/tee-oikaisu db oikaisu-specql))))
(defn poista-tavoitehinnan-oikaisu [db kayttaja {::valikatselmus/keys [oikaisun-id] :as tiedot}]
{:pre [(number? oikaisun-id)]}
(log/debug "poista-tavoitehinnan-oikaisu :: tiedot" (pr-str tiedot))
(let [oikaisu (valikatselmus-q/hae-oikaisu db oikaisun-id)
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi oikaisu)
urakka-id (::urakka/id oikaisu)
urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do (oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/poista-oikaisu db tiedot)))
(defn hae-tavoitehintojen-oikaisut [db kayttaja tiedot]
(oikeudet/vaadi-lukuoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu kayttaja (::urakka/id tiedot))
(let [urakka-id (::urakka/id tiedot)]
(assert (number? urakka-id) "Virhe urakan ID:ssä.")
(valikatselmus-q/hae-oikaisut db tiedot)))
(defn oikaistu-tavoitehinta-vuodelle [db urakka-id hoitokauden-alkuvuosi]
(:tavoitehinta-oikaistu
(budjettisuunnittelu-q/budjettitavoite-vuodelle db urakka-id hoitokauden-alkuvuosi)))
(defn tarkista-kattohinta-suurempi-kuin-tavoitehinta [db urakka-id hoitokauden-alkuvuosi uusi-kattohinta]
(let [oikaistu-tavoitehinta (oikaistu-tavoitehinta-vuodelle db urakka-id hoitokauden-alkuvuosi)]
(when-not oikaistu-tavoitehinta
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti "Oikaistua tavoitehintaa ei ole saatavilla, joten uutta kattohintaa ei voida asettaa"}}))
(when-not (>= uusi-kattohinta oikaistu-tavoitehinta)
(throw+ {:type "Error"
:virheet {:koodi "ERROR" :viesti "Kattohinnan täytyy olla suurempi kuin tavoitehinta"}}))))
loppuvuodesta 2019 - 2020 alkaneille urakoille .
.
(defn tallenna-kattohinnan-oikaisu
[db kayttaja {urakka-id ::urakka/id
hoitokauden-alkuvuosi ::valikatselmus/hoitokauden-alkuvuosi
uusi-kattohinta ::valikatselmus/uusi-kattohinta
:as tiedot}]
{:pre [(number? urakka-id) (pos-int? hoitokauden-alkuvuosi) (number? uusi-kattohinta) (pos? uusi-kattohinta)]}
(log/debug "tallenna-kattohinnan-oikaisu :: tiedot" (pr-str tiedot))
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(jdbc/with-db-transaction [db db]
(let [urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :kattohinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi)
(tarkista-kattohinta-suurempi-kuin-tavoitehinta db urakka-id hoitokauden-alkuvuosi uusi-kattohinta))
vanha-rivi (valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi)
oikaisu-specql (merge
vanha-rivi
{::urakka/id urakka-id
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (pvm/nyt)
::muokkaustiedot/muokattu (pvm/nyt)
::valikatselmus/uusi-kattohinta (bigdec uusi-kattohinta)
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi})]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(if (::valikatselmus/kattohinnan-oikaisun-id oikaisu-specql)
(do (valikatselmus-q/paivita-kattohinnan-oikaisu db oikaisu-specql)
(valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi))
(valikatselmus-q/tee-kattohinnan-oikaisu db oikaisu-specql)))))
(defn poista-kattohinnan-oikaisu [db kayttaja {hoitokauden-alkuvuosi ::valikatselmus/hoitokauden-alkuvuosi urakka-id ::urakka/id :as tiedot}]
{:pre [(number? urakka-id) (pos-int? hoitokauden-alkuvuosi)]}
(log/debug "poista-kattohinnan-oikaisu :: tiedot" (pr-str tiedot))
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
urakka-id)
(jdbc/with-db-transaction [db db]
(let [urakka (first (q-urakat/hae-urakka db urakka-id))
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :tavoitehinnan-oikaisu)
#_ (tarkista-aikavali urakka :tavoitehinnan-oikaisu kayttaja valittu-hoitokausi))]
(poista-urakan-paatokset db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/poista-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi kayttaja)
(valikatselmus-q/hae-kattohinnan-oikaisu db urakka-id hoitokauden-alkuvuosi))))
(defn hae-kattohintojen-oikaisut [db _kayttaja tiedot]
(let [urakka-id (::urakka/id tiedot)]
(assert (number? urakka-id) "Virhe urakan ID:ssä.")
(valikatselmus-q/hae-kattohinnan-oikaisut db tiedot)))
(defn tee-paatoksen-tiedot [tiedot kayttaja hoitokauden-alkuvuosi erilliskustannus_id sanktio_id]
(merge tiedot {::valikatselmus/tyyppi (name (::valikatselmus/tyyppi tiedot))
::valikatselmus/hoitokauden-alkuvuosi hoitokauden-alkuvuosi
::valikatselmus/siirto (bigdec (or (::valikatselmus/siirto tiedot) 0))
::valikatselmus/urakoitsijan-maksu (bigdec (or (::valikatselmus/urakoitsijan-maksu tiedot) 0))
::valikatselmus/tilaajan-maksu (bigdec (or (::valikatselmus/tilaajan-maksu tiedot) 0))
::valikatselmus/erilliskustannus-id erilliskustannus_id
::valikatselmus/sanktio-id sanktio_id
::muokkaustiedot/poistettu? false
::muokkaustiedot/luoja-id (:id kayttaja)
::muokkaustiedot/muokkaaja-id (:id kayttaja)
::muokkaustiedot/luotu (or (::muokkaustiedot/luotu tiedot) (pvm/nyt))
::muokkaustiedot/muokattu (or (::muokkaustiedot/muokattu tiedot) (pvm/nyt))}))
(defn hae-urakan-paatokset [db kayttaja tiedot]
(oikeudet/vaadi-lukuoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
(::urakka/id tiedot))
(valikatselmus-q/hae-urakan-paatokset db tiedot))
(defn- lupauksen-indeksi
"Lupausbonukselle ja -sanktiolle lisätään indeksi urakan tiedoista, mikäli ne on MH-urakoita ja alkavat vuonna -19 tai -20"
[urakan-tiedot]
(if (and
(= "teiden-hoito" (:tyyppi urakan-tiedot))
(or
(= (-> urakan-tiedot :alkupvm pvm/vuosi) 2020)
(= (-> urakan-tiedot :alkupvm pvm/vuosi) 2019)))
(:indeksi urakan-tiedot)
nil))
(defn- tallenna-lupaussanktio [db paatoksen-tiedot kayttaja]
(when (= ::valikatselmus/lupaussanktio (::valikatselmus/tyyppi paatoksen-tiedot))
(let [urakka-id (::urakka/id paatoksen-tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
toimenpideinstanssi-id (valikatselmus-q/hae-urakan-bonuksen-toimenpideinstanssi-id db urakka-id)
perustelu (str "Urakoitsija sai " (::valikatselmus/lupaus-toteutuneet-pisteet paatoksen-tiedot)
" pistettä ja lupasi " (::valikatselmus/lupaus-luvatut-pisteet paatoksen-tiedot) " pistettä.")
kohdistuspvm (konv/sql-date (pvm/luo-pvm-dec-kk (inc (::valikatselmus/hoitokauden-alkuvuosi paatoksen-tiedot)) 9 15))
" alkuvuodesta , indeksejä ei välttämättä / sanktioissa . MHU urakoissa 2021 niitä ei sidota indeksiin "
indeksi (lupauksen-indeksi urakka)
laatupoikkeama {:tekijanimi (:nimi kayttaja)
:paatos {:paatos "sanktio", :kasittelyaika (pvm/nyt), :perustelu perustelu, :kasittelytapa :valikatselmus}
:kohde nil
:aika kohdistuspvm
:urakka urakka-id
:yllapitokohde nil}
lupaussanktiotyyppi (first (sanktiot-q/hae-sanktiotyypin-tiedot-koodilla db {:koodit 0}))
sanktio {:kasittelyaika (pvm/nyt)
:suorasanktio true,
:laji :lupaussanktio,
:summa (::valikatselmus/urakoitsijan-maksu paatoksen-tiedot),
:toimenpideinstanssi toimenpideinstanssi-id,
:perintapvm kohdistuspvm
Lupaussanktion tyyppiä ei
:tyyppi lupaussanktiotyyppi
:indeksi indeksi}
Tallennus palauttaa sanktio - id : n
uusin-sanktio-id (laadunseuranta-palvelu/tallenna-suorasanktio db kayttaja sanktio laatupoikkeama urakka-id [nil nil])]
uusin-sanktio-id)))
(defn- tallenna-lupausbonus
"Lupauspäätöstä tallennettaessa voidaan tallentaa myös lupausbonus"
[db paatoksen-tiedot kayttaja]
(when (= ::valikatselmus/lupausbonus (::valikatselmus/tyyppi paatoksen-tiedot))
(let [urakka-id (::urakka/id paatoksen-tiedot)
urakan-tiedot (first (urakat-q/hae-urakka db urakka-id))
indeksin-nimi (lupauksen-indeksi urakan-tiedot)
toimenpideinstanssi-id (valikatselmus-q/hae-urakan-bonuksen-toimenpideinstanssi-id db urakka-id)
sopimus-id (:id (first (urakat-q/hae-urakan-sopimukset db urakka-id)))
laskutuspvm (konv/sql-date (pvm/luo-pvm-dec-kk (inc (::valikatselmus/hoitokauden-alkuvuosi paatoksen-tiedot)) 9 15))
lisatiedot (str "Urakoitsija sai " (::valikatselmus/lupaus-toteutuneet-pisteet paatoksen-tiedot)
" pistettä ja lupasi " (::valikatselmus/lupaus-luvatut-pisteet paatoksen-tiedot) " pistettä.")
ek {:tyyppi "lupausbonus"
:urakka urakka-id
:sopimus sopimus-id
:toimenpideinstanssi toimenpideinstanssi-id
:pvm laskutuspvm
:rahasumma (::valikatselmus/tilaajan-maksu paatoksen-tiedot)
:indeksin_nimi indeksin-nimi
:lisatieto lisatiedot
:laskutuskuukausi laskutuspvm
:kasittelytapa "valikatselmus"
:luoja (:id kayttaja)}
bonus (toteumat-q/luo-erilliskustannus<! db ek)]
(:id bonus))))
(defn tee-paatos-urakalle [db kayttaja tiedot]
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu
kayttaja
(::urakka/id tiedot))
(log/debug "tee-paatos-urakalle :: tiedot" (pr-str tiedot))
(let [urakka-id (::urakka/id tiedot)
urakka (first (q-urakat/hae-urakka db urakka-id))
hoitokauden-alkuvuosi (::valikatselmus/hoitokauden-alkuvuosi tiedot)
valittu-hoitokausi [(pvm/hoitokauden-alkupvm hoitokauden-alkuvuosi)
(pvm/hoitokauden-loppupvm (inc hoitokauden-alkuvuosi))]
_ (do
(tarkista-valikatselmusten-urakkatyyppi urakka :paatos)
#_ (tarkista-aikavali urakka :paatos kayttaja valittu-hoitokausi))
paatoksen-tyyppi (::valikatselmus/tyyppi tiedot)
tavoitehinta (valikatselmus-q/hae-oikaistu-tavoitehinta db {:urakka-id urakka-id
:hoitokauden-alkuvuosi hoitokauden-alkuvuosi})
kattohinta (valikatselmus-q/hae-oikaistu-kattohinta db {:urakka-id urakka-id
:hoitokauden-alkuvuosi hoitokauden-alkuvuosi})
erilliskustannus_id (tallenna-lupausbonus db tiedot kayttaja)
sanktio_id (tallenna-lupaussanktio db tiedot kayttaja)]
(case paatoksen-tyyppi
::valikatselmus/tavoitehinnan-ylitys (tarkista-tavoitehinnan-ylitys tiedot tavoitehinta kattohinta)
::valikatselmus/kattohinnan-ylitys (tarkista-kattohinnan-ylitys tiedot urakka)
::valikatselmus/tavoitehinnan-alitus (tarkista-tavoitehinnan-alitus db tiedot urakka tavoitehinta hoitokauden-alkuvuosi)
::valikatselmus/lupausbonus (tarkista-lupausbonus db kayttaja tiedot)
::valikatselmus/lupaussanktio (tarkista-lupaussanktio db kayttaja tiedot))
(valikatselmus-q/tee-paatos db (tee-paatoksen-tiedot tiedot kayttaja hoitokauden-alkuvuosi erilliskustannus_id sanktio_id))))
(defn poista-paatos [db kayttaja {::valikatselmus/keys [paatoksen-id] :as tiedot}]
(oikeudet/vaadi-kirjoitusoikeus oikeudet/urakat-suunnittelu-kustannussuunnittelu kayttaja (::urakka/id tiedot))
(log/debug "poista-lupaus-paatos :: tiedot" (pr-str tiedot))
(if (number? paatoksen-id)
Poista mahdollinen lupausbonus / lupaussanktio
paatos (first (valikatselmus-q/hae-paatos db paatoksen-id))
urakka-id (:urakka-id paatos)
Poista joko lupaussanktio tai lupausbonus täsmää
_ (cond
(and
(= (:tyyppi paatos) "lupaussanktio")
(not (nil? (:sanktio_id paatos))))
(laadunseuranta-palvelu/poista-suorasanktio db kayttaja {:id (:sanktio_id paatos) :urakka-id urakka-id})
(and
(= (:tyyppi paatos) "lupausbonus")
(not (nil? (:erilliskustannus_id paatos))))
(toteumat-palvelu/poista-erilliskustannus db kayttaja
{:id (:erilliskustannus_id paatos) :urakka-id urakka-id}))
vastaus (valikatselmus-q/poista-paatos db paatoksen-id)]
vastaus)
(heita-virhe "Päätöksen id puuttuu!")))
(defrecord Valikatselmukset []
component/Lifecycle
(start [this]
(let [http (:http-palvelin this)
db (:db this)]
(julkaise-palvelu http :tallenna-tavoitehinnan-oikaisu
(fn [user tiedot]
(tallenna-tavoitehinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-tavoitehintojen-oikaisut
(fn [user tiedot]
(hae-tavoitehintojen-oikaisut db user tiedot)))
(julkaise-palvelu http :poista-tavoitehinnan-oikaisu
(fn [user tiedot]
(poista-tavoitehinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :tallenna-kattohinnan-oikaisu
(fn [user tiedot]
(tallenna-kattohinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-kattohintojen-oikaisut
(fn [user tiedot]
(hae-kattohintojen-oikaisut db user tiedot)))
(julkaise-palvelu http :poista-kattohinnan-oikaisu
(fn [user tiedot]
(poista-kattohinnan-oikaisu db user tiedot)))
(julkaise-palvelu http :hae-urakan-paatokset
(fn [user tiedot]
(hae-urakan-paatokset db user tiedot)))
(julkaise-palvelu http :tallenna-urakan-paatos
(fn [user tiedot]
(tee-paatos-urakalle db user tiedot)))
(julkaise-palvelu http :poista-paatos
(fn [user tiedot]
(poista-paatos db user tiedot)))
this))
(stop [this]
(poista-palvelut (:http-palvelin this)
:tallenna-tavoitehinnan-oikaisu
:hae-tavoitehintojen-oikaisut
:poista-tavoitehinnan-oikaisu
:tallenna-kattohinnan-oikaisu
:hae-kattohintojen-oikaisut
:poista-kattohinnan-oikaisu
:hae-urakan-paatokset
:tallenna-urakan-paatos
:poista-paatos)
this))
|
f1a2ace98da3633b33a4481bb686b7508c7670b66229a748a819733bf1a95b4c | hanshuebner/vlm | sysdcl.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : SCT ; Base : 10 ; Lowercase : Yes -*-
(defsystem Alpha-AXP-Assembler
(:pretty-name "Alpha AXP Assembler"
:default-pathname "VLM:ASSEMBLER;")
(:serial
"alphapckg"
"alphadsdl"
"alpha"
"sct-support"))
(defsystem POWERPC-Assembler
(:pretty-name "PowerPC Assembler"
:default-pathname "VLM:ASSEMBLER;")
(:serial
"powerpckg"
"powerdsdl"
"power"
"power-sct-support"))
| null | https://raw.githubusercontent.com/hanshuebner/vlm/20510ddc98b52252a406012a50a4d3bbd1b75dd0/assembler/sysdcl.lisp | lisp | Syntax : Common - Lisp ; Package : SCT ; Base : 10 ; Lowercase : Yes -*- |
(defsystem Alpha-AXP-Assembler
(:pretty-name "Alpha AXP Assembler"
:default-pathname "VLM:ASSEMBLER;")
(:serial
"alphapckg"
"alphadsdl"
"alpha"
"sct-support"))
(defsystem POWERPC-Assembler
(:pretty-name "PowerPC Assembler"
:default-pathname "VLM:ASSEMBLER;")
(:serial
"powerpckg"
"powerdsdl"
"power"
"power-sct-support"))
|
13c1bdadd55d7c43c68ffe062e9ceb1e42ab4bb7ad34cc4087e739b23d63e428 | emezeske/lein-cljsbuild | config.clj | (ns leiningen.cljsbuild.config
"Utilities for parsing the cljsbuild config."
(:require
[clojure.pprint :as pprint]
[leiningen.cljsbuild.util :as util]))
(defn in-target-path [target-path subpath]
(str target-path "/cljsbuild-" subpath))
(defn- compiler-output-dir-base [target-path]
(in-target-path target-path "compiler-"))
(def compiler-global-dirs
{:libs "closure-js/libs"
:externs "closure-js/externs"})
(defn- default-global-options [target-path]
{:repl-launch-commands {}
:repl-listen-port 9000
:test-commands {}
:crossover-path (in-target-path target-path "crossover")
:crossover-jar false
:crossovers []})
(defn- default-compiler-options [target-path]
{:externs []
:libs []})
(defn- default-build-options [target-path]
{:source-paths ["src-cljs"]
:jar false
:notify-command nil
:incremental true
:assert true
:compiler (default-compiler-options target-path)})
(defn convert-builds-map [options]
(update-in options [:builds]
#(if (map? %)
(for [[id build] %]
(assoc build :id (name id)))
%)))
(defn- backwards-compat-builds [options]
(cond
(and (map? options) (some #{:compiler :source-path :source-paths} (keys options)))
{:builds [options]}
(vector? options)
{:builds options}
:else
options))
(defn- backwards-compat-source-path [{:keys [builds] :as options}]
(assoc options :builds
(for [build builds]
(if-let [source-path (:source-path build)]
(dissoc
(assoc build :source-paths
(vec (concat (:source-paths build) [source-path])))
:source-path)
build))))
(defn- backwards-compat-crossovers [{:keys [builds crossovers] :as options}]
(let [all-crossovers (->> builds
(mapcat :crossovers)
(concat crossovers)
(distinct)
(vec))
no-crossovers (assoc options
:builds (vec (map #(dissoc % :crossovers) builds)))]
(if (empty? all-crossovers)
no-crossovers
(assoc no-crossovers
:crossovers all-crossovers))))
(defn backwards-compat [options]
(-> options
backwards-compat-builds
backwards-compat-source-path
backwards-compat-crossovers))
(defn- warn-deprecated [options]
(letfn [(delim [] (println (apply str (take 80 (repeat "-")))))]
(delim)
(println
(str
"WARNING: your :cljsbuild configuration is in a deprecated format. It has been\n"
"automatically converted it to the new format, which will be printed below.\n"
"It is recommended that you update your :cljsbuild configuration ASAP."))
(delim)
(println ":cljsbuild")
(pprint/pprint options)
(delim)
(println
(str
"See -cljsbuild/blob/master/README.md\n"
"for details on the new format."))
(delim)
options))
(declare deep-merge-item)
(defn- deep-merge [& ms]
(apply merge-with deep-merge-item ms))
(defn- deep-merge-item [a b]
(if (and (map? a) (map? b))
(deep-merge a b)
b))
(defn set-default-build-options [target-path options]
(let [options (deep-merge (default-build-options target-path) options)]
(if (or (get-in options [:compiler :output-to])
(get-in options [:compiler :modules]))
options
(assoc-in options [:compiler :output-to] (in-target-path target-path "main.js")))))
(defn- set-default-output-dirs [target-path options]
(let [output-dir-key [:compiler :output-dir]
relative-target-path (when target-path
(util/relative-path (util/get-working-dir) target-path))
builds
(for [[build counter] (map vector (:builds options) (range))]
(if (get-in build output-dir-key)
build
(assoc-in build output-dir-key
(str (compiler-output-dir-base relative-target-path) counter))))]
(if (or (empty? builds)
(apply distinct? (map #(get-in % output-dir-key) builds)))
(assoc options :builds builds)
(throw (Exception. (str "All " output-dir-key " options must be distinct."))))))
(defn set-default-options [target-path options]
(set-default-output-dirs target-path
(deep-merge (default-global-options target-path)
(assoc options :builds
(map #(set-default-build-options target-path %) (:builds options))))))
(defn set-build-global-dirs [build]
(reduce (fn [build [k v]] (update-in build [:compiler k] conj v))
build
compiler-global-dirs))
(defn set-compiler-global-dirs [options]
(assoc options :builds
(map set-build-global-dirs (:builds options))))
(defn- normalize-options
"Sets default options and accounts for backwards compatibility."
[target-path options]
(let [convert (convert-builds-map options)
compat (backwards-compat convert)]
(when (and options (not= convert compat))
(warn-deprecated compat))
(->> compat
(set-default-options target-path)
set-compiler-global-dirs)))
(defn parse-shell-command [raw]
(let [[shell tail] (split-with (comp not keyword?) raw)
options (apply hash-map tail)]
(merge {:shell shell} options)))
(defn parse-notify-command [build]
(assoc build :parsed-notify-command
(parse-shell-command (:notify-command build))))
(defn warn-unsupported-warn-on-undeclared [build]
(when (contains? build :warn-on-undeclared)
(println "WARNING: the :warn-on-undeclared option is no longer available.")
(println "Set \":warnings true\" in your :compiler options instead.")))
(defn warn-unsupported-notify-command [build]
(when (or (first (filter #(= "%" %) (:shell (:parsed-notify-command build))))
(:beep (:parsed-notify-command build)))
(println "WARNING: the :notify-command option no longer accepts the \"%\" or :beep options.")
(println "See -cljsbuild/blob/master/doc/RELEASE-NOTES.md for details.")))
(defn extract-options
"Given a project, returns a seq of cljsbuild option maps."
[project]
(when (nil? (:cljsbuild project))
(println "WARNING: no :cljsbuild entry found in" (:name project) "project definition."))
(let [raw-options (:cljsbuild project)]
(normalize-options (:target-path project) raw-options)))
| null | https://raw.githubusercontent.com/emezeske/lein-cljsbuild/089193c74e362c143d30dfca21a21e95c7ca112a/plugin/src/leiningen/cljsbuild/config.clj | clojure | (ns leiningen.cljsbuild.config
"Utilities for parsing the cljsbuild config."
(:require
[clojure.pprint :as pprint]
[leiningen.cljsbuild.util :as util]))
(defn in-target-path [target-path subpath]
(str target-path "/cljsbuild-" subpath))
(defn- compiler-output-dir-base [target-path]
(in-target-path target-path "compiler-"))
(def compiler-global-dirs
{:libs "closure-js/libs"
:externs "closure-js/externs"})
(defn- default-global-options [target-path]
{:repl-launch-commands {}
:repl-listen-port 9000
:test-commands {}
:crossover-path (in-target-path target-path "crossover")
:crossover-jar false
:crossovers []})
(defn- default-compiler-options [target-path]
{:externs []
:libs []})
(defn- default-build-options [target-path]
{:source-paths ["src-cljs"]
:jar false
:notify-command nil
:incremental true
:assert true
:compiler (default-compiler-options target-path)})
(defn convert-builds-map [options]
(update-in options [:builds]
#(if (map? %)
(for [[id build] %]
(assoc build :id (name id)))
%)))
(defn- backwards-compat-builds [options]
(cond
(and (map? options) (some #{:compiler :source-path :source-paths} (keys options)))
{:builds [options]}
(vector? options)
{:builds options}
:else
options))
(defn- backwards-compat-source-path [{:keys [builds] :as options}]
(assoc options :builds
(for [build builds]
(if-let [source-path (:source-path build)]
(dissoc
(assoc build :source-paths
(vec (concat (:source-paths build) [source-path])))
:source-path)
build))))
(defn- backwards-compat-crossovers [{:keys [builds crossovers] :as options}]
(let [all-crossovers (->> builds
(mapcat :crossovers)
(concat crossovers)
(distinct)
(vec))
no-crossovers (assoc options
:builds (vec (map #(dissoc % :crossovers) builds)))]
(if (empty? all-crossovers)
no-crossovers
(assoc no-crossovers
:crossovers all-crossovers))))
(defn backwards-compat [options]
(-> options
backwards-compat-builds
backwards-compat-source-path
backwards-compat-crossovers))
(defn- warn-deprecated [options]
(letfn [(delim [] (println (apply str (take 80 (repeat "-")))))]
(delim)
(println
(str
"WARNING: your :cljsbuild configuration is in a deprecated format. It has been\n"
"automatically converted it to the new format, which will be printed below.\n"
"It is recommended that you update your :cljsbuild configuration ASAP."))
(delim)
(println ":cljsbuild")
(pprint/pprint options)
(delim)
(println
(str
"See -cljsbuild/blob/master/README.md\n"
"for details on the new format."))
(delim)
options))
(declare deep-merge-item)
(defn- deep-merge [& ms]
(apply merge-with deep-merge-item ms))
(defn- deep-merge-item [a b]
(if (and (map? a) (map? b))
(deep-merge a b)
b))
(defn set-default-build-options [target-path options]
(let [options (deep-merge (default-build-options target-path) options)]
(if (or (get-in options [:compiler :output-to])
(get-in options [:compiler :modules]))
options
(assoc-in options [:compiler :output-to] (in-target-path target-path "main.js")))))
(defn- set-default-output-dirs [target-path options]
(let [output-dir-key [:compiler :output-dir]
relative-target-path (when target-path
(util/relative-path (util/get-working-dir) target-path))
builds
(for [[build counter] (map vector (:builds options) (range))]
(if (get-in build output-dir-key)
build
(assoc-in build output-dir-key
(str (compiler-output-dir-base relative-target-path) counter))))]
(if (or (empty? builds)
(apply distinct? (map #(get-in % output-dir-key) builds)))
(assoc options :builds builds)
(throw (Exception. (str "All " output-dir-key " options must be distinct."))))))
(defn set-default-options [target-path options]
(set-default-output-dirs target-path
(deep-merge (default-global-options target-path)
(assoc options :builds
(map #(set-default-build-options target-path %) (:builds options))))))
(defn set-build-global-dirs [build]
(reduce (fn [build [k v]] (update-in build [:compiler k] conj v))
build
compiler-global-dirs))
(defn set-compiler-global-dirs [options]
(assoc options :builds
(map set-build-global-dirs (:builds options))))
(defn- normalize-options
"Sets default options and accounts for backwards compatibility."
[target-path options]
(let [convert (convert-builds-map options)
compat (backwards-compat convert)]
(when (and options (not= convert compat))
(warn-deprecated compat))
(->> compat
(set-default-options target-path)
set-compiler-global-dirs)))
(defn parse-shell-command [raw]
(let [[shell tail] (split-with (comp not keyword?) raw)
options (apply hash-map tail)]
(merge {:shell shell} options)))
(defn parse-notify-command [build]
(assoc build :parsed-notify-command
(parse-shell-command (:notify-command build))))
(defn warn-unsupported-warn-on-undeclared [build]
(when (contains? build :warn-on-undeclared)
(println "WARNING: the :warn-on-undeclared option is no longer available.")
(println "Set \":warnings true\" in your :compiler options instead.")))
(defn warn-unsupported-notify-command [build]
(when (or (first (filter #(= "%" %) (:shell (:parsed-notify-command build))))
(:beep (:parsed-notify-command build)))
(println "WARNING: the :notify-command option no longer accepts the \"%\" or :beep options.")
(println "See -cljsbuild/blob/master/doc/RELEASE-NOTES.md for details.")))
(defn extract-options
"Given a project, returns a seq of cljsbuild option maps."
[project]
(when (nil? (:cljsbuild project))
(println "WARNING: no :cljsbuild entry found in" (:name project) "project definition."))
(let [raw-options (:cljsbuild project)]
(normalize-options (:target-path project) raw-options)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.