_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
a799626dee7be3976bdb5e0cac4da50ee79b79d9cf1091e8eb97806346ec068b
babashka/nbb
example.cljs
;; This script demonstrates use of tinyhttp with a logging middleware (ns example (:require ["@tinyhttp/app" :as app] ["@tinyhttp/logger" :as logger])) (def app (app/App.)) (-> app (.use (logger/logger)) (.get "/" (fn [_req res] (.send res "<h1>Hello world</h1>"))) (.get "/page/:page/" (fn [req res] (-> res (.status 200) (.send (apply str [(str "<h1>" "What a cool page" "</h1>") (str "<h2>Path</h2>") (str "<pre>" (.-path req) "</pre>") (str "<h2>Params</h2>") (str "<pre>" (js/JSON.stringify (.-params req) nil 2) "</pre>")]) )))) (.listen 3000 (fn [] (js/console.log "Listening on :3000"))))
null
https://raw.githubusercontent.com/babashka/nbb/10ea0d40c3e0963888683a4935c94eb02a643a93/examples/tinyhttp/example.cljs
clojure
This script demonstrates use of tinyhttp with a logging middleware
(ns example (:require ["@tinyhttp/app" :as app] ["@tinyhttp/logger" :as logger])) (def app (app/App.)) (-> app (.use (logger/logger)) (.get "/" (fn [_req res] (.send res "<h1>Hello world</h1>"))) (.get "/page/:page/" (fn [req res] (-> res (.status 200) (.send (apply str [(str "<h1>" "What a cool page" "</h1>") (str "<h2>Path</h2>") (str "<pre>" (.-path req) "</pre>") (str "<h2>Params</h2>") (str "<pre>" (js/JSON.stringify (.-params req) nil 2) "</pre>")]) )))) (.listen 3000 (fn [] (js/console.log "Listening on :3000"))))
e0e29da98b82423394e03728eeb3976de8ae76e766edddd416d726d224118a1c
esl/MongooseIM
accounts_SUITE.erl
-module(accounts_SUITE). -compile([export_all, nowarn_export_all]). -include_lib("escalus/include/escalus.hrl"). -include_lib("escalus/include/escalus_xmlns.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("exml/include/exml.hrl"). -import(distributed_helper, [mim/0, require_rpc_nodes/1, rpc/4]). -import(mongoose_helper, [wait_for_user/3]). -import(domain_helper, [domain/0, host_type/0]). %%-------------------------------------------------------------------- %% Suite configuration %%-------------------------------------------------------------------- -define(REGISTRATION_TIMEOUT, 2). %% seconds all() -> [ {group, register}, {group, registration_watchers}, {group, bad_registration}, {group, bad_cancelation}, {group, registration_timeout}, {group, change_account_details}, {group, change_account_details_store_plain}, {group, utilities} ]. groups() -> [{register, [parallel], [register, already_registered, registration_conflict, check_unregistered]}, {registration_watchers, [sequence], [admin_notify]}, {bad_registration, [sequence], [null_password]}, {bad_cancelation, [sequence], [bad_request_registration_cancelation, not_allowed_registration_cancelation]}, {registration_timeout, [sequence], [registration_timeout, registration_failure_timeout]}, {change_account_details, [parallel], change_password_tests()}, {change_account_details_store_plain, [parallel], change_password_tests()}, {utilities, [{group, user_info}, {group, users_number_estimate}]}, {user_info, [parallel], [list_users, list_selected_users, count_users, count_selected_users]}, {users_number_estimate, [], [count_users_estimate]} ]. suite() -> require_rpc_nodes([mim]) ++ escalus:suite(). change_password_tests() -> [change_password, change_password_to_null]. %%-------------------------------------------------------------------- Init & teardown %%-------------------------------------------------------------------- init_per_suite(Config1) -> ok = dynamic_modules:ensure_modules(host_type(), required_modules()), Config2 = [{mod_register_options, mod_register_options()} | Config1], escalus:init_per_suite([{escalus_user_db, xmpp} | Config2]). end_per_suite(Config) -> escalus_fresh:clean(), escalus:end_per_suite(Config). required_modules() -> [{mod_register, mod_register_options()}]. mod_register_options() -> config_parser_helper:mod_config(mod_register, #{ip_access => [{allow, "127.0.0.0/8"}, {deny, "0.0.0.0/0"}], access => register}). init_per_group(bad_cancelation, Config) -> escalus:create_users(Config, escalus:get_users([alice])); init_per_group(change_account_details, Config) -> [{escalus_user_db, {module, escalus_ejabberd}} |Config]; init_per_group(change_account_details_store_plain, Config) -> AuthOpts = mongoose_helper:auth_opts_with_password_format(plain), Config1 = mongoose_helper:backup_and_set_config_option(Config, auth, AuthOpts), [{escalus_user_db, {module, escalus_ejabberd}} |Config1]; init_per_group(registration_timeout, Config) -> set_registration_timeout(Config); init_per_group(utilities, Config) -> escalus:create_users(Config, escalus:get_users([alice, bob])); init_per_group(users_number_estimate, Config) -> AuthOpts = get_auth_opts(), NewAuthOpts = AuthOpts#{rdbms => #{users_number_estimate => true}}, set_auth_opts(Config, NewAuthOpts); init_per_group(_GroupName, Config) -> Config. end_per_group(change_account_details, Config) -> escalus_fresh:clean(), [{escalus_user_db, xmpp} | Config]; end_per_group(change_account_details_store_plain, Config) -> escalus_fresh:clean(), mongoose_helper:restore_config(Config), [{escalus_user_db, xmpp} | Config]; end_per_group(bad_cancelation, Config) -> escalus:delete_users(Config, escalus:get_users([alice])); end_per_group(registration_timeout, Config) -> restore_registration_timeout(Config); end_per_group(utilities, Config) -> escalus:delete_users(Config, escalus:get_users([alice, bob])); end_per_group(users_number_estimate, Config) -> mongoose_helper:restore_config(Config); end_per_group(_GroupName, Config) -> Config. get_auth_opts() -> rpc(mim(), mongoose_config, get_opt, [{auth, host_type()}]). set_auth_opts(Config, AuthOpts) -> rpc(mim(), ejabberd_auth, stop, [host_type()]), Config1 = mongoose_helper:backup_and_set_config_option(Config, {auth, host_type()}, AuthOpts), rpc(mim(), ejabberd_auth, start, [host_type()]), Config1. init_per_testcase(admin_notify, Config) -> [{_, AdminSpec}] = escalus_users:get_users([admin]), [AdminU, AdminS, _AdminP] = escalus_users:get_usp(Config, AdminSpec), AdminJid = <<AdminU/binary, "@", AdminS/binary>>, enable_watcher(Config, AdminJid), escalus:init_per_testcase(admin_notify, Config); init_per_testcase(not_allowed_registration_cancelation, Config) -> %% Use a configuration that will not allow inband cancelation (and registration). reload_mod_register_option(Config, access, none), escalus:init_per_testcase(not_allowed_registration_cancelation, Config); init_per_testcase(registration_failure_timeout, Config) -> Config1 = deny_everyone_registration(Config), escalus:init_per_testcase(registration_failure_timeout, Config1); init_per_testcase(CaseName, Config) when CaseName =:= list_selected_users; CaseName =:= count_selected_users -> case mongoose_helper:auth_modules() of [Mod | _] when Mod =:= ejabberd_auth_rdbms; Mod =:= ejabberd_auth_internal -> escalus:init_per_testcase(CaseName, Config); Modules -> {skip, {"Queries for selected users not supported", Modules}} end; init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(register, Config) -> escalus:end_per_testcase(register, Config); end_per_testcase(admin_notify, Config) -> disable_watcher(Config), escalus:delete_users(Config, escalus:get_users([alice, bob, admin])), escalus:end_per_testcase(admin_notify, Config); end_per_testcase(registration_conflict, Config) -> escalus_users:delete_users(Config, escalus:get_users([alice])), escalus:end_per_testcase(registration_conflict, Config); end_per_testcase(not_allowed_registration_cancelation, Config) -> restore_mod_register_options(Config), escalus:end_per_testcase(not_allowed_registration_cancelation, Config); end_per_testcase(registration_timeout, Config) -> escalus:delete_users(Config, escalus:get_users([alice, bob])), escalus:end_per_testcase(registration_timeout, Config); end_per_testcase(registration_failure_timeout, Config) -> mongoose_helper:restore_config_option(Config, [{access, host_type()}, register]), escalus:end_per_testcase(registration_failure_timeout, Config); end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). register(Config) -> [{Name1, _UserSpec1}, {Name2, _UserSpec2}] = escalus_users:get_users([alice, bob]), escalus_fresh:create_users(Config, escalus:get_users([Name1, Name2])). already_registered(Config) -> escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> escalus:send(Alice, escalus_stanza:get_registration_fields()), Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_result, Stanza), true = has_registered_element(Stanza) end). registration_conflict(Config) -> [Alice] = escalus_users:get_users([alice]), {ok, result, _Stanza} = escalus_users:create_user(Config, Alice), {ok, conflict, _Raw} = escalus_users:create_user(Config, Alice). admin_notify(Config) -> [{Name1, UserSpec1}, {Name2, UserSpec2}] = escalus_users:get_users([alice, bob]), [{_, AdminSpec}] = escalus_users:get_users([admin]), Username1 = jid:str_tolower(escalus_users:get_username(Config, UserSpec1)), Username2 = jid:str_tolower(escalus_users:get_username(Config, UserSpec2)), [AdminU, AdminS, AdminP] = escalus_users:get_usp(Config, AdminSpec), rpc(mim(), ejabberd_auth, try_register, [mongoose_helper:make_jid(AdminU, AdminS), AdminP]), escalus:story(Config, [{admin, 1}], fun(Admin) -> escalus:create_users(Config, escalus:get_users([Name1, Name2])), Predicates = [ fun(Stanza) -> Body = exml_query:path(Stanza, [{element, <<"body">>}, cdata]), escalus_pred:is_chat_message(Stanza) andalso re:run(Body, <<"registered">>, []) =/= nomatch andalso re:run(Body, Username, []) =/= nomatch end || Username <- [Username1, Username2] ], escalus:assert_many(Predicates, escalus:wait_for_stanzas(Admin, 2)) end). null_password(Config) -> Details = escalus_fresh:freshen_spec(Config, alice), Alice = {alice, lists:keyreplace(password, 1, Details, {password, <<>>})}, {error, _, Response} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, Response), %% This error response means there was no character data, i.e. elements ` < password\ > ' or ` < password></password > ' where %% indeed present. {username, Name} = lists:keyfind(username, 1, Details), {server, Server} = lists:keyfind(server, 1, Details), escalus:assert(is_error, [<<"modify">>, <<"not-acceptable">>], Response), false = rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Name, Server)]). check_unregistered(Config) -> [{_, UserSpec}] = escalus_users:get_users([bob]), [Username, Server, _Pass] = escalus_users:get_usp(Config, UserSpec), false = rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Username, Server)]). bad_request_registration_cancelation(Config) -> To quote XEP 0077 , section 3.2 , table 1 ( unregister error %% cases): "The <remove/> element [is] not the only child element %% of the <query/> element." escalus:story(Config, [{alice, 1}], fun(Alice) -> sends bad cancelation request escalus:send(Alice, bad_cancelation_stanza()), receives failure response Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, Stanza), escalus:assert(is_error, [<<"modify">>, <<"bad-request">>], Stanza) end). not_allowed_registration_cancelation(Config) -> To quote XEP 0077 , section 3.2 , table 1 ( unregister error %% cases): "No sender is allowed to cancel registrations in-band." escalus:story(Config, [{alice, 1}], fun(Alice) -> sends cancelation request escalus:send(Alice, escalus_stanza:remove_account()), receives failure response Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, Stanza), escalus:assert(is_error, [<<"cancel">>, <<"not-allowed">>], Stanza) end). registration_timeout(Config) -> [Alice, Bob] = escalus_users:get_users([alice, bob]), The first user should be created successfully wait_for_user(Config, Alice, ?REGISTRATION_TIMEOUT), Creation of the second one should err because of not timing out yet {error, failed_to_register, Stanza} = escalus_users:create_user(Config, Bob), escalus:assert(is_iq_error, Stanza), %% Something else may be more acceptable for the assertion below ... 2nd paragraph , section 3.1.1 , XEP 0077 : [ ... ] a server MAY return a ` < not - acceptable/ > ' stanza error if [ ... ] an entity attempts to register a second identity after %% successfully completing the registration use case. escalus:assert(is_error, [<<"wait">>, <<"resource-constraint">>], Stanza), %% After timeout, the user should be registered successfully wait_for_user(Config, Bob, erlang:round(?REGISTRATION_TIMEOUT * 1.5 * 1000)). registration_failure_timeout(Config) -> timer:sleep(timer:seconds(?REGISTRATION_TIMEOUT + 1)), [Alice] = escalus_users:get_users([alice]), Registration of the first user should fail because of access denial {error,failed_to_register,R} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, R), escalus:assert(is_error, [<<"auth">>, <<"forbidden">>], R), Registration of a second one should fail because requests were %% made in quick succession {error,failed_to_register,S} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, S), escalus:assert(is_error, [<<"wait">>, <<"resource-constraint">>], S). change_password(Config) -> escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> Username = escalus_client:username(Alice), escalus:send(Alice, Q = escalus_stanza:iq_set(?NS_INBAND_REGISTER, [#xmlel{name = <<"username">>, children = [#xmlcdata{content = Username}]}, #xmlel{name = <<"password">>, children = [#xmlcdata{content = strong_pwd()}]}])), R = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_result, [Q], R) end). change_password_to_null(Config) -> Section 3.3 , XEP 0077 : If the user provides an empty password %% element or a password element that contains no XML character data ( i.e. , either < password/ > or < password></password > ) , the %% server or service MUST NOT change the password to a null value, %% but instead MUST maintain the existing password. By the above , ` end_per_testcase ' should succeed . XEP 0077 %% doesn't say how how an XMPP sever should respond, but since %% this is in IQ, it must: so we choose to require a `not-allowed' %% response. escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> Username = escalus_client:username(Alice), escalus:send(Alice, escalus_stanza:iq_set(?NS_INBAND_REGISTER, [#xmlel{name = <<"username">>, children = [#xmlcdata{content = Username}]}, #xmlel{name = <<"password">>, children = [#xmlcdata{content = <<"">>}]}])), R = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, R), escalus:assert(is_error, [<<"modify">>, <<"bad-request">>], R) end). Tests for utility functions currently accessible only from the Erlang shell list_users(_Config) -> Users = [{<<"alice">>, domain()}, {<<"bob">>, domain()}], ?assertEqual(Users, lists:sort(rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain()]))). list_selected_users(_Config) -> Alice = {<<"alice">>, domain()}, Bob = {<<"bob">>, domain()}, ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{from, 1}, {to, 1}]])), ?assertEqual([Bob], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{from, 2}, {to, 10}]])), ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<"a">>}]])), ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<"a">>}, {from, 1}, {to, 10}]])), ?assertEqual([Bob], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<>>}, {from, 2}, {to, 10}]])). count_users(_Config) -> ?assertEqual(2, rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain()])). count_users_estimate(_Config) -> Count = rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain()]), ?assert(is_integer(Count) andalso Count >= 0). count_selected_users(_Config) -> ?assertEqual(1, rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain(), [{prefix, <<"a">>}]])). %%-------------------------------------------------------------------- %% Helpers %%-------------------------------------------------------------------- skip_if_mod_register_not_enabled(Config) -> case escalus_users:is_mod_register_enabled(Config) of true -> Config; % will create users inside test case _ -> {skip, mod_register_disabled} end. strong_pwd() -> <<"Sup3r","c4li","fr4g1","l1571c","3xp1","4l1","d0c10u5">>. set_registration_timeout(Config) -> mongoose_helper:backup_and_set_config_option(Config, registration_timeout, ?REGISTRATION_TIMEOUT). restore_registration_timeout(Config) -> mongoose_helper:restore_config_option(Config, registration_timeout). deny_everyone_registration(Config) -> mongoose_helper:backup_and_set_config_option(Config, [{access, host_type()}, register], [#{acl => all, value => deny}]). has_registered_element(Stanza) -> [#xmlel{name = <<"registered">>}] =:= exml_query:paths(Stanza, [{element, <<"query">>}, {element, <<"registered">>}]). bad_cancelation_stanza() -> escalus_stanza:iq(<<"set">>, [#xmlel{name = <<"query">>, attrs = [{<<"xmlns">>, <<"jabber:iq:register">>}], children = [#xmlel{name = <<"remove">>}, %% The <remove/> element is not the only child element of the %% <query/> element. #xmlel{name = <<"foo">>}]}]). user_exists(Name, Config) -> {Name, Client} = escalus_users:get_user_by_name(Name), [Username, Server, _Pass] = escalus_users:get_usp(Config, Client), rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Username, Server)]). reload_mod_register_option(Config, Key, Value) -> Host = host_type(), Args = proplists:get_value(mod_register_options, Config), Args1 = maps:put(Key, Value, Args), dynamic_modules:restart(Host, mod_register, Args1). restore_mod_register_options(Config) -> Host = host_type(), Args = proplists:get_value(mod_register_options, Config), dynamic_modules:restart(Host, mod_register, Args). enable_watcher(Config, Watcher) -> reload_mod_register_option(Config, registration_watchers, [Watcher]). disable_watcher(Config) -> restore_mod_register_options(Config).
null
https://raw.githubusercontent.com/esl/MongooseIM/ed87b58fa159af1fb613d76e3c26ea085aad16f5/big_tests/tests/accounts_SUITE.erl
erlang
-------------------------------------------------------------------- Suite configuration -------------------------------------------------------------------- seconds -------------------------------------------------------------------- -------------------------------------------------------------------- Use a configuration that will not allow inband cancelation (and registration). This error response means there was no character data, indeed present. cases): "The <remove/> element [is] not the only child element of the <query/> element." cases): "No sender is allowed to cancel registrations in-band." Something else may be more acceptable for the assertion successfully completing the registration use case. After timeout, the user should be registered successfully made in quick succession element or a password element that contains no XML character server or service MUST NOT change the password to a null value, but instead MUST maintain the existing password. doesn't say how how an XMPP sever should respond, but since this is in IQ, it must: so we choose to require a `not-allowed' response. -------------------------------------------------------------------- Helpers -------------------------------------------------------------------- will create users inside test case The <remove/> element is not the only child element of the <query/> element.
-module(accounts_SUITE). -compile([export_all, nowarn_export_all]). -include_lib("escalus/include/escalus.hrl"). -include_lib("escalus/include/escalus_xmlns.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("exml/include/exml.hrl"). -import(distributed_helper, [mim/0, require_rpc_nodes/1, rpc/4]). -import(mongoose_helper, [wait_for_user/3]). -import(domain_helper, [domain/0, host_type/0]). all() -> [ {group, register}, {group, registration_watchers}, {group, bad_registration}, {group, bad_cancelation}, {group, registration_timeout}, {group, change_account_details}, {group, change_account_details_store_plain}, {group, utilities} ]. groups() -> [{register, [parallel], [register, already_registered, registration_conflict, check_unregistered]}, {registration_watchers, [sequence], [admin_notify]}, {bad_registration, [sequence], [null_password]}, {bad_cancelation, [sequence], [bad_request_registration_cancelation, not_allowed_registration_cancelation]}, {registration_timeout, [sequence], [registration_timeout, registration_failure_timeout]}, {change_account_details, [parallel], change_password_tests()}, {change_account_details_store_plain, [parallel], change_password_tests()}, {utilities, [{group, user_info}, {group, users_number_estimate}]}, {user_info, [parallel], [list_users, list_selected_users, count_users, count_selected_users]}, {users_number_estimate, [], [count_users_estimate]} ]. suite() -> require_rpc_nodes([mim]) ++ escalus:suite(). change_password_tests() -> [change_password, change_password_to_null]. Init & teardown init_per_suite(Config1) -> ok = dynamic_modules:ensure_modules(host_type(), required_modules()), Config2 = [{mod_register_options, mod_register_options()} | Config1], escalus:init_per_suite([{escalus_user_db, xmpp} | Config2]). end_per_suite(Config) -> escalus_fresh:clean(), escalus:end_per_suite(Config). required_modules() -> [{mod_register, mod_register_options()}]. mod_register_options() -> config_parser_helper:mod_config(mod_register, #{ip_access => [{allow, "127.0.0.0/8"}, {deny, "0.0.0.0/0"}], access => register}). init_per_group(bad_cancelation, Config) -> escalus:create_users(Config, escalus:get_users([alice])); init_per_group(change_account_details, Config) -> [{escalus_user_db, {module, escalus_ejabberd}} |Config]; init_per_group(change_account_details_store_plain, Config) -> AuthOpts = mongoose_helper:auth_opts_with_password_format(plain), Config1 = mongoose_helper:backup_and_set_config_option(Config, auth, AuthOpts), [{escalus_user_db, {module, escalus_ejabberd}} |Config1]; init_per_group(registration_timeout, Config) -> set_registration_timeout(Config); init_per_group(utilities, Config) -> escalus:create_users(Config, escalus:get_users([alice, bob])); init_per_group(users_number_estimate, Config) -> AuthOpts = get_auth_opts(), NewAuthOpts = AuthOpts#{rdbms => #{users_number_estimate => true}}, set_auth_opts(Config, NewAuthOpts); init_per_group(_GroupName, Config) -> Config. end_per_group(change_account_details, Config) -> escalus_fresh:clean(), [{escalus_user_db, xmpp} | Config]; end_per_group(change_account_details_store_plain, Config) -> escalus_fresh:clean(), mongoose_helper:restore_config(Config), [{escalus_user_db, xmpp} | Config]; end_per_group(bad_cancelation, Config) -> escalus:delete_users(Config, escalus:get_users([alice])); end_per_group(registration_timeout, Config) -> restore_registration_timeout(Config); end_per_group(utilities, Config) -> escalus:delete_users(Config, escalus:get_users([alice, bob])); end_per_group(users_number_estimate, Config) -> mongoose_helper:restore_config(Config); end_per_group(_GroupName, Config) -> Config. get_auth_opts() -> rpc(mim(), mongoose_config, get_opt, [{auth, host_type()}]). set_auth_opts(Config, AuthOpts) -> rpc(mim(), ejabberd_auth, stop, [host_type()]), Config1 = mongoose_helper:backup_and_set_config_option(Config, {auth, host_type()}, AuthOpts), rpc(mim(), ejabberd_auth, start, [host_type()]), Config1. init_per_testcase(admin_notify, Config) -> [{_, AdminSpec}] = escalus_users:get_users([admin]), [AdminU, AdminS, _AdminP] = escalus_users:get_usp(Config, AdminSpec), AdminJid = <<AdminU/binary, "@", AdminS/binary>>, enable_watcher(Config, AdminJid), escalus:init_per_testcase(admin_notify, Config); init_per_testcase(not_allowed_registration_cancelation, Config) -> reload_mod_register_option(Config, access, none), escalus:init_per_testcase(not_allowed_registration_cancelation, Config); init_per_testcase(registration_failure_timeout, Config) -> Config1 = deny_everyone_registration(Config), escalus:init_per_testcase(registration_failure_timeout, Config1); init_per_testcase(CaseName, Config) when CaseName =:= list_selected_users; CaseName =:= count_selected_users -> case mongoose_helper:auth_modules() of [Mod | _] when Mod =:= ejabberd_auth_rdbms; Mod =:= ejabberd_auth_internal -> escalus:init_per_testcase(CaseName, Config); Modules -> {skip, {"Queries for selected users not supported", Modules}} end; init_per_testcase(CaseName, Config) -> escalus:init_per_testcase(CaseName, Config). end_per_testcase(register, Config) -> escalus:end_per_testcase(register, Config); end_per_testcase(admin_notify, Config) -> disable_watcher(Config), escalus:delete_users(Config, escalus:get_users([alice, bob, admin])), escalus:end_per_testcase(admin_notify, Config); end_per_testcase(registration_conflict, Config) -> escalus_users:delete_users(Config, escalus:get_users([alice])), escalus:end_per_testcase(registration_conflict, Config); end_per_testcase(not_allowed_registration_cancelation, Config) -> restore_mod_register_options(Config), escalus:end_per_testcase(not_allowed_registration_cancelation, Config); end_per_testcase(registration_timeout, Config) -> escalus:delete_users(Config, escalus:get_users([alice, bob])), escalus:end_per_testcase(registration_timeout, Config); end_per_testcase(registration_failure_timeout, Config) -> mongoose_helper:restore_config_option(Config, [{access, host_type()}, register]), escalus:end_per_testcase(registration_failure_timeout, Config); end_per_testcase(CaseName, Config) -> escalus:end_per_testcase(CaseName, Config). register(Config) -> [{Name1, _UserSpec1}, {Name2, _UserSpec2}] = escalus_users:get_users([alice, bob]), escalus_fresh:create_users(Config, escalus:get_users([Name1, Name2])). already_registered(Config) -> escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> escalus:send(Alice, escalus_stanza:get_registration_fields()), Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_result, Stanza), true = has_registered_element(Stanza) end). registration_conflict(Config) -> [Alice] = escalus_users:get_users([alice]), {ok, result, _Stanza} = escalus_users:create_user(Config, Alice), {ok, conflict, _Raw} = escalus_users:create_user(Config, Alice). admin_notify(Config) -> [{Name1, UserSpec1}, {Name2, UserSpec2}] = escalus_users:get_users([alice, bob]), [{_, AdminSpec}] = escalus_users:get_users([admin]), Username1 = jid:str_tolower(escalus_users:get_username(Config, UserSpec1)), Username2 = jid:str_tolower(escalus_users:get_username(Config, UserSpec2)), [AdminU, AdminS, AdminP] = escalus_users:get_usp(Config, AdminSpec), rpc(mim(), ejabberd_auth, try_register, [mongoose_helper:make_jid(AdminU, AdminS), AdminP]), escalus:story(Config, [{admin, 1}], fun(Admin) -> escalus:create_users(Config, escalus:get_users([Name1, Name2])), Predicates = [ fun(Stanza) -> Body = exml_query:path(Stanza, [{element, <<"body">>}, cdata]), escalus_pred:is_chat_message(Stanza) andalso re:run(Body, <<"registered">>, []) =/= nomatch andalso re:run(Body, Username, []) =/= nomatch end || Username <- [Username1, Username2] ], escalus:assert_many(Predicates, escalus:wait_for_stanzas(Admin, 2)) end). null_password(Config) -> Details = escalus_fresh:freshen_spec(Config, alice), Alice = {alice, lists:keyreplace(password, 1, Details, {password, <<>>})}, {error, _, Response} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, Response), i.e. elements ` < password\ > ' or ` < password></password > ' where {username, Name} = lists:keyfind(username, 1, Details), {server, Server} = lists:keyfind(server, 1, Details), escalus:assert(is_error, [<<"modify">>, <<"not-acceptable">>], Response), false = rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Name, Server)]). check_unregistered(Config) -> [{_, UserSpec}] = escalus_users:get_users([bob]), [Username, Server, _Pass] = escalus_users:get_usp(Config, UserSpec), false = rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Username, Server)]). bad_request_registration_cancelation(Config) -> To quote XEP 0077 , section 3.2 , table 1 ( unregister error escalus:story(Config, [{alice, 1}], fun(Alice) -> sends bad cancelation request escalus:send(Alice, bad_cancelation_stanza()), receives failure response Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, Stanza), escalus:assert(is_error, [<<"modify">>, <<"bad-request">>], Stanza) end). not_allowed_registration_cancelation(Config) -> To quote XEP 0077 , section 3.2 , table 1 ( unregister error escalus:story(Config, [{alice, 1}], fun(Alice) -> sends cancelation request escalus:send(Alice, escalus_stanza:remove_account()), receives failure response Stanza = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, Stanza), escalus:assert(is_error, [<<"cancel">>, <<"not-allowed">>], Stanza) end). registration_timeout(Config) -> [Alice, Bob] = escalus_users:get_users([alice, bob]), The first user should be created successfully wait_for_user(Config, Alice, ?REGISTRATION_TIMEOUT), Creation of the second one should err because of not timing out yet {error, failed_to_register, Stanza} = escalus_users:create_user(Config, Bob), escalus:assert(is_iq_error, Stanza), below ... 2nd paragraph , section 3.1.1 , XEP 0077 : [ ... ] a server MAY return a ` < not - acceptable/ > ' stanza error if [ ... ] an entity attempts to register a second identity after escalus:assert(is_error, [<<"wait">>, <<"resource-constraint">>], Stanza), wait_for_user(Config, Bob, erlang:round(?REGISTRATION_TIMEOUT * 1.5 * 1000)). registration_failure_timeout(Config) -> timer:sleep(timer:seconds(?REGISTRATION_TIMEOUT + 1)), [Alice] = escalus_users:get_users([alice]), Registration of the first user should fail because of access denial {error,failed_to_register,R} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, R), escalus:assert(is_error, [<<"auth">>, <<"forbidden">>], R), Registration of a second one should fail because requests were {error,failed_to_register,S} = escalus_users:create_user(Config, Alice), escalus:assert(is_iq_error, S), escalus:assert(is_error, [<<"wait">>, <<"resource-constraint">>], S). change_password(Config) -> escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> Username = escalus_client:username(Alice), escalus:send(Alice, Q = escalus_stanza:iq_set(?NS_INBAND_REGISTER, [#xmlel{name = <<"username">>, children = [#xmlcdata{content = Username}]}, #xmlel{name = <<"password">>, children = [#xmlcdata{content = strong_pwd()}]}])), R = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_result, [Q], R) end). change_password_to_null(Config) -> Section 3.3 , XEP 0077 : If the user provides an empty password data ( i.e. , either < password/ > or < password></password > ) , the By the above , ` end_per_testcase ' should succeed . XEP 0077 escalus_fresh:story(Config, [{alice, 1}], fun(Alice) -> Username = escalus_client:username(Alice), escalus:send(Alice, escalus_stanza:iq_set(?NS_INBAND_REGISTER, [#xmlel{name = <<"username">>, children = [#xmlcdata{content = Username}]}, #xmlel{name = <<"password">>, children = [#xmlcdata{content = <<"">>}]}])), R = escalus:wait_for_stanza(Alice), escalus:assert(is_iq_error, R), escalus:assert(is_error, [<<"modify">>, <<"bad-request">>], R) end). Tests for utility functions currently accessible only from the Erlang shell list_users(_Config) -> Users = [{<<"alice">>, domain()}, {<<"bob">>, domain()}], ?assertEqual(Users, lists:sort(rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain()]))). list_selected_users(_Config) -> Alice = {<<"alice">>, domain()}, Bob = {<<"bob">>, domain()}, ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{from, 1}, {to, 1}]])), ?assertEqual([Bob], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{from, 2}, {to, 10}]])), ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<"a">>}]])), ?assertEqual([Alice], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<"a">>}, {from, 1}, {to, 10}]])), ?assertEqual([Bob], rpc(mim(), ejabberd_auth, get_vh_registered_users, [domain(), [{prefix, <<>>}, {from, 2}, {to, 10}]])). count_users(_Config) -> ?assertEqual(2, rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain()])). count_users_estimate(_Config) -> Count = rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain()]), ?assert(is_integer(Count) andalso Count >= 0). count_selected_users(_Config) -> ?assertEqual(1, rpc(mim(), ejabberd_auth, get_vh_registered_users_number, [domain(), [{prefix, <<"a">>}]])). skip_if_mod_register_not_enabled(Config) -> case escalus_users:is_mod_register_enabled(Config) of true -> _ -> {skip, mod_register_disabled} end. strong_pwd() -> <<"Sup3r","c4li","fr4g1","l1571c","3xp1","4l1","d0c10u5">>. set_registration_timeout(Config) -> mongoose_helper:backup_and_set_config_option(Config, registration_timeout, ?REGISTRATION_TIMEOUT). restore_registration_timeout(Config) -> mongoose_helper:restore_config_option(Config, registration_timeout). deny_everyone_registration(Config) -> mongoose_helper:backup_and_set_config_option(Config, [{access, host_type()}, register], [#{acl => all, value => deny}]). has_registered_element(Stanza) -> [#xmlel{name = <<"registered">>}] =:= exml_query:paths(Stanza, [{element, <<"query">>}, {element, <<"registered">>}]). bad_cancelation_stanza() -> escalus_stanza:iq(<<"set">>, [#xmlel{name = <<"query">>, attrs = [{<<"xmlns">>, <<"jabber:iq:register">>}], children = [#xmlel{name = <<"remove">>}, #xmlel{name = <<"foo">>}]}]). user_exists(Name, Config) -> {Name, Client} = escalus_users:get_user_by_name(Name), [Username, Server, _Pass] = escalus_users:get_usp(Config, Client), rpc(mim(), ejabberd_auth, does_user_exist, [mongoose_helper:make_jid(Username, Server)]). reload_mod_register_option(Config, Key, Value) -> Host = host_type(), Args = proplists:get_value(mod_register_options, Config), Args1 = maps:put(Key, Value, Args), dynamic_modules:restart(Host, mod_register, Args1). restore_mod_register_options(Config) -> Host = host_type(), Args = proplists:get_value(mod_register_options, Config), dynamic_modules:restart(Host, mod_register, Args). enable_watcher(Config, Watcher) -> reload_mod_register_option(Config, registration_watchers, [Watcher]). disable_watcher(Config) -> restore_mod_register_options(Config).
f3ae1bb31e8976c920a132335476bc182abd79c6f8e84c7f3e8f6eba4e7734f3
imandra-ai/ocaml-opentelemetry
gen.ml
let atomic_before_412 = {| type 'a t = {mutable x: 'a} let[@inline] make x = {x} let[@inline] get {x} = x let[@inline] set r x = r.x <- x let[@inline never] exchange r x = (* critical section *) let y = r.x in r.x <- x; (* end critical section *) y let[@inline never] compare_and_set r seen v = (* critical section *) if r.x == seen then ( r.x <- v; true ) else false let[@inline never] fetch_and_add r x = let v = r.x in r.x <- x + r.x; v let[@inline never] incr r = r.x <- 1 + r.x let[@inline never] decr r = r.x <- r.x - 1 |} let atomic_after_412 = {|include Stdlib.Atomic|} let write_file file s = let oc = open_out file in output_string oc s; close_out oc let copy_file file1 file2 = let oc = open_out file2 in let ic = open_in file1 in let buf = Bytes.create 1024 in try while true do let n = input ic buf 0 (Bytes.length buf) in if n = 0 then raise End_of_file; output oc buf 0 n done with End_of_file -> () let () = let version = Scanf.sscanf Sys.ocaml_version "%d.%d.%s" (fun x y _ -> x, y) in write_file "atomic.ml" (if version >= (4, 12) then atomic_after_412 else atomic_before_412); copy_file (if version >= (4, 12) then "atomic.post412.mli" else "atomic.pre412.mli") "atomic.mli"; ()
null
https://raw.githubusercontent.com/imandra-ai/ocaml-opentelemetry/0fb530125a3ce4e7e1d23ddadb40ca25e84b27a1/src/atomic/gen.ml
ocaml
critical section end critical section critical section
let atomic_before_412 = {| type 'a t = {mutable x: 'a} let[@inline] make x = {x} let[@inline] get {x} = x let[@inline] set r x = r.x <- x let[@inline never] exchange r x = let y = r.x in r.x <- x; y let[@inline never] compare_and_set r seen v = if r.x == seen then ( r.x <- v; true ) else false let[@inline never] fetch_and_add r x = let v = r.x in r.x <- x + r.x; v let[@inline never] incr r = r.x <- 1 + r.x let[@inline never] decr r = r.x <- r.x - 1 |} let atomic_after_412 = {|include Stdlib.Atomic|} let write_file file s = let oc = open_out file in output_string oc s; close_out oc let copy_file file1 file2 = let oc = open_out file2 in let ic = open_in file1 in let buf = Bytes.create 1024 in try while true do let n = input ic buf 0 (Bytes.length buf) in if n = 0 then raise End_of_file; output oc buf 0 n done with End_of_file -> () let () = let version = Scanf.sscanf Sys.ocaml_version "%d.%d.%s" (fun x y _ -> x, y) in write_file "atomic.ml" (if version >= (4, 12) then atomic_after_412 else atomic_before_412); copy_file (if version >= (4, 12) then "atomic.post412.mli" else "atomic.pre412.mli") "atomic.mli"; ()
5d46b9dd1a535ac525dd2859247a953851d688343d8b7323f3d383db99648905
Chris00/fftw-ocaml
fftw3_utils.ml
open Printf * { 2 Helper funs } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ***********************************************************************) (* specialized for speed *) let min i j = if (i:int) < j then i else j module List = struct include List let rec list_iteri_loop f i = function | [] -> () | a :: tl -> f i a; list_iteri_loop f (succ i) tl let iteri ~(f: int -> _ -> unit) l = list_iteri_loop f 0 l end let option_map f = function Some v -> Some(f v) | None -> None (** Return a string showing the content of the array *) let string_of_array a = if Array.length a = 0 then "[| |]" else begin let b = Buffer.create 80 in Buffer.add_string b "[|"; Buffer.add_string b (string_of_int a.(0)); for i = 1 to Array.length a - 1 do Buffer.add_string b "; "; Buffer.add_string b (string_of_int a.(i)); done; Buffer.add_string b "|]"; Buffer.contents b end * [ get_rank default m ] returns the length of by the first array in the list of options [ m ] . the list of options [m]. *) let rec get_rank default = function | [] -> default | None :: t -> get_rank default t | Some m :: _ -> Array.length m let get_mat_rank name rank default = function | None -> Array.make rank default (* Create matrix with default value *) | Some m -> if Array.length m <> rank then invalid_arg(sprintf "%s: expected length=%i, got=%i" name rank (Array.length m)); m * { 2 Geometry checks } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ***********************************************************************) (* This module perform some checks on the dimensions and howmany specifications that depend on the layout but not on the precision. *) module Geom = struct let rec different_sub ofs1 n1 ofs2 n2 len = len > 0 && (n1.(ofs1) <> n2.(ofs2) || different_sub (ofs1 + 1) n1 (ofs2 + 1) n2 (len - 1)) (* The arrays of dimensions are always arranged from the slow varying dimension to the fast one. This the "special" dimension is always last. *) let r2c ni no = let len = Array.length ni in len <> Array.length no || ni.(len - 1)/2 + 1 <> no.(len - 1) || different_sub 0 ni 0 no (len - 2) let logical_c2c ni no msg = if ni <> no then invalid_arg msg; ni let logical_r2r = logical_c2c let logical_r2c ni no msg = if r2c ni no then invalid_arg msg; ni let logical_c2r ni no msg = logical_r2c no ni msg end
null
https://raw.githubusercontent.com/Chris00/fftw-ocaml/0474c42f38d5f375b6187dc089b34c56ec0e76dd/src/fftw3_utils.ml
ocaml
specialized for speed * Return a string showing the content of the array Create matrix with default value This module perform some checks on the dimensions and howmany specifications that depend on the layout but not on the precision. The arrays of dimensions are always arranged from the slow varying dimension to the fast one. This the "special" dimension is always last.
open Printf * { 2 Helper funs } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ***********************************************************************) let min i j = if (i:int) < j then i else j module List = struct include List let rec list_iteri_loop f i = function | [] -> () | a :: tl -> f i a; list_iteri_loop f (succ i) tl let iteri ~(f: int -> _ -> unit) l = list_iteri_loop f 0 l end let option_map f = function Some v -> Some(f v) | None -> None let string_of_array a = if Array.length a = 0 then "[| |]" else begin let b = Buffer.create 80 in Buffer.add_string b "[|"; Buffer.add_string b (string_of_int a.(0)); for i = 1 to Array.length a - 1 do Buffer.add_string b "; "; Buffer.add_string b (string_of_int a.(i)); done; Buffer.add_string b "|]"; Buffer.contents b end * [ get_rank default m ] returns the length of by the first array in the list of options [ m ] . the list of options [m]. *) let rec get_rank default = function | [] -> default | None :: t -> get_rank default t | Some m :: _ -> Array.length m let get_mat_rank name rank default = function | Some m -> if Array.length m <> rank then invalid_arg(sprintf "%s: expected length=%i, got=%i" name rank (Array.length m)); m * { 2 Geometry checks } * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ***********************************************************************) module Geom = struct let rec different_sub ofs1 n1 ofs2 n2 len = len > 0 && (n1.(ofs1) <> n2.(ofs2) || different_sub (ofs1 + 1) n1 (ofs2 + 1) n2 (len - 1)) let r2c ni no = let len = Array.length ni in len <> Array.length no || ni.(len - 1)/2 + 1 <> no.(len - 1) || different_sub 0 ni 0 no (len - 2) let logical_c2c ni no msg = if ni <> no then invalid_arg msg; ni let logical_r2r = logical_c2c let logical_r2c ni no msg = if r2c ni no then invalid_arg msg; ni let logical_c2r ni no msg = logical_r2c no ni msg end
8938055dbc6dfa8c9405fbee42df1e4b1c0bff5a91cfdbe17f3ec9097cc1a6dc
danhper/evm-analyzer
tracer.ml
open Core open TracerTypes type t = { contract_address: String.t; tx_hash: String.t; block_number: Int.t; taggers: Tagger.t List.t List.t; } let create ~block_number ~tx_hash ~taggers contract_address = { contract_address; taggers; tx_hash; block_number; } let log ~debug ~env trace = let open Trace in if debug then let stack_str = EStack.to_string ~f:StackValue.show env.Env.stack in let op_code_str = Op.to_string trace.op in Out_channel.printf "%d: %s %s\n" trace.pc op_code_str stack_str let nested_call_address op args = let open Op in match op, args with | (Call | Callcode | Staticcall | Delegatecall), (_gas :: addr :: _rest) -> Some (addr.StackValue.value) | _ -> None let execute_traces ?debug:(debug=false) ?timeout ?db t traces = let db = Option.value ~default:(FactDb.create ()) db in let start_time = Unix.gettimeofday () in let rec execute_trace ~env ~taggers _acc trace = log ~debug ~env trace; let has_timeouted = match timeout with | Some t -> let ellapsed_time = Unix.gettimeofday () -. start_time in ellapsed_time > t | None -> false in if has_timeouted then true else execute_trace' ~env ~taggers trace and execute_trace' ~env ~taggers trace = let () = match trace.op with | Op.Dup n -> EStack.dup env.Env.stack (n - 1) | Op.Swap n -> EStack.swap env.Env.stack (n - 1) | _ -> () in let args_count = Op.input_count trace.op in let args = List.rev (List.init args_count ~f:(fun _ -> EStack.pop env.Env.stack)) in let result = Option.map ~f:(StackValue.create ~id:trace.Trace.index) trace.result in let full_trace = FullTrace.({ result; args; trace; env; }) in List.iter ~f:(fun t -> t db full_trace) taggers; Option.iter result ~f:(EStack.push env.Env.stack); match trace.Trace.children with | [] -> false | children -> let new_address = Option.value ~default:env.address (nested_call_address trace.op args) in execute_traces new_address children taggers and execute_traces address traces taggers = let env = Env.create ~block_number:t.block_number ~tx_hash:t.tx_hash address in List.fold ~init:false traces ~f:(execute_trace ~env ~taggers:taggers) in let result = List.map ~f:(execute_traces (BigInt.of_hex t.contract_address) traces) t.taggers in let timeouted = List.for_all ~f:Fn.id result in (db, timeouted)
null
https://raw.githubusercontent.com/danhper/evm-analyzer/9fb1cf6dc743c2f779973b2f0892047ebbd4e5fd/src/tracer.ml
ocaml
open Core open TracerTypes type t = { contract_address: String.t; tx_hash: String.t; block_number: Int.t; taggers: Tagger.t List.t List.t; } let create ~block_number ~tx_hash ~taggers contract_address = { contract_address; taggers; tx_hash; block_number; } let log ~debug ~env trace = let open Trace in if debug then let stack_str = EStack.to_string ~f:StackValue.show env.Env.stack in let op_code_str = Op.to_string trace.op in Out_channel.printf "%d: %s %s\n" trace.pc op_code_str stack_str let nested_call_address op args = let open Op in match op, args with | (Call | Callcode | Staticcall | Delegatecall), (_gas :: addr :: _rest) -> Some (addr.StackValue.value) | _ -> None let execute_traces ?debug:(debug=false) ?timeout ?db t traces = let db = Option.value ~default:(FactDb.create ()) db in let start_time = Unix.gettimeofday () in let rec execute_trace ~env ~taggers _acc trace = log ~debug ~env trace; let has_timeouted = match timeout with | Some t -> let ellapsed_time = Unix.gettimeofday () -. start_time in ellapsed_time > t | None -> false in if has_timeouted then true else execute_trace' ~env ~taggers trace and execute_trace' ~env ~taggers trace = let () = match trace.op with | Op.Dup n -> EStack.dup env.Env.stack (n - 1) | Op.Swap n -> EStack.swap env.Env.stack (n - 1) | _ -> () in let args_count = Op.input_count trace.op in let args = List.rev (List.init args_count ~f:(fun _ -> EStack.pop env.Env.stack)) in let result = Option.map ~f:(StackValue.create ~id:trace.Trace.index) trace.result in let full_trace = FullTrace.({ result; args; trace; env; }) in List.iter ~f:(fun t -> t db full_trace) taggers; Option.iter result ~f:(EStack.push env.Env.stack); match trace.Trace.children with | [] -> false | children -> let new_address = Option.value ~default:env.address (nested_call_address trace.op args) in execute_traces new_address children taggers and execute_traces address traces taggers = let env = Env.create ~block_number:t.block_number ~tx_hash:t.tx_hash address in List.fold ~init:false traces ~f:(execute_trace ~env ~taggers:taggers) in let result = List.map ~f:(execute_traces (BigInt.of_hex t.contract_address) traces) t.taggers in let timeouted = List.for_all ~f:Fn.id result in (db, timeouted)
e2547ea7c71302a9e04374f111736232b8161dde1c13c495847360b02f30e95d
flambard/CLERIC
handshake-tests.lisp
(in-package :cleric-test) (in-suite handshake) (test name-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-name-message 5 0 "")))) (read-name-message in)) 'name)) ) (test status-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-status-message "ok")))) (read-status-message in)) 'status)) ) (test challenge-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-message 5 0 8236487 "")))) (read-challenge-message in)) 'challenge)) ) (test challenge-reply-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-reply-message 8236487 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))) (read-challenge-reply-message in)) 'challenge-reply)) ) (test challenge-ack-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-ack-message #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))) (read-challenge-ack-message in)) 'challenge-ack)) )
null
https://raw.githubusercontent.com/flambard/CLERIC/12bc9a37cd273c48f670c68e91bf4d4db3441ecb/test/handshake-tests.lisp
lisp
(in-package :cleric-test) (in-suite handshake) (test name-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-name-message 5 0 "")))) (read-name-message in)) 'name)) ) (test status-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-status-message "ok")))) (read-status-message in)) 'status)) ) (test challenge-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-message 5 0 8236487 "")))) (read-challenge-message in)) 'challenge)) ) (test challenge-reply-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-reply-message 8236487 #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))) (read-challenge-reply-message in)) 'challenge-reply)) ) (test challenge-ack-message (is (typep (with-input-from-sequence (in (with-output-to-sequence (out) (write-message out (make-challenge-ack-message #(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16))))) (read-challenge-ack-message in)) 'challenge-ack)) )
f594e8e776141c7e2c770fa33dfaeb8eb3e4012e56b44b2fea17aa6b8a1b75f7
snoyberg/githash
Example.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE TemplateHaskell # module Main where import Prelude (String, concat, error, otherwise, show) import GitHash panic :: String -> a panic msg = error panicMsg where panicMsg = concat [ "[panic ", giBranch gi, "@", giHash gi , " (", giCommitDate gi, ")" , " (", show (giCommitCount gi), " commits in HEAD)" , dirty, "] ", msg ] dirty | giDirty gi = " (uncommitted files present)" | otherwise = "" gi = $$tGitInfoCwd main = panic "oh no!"
null
https://raw.githubusercontent.com/snoyberg/githash/bec020faa0d5219a7b75b8183c28c2d34497e57f/Example.hs
haskell
# LANGUAGE NoImplicitPrelude # # LANGUAGE TemplateHaskell # module Main where import Prelude (String, concat, error, otherwise, show) import GitHash panic :: String -> a panic msg = error panicMsg where panicMsg = concat [ "[panic ", giBranch gi, "@", giHash gi , " (", giCommitDate gi, ")" , " (", show (giCommitCount gi), " commits in HEAD)" , dirty, "] ", msg ] dirty | giDirty gi = " (uncommitted files present)" | otherwise = "" gi = $$tGitInfoCwd main = panic "oh no!"
575c9b29741fa87a100fa5ac81d0352dc5e6b4d84dd272b5c31e68a2aae10b4b
sgbj/MaximaSharp
gderiv.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 1.221 2010/05/26 19:25:52 " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.204 2010/02/23 05:21:30 " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.114 2010/05/17 01:42:14 " ) Using Lisp CMU Common Lisp CVS Head 2010 - 05 - 25 18:21:07 ( 20A Unicode ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package :colnew) (defun gderiv (gi nrow irow zval dgz mode dgsub) (declare (type (array double-float (*)) dgz zval) (type (f2cl-lib:integer4) mode irow nrow) (type (array double-float (*)) gi)) (let () (symbol-macrolet ((mstar (aref (colord-part-0 *colord-common-block*) 2)) (izeta (aref (colsid-part-1 *colsid-common-block*) 0)) (nonlin (aref (colnln-part-0 *colnln-common-block*) 0)) (iter (aref (colnln-part-0 *colnln-common-block*) 1))) (f2cl-lib:with-multi-array-data ((gi double-float gi-%data% gi-%offset%) (zval double-float zval-%data% zval-%offset%) (dgz double-float dgz-%data% dgz-%offset%)) (prog ((dot 0.0) (j 0) (dg (make-array 40 :element-type 'double-float))) (declare (type (array double-float (40)) dg) (type (f2cl-lib:integer4) j) (type double-float dot)) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody label10 (setf (f2cl-lib:fref dg (j) ((1 40))) 0.0))) (multiple-value-bind (var-0 var-1 var-2) (funcall dgsub izeta zval dg) (declare (ignore var-1 var-2)) (when var-0 (setf izeta var-0))) (if (or (= nonlin 0) (> iter 0)) (go label30)) (setf dot 0.0) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody label20 (setf dot (+ dot (* (f2cl-lib:fref dg (j) ((1 40))) (f2cl-lib:fref zval-%data% (j) ((1 1)) zval-%offset%)))))) (setf (f2cl-lib:fref dgz-%data% (izeta) ((1 1)) dgz-%offset%) dot) label30 (if (= mode 2) (go label50)) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody (setf (f2cl-lib:fref gi-%data% (irow j) ((1 nrow) (1 1)) gi-%offset%) (f2cl-lib:fref dg (j) ((1 40)))) label40 (setf (f2cl-lib:fref gi-%data% (irow (f2cl-lib:int-add mstar j)) ((1 nrow) (1 1)) gi-%offset%) 0.0))) (go end_label) label50 (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody (setf (f2cl-lib:fref gi-%data% (irow j) ((1 nrow) (1 1)) gi-%offset%) 0.0) label60 (setf (f2cl-lib:fref gi-%data% (irow (f2cl-lib:int-add mstar j)) ((1 nrow) (1 1)) gi-%offset%) (f2cl-lib:fref dg (j) ((1 40)))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil))))))) (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::gderiv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (1)) (array double-float (1)) (fortran-to-lisp::integer4) t) :return-values '(nil nil nil nil nil nil nil) :calls 'nil)))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/colnew/lisp/gderiv.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))
( " f2cl1.l , v 1.221 2010/05/26 19:25:52 " " f2cl2.l , v 1.37 2008/02/22 22:19:33 rtoy Exp $ " " f2cl3.l , v 1.6 2008/02/22 22:19:33 rtoy Exp $ " " f2cl4.l , v 1.7 2008/02/22 22:19:34 rtoy Exp $ " " f2cl5.l , v 1.204 2010/02/23 05:21:30 " " f2cl6.l , v 1.48 2008/08/24 00:56:27 rtoy Exp $ " " macros.l , v 1.114 2010/05/17 01:42:14 " ) Using Lisp CMU Common Lisp CVS Head 2010 - 05 - 25 18:21:07 ( 20A Unicode ) (in-package :colnew) (defun gderiv (gi nrow irow zval dgz mode dgsub) (declare (type (array double-float (*)) dgz zval) (type (f2cl-lib:integer4) mode irow nrow) (type (array double-float (*)) gi)) (let () (symbol-macrolet ((mstar (aref (colord-part-0 *colord-common-block*) 2)) (izeta (aref (colsid-part-1 *colsid-common-block*) 0)) (nonlin (aref (colnln-part-0 *colnln-common-block*) 0)) (iter (aref (colnln-part-0 *colnln-common-block*) 1))) (f2cl-lib:with-multi-array-data ((gi double-float gi-%data% gi-%offset%) (zval double-float zval-%data% zval-%offset%) (dgz double-float dgz-%data% dgz-%offset%)) (prog ((dot 0.0) (j 0) (dg (make-array 40 :element-type 'double-float))) (declare (type (array double-float (40)) dg) (type (f2cl-lib:integer4) j) (type double-float dot)) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody label10 (setf (f2cl-lib:fref dg (j) ((1 40))) 0.0))) (multiple-value-bind (var-0 var-1 var-2) (funcall dgsub izeta zval dg) (declare (ignore var-1 var-2)) (when var-0 (setf izeta var-0))) (if (or (= nonlin 0) (> iter 0)) (go label30)) (setf dot 0.0) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody label20 (setf dot (+ dot (* (f2cl-lib:fref dg (j) ((1 40))) (f2cl-lib:fref zval-%data% (j) ((1 1)) zval-%offset%)))))) (setf (f2cl-lib:fref dgz-%data% (izeta) ((1 1)) dgz-%offset%) dot) label30 (if (= mode 2) (go label50)) (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody (setf (f2cl-lib:fref gi-%data% (irow j) ((1 nrow) (1 1)) gi-%offset%) (f2cl-lib:fref dg (j) ((1 40)))) label40 (setf (f2cl-lib:fref gi-%data% (irow (f2cl-lib:int-add mstar j)) ((1 nrow) (1 1)) gi-%offset%) 0.0))) (go end_label) label50 (f2cl-lib:fdo (j 1 (f2cl-lib:int-add j 1)) ((> j mstar) nil) (tagbody (setf (f2cl-lib:fref gi-%data% (irow j) ((1 nrow) (1 1)) gi-%offset%) 0.0) label60 (setf (f2cl-lib:fref gi-%data% (irow (f2cl-lib:int-add mstar j)) ((1 nrow) (1 1)) gi-%offset%) (f2cl-lib:fref dg (j) ((1 40)))))) (go end_label) end_label (return (values nil nil nil nil nil nil nil))))))) (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::gderiv fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((array double-float (*)) (fortran-to-lisp::integer4) (fortran-to-lisp::integer4) (array double-float (1)) (array double-float (1)) (fortran-to-lisp::integer4) t) :return-values '(nil nil nil nil nil nil nil) :calls 'nil)))
e257acf918b82f4c4003bf5cd8c2a78409d9c1af389cc07966f345b60ed33efa
tolysz/ghcjs-stack
Types.hs
# LANGUAGE DeriveGeneric # ----------------------------------------------------------------------------- -- | Module : Distribution . Client . Init . Types Copyright : ( c ) , 2009 -- License : BSD-like -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Some types used by the 'cabal init' command. -- ----------------------------------------------------------------------------- module Distribution.Client.Init.Types where import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Compat.Semigroup import Distribution.Version import Distribution.Verbosity import qualified Distribution.Package as P import Distribution.License import Distribution.ModuleName import Language.Haskell.Extension ( Language(..), Extension ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Compat.ReadP as Parse import Distribution.Text import GHC.Generics ( Generic ) | InitFlags is really just a simple type to represent certain -- portions of a .cabal file. Rather than have a flag for EVERY -- possible field, we just have one for each field that the user is -- likely to want and/or that we are likely to be able to -- intelligently guess. data InitFlags = InitFlags { nonInteractive :: Flag Bool , quiet :: Flag Bool , packageDir :: Flag FilePath , noComments :: Flag Bool , minimal :: Flag Bool , packageName :: Flag P.PackageName , version :: Flag Version , cabalVersion :: Flag VersionRange , license :: Flag License , author :: Flag String , email :: Flag String , homepage :: Flag String , synopsis :: Flag String , category :: Flag (Either String Category) , extraSrc :: Maybe [String] , packageType :: Flag PackageType , mainIs :: Flag FilePath , language :: Flag Language , exposedModules :: Maybe [ModuleName] , otherModules :: Maybe [ModuleName] , otherExts :: Maybe [Extension] , dependencies :: Maybe [P.Dependency] , sourceDirs :: Maybe [String] , buildTools :: Maybe [String] , initVerbosity :: Flag Verbosity , overwrite :: Flag Bool } deriving (Show, Generic) -- the Monoid instance for Flag has later values override earlier -- ones, which is why we want Maybe [foo] for collecting foo values, -- not Flag [foo]. data PackageType = Library | Executable deriving (Show, Read, Eq) instance Text PackageType where disp = Disp.text . show parse = Parse.choice $ map (fmap read . Parse.string . show) [Library, Executable] instance Monoid InitFlags where mempty = gmempty mappend = (<>) instance Semigroup InitFlags where (<>) = gmappend -- | Some common package categories. data Category = Codec | Concurrency | Control | Data | Database | Development | Distribution | Game | Graphics | Language | Math | Network | Sound | System | Testing | Text | Web deriving (Read, Show, Eq, Ord, Bounded, Enum) instance Text Category where disp = Disp.text . show parse = Parse.choice $ map (fmap read . Parse.string . show) [Codec .. ]
null
https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/cabal-install/Distribution/Client/Init/Types.hs
haskell
--------------------------------------------------------------------------- | License : BSD-like Maintainer : Stability : provisional Portability : portable Some types used by the 'cabal init' command. --------------------------------------------------------------------------- portions of a .cabal file. Rather than have a flag for EVERY possible field, we just have one for each field that the user is likely to want and/or that we are likely to be able to intelligently guess. the Monoid instance for Flag has later values override earlier ones, which is why we want Maybe [foo] for collecting foo values, not Flag [foo]. | Some common package categories.
# LANGUAGE DeriveGeneric # Module : Distribution . Client . Init . Types Copyright : ( c ) , 2009 module Distribution.Client.Init.Types where import Distribution.Simple.Setup ( Flag(..) ) import Distribution.Compat.Semigroup import Distribution.Version import Distribution.Verbosity import qualified Distribution.Package as P import Distribution.License import Distribution.ModuleName import Language.Haskell.Extension ( Language(..), Extension ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Compat.ReadP as Parse import Distribution.Text import GHC.Generics ( Generic ) | InitFlags is really just a simple type to represent certain data InitFlags = InitFlags { nonInteractive :: Flag Bool , quiet :: Flag Bool , packageDir :: Flag FilePath , noComments :: Flag Bool , minimal :: Flag Bool , packageName :: Flag P.PackageName , version :: Flag Version , cabalVersion :: Flag VersionRange , license :: Flag License , author :: Flag String , email :: Flag String , homepage :: Flag String , synopsis :: Flag String , category :: Flag (Either String Category) , extraSrc :: Maybe [String] , packageType :: Flag PackageType , mainIs :: Flag FilePath , language :: Flag Language , exposedModules :: Maybe [ModuleName] , otherModules :: Maybe [ModuleName] , otherExts :: Maybe [Extension] , dependencies :: Maybe [P.Dependency] , sourceDirs :: Maybe [String] , buildTools :: Maybe [String] , initVerbosity :: Flag Verbosity , overwrite :: Flag Bool } deriving (Show, Generic) data PackageType = Library | Executable deriving (Show, Read, Eq) instance Text PackageType where disp = Disp.text . show parse = Parse.choice $ map (fmap read . Parse.string . show) [Library, Executable] instance Monoid InitFlags where mempty = gmempty mappend = (<>) instance Semigroup InitFlags where (<>) = gmappend data Category = Codec | Concurrency | Control | Data | Database | Development | Distribution | Game | Graphics | Language | Math | Network | Sound | System | Testing | Text | Web deriving (Read, Show, Eq, Ord, Bounded, Enum) instance Text Category where disp = Disp.text . show parse = Parse.choice $ map (fmap read . Parse.string . show) [Codec .. ]
cd46ee2fe3c4710f5ca93f4b04c7b5a5cc547004d623debe1824faf63bce75f0
ocaml/ocaml
test.ml
(* TEST modules = "stubs.c" include runtime_events *) external start_runtime_events : unit -> unit = "start_runtime_events" external get_event_counts : unit -> (int * int) = "get_event_counts" let () = start_runtime_events (); for a = 0 to 2 do ignore(Sys.opaque_identity(ref 42)); Gc.compact () done; let (minors, majors) = get_event_counts () in Printf.printf "minors: %d, majors: %d\n" minors majors; (* Now test we can pause/resume while we're doing things *) for a = 0 to 2 do ignore(Sys.opaque_identity(ref 42)); Runtime_events.resume (); Gc.compact (); Runtime_events.pause () done; Printf.printf "minors: %d, majors: %d\n" minors majors
null
https://raw.githubusercontent.com/ocaml/ocaml/ab544472480452e600eebf1f072970d5b71d7fb2/testsuite/tests/lib-runtime-events/test.ml
ocaml
TEST modules = "stubs.c" include runtime_events Now test we can pause/resume while we're doing things
external start_runtime_events : unit -> unit = "start_runtime_events" external get_event_counts : unit -> (int * int) = "get_event_counts" let () = start_runtime_events (); for a = 0 to 2 do ignore(Sys.opaque_identity(ref 42)); Gc.compact () done; let (minors, majors) = get_event_counts () in Printf.printf "minors: %d, majors: %d\n" minors majors; for a = 0 to 2 do ignore(Sys.opaque_identity(ref 42)); Runtime_events.resume (); Gc.compact (); Runtime_events.pause () done; Printf.printf "minors: %d, majors: %d\n" minors majors
04473e9148cae29531b889577716032c0a2fa07e42b3aab7b3472e48dddfe9c7
ferd/erlang-history
group_history.erl
-module(group_history). -export([load/0, add/1]). -define(DEFAULT_HIST_FILE, ".erlang-hist"). -define(DEFAULT_HIST_SIZE, 500). -define(TABLE, shell_group_hist). -define(DEFAULT_AUTOSAVE, 500). -define(DEFAULT_DROP, []). %% History is node-based, but history of many jobs on a single node %% are mixed in together. -record(opts, {hist=true, hist_file, hist_size}). %%% PUBLIC %% Loads the shell history from memory. This function should only be %% called from group:server/3 to inject itself in the previous commands %% stack. load() -> case opts() of #opts{hist=false} -> []; #opts{hist_file=F, hist_size=S} -> wait_for_kernel_safe_sup(), %% We cannot repair the table automatically. The current process %% is handling output and dets repairing a table outputs a message. Due to how the IO protocol works , this leads to a deadlock where %% we wait to reply to ourselves in some circumstances. case dets:open_file(?TABLE, [{file,F}, {auto_save, opt(hist_auto_save)}, {repair, false}]) of {ok, ?TABLE} -> load_history(S); {error, {needs_repair, F}} -> repair_table(F); {error, Error} -> %% We can't recover from this. unknown_error_warning(Error), application:set_env(kernel, hist, false), [] end end. load_history(S) -> case dets:lookup(?TABLE, ct) of [] -> % 1st run dets:insert(?TABLE, {ct,1}), load(1, 1-S); [{ct,OldCt}] -> load(OldCt, OldCt-S); {error,{{bad_object,_Reason},TableFile}} -> corrupt_warning(TableFile), []; {error,{bad_object_header,TableFile}} -> corrupt_warning(TableFile), [] end. %% Repairing the table means we need to spawn a new process to do it for us. %% That process will then try to message the current group leader with mentions %% of trying to repair the table. We need to absorb these, let the process %% repair, then close the table in order for us to open it again and finally %% be free! repair_table(F) -> %% Start a process to open and close the table to repair it, different %% from the current shell process. R = make_ref(), S = self(), spawn(fun() -> {ok, ?TABLE} = dets:open_file(?TABLE, [{file,F},{repair,force}]), dets:close(?TABLE), S ! R end), Messages from the IO protocol will only need to be received if we %% currently are the group leader (in this case, the 'user' process). %% if this is not 'user', we can move on. case process_info(self(), registered_name) of {registered_name, user} -> receive {io_request,From,ReplyAs, {put_chars,_Encoding,io_lib,format, ["dets:"++_, [F, [_|_]]]}} -> From ! {io_reply, ReplyAs, ok} end; _ -> ok end, %% now we wait for the worker to close the table, telling us it's safe %% to load it on our own. receive R -> ok end, load(). %% Adds a given line to the history, add(Line) -> add(Line, opt(hist)). %% only add lines that do not match something to drop from history. The behaviour %% to avoid storing empty or duplicate lines is in fact implemented within group : . add(Line, true) -> case lists:member(Line, opt(hist_drop)) of false -> case dets:lookup(?TABLE, ct) of [{ct, Ct}] -> dets:insert(?TABLE, {Ct, Line}), dets:delete(?TABLE, Ct-opt(hist_size)), dets:update_counter(?TABLE, ct, {2,1}); {error,{{bad_object,_Reason},HistFile}} -> corrupt_warning(HistFile); {error,{bad_object_header, HistFile}} -> corrupt_warning(HistFile) end; true -> ok end; add(_, false) -> ok. %%% PRIVATE %% Gets a short record of vital options when setting things up. opts() -> #opts{hist=opt(hist), hist_file=opt(hist_file), hist_size=opt(hist_size)}. %% Defines whether history should be allowed at all. opt(hist) -> case application:get_env(kernel, hist) of {ok, true} -> true; {ok, false} -> false; _Default -> true end; %% Defines what the base name and path of the history file will be. %% By default, the file sits in the user's home directory as %% '.erlang-history.'. All filenames get the node name apended %% to them. opt(hist_file) -> case {opt(hist), application:get_env(kernel, hist_file)} of {true, undefined} -> case init:get_argument(home) of {ok, [[Home]]} -> Name = filename:join([Home, ?DEFAULT_HIST_FILE]), application:set_env(kernel, hist_file, Name), opt(hist_file); _ -> error_logger:error_msg("No place found to save shell history"), erlang:error(badarg) end; {true, {ok, Val}} -> Val++"."++atom_to_list(node()); {false, _} -> undefined end; Defines how many commands should be kept in memory . Default is 500 . opt(hist_size) -> case {opt(hist), application:get_env(kernel, hist_size)} of {true, undefined} -> application:set_env(kernel, hist_size, ?DEFAULT_HIST_SIZE), ?DEFAULT_HIST_SIZE; {true, {ok,Val}} -> Val; {false, _} -> undefined end; %% This handles the delay of auto-saving of DETS. This isn't public %% and the value is currently very short so that shell crashes do not %% corrupt the file history. opt(hist_auto_save) -> case application:get_env(kernel, hist_auto_save) of undefined -> application:set_env(kernel, hist_auto_save, ?DEFAULT_AUTOSAVE), ?DEFAULT_AUTOSAVE; {ok, V} -> V end; %% Allows to define a list of strings that should not be kept in history. one example would be [ " q().","init : stop().","halt ( ) . " ] if you do not %% want to keep ways to shut down the shell. opt(hist_drop) -> case application:get_env(kernel, hist_drop) of undefined -> application:set_env(kernel, hist_drop, ?DEFAULT_DROP), ?DEFAULT_DROP; {ok, V} when is_list(V) -> [Ln++"\n" || Ln <- V]; {ok, _} -> ?DEFAULT_DROP end. %% Because loading the shell happens really damn early, processes we depend on %% might not be there yet. Luckily, the load function is called from the shell %% after a new process has been spawned, so we can block in here wait_for_kernel_safe_sup() -> case whereis(kernel_safe_sup) of undefined -> timer:sleep(50), wait_for_kernel_safe_sup(); _ -> ok end. %% Load all the elements previously saved in history load(N, _) when N =< 0 -> []; load(N, M) when N =< M -> truncate(M), []; load(N, M) -> case dets:lookup(?TABLE, N-1) of %case dets:lookup(?TABLE, N-1) of [] -> []; % nothing in history [{_,Entry}] -> [Entry | load(N-1,M)]; {error, {{bad_object,_Reason},_TableFile}} -> corrupt_entry_warning(), load(N-1,M); {error, {bad_object_header,_TableFile}} -> corrupt_entry_warning(), load(N-1,M) end. If the history size was changed between two shell sessions , we have to %% truncate the old history. truncate(N) when N =< 0 -> ok; truncate(N) -> dets:delete(?TABLE, N), truncate(N-1). corrupt_entry_warning() -> case get('$#erlang-history-entry-corrupted') of undefined -> io:format(standard_error, "An erlang-history entry was corrupted by DETS. " "Skipping entry...~n", []), put('$#erlang-history-entry-corrupted',true), ok; true -> ok end. corrupt_warning(TableFile) -> case get('$#erlang-history-corrupted') of undefined -> io:format(standard_error, "The erlang-history file at ~s was corrupted by DETS. " "An attempt to repair the file will be made, but if it fails, " "history will be ignored for the rest of this session. If the " "problem persists, please delete the history file " "(and maybe submit it with a bug report).~n", [TableFile]), dets:close(?TABLE), dets:open_file(?TABLE, [{file,(opts())#opts.hist_file},{auto_save, opt(hist_auto_save)},{repair,force}]), put('$#erlang-history-corrupted',true), ok; true -> ok end. unknown_error_warning(Error) -> case get('$#erlang-history-unknown-error') of undefined -> %% Don't display if we're user -- children will send it on our %% behalf case process_info(self(), registered_name) of {registered_name, user} -> ok; _ -> io:format(standard_error, "The erlang-history file could not be opened, and " "history will be ignored for the rest of the session.~n" "The error received was: ~p~n", [Error]) end, put('$#erlang-history-unknown-error',true), ok; true -> ok end.
null
https://raw.githubusercontent.com/ferd/erlang-history/3d74dbc36f942dec3981e44a39454257ada71d37/src/3.2/group_history.erl
erlang
History is node-based, but history of many jobs on a single node are mixed in together. PUBLIC Loads the shell history from memory. This function should only be called from group:server/3 to inject itself in the previous commands stack. We cannot repair the table automatically. The current process is handling output and dets repairing a table outputs a message. we wait to reply to ourselves in some circumstances. We can't recover from this. 1st run Repairing the table means we need to spawn a new process to do it for us. That process will then try to message the current group leader with mentions of trying to repair the table. We need to absorb these, let the process repair, then close the table in order for us to open it again and finally be free! Start a process to open and close the table to repair it, different from the current shell process. currently are the group leader (in this case, the 'user' process). if this is not 'user', we can move on. now we wait for the worker to close the table, telling us it's safe to load it on our own. Adds a given line to the history, only add lines that do not match something to drop from history. The behaviour to avoid storing empty or duplicate lines is in fact implemented within PRIVATE Gets a short record of vital options when setting things up. Defines whether history should be allowed at all. Defines what the base name and path of the history file will be. By default, the file sits in the user's home directory as '.erlang-history.'. All filenames get the node name apended to them. This handles the delay of auto-saving of DETS. This isn't public and the value is currently very short so that shell crashes do not corrupt the file history. Allows to define a list of strings that should not be kept in history. want to keep ways to shut down the shell. Because loading the shell happens really damn early, processes we depend on might not be there yet. Luckily, the load function is called from the shell after a new process has been spawned, so we can block in here Load all the elements previously saved in history case dets:lookup(?TABLE, N-1) of nothing in history truncate the old history. Don't display if we're user -- children will send it on our behalf
-module(group_history). -export([load/0, add/1]). -define(DEFAULT_HIST_FILE, ".erlang-hist"). -define(DEFAULT_HIST_SIZE, 500). -define(TABLE, shell_group_hist). -define(DEFAULT_AUTOSAVE, 500). -define(DEFAULT_DROP, []). -record(opts, {hist=true, hist_file, hist_size}). load() -> case opts() of #opts{hist=false} -> []; #opts{hist_file=F, hist_size=S} -> wait_for_kernel_safe_sup(), Due to how the IO protocol works , this leads to a deadlock where case dets:open_file(?TABLE, [{file,F}, {auto_save, opt(hist_auto_save)}, {repair, false}]) of {ok, ?TABLE} -> load_history(S); {error, {needs_repair, F}} -> repair_table(F); {error, Error} -> unknown_error_warning(Error), application:set_env(kernel, hist, false), [] end end. load_history(S) -> case dets:lookup(?TABLE, ct) of dets:insert(?TABLE, {ct,1}), load(1, 1-S); [{ct,OldCt}] -> load(OldCt, OldCt-S); {error,{{bad_object,_Reason},TableFile}} -> corrupt_warning(TableFile), []; {error,{bad_object_header,TableFile}} -> corrupt_warning(TableFile), [] end. repair_table(F) -> R = make_ref(), S = self(), spawn(fun() -> {ok, ?TABLE} = dets:open_file(?TABLE, [{file,F},{repair,force}]), dets:close(?TABLE), S ! R end), Messages from the IO protocol will only need to be received if we case process_info(self(), registered_name) of {registered_name, user} -> receive {io_request,From,ReplyAs, {put_chars,_Encoding,io_lib,format, ["dets:"++_, [F, [_|_]]]}} -> From ! {io_reply, ReplyAs, ok} end; _ -> ok end, receive R -> ok end, load(). add(Line) -> add(Line, opt(hist)). group : . add(Line, true) -> case lists:member(Line, opt(hist_drop)) of false -> case dets:lookup(?TABLE, ct) of [{ct, Ct}] -> dets:insert(?TABLE, {Ct, Line}), dets:delete(?TABLE, Ct-opt(hist_size)), dets:update_counter(?TABLE, ct, {2,1}); {error,{{bad_object,_Reason},HistFile}} -> corrupt_warning(HistFile); {error,{bad_object_header, HistFile}} -> corrupt_warning(HistFile) end; true -> ok end; add(_, false) -> ok. opts() -> #opts{hist=opt(hist), hist_file=opt(hist_file), hist_size=opt(hist_size)}. opt(hist) -> case application:get_env(kernel, hist) of {ok, true} -> true; {ok, false} -> false; _Default -> true end; opt(hist_file) -> case {opt(hist), application:get_env(kernel, hist_file)} of {true, undefined} -> case init:get_argument(home) of {ok, [[Home]]} -> Name = filename:join([Home, ?DEFAULT_HIST_FILE]), application:set_env(kernel, hist_file, Name), opt(hist_file); _ -> error_logger:error_msg("No place found to save shell history"), erlang:error(badarg) end; {true, {ok, Val}} -> Val++"."++atom_to_list(node()); {false, _} -> undefined end; Defines how many commands should be kept in memory . Default is 500 . opt(hist_size) -> case {opt(hist), application:get_env(kernel, hist_size)} of {true, undefined} -> application:set_env(kernel, hist_size, ?DEFAULT_HIST_SIZE), ?DEFAULT_HIST_SIZE; {true, {ok,Val}} -> Val; {false, _} -> undefined end; opt(hist_auto_save) -> case application:get_env(kernel, hist_auto_save) of undefined -> application:set_env(kernel, hist_auto_save, ?DEFAULT_AUTOSAVE), ?DEFAULT_AUTOSAVE; {ok, V} -> V end; one example would be [ " q().","init : stop().","halt ( ) . " ] if you do not opt(hist_drop) -> case application:get_env(kernel, hist_drop) of undefined -> application:set_env(kernel, hist_drop, ?DEFAULT_DROP), ?DEFAULT_DROP; {ok, V} when is_list(V) -> [Ln++"\n" || Ln <- V]; {ok, _} -> ?DEFAULT_DROP end. wait_for_kernel_safe_sup() -> case whereis(kernel_safe_sup) of undefined -> timer:sleep(50), wait_for_kernel_safe_sup(); _ -> ok end. load(N, _) when N =< 0 -> []; load(N, M) when N =< M -> truncate(M), []; load(N, M) -> case dets:lookup(?TABLE, N-1) of [{_,Entry}] -> [Entry | load(N-1,M)]; {error, {{bad_object,_Reason},_TableFile}} -> corrupt_entry_warning(), load(N-1,M); {error, {bad_object_header,_TableFile}} -> corrupt_entry_warning(), load(N-1,M) end. If the history size was changed between two shell sessions , we have to truncate(N) when N =< 0 -> ok; truncate(N) -> dets:delete(?TABLE, N), truncate(N-1). corrupt_entry_warning() -> case get('$#erlang-history-entry-corrupted') of undefined -> io:format(standard_error, "An erlang-history entry was corrupted by DETS. " "Skipping entry...~n", []), put('$#erlang-history-entry-corrupted',true), ok; true -> ok end. corrupt_warning(TableFile) -> case get('$#erlang-history-corrupted') of undefined -> io:format(standard_error, "The erlang-history file at ~s was corrupted by DETS. " "An attempt to repair the file will be made, but if it fails, " "history will be ignored for the rest of this session. If the " "problem persists, please delete the history file " "(and maybe submit it with a bug report).~n", [TableFile]), dets:close(?TABLE), dets:open_file(?TABLE, [{file,(opts())#opts.hist_file},{auto_save, opt(hist_auto_save)},{repair,force}]), put('$#erlang-history-corrupted',true), ok; true -> ok end. unknown_error_warning(Error) -> case get('$#erlang-history-unknown-error') of undefined -> case process_info(self(), registered_name) of {registered_name, user} -> ok; _ -> io:format(standard_error, "The erlang-history file could not be opened, and " "history will be ignored for the rest of the session.~n" "The error received was: ~p~n", [Error]) end, put('$#erlang-history-unknown-error',true), ok; true -> ok end.
ccd90d82d9f5113f385f2a643aa2315b16740a29a1119a511bcac43367c02ca3
abooij/sudbury
Wayland.hs
Copyright © 2014 Intel Corporation Copyright © 2016 - 2017 to use , copy , modify , distribute , and sell this software and its documentation for any purpose is hereby granted without fee , provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation , and that the name of the copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific , written prior permission . The copyright holders make no representations about the suitability of this software for any purpose . It is provided " as is " without express or implied warranty . THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE , INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS , IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL , INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . Copyright © 2014 Intel Corporation Copyright © 2016-2017 Auke Booij Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of the copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The copyright holders make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -} {-# LANGUAGE CPP #-} # LANGUAGE ForeignFunctionInterface # module Graphics.Sudbury.Socket.Wayland (sendToWayland, recvFromWayland) where import qualified Control.Concurrent as CC import qualified Data.ByteString as BS import Foreign import Foreign.C.Types import System.Posix.Types (Fd(..)) foreign import ccall unsafe "wayland-msg-handling.h sendmsg_wayland" c_sendmsg_wayland :: CInt -- fd buf -> CInt -- bufsize -> Ptr CInt -- fds -> CInt -- n_fds -> IO CInt -- bytes sent foreign import ccall unsafe "wayland-msg-handling.h recvmsg_wayland" c_recvmsg_wayland :: CInt -- fd buf -> CInt -- bufsize -> Ptr CInt -- fds -> CInt -- fdbufsize -> Ptr CInt -- n_fds -> IO CInt -- bytes received TODO limit number of ` Fd`s to be sent to 28 . sendToWayland :: Fd -> BS.ByteString -> [Fd] -> IO CInt sendToWayland socket bs fds = do CC.threadWaitWrite $ fromIntegral socket BS.useAsCStringLen bs sendData where c_fds = map fromIntegral fds sendData (bytePtr, byteLen) = withArrayLen c_fds $ \fdLen fdArray -> do let c_byteLen = fromIntegral byteLen let c_fdLen = fromIntegral fdLen len <- c_sendmsg_wayland (fromIntegral socket) bytePtr c_byteLen fdArray c_fdLen if len < 0 then ioError $ userError "sendmsg failed" else return len recvFromWayland :: Fd -> IO (BS.ByteString, [Fd]) recvFromWayland socket = allocaArray 4096 $ \cbuf -> do CC.threadWaitRead $ fromIntegral socket alloca $ \nFds_ptr -> allocaArray (4*28) $ \fdArray -> do len <- c_recvmsg_wayland (fromIntegral socket) cbuf 4096 fdArray (4*28) nFds_ptr if len < 0 then ioError $ userError "recvmsg failed" else do bs <- BS.packCStringLen (cbuf, fromIntegral len) nFds <- peek nFds_ptr fds <- peekArray (fromIntegral nFds) fdArray return (bs, map fromIntegral fds)
null
https://raw.githubusercontent.com/abooij/sudbury/a9ab559728487d78469db73ecf516d145b6c21ec/Graphics/Sudbury/Socket/Wayland.hs
haskell
# LANGUAGE CPP # fd bufsize fds n_fds bytes sent fd bufsize fds fdbufsize n_fds bytes received
Copyright © 2014 Intel Corporation Copyright © 2016 - 2017 to use , copy , modify , distribute , and sell this software and its documentation for any purpose is hereby granted without fee , provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation , and that the name of the copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific , written prior permission . The copyright holders make no representations about the suitability of this software for any purpose . It is provided " as is " without express or implied warranty . THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE , INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS , IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL , INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . Copyright © 2014 Intel Corporation Copyright © 2016-2017 Auke Booij Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of the copyright holders not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The copyright holders make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -} # LANGUAGE ForeignFunctionInterface # module Graphics.Sudbury.Socket.Wayland (sendToWayland, recvFromWayland) where import qualified Control.Concurrent as CC import qualified Data.ByteString as BS import Foreign import Foreign.C.Types import System.Posix.Types (Fd(..)) foreign import ccall unsafe "wayland-msg-handling.h sendmsg_wayland" buf foreign import ccall unsafe "wayland-msg-handling.h recvmsg_wayland" buf TODO limit number of ` Fd`s to be sent to 28 . sendToWayland :: Fd -> BS.ByteString -> [Fd] -> IO CInt sendToWayland socket bs fds = do CC.threadWaitWrite $ fromIntegral socket BS.useAsCStringLen bs sendData where c_fds = map fromIntegral fds sendData (bytePtr, byteLen) = withArrayLen c_fds $ \fdLen fdArray -> do let c_byteLen = fromIntegral byteLen let c_fdLen = fromIntegral fdLen len <- c_sendmsg_wayland (fromIntegral socket) bytePtr c_byteLen fdArray c_fdLen if len < 0 then ioError $ userError "sendmsg failed" else return len recvFromWayland :: Fd -> IO (BS.ByteString, [Fd]) recvFromWayland socket = allocaArray 4096 $ \cbuf -> do CC.threadWaitRead $ fromIntegral socket alloca $ \nFds_ptr -> allocaArray (4*28) $ \fdArray -> do len <- c_recvmsg_wayland (fromIntegral socket) cbuf 4096 fdArray (4*28) nFds_ptr if len < 0 then ioError $ userError "recvmsg failed" else do bs <- BS.packCStringLen (cbuf, fromIntegral len) nFds <- peek nFds_ptr fds <- peekArray (fromIntegral nFds) fdArray return (bs, map fromIntegral fds)
358569cafdcfba4671e58cf8aeadca13b53279cfac7536f07d863e542473b019
votinginfoproject/data-processor
election_administration_test.clj
(ns vip.data-processor.validation.v5.election-administration-test (:require [vip.data-processor.validation.v5.election-administration :as v5.election-admin] [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as psql] [vip.data-processor.validation.xml :as xml] [clojure.string :as str] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres validate-no-missing-departments-test (testing "missing Department element is an error" (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-no-missing-departments) errors (all-errors errors-chan)] (is (contains-error? errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.2.Department" :error-type :missing})) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.0.Department"}) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.1.Department"}) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.3.Department"})))) (deftest ^:postgres validate-voter-service-type-format-test (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-voter-service-type-format) errors (all-errors errors-chan)] (testing "valid VoterService -> Type is OK" (assert-no-problems errors {:severity :errors :scope :election-administration :identifier (str/join "." ["VipObject" "0" "ElectionAdministration" "0" "Department" "0" "VoterService" "0" "Type" "0"])})) (testing "invalid VoterService -> Type is an error" (is (contains-error? errors {:severity :errors :scope :election-administration :identifier (str/join "." ["VipObject" "0" "ElectionAdministration" "1" "Department" "0" "VoterService" "0" "Type" "0"]) :error-type :format}))))) (deftest ^:postgres validate-no-missing-notice-texts (testing "missing Department element is an error" (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-no-missing-notice-texts) errors (all-errors errors-chan)] (is (contains-error? errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea003" :error-type :missing})) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea001" :error-type :missing}) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea002" :error-type :missing}) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea004" :error-type :missing}))))
null
https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/validation/v5/election_administration_test.clj
clojure
(ns vip.data-processor.validation.v5.election-administration-test (:require [vip.data-processor.validation.v5.election-administration :as v5.election-admin] [clojure.test :refer :all] [vip.data-processor.test-helpers :refer :all] [vip.data-processor.db.postgres :as psql] [vip.data-processor.validation.xml :as xml] [clojure.string :as str] [clojure.core.async :as a])) (use-fixtures :once setup-postgres) (deftest ^:postgres validate-no-missing-departments-test (testing "missing Department element is an error" (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-no-missing-departments) errors (all-errors errors-chan)] (is (contains-error? errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.2.Department" :error-type :missing})) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.0.Department"}) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.1.Department"}) (assert-no-problems errors {:severity :errors :scope :election-administration :identifier "VipObject.0.ElectionAdministration.3.Department"})))) (deftest ^:postgres validate-voter-service-type-format-test (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-voter-service-type-format) errors (all-errors errors-chan)] (testing "valid VoterService -> Type is OK" (assert-no-problems errors {:severity :errors :scope :election-administration :identifier (str/join "." ["VipObject" "0" "ElectionAdministration" "0" "Department" "0" "VoterService" "0" "Type" "0"])})) (testing "invalid VoterService -> Type is an error" (is (contains-error? errors {:severity :errors :scope :election-administration :identifier (str/join "." ["VipObject" "0" "ElectionAdministration" "1" "Department" "0" "VoterService" "0" "Type" "0"]) :error-type :format}))))) (deftest ^:postgres validate-no-missing-notice-texts (testing "missing Department element is an error" (let [errors-chan (a/chan 100) ctx {:xml-source-file-path (xml-input "v5-election-administrations.xml") :errors-chan errors-chan} out-ctx (-> ctx psql/start-run xml/load-xml-ltree v5.election-admin/validate-no-missing-notice-texts) errors (all-errors errors-chan)] (is (contains-error? errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea003" :error-type :missing})) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea001" :error-type :missing}) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea002" :error-type :missing}) (assert-no-problems errors {:severity :errors :scope :election-administration :error-value :missing-election-notice-text :parent-element-id "ea004" :error-type :missing}))))
02f8a7e86477fc16a0cd3f7088536a45928ba471ae2eba4bda9d99fb563440ed
ucsd-progsys/dsolve
array_size.ml
let x y = size y in x [|1;2;3|];;
null
https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/tests/POPL2008/array_size.ml
ocaml
let x y = size y in x [|1;2;3|];;
0a6887e16a06726233e6c5414d4ff2e587c187dc0dc3b1e7d1781ebfe3cb31f4
day8/re-frame-tracer
core.cljs
(ns re-frame-tracer.core (:require [clojure.walk :refer [prewalk walk]] [clairvoyant.core :refer [ITraceEnter ITraceError ITraceExit]])) (defn tracer [& {:keys [color tag] :as options}] (let [pr-val (fn pr-val [x] x) log-binding (fn [form init] (.groupCollapsed js/console "%c%s" "font-weight:bold;" (pr-str form) (pr-val init))) log-exit (fn [exit] (.log js/console "=>" (pr-val exit))) has-bindings? #{'fn* `fn 'fn 'defn `defn 'defn- `defn- 'defmethod `defmethod 'deftype `deftype 'defrecord `defrecord 'reify `reify 'let `let 'extend-type `extend-type 'extend-protocol `extend-protocol} fn-like? (disj has-bindings? 'let `let)] (reify ITraceEnter (-trace-enter [_ {:keys [anonymous? arglist args dispatch-val form init name ns op protocol]}] (cond (fn-like? op) (let [title (if protocol (str protocol " " name " " arglist) (str ns "/" name (when tag (str " " tag)) (when dispatch-val (str " " (pr-str dispatch-val))) (str " " arglist) (when anonymous? " (anonymous)"))) arglist (remove '#{&} arglist)] (.groupCollapsed js/console "%c%s" (str "color:" color ";") title) (.group js/console "bindings")) (#{'let `let} op) (let [title (str op)] (.groupCollapsed js/console title) (.group js/console "bindings")) (#{'binding} op) (log-binding form init))) ITraceExit (-trace-exit [_ {:keys [op exit]}] (cond (#{'binding} op) (do (log-exit exit) (.groupEnd js/console)) (has-bindings? op) (do (.groupEnd js/console) (log-exit exit) (.groupEnd js/console)))) ITraceError (-trace-error [_ {:keys [op form error ex-data]}] (cond (#{'binding} op) (do (.error js/console (.-stack error)) (when ex-data (.groupCollapsed js/console "ex-data") (.groupCollapsed js/console (pr-val ex-data)) (.groupEnd js/console) (.groupEnd js/console))) (has-bindings? op) (do (.groupEnd js/console) (do (.error js/console (.-stack error)) (when ex-data (.groupCollapsed js/console "ex-data") (.groupCollapsed js/console (pr-val ex-data)) (.groupEnd js/console) (.groupEnd js/console))) (.groupEnd js/console)))))))
null
https://raw.githubusercontent.com/day8/re-frame-tracer/e3314c3fd3f90aca10ea1a357523942791f7c2e3/src/re_frame_tracer/core.cljs
clojure
(ns re-frame-tracer.core (:require [clojure.walk :refer [prewalk walk]] [clairvoyant.core :refer [ITraceEnter ITraceError ITraceExit]])) (defn tracer [& {:keys [color tag] :as options}] (let [pr-val (fn pr-val [x] x) log-binding (fn [form init] (.groupCollapsed js/console "%c%s" "font-weight:bold;" (pr-str form) (pr-val init))) log-exit (fn [exit] (.log js/console "=>" (pr-val exit))) has-bindings? #{'fn* `fn 'fn 'defn `defn 'defn- `defn- 'defmethod `defmethod 'deftype `deftype 'defrecord `defrecord 'reify `reify 'let `let 'extend-type `extend-type 'extend-protocol `extend-protocol} fn-like? (disj has-bindings? 'let `let)] (reify ITraceEnter (-trace-enter [_ {:keys [anonymous? arglist args dispatch-val form init name ns op protocol]}] (cond (fn-like? op) (let [title (if protocol (str protocol " " name " " arglist) (str ns "/" name (when tag (str " " tag)) (when dispatch-val (str " " (pr-str dispatch-val))) (str " " arglist) (when anonymous? " (anonymous)"))) arglist (remove '#{&} arglist)] (.groupCollapsed js/console "%c%s" (str "color:" color ";") title) (.group js/console "bindings")) (#{'let `let} op) (let [title (str op)] (.groupCollapsed js/console title) (.group js/console "bindings")) (#{'binding} op) (log-binding form init))) ITraceExit (-trace-exit [_ {:keys [op exit]}] (cond (#{'binding} op) (do (log-exit exit) (.groupEnd js/console)) (has-bindings? op) (do (.groupEnd js/console) (log-exit exit) (.groupEnd js/console)))) ITraceError (-trace-error [_ {:keys [op form error ex-data]}] (cond (#{'binding} op) (do (.error js/console (.-stack error)) (when ex-data (.groupCollapsed js/console "ex-data") (.groupCollapsed js/console (pr-val ex-data)) (.groupEnd js/console) (.groupEnd js/console))) (has-bindings? op) (do (.groupEnd js/console) (do (.error js/console (.-stack error)) (when ex-data (.groupCollapsed js/console "ex-data") (.groupCollapsed js/console (pr-val ex-data)) (.groupEnd js/console) (.groupEnd js/console))) (.groupEnd js/console)))))))
b795a92726df97258b073e0a9fcfa283b19bc8390618abca8cc40639f379c59f
tweag/ormolu
dollar-chains-2.hs
module Main where foo = bar $ do 1 $ quux abc = a1 $ a2 $ do 3 cde = b1 $ b2 $ b3 $ \c -> putStrLn "foo"
null
https://raw.githubusercontent.com/tweag/ormolu/1f63136d047205f95b7d3c0f6aa34c34bb29ac7f/data/examples/declaration/value/function/infix/dollar-chains-2.hs
haskell
module Main where foo = bar $ do 1 $ quux abc = a1 $ a2 $ do 3 cde = b1 $ b2 $ b3 $ \c -> putStrLn "foo"
865f64668f862fd20a2eb1b7728c0eb717bf49dbb81507481676b48563374604
YoshikuniJujo/test_haskell
TryClassSwizzle.hs
# LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts , FlexibleInstances , UndecidableInstances # {-# LANGUAGE StandaloneDeriving, DeriveGeneric #-} # OPTIONS_GHC -Wall -fno - warn - tabs -fno - warn - orphans # module TryClassSwizzle where import qualified GHC.Generics as G import Data.List import SwizzleGen import SwizzleFunOld concat <$> classSwizzle `mapM` [1 .. 19] xx :: Swizzle1 a => a -> (X a, X a) xx a_ = (x a_, x a_) xxx :: Swizzle1 a => a -> (X a, X a, X a) xxx a_ = (x a_, x a_, x a_) xy :: Swizzle2 a => a -> (X a, Y a) xy a_ = (x a_, y a_) yx :: Swizzle2 a => a -> (Y a, X a) yx a_ = (y a_, x a_) ypq :: Swizzle11 a => a -> (Y a, P a, Q a) ypq a_ = (y a_, p a_, q a_) swizzle "yps" concat <$> swizzle `mapM` permutations "xyzw" swizzle "zzxw" concat <$> swizzle `mapM` permutations "xyz" data Point3d = Point3d Double Double Double deriving (Show, G.Generic) instance Swizzle1 Point3d where type X Point3d = Double instance Swizzle2 Point3d where type Y Point3d = Double instance Swizzle3 Point3d where type Z Point3d = Double
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/9e7c265cb7f1d6b71e17d5ee87fd5d491070b959/features/generics/try-generics/src/TryClassSwizzle.hs
haskell
# LANGUAGE StandaloneDeriving, DeriveGeneric #
# LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # # LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts , FlexibleInstances , UndecidableInstances # # OPTIONS_GHC -Wall -fno - warn - tabs -fno - warn - orphans # module TryClassSwizzle where import qualified GHC.Generics as G import Data.List import SwizzleGen import SwizzleFunOld concat <$> classSwizzle `mapM` [1 .. 19] xx :: Swizzle1 a => a -> (X a, X a) xx a_ = (x a_, x a_) xxx :: Swizzle1 a => a -> (X a, X a, X a) xxx a_ = (x a_, x a_, x a_) xy :: Swizzle2 a => a -> (X a, Y a) xy a_ = (x a_, y a_) yx :: Swizzle2 a => a -> (Y a, X a) yx a_ = (y a_, x a_) ypq :: Swizzle11 a => a -> (Y a, P a, Q a) ypq a_ = (y a_, p a_, q a_) swizzle "yps" concat <$> swizzle `mapM` permutations "xyzw" swizzle "zzxw" concat <$> swizzle `mapM` permutations "xyz" data Point3d = Point3d Double Double Double deriving (Show, G.Generic) instance Swizzle1 Point3d where type X Point3d = Double instance Swizzle2 Point3d where type Y Point3d = Double instance Swizzle3 Point3d where type Z Point3d = Double
ce19c0e757237f2d09b3362608769d019403b39e3a72679456a9d985092ff2c4
google/lisp-koans
contemplate.lisp
Copyright 2013 Google Inc. ;;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; -2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (in-package :cl-user) Though Clozure / CCL runs lisp - koans on the command line using ;;; "ccl -l contemplate.lisp", the following lines are needed to meditate on the koans within the CCL IDE . ( The : hemlock is used to distiguish between ccl commandline and the IDE ) #+(and :ccl :hemlock) (setf *default-pathname-defaults* (directory-namestring *load-pathname*)) (load "test-framework.lisp") (load "lisp-koans.lisp") #+quicklisp (ql:quickload :bordeaux-threads) (lisp-koans.core:main)
null
https://raw.githubusercontent.com/google/lisp-koans/df5e58dc88429ef0ff202d0b45c21ce572144ba8/contemplate.lisp
lisp
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. "ccl -l contemplate.lisp", the following lines are needed to
Copyright 2013 Google Inc. distributed under the License is distributed on an " AS IS " BASIS , (in-package :cl-user) Though Clozure / CCL runs lisp - koans on the command line using meditate on the koans within the CCL IDE . ( The : hemlock is used to distiguish between ccl commandline and the IDE ) #+(and :ccl :hemlock) (setf *default-pathname-defaults* (directory-namestring *load-pathname*)) (load "test-framework.lisp") (load "lisp-koans.lisp") #+quicklisp (ql:quickload :bordeaux-threads) (lisp-koans.core:main)
783c22bc05e25543bec3ee88288795e63bd1af127d95ae89b928458b67c0b370
fakedata-haskell/fakedata
Zelda.hs
# LANGUAGE TemplateHaskell # {-# LANGUAGE OverloadedStrings #-} module Faker.Game.Zelda where import Data.Text import Faker import Faker.Internal import Faker.Provider.Zelda import Faker.TH $(generateFakeField "zelda" "games") $(generateFakeField "zelda" "characters") $(generateFakeField "zelda" "locations") $(generateFakeField "zelda" "items")
null
https://raw.githubusercontent.com/fakedata-haskell/fakedata/e6fbc16cfa27b2d17aa449ea8140788196ca135b/src/Faker/Game/Zelda.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TemplateHaskell # module Faker.Game.Zelda where import Data.Text import Faker import Faker.Internal import Faker.Provider.Zelda import Faker.TH $(generateFakeField "zelda" "games") $(generateFakeField "zelda" "characters") $(generateFakeField "zelda" "locations") $(generateFakeField "zelda" "items")
54f55abb6adb5c0de4c9d22067805d5c67d7a696f1f520177d83376c263ab48d
GaloisInc/daedalus
GUID.hs
# Language GeneralizedNewtypeDeriving , DeriveGeneric , DeriveLift # module Daedalus.GUID (GUID , invalidGUID , firstValidGUID , succGUID , getNextGUID , mkGUIDState , mkGUIDState' , guidString , HasGUID(..) , FreshM, runFresh, runFreshIn ) where import Control.DeepSeq (NFData) import GHC.Generics (Generic) import MonadLib import Daedalus.PP import qualified Daedalus.TH as TH newtype GUID = GUID { getGUID :: Int } deriving (Ord, Eq, Show, Generic, NFData,TH.Lift) instance PP GUID where pp (GUID n) = int n guidString :: GUID -> String guidString = show . getGUID -- Used before we have resolved scope invalidGUID :: GUID invalidGUID = GUID (-1) firstValidGUID :: GUID firstValidGUID = GUID 0 succGUID :: GUID -> GUID succGUID guid = GUID (getGUID guid + 1) mkGUIDState :: StateM m s => (s -> GUID) -> (GUID -> s -> s) -> (GUID -> (a, GUID)) -> m a mkGUIDState proj inj f = sets (mkGUIDState' proj inj f) mkGUIDState' :: (s -> GUID) -> (GUID -> s -> s) -> (GUID -> (a, GUID)) -> (s -> (a, s)) mkGUIDState' proj inj = \f s -> let (r, guid') = f (proj s) in (r, inj guid' s) getNextGUID :: HasGUID m => m GUID getNextGUID = guidState (\guid -> (guid, succGUID guid)) newtype FreshM a = FreshM (StateT GUID Id a) deriving (Functor,Applicative,Monad) instance HasGUID FreshM where guidState f = FreshM (sets f) runFresh :: FreshM a -> GUID -> (a,GUID) runFresh (FreshM m) n = runId (runStateT n m) runFreshIn :: HasGUID m => FreshM a -> m a runFreshIn = guidState . runFresh class Monad m => HasGUID m where guidState :: (GUID -> (a, GUID)) -> m a instance (HasGUID m) => HasGUID (IdT m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ReaderT i m) where guidState = lift . guidState instance (HasGUID m,Monoid i) => HasGUID (WriterT i m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (StateT s m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ExceptionT i m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ChoiceT m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ContT i m) where guidState = lift . guidState
null
https://raw.githubusercontent.com/GaloisInc/daedalus/d02dda2e149ffa0e7bcca59cddc4991b875006e4/daedalus-utils/src/Daedalus/GUID.hs
haskell
Used before we have resolved scope
# Language GeneralizedNewtypeDeriving , DeriveGeneric , DeriveLift # module Daedalus.GUID (GUID , invalidGUID , firstValidGUID , succGUID , getNextGUID , mkGUIDState , mkGUIDState' , guidString , HasGUID(..) , FreshM, runFresh, runFreshIn ) where import Control.DeepSeq (NFData) import GHC.Generics (Generic) import MonadLib import Daedalus.PP import qualified Daedalus.TH as TH newtype GUID = GUID { getGUID :: Int } deriving (Ord, Eq, Show, Generic, NFData,TH.Lift) instance PP GUID where pp (GUID n) = int n guidString :: GUID -> String guidString = show . getGUID invalidGUID :: GUID invalidGUID = GUID (-1) firstValidGUID :: GUID firstValidGUID = GUID 0 succGUID :: GUID -> GUID succGUID guid = GUID (getGUID guid + 1) mkGUIDState :: StateM m s => (s -> GUID) -> (GUID -> s -> s) -> (GUID -> (a, GUID)) -> m a mkGUIDState proj inj f = sets (mkGUIDState' proj inj f) mkGUIDState' :: (s -> GUID) -> (GUID -> s -> s) -> (GUID -> (a, GUID)) -> (s -> (a, s)) mkGUIDState' proj inj = \f s -> let (r, guid') = f (proj s) in (r, inj guid' s) getNextGUID :: HasGUID m => m GUID getNextGUID = guidState (\guid -> (guid, succGUID guid)) newtype FreshM a = FreshM (StateT GUID Id a) deriving (Functor,Applicative,Monad) instance HasGUID FreshM where guidState f = FreshM (sets f) runFresh :: FreshM a -> GUID -> (a,GUID) runFresh (FreshM m) n = runId (runStateT n m) runFreshIn :: HasGUID m => FreshM a -> m a runFreshIn = guidState . runFresh class Monad m => HasGUID m where guidState :: (GUID -> (a, GUID)) -> m a instance (HasGUID m) => HasGUID (IdT m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ReaderT i m) where guidState = lift . guidState instance (HasGUID m,Monoid i) => HasGUID (WriterT i m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (StateT s m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ExceptionT i m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ChoiceT m) where guidState = lift . guidState instance (HasGUID m) => HasGUID (ContT i m) where guidState = lift . guidState
b31da05eb5266718b1646d84a2534bdebdf8145fbc8fc4fd1cc3297015e43212
rkallos/canal
canal_utils.erl
-module(canal_utils). -include("include/canal_internal.hrl"). -export([ error_msg/1, error_msg/2, getopt/1, info_msg/1, info_msg/2, warning_msg/1, warning_msg/2 ]). -spec error_msg(string()) -> ok. error_msg(Msg) -> error_logger:error_msg(Msg). -spec error_msg(string(), list()) -> ok. error_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:error_msg(Msg2). -spec getopt(atom()) -> term(). getopt(credentials) -> ?GET_ENV(credentials, undefined); getopt(timeout) -> getopt2([ os:getenv("CANAL_REQUEST_TIMEOUT"), ?GET_ENV(request_timeout, false), ?DEFAULT_REQUEST_TIMEOUT ]); getopt(token) -> getopt2([ os:getenv("VAULT_TOKEN"), ?GET_ENV(vault_token, false), undefined ]); getopt(url) -> iolist_to_binary(getopt2([ os:getenv("VAULT_URL"), ?GET_ENV(url, false), ?DEFAULT_URL ])). -spec info_msg(string()) -> ok. info_msg(Msg) -> error_logger:info_msg(Msg). -spec info_msg(string(), list()) -> ok. info_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:info_msg(Msg2). -spec warning_msg(string()) -> ok. warning_msg(Msg) -> error_logger:warning_msg(Msg). -spec warning_msg(string(), list()) -> ok. warning_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:warning_msg(Msg2). %% private -spec getopt2([false | term()]) -> false | term(). getopt2([Last]) -> Last; getopt2([false | T]) -> getopt2(T); getopt2([H | _]) -> H.
null
https://raw.githubusercontent.com/rkallos/canal/b1456e81615e986b04fd6727302972c55e10ad80/src/canal_utils.erl
erlang
private
-module(canal_utils). -include("include/canal_internal.hrl"). -export([ error_msg/1, error_msg/2, getopt/1, info_msg/1, info_msg/2, warning_msg/1, warning_msg/2 ]). -spec error_msg(string()) -> ok. error_msg(Msg) -> error_logger:error_msg(Msg). -spec error_msg(string(), list()) -> ok. error_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:error_msg(Msg2). -spec getopt(atom()) -> term(). getopt(credentials) -> ?GET_ENV(credentials, undefined); getopt(timeout) -> getopt2([ os:getenv("CANAL_REQUEST_TIMEOUT"), ?GET_ENV(request_timeout, false), ?DEFAULT_REQUEST_TIMEOUT ]); getopt(token) -> getopt2([ os:getenv("VAULT_TOKEN"), ?GET_ENV(vault_token, false), undefined ]); getopt(url) -> iolist_to_binary(getopt2([ os:getenv("VAULT_URL"), ?GET_ENV(url, false), ?DEFAULT_URL ])). -spec info_msg(string()) -> ok. info_msg(Msg) -> error_logger:info_msg(Msg). -spec info_msg(string(), list()) -> ok. info_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:info_msg(Msg2). -spec warning_msg(string()) -> ok. warning_msg(Msg) -> error_logger:warning_msg(Msg). -spec warning_msg(string(), list()) -> ok. warning_msg(Format, Args) -> Msg = io_lib:format(Format, Args), Msg2 = lists:flatten(Msg), error_logger:warning_msg(Msg2). -spec getopt2([false | term()]) -> false | term(). getopt2([Last]) -> Last; getopt2([false | T]) -> getopt2(T); getopt2([H | _]) -> H.
6507e05b24464f89bf2daec87f6f9a3c4cc546c2c3331fecb69c2ea97298b6fb
hammerlab/coclobas
biokepi_machine.ml
#use "topfind";; #thread #require "coclobas.ketrew_backend,biokepi";; open Nonstd module String = Sosa.Native_string let (//) = Filename.concat let env_exn s = try Sys.getenv s with _ -> ksprintf failwith "Missing environment variable %S" s let work_dir = env_exn "BIOKEPI_WORK_DIR" let install_tools_path = try env_exn "INSTALL_TOOLS_PATH" with _ -> work_dir // "toolkit" let pyensembl_cache_dir = try env_exn "PYENSEMBLE_CACHE_DIR" with _ -> work_dir // "pyensembl-cache" let reference_genomes_path = try env_exn "REFERENCE_GENOME_PATH" with _ -> work_dir // "reference-genome" let allow_daemonize = try env_exn "ALLOW_DAEMONIZE" = "true" with _ -> false let image = try env_exn "DOCKER_IMAGE" with _ -> "hammerlab/biokepi-run" let env_exn_tool_loc s tool = try (`Wget (Sys.getenv s)) with _ -> `Fail (sprintf "No location provided for %s" tool) let gatk_jar_location () = env_exn_tool_loc "GATK_JAR_URL" "GATK" let mutect_jar_location () = env_exn_tool_loc "MUTECT_JAR_URL" "MuTect" let netmhc_tool_locations () = Biokepi.Setup.Netmhc.({ netmhc=env_exn_tool_loc "NETMHC_TARBALL_URL" "NetMHC"; netmhcpan=env_exn_tool_loc "NETMHCPAN_TARBALL_URL" "NetMHCpan"; pickpocket=env_exn_tool_loc "PICKPOCKET_TARBALL_URL" "PickPocket"; netmhccons=env_exn_tool_loc "NETMHCCONS_TARBALL_URL" "NetMHCcons"; }) let volume_mounts = env_exn "NFS_MOUNTS" |> String.split ~on:(`Character ':') |> List.map ~f:(fun csv -> String.split ~on:(`Character ',') csv |> begin function | host :: path :: witness :: point :: [] -> `Nfs ( Coclobas.Kube_job.Specification.Nfs_mount.make ~host ~path ~point ()) | other -> ksprintf failwith "Wrong format for NFS_MOUNTS: %S" csv end) let name = "Coclomachine" let biokepi_machine = let host = Ketrew.EDSL.Host.parse "/tmp/KT-coclomachine/" in let max_processors = 7 in let run_program ?name ?(requirements = []) p = let open Ketrew.EDSL in let how = if (List.mem ~set:requirements `Quick_run || List.mem ~set:requirements `Internet_access) && allow_daemonize then `On_server_node else `Submit_to_coclobas in let with_umask prog = Program.(sh "umask 000" && sh "whoami" && sh "groups" && prog) in match how with | `On_server_node -> daemonize ~host ~using:`Python_daemon (with_umask p) | `Submit_to_coclobas -> Coclobas_ketrew_backend.Plugin.run_program ~base_url:":8082" ~image ~volume_mounts Program.( sh " -m 777 -p /cloco - kube / playground " & & sh "echo User" && sh "whoami" && sh "echo Host" && sh "hostname" && sh "echo Machine" && sh "uname -a" && p |> with_umask) in let open Biokepi.Setup.Download_reference_genomes in let toolkit = Biokepi.Setup.Tool_providers.default_toolkit () ~host ~install_tools_path ~run_program ~gatk_jar_location ~mutect_jar_location ~netmhc_tool_locations in Biokepi.Machine.create name ~pyensembl_cache_dir ~max_processors ~get_reference_genome:(fun name -> Biokepi.Setup.Download_reference_genomes.get_reference_genome name ~toolkit ~host ~run_program ~destination_path:reference_genomes_path) ~host ~toolkit ~run_program ~work_dir:(work_dir // "work")
null
https://raw.githubusercontent.com/hammerlab/coclobas/5341ea53fdb5bcea0dfac3e4bd94213b34a48bb9/tools/docker/biokepi_machine.ml
ocaml
#use "topfind";; #thread #require "coclobas.ketrew_backend,biokepi";; open Nonstd module String = Sosa.Native_string let (//) = Filename.concat let env_exn s = try Sys.getenv s with _ -> ksprintf failwith "Missing environment variable %S" s let work_dir = env_exn "BIOKEPI_WORK_DIR" let install_tools_path = try env_exn "INSTALL_TOOLS_PATH" with _ -> work_dir // "toolkit" let pyensembl_cache_dir = try env_exn "PYENSEMBLE_CACHE_DIR" with _ -> work_dir // "pyensembl-cache" let reference_genomes_path = try env_exn "REFERENCE_GENOME_PATH" with _ -> work_dir // "reference-genome" let allow_daemonize = try env_exn "ALLOW_DAEMONIZE" = "true" with _ -> false let image = try env_exn "DOCKER_IMAGE" with _ -> "hammerlab/biokepi-run" let env_exn_tool_loc s tool = try (`Wget (Sys.getenv s)) with _ -> `Fail (sprintf "No location provided for %s" tool) let gatk_jar_location () = env_exn_tool_loc "GATK_JAR_URL" "GATK" let mutect_jar_location () = env_exn_tool_loc "MUTECT_JAR_URL" "MuTect" let netmhc_tool_locations () = Biokepi.Setup.Netmhc.({ netmhc=env_exn_tool_loc "NETMHC_TARBALL_URL" "NetMHC"; netmhcpan=env_exn_tool_loc "NETMHCPAN_TARBALL_URL" "NetMHCpan"; pickpocket=env_exn_tool_loc "PICKPOCKET_TARBALL_URL" "PickPocket"; netmhccons=env_exn_tool_loc "NETMHCCONS_TARBALL_URL" "NetMHCcons"; }) let volume_mounts = env_exn "NFS_MOUNTS" |> String.split ~on:(`Character ':') |> List.map ~f:(fun csv -> String.split ~on:(`Character ',') csv |> begin function | host :: path :: witness :: point :: [] -> `Nfs ( Coclobas.Kube_job.Specification.Nfs_mount.make ~host ~path ~point ()) | other -> ksprintf failwith "Wrong format for NFS_MOUNTS: %S" csv end) let name = "Coclomachine" let biokepi_machine = let host = Ketrew.EDSL.Host.parse "/tmp/KT-coclomachine/" in let max_processors = 7 in let run_program ?name ?(requirements = []) p = let open Ketrew.EDSL in let how = if (List.mem ~set:requirements `Quick_run || List.mem ~set:requirements `Internet_access) && allow_daemonize then `On_server_node else `Submit_to_coclobas in let with_umask prog = Program.(sh "umask 000" && sh "whoami" && sh "groups" && prog) in match how with | `On_server_node -> daemonize ~host ~using:`Python_daemon (with_umask p) | `Submit_to_coclobas -> Coclobas_ketrew_backend.Plugin.run_program ~base_url:":8082" ~image ~volume_mounts Program.( sh " -m 777 -p /cloco - kube / playground " & & sh "echo User" && sh "whoami" && sh "echo Host" && sh "hostname" && sh "echo Machine" && sh "uname -a" && p |> with_umask) in let open Biokepi.Setup.Download_reference_genomes in let toolkit = Biokepi.Setup.Tool_providers.default_toolkit () ~host ~install_tools_path ~run_program ~gatk_jar_location ~mutect_jar_location ~netmhc_tool_locations in Biokepi.Machine.create name ~pyensembl_cache_dir ~max_processors ~get_reference_genome:(fun name -> Biokepi.Setup.Download_reference_genomes.get_reference_genome name ~toolkit ~host ~run_program ~destination_path:reference_genomes_path) ~host ~toolkit ~run_program ~work_dir:(work_dir // "work")
374e64f589f53cbcf97c52baff4c618e9d7db32b7fdfee9c07a698aa579bc925
madgen/temporalog
AST.hs
{-# LANGUAGE GADTs #-} # LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE DuplicateRecordFields # # LANGUAGE KindSignatures # # LANGUAGE RecordWildCards # # LANGUAGE PatternSynonyms # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # # LANGUAGE ScopedTypeVariables # module Language.Temporalog.AST ( Program , Statement , Declaration(..) , PredicateDeclaration(..), JoinDeclaration(..) , Sentence , Query , Clause , Fact , Subgoal , pattern SAtom, pattern SNeg, pattern SConj, pattern SDisj , pattern SAtomF, pattern SNegF, pattern SConjF, pattern SDisjF , pattern SDogru, pattern SDogruF , pattern SEX, pattern SEF, pattern SEG, pattern SEU , pattern SAX, pattern SAF, pattern SAG, pattern SAU , pattern SHeadJump, pattern SBodyJump, pattern SBind , pattern SEXF, pattern SEFF, pattern SEGF, pattern SEUF , pattern SAXF, pattern SAFF, pattern SAGF, pattern SAUF , pattern SHeadJumpF, pattern SBodyJumpF, pattern SBindF , TimeSym(..) , HOp(..), BOp(..), ElaborationStatus(..), Temporal(..) , AG.OpKind(..) , timePred , AG.SomeOp(..) , AG.AtomicFormula(..) , PredicateSymbol(..) , AG.Term(..) , AG.TermType(..) , AG.termType , AG.Var(..) , AG.Sym(..) , AG.declarations, AG.sentences , AG.queries, AG.clauses, AG.facts , predicateDeclarations, joinDeclarations , AG.variables , freeVars , AG.operation ) where import Protolude hiding ((<>), empty) import Data.Functor.Foldable (Base, cata) import Text.PrettyPrint ((<+>), (<>), empty, hcat) import Language.Exalog.Pretty.Helper ((<+?>), prettyC) import Language.Exalog.Core (PredicateSymbol(..)) import Language.Exalog.SrcLoc import qualified Language.Vanillalog.Generic.AST as AG import Language.Vanillalog.Generic.Pretty ( Pretty(..) , HasPrecedence(..) ) type Program eleb = AG.Program Declaration (HOp eleb) (BOp eleb 'Temporal) type Statement eleb = AG.Statement Declaration (HOp eleb) (BOp eleb 'Temporal) type Sentence eleb = AG.Sentence (HOp eleb) (BOp eleb 'Temporal) type Query eleb = AG.Query (HOp eleb) (BOp eleb 'Temporal) type Clause eleb = AG.Clause (HOp eleb) (BOp eleb 'Temporal) type Fact eleb = AG.Fact (HOp eleb) type Subgoal = AG.Subgoal data Declaration = DeclPred {_predDecl :: PredicateDeclaration} | DeclJoin {_joinDecl :: JoinDeclaration} data PredicateDeclaration = PredicateDeclaration { _span :: SrcSpan , _atomType :: AG.AtomicFormula AG.TermType , _timePredSyms :: Maybe [ PredicateSymbol ] } data JoinDeclaration = JoinDeclaration { _span :: SrcSpan , _joint :: PredicateSymbol } data ElaborationStatus = Explicit | Implicit data TimeSym :: ElaborationStatus -> Type where Imp :: TimeSym 'Implicit Exp :: PredicateSymbol -> TimeSym eleb deriving instance Eq (TimeSym eleb) deriving instance Ord (TimeSym eleb) data Temporal = Temporal | ATemporal data BOp :: ElaborationStatus -> Temporal -> AG.OpKind -> Type where Negation :: BOp eleb temp 'AG.Unary Conjunction :: BOp eleb temp 'AG.Binary Disjunction :: BOp eleb temp 'AG.Binary Dogru :: BOp eleb temp 'AG.Nullary AX :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EX :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AG :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EG :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AF :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EF :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AU :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Binary EU :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Binary Bind :: TimeSym eleb -> AG.Var -> BOp eleb 'Temporal 'AG.Unary BodyJump :: TimeSym eleb -> AG.Term -> BOp eleb 'Temporal 'AG.Unary timePred :: BOp 'Explicit temp a -> Maybe PredicateSymbol timePred op = case op of AX (Exp timePredicate) -> Just timePredicate EX (Exp timePredicate) -> Just timePredicate AG (Exp timePredicate) -> Just timePredicate EG (Exp timePredicate) -> Just timePredicate AF (Exp timePredicate) -> Just timePredicate EF (Exp timePredicate) -> Just timePredicate AU (Exp timePredicate) -> Just timePredicate EU (Exp timePredicate) -> Just timePredicate Bind (Exp timePredicate) _ -> Just timePredicate BodyJump (Exp timePredicate) _ -> Just timePredicate _ -> Nothing data HOp :: ElaborationStatus -> AG.OpKind -> Type where HeadJump :: TimeSym eleb -> AG.Term -> HOp eleb 'AG.Unary deriving instance Ord (HOp eleb opKind) deriving instance Ord (BOp eleb temp opKind) deriving instance Eq (HOp eleb opKind) deriving instance Eq (BOp eleb temp opKind) pattern SAtom span atom = AG.SAtom span atom pattern SNeg span sub = AG.SUnOp span Negation sub pattern SConj span sub1 sub2 = AG.SBinOp span Conjunction sub1 sub2 pattern SDisj span sub1 sub2 = AG.SBinOp span Disjunction sub1 sub2 pattern SDogru span = AG.SNullOp span Dogru pattern SAX span timeSym phi = AG.SUnOp span (AX timeSym) phi pattern SEX span timeSym phi = AG.SUnOp span (EX timeSym) phi pattern SAG span timeSym phi = AG.SUnOp span (AG timeSym) phi pattern SEG span timeSym phi = AG.SUnOp span (EG timeSym) phi pattern SAF span timeSym phi = AG.SUnOp span (AF timeSym) phi pattern SEF span timeSym phi = AG.SUnOp span (EF timeSym) phi pattern SAU span timeSym phi psi = AG.SBinOp span (AU timeSym) phi psi pattern SEU span timeSym phi psi = AG.SBinOp span (EU timeSym) phi psi pattern SBind span timeSym var phi = AG.SUnOp span (Bind timeSym var) phi pattern SHeadJump span phi timeSym time = AG.SUnOp span (HeadJump timeSym time) phi pattern SBodyJump span phi timeSym time = AG.SUnOp span (BodyJump timeSym time) phi pattern SAtomF span atom = AG.SAtomF span atom pattern SNegF span child = AG.SUnOpF span Negation child pattern SConjF span child1 child2 = AG.SBinOpF span Conjunction child1 child2 pattern SDisjF span child1 child2 = AG.SBinOpF span Disjunction child1 child2 pattern SDogruF span = AG.SNullOpF span Dogru pattern SAXF span timeSym child = AG.SUnOpF span (AX timeSym) child pattern SEXF span timeSym child = AG.SUnOpF span (EX timeSym) child pattern SAGF span timeSym child = AG.SUnOpF span (AG timeSym) child pattern SEGF span timeSym child = AG.SUnOpF span (EG timeSym) child pattern SAFF span timeSym child = AG.SUnOpF span (AF timeSym) child pattern SEFF span timeSym child = AG.SUnOpF span (EF timeSym) child pattern SAUF span timeSym child1 child2 = AG.SBinOpF span (AU timeSym) child1 child2 pattern SEUF span timeSym child1 child2 = AG.SBinOpF span (EU timeSym) child1 child2 pattern SBindF span timeSym var child = AG.SUnOpF span (Bind timeSym var) child pattern SHeadJumpF span child timeSym time = AG.SUnOpF span (HeadJump timeSym time) child pattern SBodyJumpF span child timeSym time = AG.SUnOpF span (BodyJump timeSym time) child ------------------------------------------------------------------------------- -- Utility functions ------------------------------------------------------------------------------- predicateDeclarations :: Program eleb -> [ PredicateDeclaration ] predicateDeclarations pr = (`mapMaybe` AG.declarations pr) $ \case DeclPred predDecl -> Just predDecl _ -> Nothing joinDeclarations :: Program eleb -> [ JoinDeclaration ] joinDeclarations pr = (`mapMaybe` AG.declarations pr) $ \case DeclJoin joinDecl -> Just joinDecl _ -> Nothing class AG.HasVariables a => HasFreeVariables a where freeVars :: a -> [ AG.Var ] instance HasFreeVariables (Sentence eleb) where freeVars AG.SFact{..} = freeVars _fact freeVars AG.SClause{..} = freeVars _clause freeVars AG.SQuery{..} = freeVars _query instance HasFreeVariables (Clause eleb) where freeVars AG.Clause{..} = freeVars _head ++ freeVars _body instance HasFreeVariables (Query eleb) where freeVars AG.Query{..} = freeVars _body instance HasFreeVariables (Fact eleb) where freeVars AG.Fact{..} = freeVars _head instance HasFreeVariables (AG.AtomicFormula t) => HasFreeVariables (AG.Subgoal (HOp eleb) t) where freeVars = cata varAlg where varAlg :: Base (AG.Subgoal (HOp eleb) t) [ AG.Var ] -> [ AG.Var ] varAlg (SHeadJumpF _ vars _ term) = case term of { AG.TVar v -> v : vars; _ -> vars } varAlg (AG.SAtomF _ atom) = freeVars atom varAlg (AG.SNullOpF _ _) = [] varAlg (AG.SUnOpF _ _ vars) = vars varAlg (AG.SBinOpF _ _ vars1 vars2) = vars1 ++ vars2 instance HasFreeVariables (AG.AtomicFormula t) => HasFreeVariables (AG.Subgoal (BOp eleb temp) t) where freeVars = cata varAlg where varAlg :: Base (AG.Subgoal (BOp eleb temp) t) [ AG.Var ] -> [ AG.Var ] varAlg (SBodyJumpF _ vars _ term) = case term of { AG.TVar v -> v : vars; _ -> vars } varAlg (SBindF _ _ var vars) = filter (var /=) vars varAlg (AG.SAtomF _ atom) = freeVars atom varAlg (AG.SNullOpF _ _) = [] varAlg (AG.SUnOpF _ _ vars) = vars varAlg (AG.SBinOpF _ _ vars1 vars2) = vars1 ++ vars2 instance HasFreeVariables (AG.AtomicFormula AG.Term) where freeVars = AG.variables instance HasFreeVariables (AG.AtomicFormula AG.Var) where freeVars = AG.variables instance HasFreeVariables (AG.AtomicFormula AG.Sym) where freeVars = AG.variables ------------------------------------------------------------------------------- -- Pretty printing related instances ------------------------------------------------------------------------------- instance Spannable Declaration where span DeclPred{..} = span _predDecl span DeclJoin{..} = span _joinDecl ------------------------------------------------------------------------------- -- Pretty printing related instances ------------------------------------------------------------------------------- instance HasPrecedence (BOp eleb temp) where precedence AG.NoOp = 0 precedence (AG.SomeOp Dogru) = 0 precedence (AG.SomeOp Negation) = 1 precedence (AG.SomeOp EX{}) = 1 precedence (AG.SomeOp EF{}) = 1 precedence (AG.SomeOp EG{}) = 1 precedence (AG.SomeOp AX{}) = 1 precedence (AG.SomeOp AF{}) = 1 precedence (AG.SomeOp AG{}) = 1 precedence (AG.SomeOp Conjunction) = 2 precedence (AG.SomeOp Disjunction) = 3 precedence (AG.SomeOp EU{}) = 4 precedence (AG.SomeOp AU{}) = 4 precedence (AG.SomeOp Bind{}) = 5 precedence (AG.SomeOp BodyJump{}) = 6 instance HasPrecedence (HOp eleb) where precedence AG.NoOp = 0 precedence (AG.SomeOp HeadJump{}) = 1 instance Pretty (TimeSym eleb) where pretty (Exp predSym) = "<" <> pretty predSym <> ">" pretty Imp = empty instance Pretty (BOp eleb temp opKind) where pretty Dogru = "TRUE" pretty Negation = "!" pretty Conjunction = ", " pretty Disjunction = "; " pretty (EX timeSym) = "EX" <+> pretty timeSym <> " " pretty (EF timeSym) = "EF" <+> pretty timeSym <> " " pretty (EG timeSym) = "EG" <+> pretty timeSym <> " " pretty (EU timeSym) = " EU" <+> pretty timeSym <> " " pretty (AX timeSym) = "AX" <+> pretty timeSym <> " " pretty (AF timeSym) = "AF" <+> pretty timeSym <> " " pretty (AG timeSym) = "AG" <+> pretty timeSym <> " " pretty (AU timeSym) = " AU" <+> pretty timeSym <> " " pretty (Bind timeSym var) = pretty timeSym <+> pretty var <+> "| " pretty (BodyJump timeSym time) = pretty timeSym <+> pretty time <+> "@ " instance Pretty (HOp eleb opKind) where pretty (HeadJump timeSym time) = pretty timeSym <+> pretty time <+> "@ " instance Pretty Declaration where pretty (DeclPred predDecl) = pretty predDecl pretty (DeclJoin joinDecl) = pretty joinDecl instance Pretty PredicateDeclaration where pretty PredicateDeclaration{..} = ".pred" <+> pretty _atomType <+> "@" <+?> maybe empty (hcat . prettyC) _timePredSyms <> "." instance Pretty JoinDeclaration where pretty JoinDeclaration{..} = ".join" <+> pretty _joint <> "."
null
https://raw.githubusercontent.com/madgen/temporalog/3896a5fcaa10a5a943ea2cee0b87baa97682f7af/src/Language/Temporalog/AST.hs
haskell
# LANGUAGE GADTs # ----------------------------------------------------------------------------- Utility functions ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Pretty printing related instances ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Pretty printing related instances -----------------------------------------------------------------------------
# LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE DuplicateRecordFields # # LANGUAGE KindSignatures # # LANGUAGE RecordWildCards # # LANGUAGE PatternSynonyms # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # # LANGUAGE ScopedTypeVariables # module Language.Temporalog.AST ( Program , Statement , Declaration(..) , PredicateDeclaration(..), JoinDeclaration(..) , Sentence , Query , Clause , Fact , Subgoal , pattern SAtom, pattern SNeg, pattern SConj, pattern SDisj , pattern SAtomF, pattern SNegF, pattern SConjF, pattern SDisjF , pattern SDogru, pattern SDogruF , pattern SEX, pattern SEF, pattern SEG, pattern SEU , pattern SAX, pattern SAF, pattern SAG, pattern SAU , pattern SHeadJump, pattern SBodyJump, pattern SBind , pattern SEXF, pattern SEFF, pattern SEGF, pattern SEUF , pattern SAXF, pattern SAFF, pattern SAGF, pattern SAUF , pattern SHeadJumpF, pattern SBodyJumpF, pattern SBindF , TimeSym(..) , HOp(..), BOp(..), ElaborationStatus(..), Temporal(..) , AG.OpKind(..) , timePred , AG.SomeOp(..) , AG.AtomicFormula(..) , PredicateSymbol(..) , AG.Term(..) , AG.TermType(..) , AG.termType , AG.Var(..) , AG.Sym(..) , AG.declarations, AG.sentences , AG.queries, AG.clauses, AG.facts , predicateDeclarations, joinDeclarations , AG.variables , freeVars , AG.operation ) where import Protolude hiding ((<>), empty) import Data.Functor.Foldable (Base, cata) import Text.PrettyPrint ((<+>), (<>), empty, hcat) import Language.Exalog.Pretty.Helper ((<+?>), prettyC) import Language.Exalog.Core (PredicateSymbol(..)) import Language.Exalog.SrcLoc import qualified Language.Vanillalog.Generic.AST as AG import Language.Vanillalog.Generic.Pretty ( Pretty(..) , HasPrecedence(..) ) type Program eleb = AG.Program Declaration (HOp eleb) (BOp eleb 'Temporal) type Statement eleb = AG.Statement Declaration (HOp eleb) (BOp eleb 'Temporal) type Sentence eleb = AG.Sentence (HOp eleb) (BOp eleb 'Temporal) type Query eleb = AG.Query (HOp eleb) (BOp eleb 'Temporal) type Clause eleb = AG.Clause (HOp eleb) (BOp eleb 'Temporal) type Fact eleb = AG.Fact (HOp eleb) type Subgoal = AG.Subgoal data Declaration = DeclPred {_predDecl :: PredicateDeclaration} | DeclJoin {_joinDecl :: JoinDeclaration} data PredicateDeclaration = PredicateDeclaration { _span :: SrcSpan , _atomType :: AG.AtomicFormula AG.TermType , _timePredSyms :: Maybe [ PredicateSymbol ] } data JoinDeclaration = JoinDeclaration { _span :: SrcSpan , _joint :: PredicateSymbol } data ElaborationStatus = Explicit | Implicit data TimeSym :: ElaborationStatus -> Type where Imp :: TimeSym 'Implicit Exp :: PredicateSymbol -> TimeSym eleb deriving instance Eq (TimeSym eleb) deriving instance Ord (TimeSym eleb) data Temporal = Temporal | ATemporal data BOp :: ElaborationStatus -> Temporal -> AG.OpKind -> Type where Negation :: BOp eleb temp 'AG.Unary Conjunction :: BOp eleb temp 'AG.Binary Disjunction :: BOp eleb temp 'AG.Binary Dogru :: BOp eleb temp 'AG.Nullary AX :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EX :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AG :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EG :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AF :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary EF :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Unary AU :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Binary EU :: TimeSym eleb -> BOp eleb 'Temporal 'AG.Binary Bind :: TimeSym eleb -> AG.Var -> BOp eleb 'Temporal 'AG.Unary BodyJump :: TimeSym eleb -> AG.Term -> BOp eleb 'Temporal 'AG.Unary timePred :: BOp 'Explicit temp a -> Maybe PredicateSymbol timePred op = case op of AX (Exp timePredicate) -> Just timePredicate EX (Exp timePredicate) -> Just timePredicate AG (Exp timePredicate) -> Just timePredicate EG (Exp timePredicate) -> Just timePredicate AF (Exp timePredicate) -> Just timePredicate EF (Exp timePredicate) -> Just timePredicate AU (Exp timePredicate) -> Just timePredicate EU (Exp timePredicate) -> Just timePredicate Bind (Exp timePredicate) _ -> Just timePredicate BodyJump (Exp timePredicate) _ -> Just timePredicate _ -> Nothing data HOp :: ElaborationStatus -> AG.OpKind -> Type where HeadJump :: TimeSym eleb -> AG.Term -> HOp eleb 'AG.Unary deriving instance Ord (HOp eleb opKind) deriving instance Ord (BOp eleb temp opKind) deriving instance Eq (HOp eleb opKind) deriving instance Eq (BOp eleb temp opKind) pattern SAtom span atom = AG.SAtom span atom pattern SNeg span sub = AG.SUnOp span Negation sub pattern SConj span sub1 sub2 = AG.SBinOp span Conjunction sub1 sub2 pattern SDisj span sub1 sub2 = AG.SBinOp span Disjunction sub1 sub2 pattern SDogru span = AG.SNullOp span Dogru pattern SAX span timeSym phi = AG.SUnOp span (AX timeSym) phi pattern SEX span timeSym phi = AG.SUnOp span (EX timeSym) phi pattern SAG span timeSym phi = AG.SUnOp span (AG timeSym) phi pattern SEG span timeSym phi = AG.SUnOp span (EG timeSym) phi pattern SAF span timeSym phi = AG.SUnOp span (AF timeSym) phi pattern SEF span timeSym phi = AG.SUnOp span (EF timeSym) phi pattern SAU span timeSym phi psi = AG.SBinOp span (AU timeSym) phi psi pattern SEU span timeSym phi psi = AG.SBinOp span (EU timeSym) phi psi pattern SBind span timeSym var phi = AG.SUnOp span (Bind timeSym var) phi pattern SHeadJump span phi timeSym time = AG.SUnOp span (HeadJump timeSym time) phi pattern SBodyJump span phi timeSym time = AG.SUnOp span (BodyJump timeSym time) phi pattern SAtomF span atom = AG.SAtomF span atom pattern SNegF span child = AG.SUnOpF span Negation child pattern SConjF span child1 child2 = AG.SBinOpF span Conjunction child1 child2 pattern SDisjF span child1 child2 = AG.SBinOpF span Disjunction child1 child2 pattern SDogruF span = AG.SNullOpF span Dogru pattern SAXF span timeSym child = AG.SUnOpF span (AX timeSym) child pattern SEXF span timeSym child = AG.SUnOpF span (EX timeSym) child pattern SAGF span timeSym child = AG.SUnOpF span (AG timeSym) child pattern SEGF span timeSym child = AG.SUnOpF span (EG timeSym) child pattern SAFF span timeSym child = AG.SUnOpF span (AF timeSym) child pattern SEFF span timeSym child = AG.SUnOpF span (EF timeSym) child pattern SAUF span timeSym child1 child2 = AG.SBinOpF span (AU timeSym) child1 child2 pattern SEUF span timeSym child1 child2 = AG.SBinOpF span (EU timeSym) child1 child2 pattern SBindF span timeSym var child = AG.SUnOpF span (Bind timeSym var) child pattern SHeadJumpF span child timeSym time = AG.SUnOpF span (HeadJump timeSym time) child pattern SBodyJumpF span child timeSym time = AG.SUnOpF span (BodyJump timeSym time) child predicateDeclarations :: Program eleb -> [ PredicateDeclaration ] predicateDeclarations pr = (`mapMaybe` AG.declarations pr) $ \case DeclPred predDecl -> Just predDecl _ -> Nothing joinDeclarations :: Program eleb -> [ JoinDeclaration ] joinDeclarations pr = (`mapMaybe` AG.declarations pr) $ \case DeclJoin joinDecl -> Just joinDecl _ -> Nothing class AG.HasVariables a => HasFreeVariables a where freeVars :: a -> [ AG.Var ] instance HasFreeVariables (Sentence eleb) where freeVars AG.SFact{..} = freeVars _fact freeVars AG.SClause{..} = freeVars _clause freeVars AG.SQuery{..} = freeVars _query instance HasFreeVariables (Clause eleb) where freeVars AG.Clause{..} = freeVars _head ++ freeVars _body instance HasFreeVariables (Query eleb) where freeVars AG.Query{..} = freeVars _body instance HasFreeVariables (Fact eleb) where freeVars AG.Fact{..} = freeVars _head instance HasFreeVariables (AG.AtomicFormula t) => HasFreeVariables (AG.Subgoal (HOp eleb) t) where freeVars = cata varAlg where varAlg :: Base (AG.Subgoal (HOp eleb) t) [ AG.Var ] -> [ AG.Var ] varAlg (SHeadJumpF _ vars _ term) = case term of { AG.TVar v -> v : vars; _ -> vars } varAlg (AG.SAtomF _ atom) = freeVars atom varAlg (AG.SNullOpF _ _) = [] varAlg (AG.SUnOpF _ _ vars) = vars varAlg (AG.SBinOpF _ _ vars1 vars2) = vars1 ++ vars2 instance HasFreeVariables (AG.AtomicFormula t) => HasFreeVariables (AG.Subgoal (BOp eleb temp) t) where freeVars = cata varAlg where varAlg :: Base (AG.Subgoal (BOp eleb temp) t) [ AG.Var ] -> [ AG.Var ] varAlg (SBodyJumpF _ vars _ term) = case term of { AG.TVar v -> v : vars; _ -> vars } varAlg (SBindF _ _ var vars) = filter (var /=) vars varAlg (AG.SAtomF _ atom) = freeVars atom varAlg (AG.SNullOpF _ _) = [] varAlg (AG.SUnOpF _ _ vars) = vars varAlg (AG.SBinOpF _ _ vars1 vars2) = vars1 ++ vars2 instance HasFreeVariables (AG.AtomicFormula AG.Term) where freeVars = AG.variables instance HasFreeVariables (AG.AtomicFormula AG.Var) where freeVars = AG.variables instance HasFreeVariables (AG.AtomicFormula AG.Sym) where freeVars = AG.variables instance Spannable Declaration where span DeclPred{..} = span _predDecl span DeclJoin{..} = span _joinDecl instance HasPrecedence (BOp eleb temp) where precedence AG.NoOp = 0 precedence (AG.SomeOp Dogru) = 0 precedence (AG.SomeOp Negation) = 1 precedence (AG.SomeOp EX{}) = 1 precedence (AG.SomeOp EF{}) = 1 precedence (AG.SomeOp EG{}) = 1 precedence (AG.SomeOp AX{}) = 1 precedence (AG.SomeOp AF{}) = 1 precedence (AG.SomeOp AG{}) = 1 precedence (AG.SomeOp Conjunction) = 2 precedence (AG.SomeOp Disjunction) = 3 precedence (AG.SomeOp EU{}) = 4 precedence (AG.SomeOp AU{}) = 4 precedence (AG.SomeOp Bind{}) = 5 precedence (AG.SomeOp BodyJump{}) = 6 instance HasPrecedence (HOp eleb) where precedence AG.NoOp = 0 precedence (AG.SomeOp HeadJump{}) = 1 instance Pretty (TimeSym eleb) where pretty (Exp predSym) = "<" <> pretty predSym <> ">" pretty Imp = empty instance Pretty (BOp eleb temp opKind) where pretty Dogru = "TRUE" pretty Negation = "!" pretty Conjunction = ", " pretty Disjunction = "; " pretty (EX timeSym) = "EX" <+> pretty timeSym <> " " pretty (EF timeSym) = "EF" <+> pretty timeSym <> " " pretty (EG timeSym) = "EG" <+> pretty timeSym <> " " pretty (EU timeSym) = " EU" <+> pretty timeSym <> " " pretty (AX timeSym) = "AX" <+> pretty timeSym <> " " pretty (AF timeSym) = "AF" <+> pretty timeSym <> " " pretty (AG timeSym) = "AG" <+> pretty timeSym <> " " pretty (AU timeSym) = " AU" <+> pretty timeSym <> " " pretty (Bind timeSym var) = pretty timeSym <+> pretty var <+> "| " pretty (BodyJump timeSym time) = pretty timeSym <+> pretty time <+> "@ " instance Pretty (HOp eleb opKind) where pretty (HeadJump timeSym time) = pretty timeSym <+> pretty time <+> "@ " instance Pretty Declaration where pretty (DeclPred predDecl) = pretty predDecl pretty (DeclJoin joinDecl) = pretty joinDecl instance Pretty PredicateDeclaration where pretty PredicateDeclaration{..} = ".pred" <+> pretty _atomType <+> "@" <+?> maybe empty (hcat . prettyC) _timePredSyms <> "." instance Pretty JoinDeclaration where pretty JoinDeclaration{..} = ".join" <+> pretty _joint <> "."
90a65d6cf908d1e7378f9c90e00cc005c65b503bea643693d9204eac36a30435
vbmithr/ocaml-websocket
wscat.ml
open Core open Async open Websocket_async let () = Logs.set_reporter (Logs_async_reporter.reporter ()) let client protocol extensions uri = let host = Option.value_exn ~message:"no host in uri" Uri.(host uri) in let port = match (Uri.port uri, Uri_services.tcp_port_of_uri uri) with | Some p, _ -> p | None, Some p -> p | _ -> invalid_arg "port cannot be inferred from URL" in let scheme = Option.value_exn ~message:"no scheme in uri" Uri.(scheme uri) in let tcp_fun (r, w) = let module C = Cohttp in let extra_headers = C.Header.init () in let extra_headers = Option.value_map protocol ~default:extra_headers ~f:(fun proto -> C.Header.add extra_headers "Sec-Websocket-Protocol" proto) in let extra_headers = Option.value_map extensions ~default:extra_headers ~f:(fun exts -> C.Header.add extra_headers "Sec-Websocket-Extensions" exts) in let r, w = client_ez ~extra_headers ~heartbeat:Time_ns.Span.(of_int_sec 5) uri r w in Deferred.all_unit [ Pipe.transfer Reader.(pipe @@ Lazy.force stdin) w ~f:(fun s -> String.chop_suffix_exn s ~suffix:"\n"); Pipe.transfer r Writer.(pipe @@ Lazy.force stderr) ~f:(fun s -> s ^ "\n"); ] in Unix.Addr_info.get ~service:(string_of_int port) ~host [] >>= function | [] -> failwithf "DNS resolution failed for %s" host () | { ai_addr; _ } :: _ -> let addr = match (scheme, ai_addr) with | _, ADDR_UNIX path -> `Unix_domain_socket path | "https", ADDR_INET (h, p) | "wss", ADDR_INET (h, p) -> let h = Ipaddr_unix.of_inet_addr h in `OpenSSL (h, p, Conduit_async.V2.Ssl.Config.create ()) | _, ADDR_INET (h, p) -> let h = Ipaddr_unix.of_inet_addr h in `TCP (h, p) in Conduit_async.V2.connect addr >>= tcp_fun let src = Logs.Src.create "websocket.wscat" let handle_client addr reader writer = let addr_str = Socket.Address.(to_string addr) in Logs_async.info ~src (fun m -> m "Client connection from %s" addr_str) >>= fun () -> let app_to_ws, sender_write = Pipe.create () in let receiver_read, ws_to_app = Pipe.create () in let check_request req = Logs_async.info ~src (fun m -> m "Incoming connnection request: %a" Cohttp.Request.pp_hum req) >>= fun () -> Deferred.return (String.equal Cohttp.Request.(uri req |> Uri.path) "/ws") in let rec loop () = Pipe.read receiver_read >>= function | `Eof -> Logs_async.info ~src (fun m -> m "Client %s disconnected" addr_str) | `Ok ({ Frame.opcode; content; _ } as frame) -> let open Frame in Logs_async.debug ~src (fun m -> m "<- %a" Frame.pp frame) >>= fun () -> let frame', closed = match opcode with | Opcode.Ping -> (Some (create ~opcode:Opcode.Pong ~content ()), false) | Opcode.Close -> (* Immediately echo and pass this last message to the user *) if String.length content >= 2 then ( Some (create ~opcode:Opcode.Close ~content:(String.sub content ~pos:0 ~len:2) ()), true ) else (Some (close 100), true) | Opcode.Pong -> (None, false) | Opcode.Text | Opcode.Binary -> (Some frame, false) | _ -> (Some (close 1002), false) in (match frame' with | None -> Deferred.unit | Some frame' -> Logs_async.debug ~src (fun m -> m "-> %a" pp frame') >>= fun () -> Pipe.write sender_write frame') >>= fun () -> if closed then Deferred.unit else loop () in Deferred.any [ (server ~check_request ~app_to_ws ~ws_to_app ~reader ~writer () >>= function | Error err when Poly.equal (Error.to_exn err) Exit -> Deferred.unit | Error err -> Error.raise err | Ok () -> Deferred.unit); loop (); ] let command = let spec = let open Command.Spec in empty +> flag "-protocol" (optional string) ~doc:"str websocket protocol header" +> flag "-extensions" (optional string) ~doc:"str websocket extensions header" +> flag "-loglevel" (optional int) ~doc:"1-3 loglevel" +> flag "-s" no_arg ~doc:" Run as server (default: no)" +> anon ("url" %: string) in let set_loglevel = function | 2 -> Logs.set_level (Some Info) | 3 -> Logs.set_level (Some Debug) | _ -> () in let run protocol extension loglevel is_server url () = Option.iter loglevel ~f:set_loglevel; let url = Uri.of_string url in match is_server with | false -> client protocol extension url | true -> let port = Option.value_exn ~message:"no port inferred from scheme" Uri_services.(tcp_port_of_uri url) in Tcp.( Server.create ~on_handler_error:`Ignore Where_to_listen.(of_port port) handle_client) >>= Tcp.Server.close_finished in Command.async_spec ~summary:"telnet-like interface to Websockets" spec run let () = Command_unix.run command
null
https://raw.githubusercontent.com/vbmithr/ocaml-websocket/3edc21aab7ced4c70313875a453dc9b03425ea13/async/wscat.ml
ocaml
Immediately echo and pass this last message to the user
open Core open Async open Websocket_async let () = Logs.set_reporter (Logs_async_reporter.reporter ()) let client protocol extensions uri = let host = Option.value_exn ~message:"no host in uri" Uri.(host uri) in let port = match (Uri.port uri, Uri_services.tcp_port_of_uri uri) with | Some p, _ -> p | None, Some p -> p | _ -> invalid_arg "port cannot be inferred from URL" in let scheme = Option.value_exn ~message:"no scheme in uri" Uri.(scheme uri) in let tcp_fun (r, w) = let module C = Cohttp in let extra_headers = C.Header.init () in let extra_headers = Option.value_map protocol ~default:extra_headers ~f:(fun proto -> C.Header.add extra_headers "Sec-Websocket-Protocol" proto) in let extra_headers = Option.value_map extensions ~default:extra_headers ~f:(fun exts -> C.Header.add extra_headers "Sec-Websocket-Extensions" exts) in let r, w = client_ez ~extra_headers ~heartbeat:Time_ns.Span.(of_int_sec 5) uri r w in Deferred.all_unit [ Pipe.transfer Reader.(pipe @@ Lazy.force stdin) w ~f:(fun s -> String.chop_suffix_exn s ~suffix:"\n"); Pipe.transfer r Writer.(pipe @@ Lazy.force stderr) ~f:(fun s -> s ^ "\n"); ] in Unix.Addr_info.get ~service:(string_of_int port) ~host [] >>= function | [] -> failwithf "DNS resolution failed for %s" host () | { ai_addr; _ } :: _ -> let addr = match (scheme, ai_addr) with | _, ADDR_UNIX path -> `Unix_domain_socket path | "https", ADDR_INET (h, p) | "wss", ADDR_INET (h, p) -> let h = Ipaddr_unix.of_inet_addr h in `OpenSSL (h, p, Conduit_async.V2.Ssl.Config.create ()) | _, ADDR_INET (h, p) -> let h = Ipaddr_unix.of_inet_addr h in `TCP (h, p) in Conduit_async.V2.connect addr >>= tcp_fun let src = Logs.Src.create "websocket.wscat" let handle_client addr reader writer = let addr_str = Socket.Address.(to_string addr) in Logs_async.info ~src (fun m -> m "Client connection from %s" addr_str) >>= fun () -> let app_to_ws, sender_write = Pipe.create () in let receiver_read, ws_to_app = Pipe.create () in let check_request req = Logs_async.info ~src (fun m -> m "Incoming connnection request: %a" Cohttp.Request.pp_hum req) >>= fun () -> Deferred.return (String.equal Cohttp.Request.(uri req |> Uri.path) "/ws") in let rec loop () = Pipe.read receiver_read >>= function | `Eof -> Logs_async.info ~src (fun m -> m "Client %s disconnected" addr_str) | `Ok ({ Frame.opcode; content; _ } as frame) -> let open Frame in Logs_async.debug ~src (fun m -> m "<- %a" Frame.pp frame) >>= fun () -> let frame', closed = match opcode with | Opcode.Ping -> (Some (create ~opcode:Opcode.Pong ~content ()), false) | Opcode.Close -> if String.length content >= 2 then ( Some (create ~opcode:Opcode.Close ~content:(String.sub content ~pos:0 ~len:2) ()), true ) else (Some (close 100), true) | Opcode.Pong -> (None, false) | Opcode.Text | Opcode.Binary -> (Some frame, false) | _ -> (Some (close 1002), false) in (match frame' with | None -> Deferred.unit | Some frame' -> Logs_async.debug ~src (fun m -> m "-> %a" pp frame') >>= fun () -> Pipe.write sender_write frame') >>= fun () -> if closed then Deferred.unit else loop () in Deferred.any [ (server ~check_request ~app_to_ws ~ws_to_app ~reader ~writer () >>= function | Error err when Poly.equal (Error.to_exn err) Exit -> Deferred.unit | Error err -> Error.raise err | Ok () -> Deferred.unit); loop (); ] let command = let spec = let open Command.Spec in empty +> flag "-protocol" (optional string) ~doc:"str websocket protocol header" +> flag "-extensions" (optional string) ~doc:"str websocket extensions header" +> flag "-loglevel" (optional int) ~doc:"1-3 loglevel" +> flag "-s" no_arg ~doc:" Run as server (default: no)" +> anon ("url" %: string) in let set_loglevel = function | 2 -> Logs.set_level (Some Info) | 3 -> Logs.set_level (Some Debug) | _ -> () in let run protocol extension loglevel is_server url () = Option.iter loglevel ~f:set_loglevel; let url = Uri.of_string url in match is_server with | false -> client protocol extension url | true -> let port = Option.value_exn ~message:"no port inferred from scheme" Uri_services.(tcp_port_of_uri url) in Tcp.( Server.create ~on_handler_error:`Ignore Where_to_listen.(of_port port) handle_client) >>= Tcp.Server.close_finished in Command.async_spec ~summary:"telnet-like interface to Websockets" spec run let () = Command_unix.run command
562304c4e47720c2f2dbb9092caa4c9f2021f9d560ad5c6a8fb36e3aa66e90fc
cryptosense/ppx_factory
factory.mli
open Ppxlib (** Structure generator *) val from_str_type_decl : (structure, rec_flag * type_declaration list) Deriving.Generator.t (** Signature generator *) val from_sig_type_decl : (signature, rec_flag * type_declaration list) Deriving.Generator.t (** Return the name of the factory function derived from a type with the given name. *) val _name_from_type_name : string -> string (** Return the name of the factory derived from a type with a given [type_name] and for the constructor with [constructor_name]. *) val _name_from_type_and_constructor_name : type_name: string -> constructor_name: string -> string
null
https://raw.githubusercontent.com/cryptosense/ppx_factory/d7cad104e64e700540a2195459ae484dc099ccf3/lib/factory.mli
ocaml
* Structure generator * Signature generator * Return the name of the factory function derived from a type with the given name. * Return the name of the factory derived from a type with a given [type_name] and for the constructor with [constructor_name].
open Ppxlib val from_str_type_decl : (structure, rec_flag * type_declaration list) Deriving.Generator.t val from_sig_type_decl : (signature, rec_flag * type_declaration list) Deriving.Generator.t val _name_from_type_name : string -> string val _name_from_type_and_constructor_name : type_name: string -> constructor_name: string -> string
cee46df5a4a909dfdd5115a2ce255c4738653d20ab8d686e4b9bf5ce54cc6465
ostinelli/ram
ram_benchmark.erl
%% ========================================================================================================== Ram - A distributed KV store for Erlang and Elixir . %% The MIT License ( MIT ) %% Copyright ( c ) 2021 - 2022 < > . %% %% Permission is hereby granted, free of charge, to any person obtaining a copy %% of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation the rights %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %% furnished to do so, subject to the following conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %% THE SOFTWARE. %% ========================================================================================================== -module(ram_benchmark). %% API -export([ start/0, put_on_node/4, get_on_node/4 ]). -export([ start_profiling/1, stop_profiling/1, start_profiling_on_node/0, stop_profiling_on_node/0 ]). %% =================================================================== %% API %% =================================================================== %% example run: `KEY_COUNT=100000 WORKERS_PER_NODE=100 NODES_COUNT=2 make bench` start() -> %% init KeyCount = list_to_integer(os:getenv("KEY_COUNT", "100000")), WorkersPerNode = list_to_integer(os:getenv("WORKERS_PER_NODE", "100")), SlavesCount = list_to_integer(os:getenv("NODES_COUNT", "2")), KeysPerNode = round(KeyCount / SlavesCount), MaxKeyCount = KeysPerNode * SlavesCount, CollectorPid = self(), io:format("====> Starting benchmark~n"), io:format(" --> Nodes: ~w~n", [SlavesCount]), io:format(" --> Total keys: ~w (~w / node)~n", [MaxKeyCount, KeysPerNode]), io:format(" --> Workers per node: ~w~n~n", [WorkersPerNode]), %% start nodes NodesInfo = lists:foldl(fun(I, Acc) -> %% start slave CountBin = integer_to_binary(I), NodeShortName = list_to_atom(binary_to_list(<<"slave_", CountBin/binary>>)), {ok, Node} = ct_slave:start(NodeShortName, [ {boot_timeout, 10}, {monitor_master, true} ]), %% add code path CodePath = code:get_path(), true = rpc:call(Node, code, set_path, [CodePath]), %% init ok = rpc:call(Node, application, set_env, [ra, data_dir, "/tmp/ra-bench"]), %% start ram ok = rpc:call(Node, ram, start, []), %% gather data FromKey = (I - 1) * KeysPerNode + 1, ToKey = FromKey + KeysPerNode - 1, %% fold [{Node, FromKey, ToKey} | Acc] end, [], lists:seq(1, SlavesCount)), %% wait for cluster Nodes = lists:foldl(fun({Node, _FromKey, _ToKey}, Acc) -> [Node | Acc] end, [], NodesInfo), ram_test_suite_helper:wait_cluster_mesh_connected(Nodes), %% cluster ram:start_cluster(Nodes), %% start registration lists:foreach(fun({Node, FromKey, ToKey}) -> rpc:cast(Node, ?MODULE, put_on_node, [CollectorPid, WorkersPerNode, FromKey, ToKey]) end, NodesInfo), %% wait PutRemoteNodesTimes = wait_from_all_remote_nodes(nodes(), []), io:format("----> Remote put times:~n"), io:format(" --> MIN: ~p secs.~n", [lists:min(PutRemoteNodesTimes)]), io:format(" --> MAX: ~p secs.~n", [lists:max(PutRemoteNodesTimes)]), PutRate = MaxKeyCount / lists:max(PutRemoteNodesTimes), io:format("====> Put rate: ~p/sec.~n~n", [PutRate]), %% start reading lists:foreach(fun({Node, FromKey, ToKey}) -> rpc:cast(Node, ?MODULE, get_on_node, [CollectorPid, WorkersPerNode, FromKey, ToKey]) end, NodesInfo), %% wait GetRemoteNodesTimes = wait_from_all_remote_nodes(nodes(), []), io:format("----> Remote get times:~n"), io:format(" --> MIN: ~p secs.~n", [lists:min(GetRemoteNodesTimes)]), io:format(" --> MAX: ~p secs.~n", [lists:max(GetRemoteNodesTimes)]), GetRate = MaxKeyCount / lists:max(GetRemoteNodesTimes), io:format("====> Get rate: ~p/sec.~n~n", [GetRate]), %% stop node init:stop(). put_on_node(CollectorPid, WorkersPerNode, FromKey, ToKey) -> do_on_node(CollectorPid, fun worker_put_on_node/2, "Put", WorkersPerNode, FromKey, ToKey). get_on_node(CollectorPid, WorkersPerNode, FromKey, ToKey) -> do_on_node(CollectorPid, fun worker_get_on_node/2, "Get", WorkersPerNode, FromKey, ToKey). do_on_node(CollectorPid, Fun, Desc, WorkersPerNode, FromKey, ToKey) -> Count = ToKey - FromKey + 1, %% spawn workers KeysPerNode = ceil(Count / WorkersPerNode), ReplyPid = self(), lists:foreach(fun(I) -> WorkerFromKey = FromKey + (I - 1) * KeysPerNode, WorkerToKey = lists:min([WorkerFromKey + KeysPerNode - 1, ToKey]), spawn(fun() -> StartAt = os:system_time(millisecond), Fun(WorkerFromKey, WorkerToKey), Time = (os:system_time(millisecond) - StartAt) / 1000, ReplyPid ! {done, Time} end) end, lists:seq(1, WorkersPerNode)), %% wait Time = wait_done_on_node(CollectorPid, 0, WorkersPerNode), io:format("----> ~s on node ~p on ~p secs.~n", [Desc, node(), Time]). worker_put_on_node(Key, WorkerToKey) when Key =< WorkerToKey -> ok = ram:put(Key, Key), worker_put_on_node(Key + 1, WorkerToKey); worker_put_on_node(_, _) -> ok. worker_get_on_node(Key, WorkerToKey) when Key =< WorkerToKey -> Key = ram:get(Key), worker_get_on_node(Key + 1, WorkerToKey); worker_get_on_node(_, _) -> ok. wait_done_on_node(CollectorPid, Time, 0) -> CollectorPid ! {done, node(), Time}, Time; wait_done_on_node(CollectorPid, Time, WorkersRemainingCount) -> receive {done, WorkerTime} -> Time1 = lists:max([WorkerTime, Time]), wait_done_on_node(CollectorPid, Time1, WorkersRemainingCount - 1) end. wait_from_all_remote_nodes([], Times) -> Times; wait_from_all_remote_nodes([RemoteNode | Tail], Times) -> receive {done, RemoteNode, Time} -> wait_from_all_remote_nodes(Tail, [Time | Times]) end. start_profiling(NodesInfo) -> {Node, _FromKey, _ToKey} = hd(NodesInfo), ok = rpc:call(Node, ?MODULE, start_profiling_on_node, []). stop_profiling(NodesInfo) -> {Node, _FromKey, _ToKey} = hd(NodesInfo), ok = rpc:call(Node, ?MODULE, stop_profiling_on_node, []). start_profiling_on_node() -> {ok, P} = eprof:start(), eprof:start_profiling(erlang:processes() -- [P]), ok. stop_profiling_on_node() -> eprof:stop_profiling(), eprof:analyze(total), ok.
null
https://raw.githubusercontent.com/ostinelli/ram/001e2695b94ac4b63ff4716be8221f1d8ce9545a/test/ram_benchmark.erl
erlang
========================================================================================================== Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ========================================================================================================== API =================================================================== API =================================================================== example run: `KEY_COUNT=100000 WORKERS_PER_NODE=100 NODES_COUNT=2 make bench` init start nodes start slave add code path init start ram gather data fold wait for cluster cluster start registration wait start reading wait stop node spawn workers wait
Ram - A distributed KV store for Erlang and Elixir . The MIT License ( MIT ) Copyright ( c ) 2021 - 2022 < > . in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , -module(ram_benchmark). -export([ start/0, put_on_node/4, get_on_node/4 ]). -export([ start_profiling/1, stop_profiling/1, start_profiling_on_node/0, stop_profiling_on_node/0 ]). start() -> KeyCount = list_to_integer(os:getenv("KEY_COUNT", "100000")), WorkersPerNode = list_to_integer(os:getenv("WORKERS_PER_NODE", "100")), SlavesCount = list_to_integer(os:getenv("NODES_COUNT", "2")), KeysPerNode = round(KeyCount / SlavesCount), MaxKeyCount = KeysPerNode * SlavesCount, CollectorPid = self(), io:format("====> Starting benchmark~n"), io:format(" --> Nodes: ~w~n", [SlavesCount]), io:format(" --> Total keys: ~w (~w / node)~n", [MaxKeyCount, KeysPerNode]), io:format(" --> Workers per node: ~w~n~n", [WorkersPerNode]), NodesInfo = lists:foldl(fun(I, Acc) -> CountBin = integer_to_binary(I), NodeShortName = list_to_atom(binary_to_list(<<"slave_", CountBin/binary>>)), {ok, Node} = ct_slave:start(NodeShortName, [ {boot_timeout, 10}, {monitor_master, true} ]), CodePath = code:get_path(), true = rpc:call(Node, code, set_path, [CodePath]), ok = rpc:call(Node, application, set_env, [ra, data_dir, "/tmp/ra-bench"]), ok = rpc:call(Node, ram, start, []), FromKey = (I - 1) * KeysPerNode + 1, ToKey = FromKey + KeysPerNode - 1, [{Node, FromKey, ToKey} | Acc] end, [], lists:seq(1, SlavesCount)), Nodes = lists:foldl(fun({Node, _FromKey, _ToKey}, Acc) -> [Node | Acc] end, [], NodesInfo), ram_test_suite_helper:wait_cluster_mesh_connected(Nodes), ram:start_cluster(Nodes), lists:foreach(fun({Node, FromKey, ToKey}) -> rpc:cast(Node, ?MODULE, put_on_node, [CollectorPid, WorkersPerNode, FromKey, ToKey]) end, NodesInfo), PutRemoteNodesTimes = wait_from_all_remote_nodes(nodes(), []), io:format("----> Remote put times:~n"), io:format(" --> MIN: ~p secs.~n", [lists:min(PutRemoteNodesTimes)]), io:format(" --> MAX: ~p secs.~n", [lists:max(PutRemoteNodesTimes)]), PutRate = MaxKeyCount / lists:max(PutRemoteNodesTimes), io:format("====> Put rate: ~p/sec.~n~n", [PutRate]), lists:foreach(fun({Node, FromKey, ToKey}) -> rpc:cast(Node, ?MODULE, get_on_node, [CollectorPid, WorkersPerNode, FromKey, ToKey]) end, NodesInfo), GetRemoteNodesTimes = wait_from_all_remote_nodes(nodes(), []), io:format("----> Remote get times:~n"), io:format(" --> MIN: ~p secs.~n", [lists:min(GetRemoteNodesTimes)]), io:format(" --> MAX: ~p secs.~n", [lists:max(GetRemoteNodesTimes)]), GetRate = MaxKeyCount / lists:max(GetRemoteNodesTimes), io:format("====> Get rate: ~p/sec.~n~n", [GetRate]), init:stop(). put_on_node(CollectorPid, WorkersPerNode, FromKey, ToKey) -> do_on_node(CollectorPid, fun worker_put_on_node/2, "Put", WorkersPerNode, FromKey, ToKey). get_on_node(CollectorPid, WorkersPerNode, FromKey, ToKey) -> do_on_node(CollectorPid, fun worker_get_on_node/2, "Get", WorkersPerNode, FromKey, ToKey). do_on_node(CollectorPid, Fun, Desc, WorkersPerNode, FromKey, ToKey) -> Count = ToKey - FromKey + 1, KeysPerNode = ceil(Count / WorkersPerNode), ReplyPid = self(), lists:foreach(fun(I) -> WorkerFromKey = FromKey + (I - 1) * KeysPerNode, WorkerToKey = lists:min([WorkerFromKey + KeysPerNode - 1, ToKey]), spawn(fun() -> StartAt = os:system_time(millisecond), Fun(WorkerFromKey, WorkerToKey), Time = (os:system_time(millisecond) - StartAt) / 1000, ReplyPid ! {done, Time} end) end, lists:seq(1, WorkersPerNode)), Time = wait_done_on_node(CollectorPid, 0, WorkersPerNode), io:format("----> ~s on node ~p on ~p secs.~n", [Desc, node(), Time]). worker_put_on_node(Key, WorkerToKey) when Key =< WorkerToKey -> ok = ram:put(Key, Key), worker_put_on_node(Key + 1, WorkerToKey); worker_put_on_node(_, _) -> ok. worker_get_on_node(Key, WorkerToKey) when Key =< WorkerToKey -> Key = ram:get(Key), worker_get_on_node(Key + 1, WorkerToKey); worker_get_on_node(_, _) -> ok. wait_done_on_node(CollectorPid, Time, 0) -> CollectorPid ! {done, node(), Time}, Time; wait_done_on_node(CollectorPid, Time, WorkersRemainingCount) -> receive {done, WorkerTime} -> Time1 = lists:max([WorkerTime, Time]), wait_done_on_node(CollectorPid, Time1, WorkersRemainingCount - 1) end. wait_from_all_remote_nodes([], Times) -> Times; wait_from_all_remote_nodes([RemoteNode | Tail], Times) -> receive {done, RemoteNode, Time} -> wait_from_all_remote_nodes(Tail, [Time | Times]) end. start_profiling(NodesInfo) -> {Node, _FromKey, _ToKey} = hd(NodesInfo), ok = rpc:call(Node, ?MODULE, start_profiling_on_node, []). stop_profiling(NodesInfo) -> {Node, _FromKey, _ToKey} = hd(NodesInfo), ok = rpc:call(Node, ?MODULE, stop_profiling_on_node, []). start_profiling_on_node() -> {ok, P} = eprof:start(), eprof:start_profiling(erlang:processes() -- [P]), ok. stop_profiling_on_node() -> eprof:stop_profiling(), eprof:analyze(total), ok.
4a0a52f12d5d2278a0f4066a8da38636506c4e34578be4f7a36c4eac19ef0881
GaloisInc/llvm-verifier
Grammar.hs
{-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # # LANGUAGE PatternGuards # {-# LANGUAGE Rank2Types #-} # LANGUAGE ViewPatterns # | Module : $ Header$ Description : Symbolic execution tests License : BSD3 Stability : provisional Point - of - contact : acfoltzer Module : $Header$ Description : Symbolic execution tests License : BSD3 Stability : provisional Point-of-contact : acfoltzer -} module Verifier.LLVM.Debugger.Grammar ( Grammar , SwitchKey , switch , hide , cmdDef , keyword , argLabel , (<||>) , opt , nat , HelpResult , helpCmds , ppCmdHelp , matcherHelp , ParseResult(..) , resolveParse , parseString , parseCompletions ) where import Control.Lens import Control.Monad.State as MTL import Data.Char import qualified Data.Foldable as Fold import Data.Kind ( Type ) import Data.List.Compat import qualified Data.Map as Map import Data.Maybe import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.String import System.Console.Haskeline (Completion(..)) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (</>)) import qualified Text.PrettyPrint.ANSI.Leijen as PP import Prelude () import Prelude.Compat hiding (mapM_) import Verifier.LLVM.Debugger.FreeApp import Verifier.LLVM.Utils.PrettyPrint ------------------------------------------------------------------------ Generic unionMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a unionMaybe u (Just x) y = Just (maybe x (u x) y) unionMaybe _ Nothing y = y ------------------------------------------------------------------------ -- List utilities | Split a list into the first elements and the last elemt . rcons :: [a] -> Maybe ([a], a) rcons l = case reverse l of [] -> Nothing (e:r) -> Just (reverse r,e) | @nonemptyPrefixes l@ returns non - empty prefixes of @l@. nonemptyPrefixes ::[a] -> [[a]] nonemptyPrefixes = tail . inits -- | @strictNonemptyPrefixes l@ returns non-empty strict prefixes of @l@. strictNonemptyPrefixes :: [a] -> [[a]] strictNonemptyPrefixes i = case rcons i of Nothing -> [] Just (r,_) -> nonemptyPrefixes r ------------------------------------------------------------------------ Token and Tokentype -- | Token from parser. data Token = Keyword String | StringLit String | NatToken Integer -- | A non-negative integer. | OpToken String | BadChar String deriving (Eq, Ord, Show) | A " type " for . Tokens with the same type need -- a space between them. data TokenType = WordTokenType | OpTokenType | BadCharType deriving (Eq, Show) -- | Type of token. tokenType :: Token -> TokenType tokenType Keyword{} = WordTokenType tokenType StringLit{} = WordTokenType tokenType NatToken{} = WordTokenType tokenType OpToken{} = OpTokenType tokenType BadChar{} = BadCharType -- | Pretty print a token. ppToken :: Token -> Doc ppToken (Keyword k) = text k ppToken (StringLit s) = dquotes (text s) ppToken (NatToken i) = integer i ppToken (OpToken k) = text k ppToken (BadChar s) = text s ------------------------------------------------------------------------ CharStream data CharStream = CSNext !Pos !Char !CharStream | CSEnd !Pos csString :: CharStream -> String csString (CSNext _ c cs) = c : csString cs csString (CSEnd _) = [] csEndPos :: CharStream -> Pos csEndPos (CSNext _ _ cs) = csEndPos cs csEndPos (CSEnd p) = p charStream :: String -> CharStream charStream = impl startPos where impl p (c:l) = CSNext p c $ impl (incPos p c) l impl p [] = CSEnd p ------------------------------------------------------------------------ -- TokenSeq type Pos = Int startPos :: Pos startPos = 0 incPos :: Pos -> Char -> Pos incPos p _ = p+1 data TokenSeq t = SeqCons Pos t (TokenSeq t) | SeqLast Pos t Pos | SeqEnd Pos tokenSeqPos :: TokenSeq t -> Pos tokenSeqPos (SeqCons p _ _) = p tokenSeqPos (SeqLast p _ _) = p tokenSeqPos (SeqEnd p) = p tokenSeqTokens :: Traversal (TokenSeq s) (TokenSeq t) s t tokenSeqTokens f (SeqCons p t s) = SeqCons p <$> f t <*> tokenSeqTokens f s tokenSeqTokens f (SeqLast p t pe) = (\ u -> SeqLast p u pe) <$> f t tokenSeqTokens _ (SeqEnd p) = pure (SeqEnd p) convertToTokens :: String -> TokenSeq Token convertToTokens = tokenize . charStream where tokenize :: CharStream -> TokenSeq Token tokenize (CSNext p c r) | isSpace c = tokenize r | c == '\"' = stringLit p [] r -- Hex literal. | c == '0' , CSNext p' 'x' r' <- r = charSeq isHexDigit isSpace (NatToken . read) p' ['x','0'] r' -- Binary literal. | c == '0' , CSNext p' 'b' r' <- r = charSeq isBinDigit isSpace (NatToken . readBinary) p' ['b','0'] r' | isDigit c = charSeq isDigit isSpace (NatToken . read) p [c] r | isToken1 c = charSeq isToken isSpace Keyword p [c] r | isOp c = charSeq isOp (\_ -> True) OpToken p [c] r | otherwise = badChar p [c] r tokenize (CSEnd p) = SeqEnd p badChar :: Pos -> String -> CharStream -> TokenSeq Token badChar p s r = SeqLast p (BadChar (s ++ csString r)) (csEndPos r) isToken1 c = isAlpha c || c `elem` ['_', '%'] isToken c = isAlphaNum c || c `elem` ['_', '%'] Recognize operator characters . isOp = (`elem` ['.', ':']) @charSeq whilePred endPred ctor pos p cs@ recognizes a word -- with characters satisfying whilePred that ends with the end of the CharStream or a character satisfying endPred . charSeq :: (Char -> Bool) -- ^ Character to accumulate. -> (Char -> Bool) -- ^ Character for end. -> (String -> Token) -- ^ Constructor for making tokens. -> Pos -> String -> CharStream -> TokenSeq Token charSeq accRec endRec ctor = go where go pos p cs@(CSNext _ c r) | accRec c = go pos (c:p) r | not (endRec c) = badChar pos (reverse p) cs go pos p r = resolve pos (ctor (reverse p)) r -- Recognize string literals stringLit :: Pos -> String -> CharStream -> TokenSeq Token stringLit pos p r0@(CSNext _ '\\' r) = case r of CSNext _ '\\' s -> stringLit pos ('\\':p) s CSNext _ '\"' s -> stringLit pos ('\"':p) s _ -> badChar pos (reverse p) r0 stringLit pos p (CSNext _ '\"' r) = resolve pos (StringLit (reverse p)) r stringLit pos p (CSNext _ c r) = stringLit pos (c:p) r stringLit pos p (CSEnd p') = badChar pos (reverse p) (CSEnd p') resolve p k (CSEnd p') = SeqLast p k p' resolve p k r = SeqCons p k (tokenize r) Read a " 0b " prefixed binary literal like " 0b1010111 " . -- This succeeds on " 0b " returning zero , which is -- non-standard. readBinary :: String -> Integer readBinary ('0':'b':bits) = foldl (\acc bit -> 2*acc + read [bit]) 0 bits readBinary lit = error $ "convertToTokens: bad binary literal: " ++ lit isBinDigit :: Char -> Bool isBinDigit = (`elem` ['0','1']) ------------------------------------------------------------------------ Grammar and type Grammar m a = App (Parser m) a data Parser (m :: Type -> Type) (a :: Type) where -- Label an argument to a command. ArgumentLabel :: PP.Doc -> Parser m () -- Label the command that this runs. CommandLabel :: PP.Doc -> Parser m () -- Hide matcher from help system. Hide :: Grammar m a -> Parser m a -- Switch expression. SwitchExpr :: SwitchMap m a -> Parser m a UnionGrammar :: Grammar m a -> Grammar m a -> Parser m a data SwitchKey = SwitchKey [Token] instance IsString SwitchKey where fromString s = SwitchKey (toListOf tokenSeqTokens tokens) where tokens = convertToTokens s switch :: forall m a . [(SwitchKey, Grammar m a)] -> Grammar m a switch = atom . SwitchExpr . impl where -- Get map from strings to associated match impl cases = execState (mapM_ (uncurry addMatch) cases) emptySwitchMap -- Update switch match at a given identifier. alter :: Token -> (SwitchMatch (Grammar m a) -> SwitchMatch (Grammar m a)) -> MTL.State (SwitchMap m a) () alter k f = smWords . at k %= (\l -> Just (f (fromMaybe emptySwitchMatch l))) keywordSeq :: [Token] -> Grammar m a -> Grammar m a keywordSeq [] m = m keywordSeq (t:r) m = switch [(SwitchKey [t], keywordSeq r m)] -- Functions for building initial map. addMatch :: SwitchKey -> Grammar m a -> MTL.State (SwitchMap m a) () addMatch (SwitchKey (k:r)) v = do let v' = keywordSeq r v alter k (switchExact ?~ v') case k of Keyword nm -> mapM_ addPrefix (strictNonemptyPrefixes nm) where addPrefix p = alter (Keyword p) (switchExtensions %~ (++[(k,v')])) _ -> return () addMatch (SwitchKey []) v = smEnd ?= v keyword :: SwitchKey -> Grammar m () keyword k = switch [(k,pure ())] argLabel :: PP.Doc -> Grammar m () argLabel = atom . ArgumentLabel cmdLabel :: String -> Grammar m () cmdLabel d = atom (CommandLabel (PP.text d)) cmdDef :: String -> a -> Grammar m a cmdDef d v = cmdLabel d *> pure v hide :: Grammar m a -> Grammar m a hide = atom . Hide (<||>) :: Grammar m a -> Grammar m a -> Grammar m a x <||> y = atom (UnionGrammar x y) infixl 3 <||> opt :: Grammar m a -> Grammar m (Maybe a) opt m = (Just <$> m) <||> pure Nothing nat :: Grammar m Integer nat = atom (SwitchExpr (fromTokenPred p)) where p = TokenPred (Just (text "<nat>")) WordTokenType f idCont f (NatToken i) = Just i f _ = Nothing ------------------------------------------------------------------------ -- TokenPred -- | A token predicate recognizes tokens with a user-definable action. data TokenPred m a where Includes what to show when printing , a predicate , . TokenPred :: (Maybe PP.Doc) -> TokenType -> (Token -> Maybe b) -> Cont (Parser m) b a -> TokenPred m a tokenPredType :: Simple Lens (TokenPred m a) TokenType tokenPredType f (TokenPred d tp p c) = (\tp' -> TokenPred d tp' p c) <$> f tp tokenPredAddCont :: TokenPred m a -> Cont (Parser m) a c -> TokenPred m c tokenPredAddCont (TokenPred d t f c) c' = TokenPred d t f (c `composeCont` c') fromTokenPred :: TokenPred m a -> SwitchMap m a fromTokenPred p = SwitchMap { _smWords = Map.empty , _smPreds = [p] , _smEnd = Nothing } ------------------------------------------------------------------------ SwitchMap data SwitchMap m a = SwitchMap { _smWords :: Map.Map Token (SwitchMatch (Grammar m a)) , _smPreds :: [TokenPred m a] , _smEnd :: Maybe (Grammar m a) } emptySwitchMap :: SwitchMap m a emptySwitchMap = SwitchMap { _smWords = Map.empty , _smPreds = [] , _smEnd = Nothing } -- | List of token predicates in map. smPreds :: Simple Lens (SwitchMap m a) [TokenPred m a] smPreds = lens _smPreds (\s v -> s { _smPreds = v }) smEnd :: Simple Lens (SwitchMap m a) (Maybe (Grammar m a)) smEnd = lens _smEnd (\s v -> s { _smEnd = v }) -- | Map of ground towns to switch matches. smWords :: Simple Lens (SwitchMap m a) (Map.Map Token (SwitchMatch (Grammar m a))) smWords = lens _smWords (\s v -> s { _smWords = v }) ------------------------------------------------------------------------ SwitchMatch data SwitchMatch a = SwitchMatch { _switchExact :: Maybe a , _switchExtensions :: [(Token, a)] } emptySwitchMatch :: SwitchMatch a emptySwitchMatch = SwitchMatch Nothing [] switchExact :: Simple Lens (SwitchMatch a) (Maybe a) switchExact = lens _switchExact (\s v -> s { _switchExact = v }) switchExtensions :: Simple Lens (SwitchMatch a) [(Token, a)] switchExtensions = lens _switchExtensions (\s v -> s { _switchExtensions = v }) switchMatchGrammars :: Traversal (SwitchMatch a) (SwitchMatch b) a b switchMatchGrammars f (SwitchMatch e x) = SwitchMatch <$> _Just f e <*> traverse (_2 f) x unionSwitchMatch :: (a -> a -> a) -> SwitchMatch a -> SwitchMatch a -> SwitchMatch a unionSwitchMatch u (SwitchMatch ex xx) (SwitchMatch ey xy) = SwitchMatch (unionMaybe u ex ey) (xx ++ xy) ------------------------------------------------------------------------ NextState data NextState m a = NextState { nsWords :: Map.Map Token (SwitchMatch (Grammar m a)) , nsPreds :: [TokenPred m a] , nsMatches :: [a] } pureNextState :: a -> NextState m a pureNextState v = NextState { nsWords = Map.empty , nsPreds = [] , nsMatches = [v] } composeNextState :: SwitchMap m a -> Cont (Parser m) a b -> NextState m b composeNextState m c = case m^.smEnd of Just a -> ns `unionNextState` ns' where ns' = resolveToNextState (a `runCont` c) Nothing -> ns where w = over switchMatchGrammars (`runCont` c) <$> m^.smWords ns = NextState { nsWords = w , nsPreds = (`tokenPredAddCont` c) <$> m^.smPreds , nsMatches = [] } unionNextState :: NextState m a -> NextState m a -> NextState m a unionNextState x y = NextState { nsWords = zw , nsPreds = zp , nsMatches = zm } where xw = nsWords x yw = nsWords y zw = Map.unionWith (unionSwitchMatch (<||>)) xw yw zp = nsPreds x ++ nsPreds y zm = nsMatches x ++ nsMatches y resolveToNextState :: Grammar m a -> NextState m a resolveToNextState (PureApp v) = pureNextState v resolveToNextState (NP u c) = case u of ArgumentLabel{} -> resolveToNextState (evalCont () c) CommandLabel{} -> resolveToNextState (evalCont () c) SwitchExpr m -> composeNextState m c Hide m -> resolveToNextState (runCont m c) UnionGrammar x y -> resolveToNextState (runCont x c) `unionNextState` resolveToNextState (runCont y c) nextStateChoices :: NextState m a -> [(Token, Grammar m a)] nextStateChoices m = [ (nm, a) | (nm,(^.switchExact) -> Just a) <- Map.toList (nsWords m) ] nextTokenTypes :: NextState m a -> [TokenType] nextTokenTypes m = wordTypes ++ predTypes where wordTypes = tokenType <$> Map.keys (nsWords m) predTypes = view tokenPredType <$> nsPreds m matchPred :: TokenPred m a -> Token -> Maybe (App (Parser m) a) matchPred (TokenPred _ _ f c) t = (`evalCont` c) <$> f t ------------------------------------------------------------------------ -- Parsing | A ParseResult consists of a data ParseResult a = ParseResult (Either Doc a) (Pos,[Completion]) resolveParse :: ParseResult r -> Either Doc r resolveParse (ParseResult v _) = v parseCompletions :: Simple Lens (ParseResult r) (Pos,[Completion]) parseCompletions f (ParseResult v cl) = ParseResult v <$> f cl parseValue :: Pos -> r -> [Completion] -> ParseResult r parseValue p v cl = ParseResult (Right v) (p, cl) parseFail :: Pos -> Doc -> [Completion] -> ParseResult r parseFail p d cl = ParseResult (Left d) (p,cl) addCompletions :: Pos -> [Completion] -> ParseResult r -> ParseResult r addCompletions p' cl = parseCompletions .~ (p',cl) -- | Create a completion token from the target word and the -- following grammar. mkCompletion :: Token -- ^ Target word -> Grammar m a -- ^ Followup matcher -> Completion mkCompletion tgt g = Completion { replacement = show (ppToken tgt) , display = show (ppToken tgt) , isFinished = spaceAfterToken tgt (resolveToNextState g) } -- | @spaceAfterToken t m@ holds if there may need to be a space between -- @t@ and the next token to be parsed. spaceAfterToken :: Token -> NextState m a -> Bool spaceAfterToken t m = any tokenCompat (nextTokenTypes m) where tokenCompat tp = tokenType t == tp expectedOneOf :: [(Token,a)] -> Doc expectedOneOf [] = text "." expectedOneOf [(x,_)] = text "; Expected:" <+> ppToken x expectedOneOf l = text "; Expected one of:" <+> commaSepList (ppToken . fst <$> l) -- | Parse result when the user's command is incomplete. -- Arguments include an explanation, prefix if the user -- has entered a token, and a list of completions. incompleteParse :: Pos -> Doc -> [(Token,Grammar m a)] -> ParseResult b incompleteParse p msg cl = parseFail p d completions where d = msg PP.<> expectedOneOf cl completions = uncurry mkCompletion <$> cl parseString :: (Applicative m, Monad m) => Grammar m a -> String -> m (ParseResult a) parseString g s = runGrammar g (convertToTokens s) runGrammar :: (Applicative m, Monad m) => Grammar m a -> TokenSeq Token -> m (ParseResult a) runGrammar (PureApp a) ts = pure (parseValue (tokenSeqPos ts) a []) runGrammar m ts = parseSwitch (resolveToNextState m) ts parseSwitch :: (Applicative m, Monad m) => NextState m a -> TokenSeq Token -> m (ParseResult a) parseSwitch m ts = case ts of SeqCons p t ts' -> parseSwitchToken m p t ts' SeqLast p t pend -> parseSwitchToken m p t (SeqEnd pend) SeqEnd p -> case nsMatches m of [] -> pure (incompleteParse p msg cl) where msg = text "Unexpected end of command" cl = nextStateChoices m [v] -> pure $ parseValue p v [] _ -> pure $ parseFail p msg [] where msg = text "Internal error: Unexpected ambiguous command." parseSwitchToken :: (Applicative m, Monad m) => NextState m a -> Pos -> Token -> TokenSeq Token -> m (ParseResult a) parseSwitchToken m p t ts = case tokenMatches ++ predMatches of a:_ -> runGrammar a ts [] -> case mma of Nothing -> pure (parseFail p d []) where d = text "Unexpected symbol" <+> dquotes (ppToken t) PP.<> expectedOneOf cl cl = nextStateChoices m Just ma -> case ma^.switchExtensions of [] -> error "internal: parsing unexpectedly failed." [(t',a)] -> addCompletions p [mkCompletion t' a] <$> runGrammar a ts _ -> pure (incompleteParse p msg cl) where msg = text "Ambiguous input" <+> dquotes (ppToken t) cl = ma^.switchExtensions where mma = nsWords m^.at t tokenMatches = case mma of Nothing -> [] Just ma -> case ma^.switchExact of Just a -> [a] Nothing -> [] predMatches = mapMaybe (`matchPred` t) (nsPreds m) ------------------------------------------------------------------------ -- Help system data ArgsI = NoArgs | EmptyArgs | SingleArg Doc | SeqArgs ArgsI ArgsI | UnionArgs (Seq ArgsI) | OptArgs ArgsI deriving (Show) emptyArgs :: ArgsI emptyArgs = EmptyArgs singleArg :: PP.Doc -> ArgsI singleArg = SingleArg seqArgs :: ArgsI -> ArgsI -> ArgsI seqArgs NoArgs _ = NoArgs seqArgs _ NoArgs = NoArgs seqArgs EmptyArgs x = x seqArgs x EmptyArgs = x seqArgs x y = SeqArgs x y -- | Returns true if empty string may be argument. allowEmpty :: ArgsI -> Bool allowEmpty EmptyArgs = True allowEmpty OptArgs{} = True allowEmpty _ = False -- | Returns sequence of arguments that may appear. asUnion :: ArgsI -> Seq ArgsI asUnion EmptyArgs = Seq.empty asUnion (OptArgs x) = asUnion x asUnion (UnionArgs x) = x asUnion x = Seq.singleton x unionArgs :: ArgsI -> ArgsI -> ArgsI unionArgs NoArgs y = y unionArgs x NoArgs = x unionArgs x y | Seq.null z = EmptyArgs | Seq.length z == 1 = OptArgs (z `Seq.index` 0) | allowEmpty x || allowEmpty y = OptArgs (UnionArgs z) | otherwise = UnionArgs z where z = asUnion x Seq.>< asUnion y ppArgsI :: ArgsI -> Doc ppArgsI NoArgs = PP.empty ppArgsI EmptyArgs = PP.empty ppArgsI (SingleArg d) = d ppArgsI (SeqArgs x y) = ppArgsI x PP.<+> ppArgsI y ppArgsI (UnionArgs s) = PP.encloseSep PP.lparen PP.rparen (PP.char '|') (Fold.toList (ppArgsI <$> s)) ppArgsI (OptArgs x) = ppArgsI x PP.<> PP.char '?' -- | Help for a specific command. data CmdHelp = CmdHelp { _cmdHelpArgs :: ArgsI , cmdHelpDesc :: PP.Doc } deriving (Show) cmdHelpArgs :: Lens' CmdHelp ArgsI cmdHelpArgs = lens _cmdHelpArgs (\s v -> s { _cmdHelpArgs = v }) ppCmdHelp :: CmdHelp -> PP.Doc ppCmdHelp cmd = PP.indent 2 $ ppArgsI (cmd^.cmdHelpArgs) PP.<+> PP.char '-' PP.<+> cmdHelpDesc cmd | @HelpResult args cmds@ contains a doc with the arguments -- and a list of commands if any. data HelpResult = HelpResult { _helpArgs :: ArgsI , _helpCmds :: [CmdHelp] } deriving (Show) helpCmds :: Lens' HelpResult [CmdHelp] helpCmds = lens _helpCmds (\s v -> s { _helpCmds = v }) emptyHelp :: HelpResult emptyHelp = HelpResult emptyArgs [] noHelp :: HelpResult noHelp = HelpResult NoArgs [] seqHelp :: HelpResult -> HelpResult -> HelpResult seqHelp (HelpResult xa xc) (HelpResult ya yc) = HelpResult (seqArgs xa ya) (xc ++ over cmdHelpArgs (seqArgs xa) `fmap` yc) unionHelp :: HelpResult -> HelpResult -> HelpResult unionHelp (HelpResult xa xc) (HelpResult ya yc) = HelpResult (xa `unionArgs` ya) (xc ++ yc) unionHelpList :: [HelpResult] -> HelpResult unionHelpList = foldr unionHelp noHelp -- | Prints a list of commands for help purposes matcherHelp :: Grammar m a -> HelpResult matcherHelp (PureApp _) = emptyHelp matcherHelp (NP u v) = parserHelp u `seqHelp` matcherHelp (contToApp v) switchHelp :: SwitchMap m a -> HelpResult switchHelp m = unionHelpList $ itemHelp <$> mapMaybe (_2 (^. switchExact)) matches where matches = Map.toList $ m^.smWords itemHelp (nm,k) = HelpResult (singleArg (ppToken nm)) [] `seqHelp` matcherHelp k parserHelp :: forall m a .Parser m a -> HelpResult parserHelp (ArgumentLabel d) = HelpResult (singleArg d) [] parserHelp (CommandLabel d) = HelpResult emptyArgs [CmdHelp emptyArgs d] parserHelp (SwitchExpr m) = switchHelp m parserHelp (Hide _) = emptyHelp parserHelp (UnionGrammar x y) = matcherHelp x `unionHelp` matcherHelp y
null
https://raw.githubusercontent.com/GaloisInc/llvm-verifier/d97ee6d2e731f48db833cc451326e737e1e39963/src/Verifier/LLVM/Debugger/Grammar.hs
haskell
# LANGUAGE GADTs # # LANGUAGE Rank2Types # ---------------------------------------------------------------------- ---------------------------------------------------------------------- List utilities | @strictNonemptyPrefixes l@ returns non-empty strict prefixes of @l@. ---------------------------------------------------------------------- | Token from parser. | A non-negative integer. a space between them. | Type of token. | Pretty print a token. ---------------------------------------------------------------------- ---------------------------------------------------------------------- TokenSeq Hex literal. Binary literal. with characters satisfying whilePred that ends with the end ^ Character to accumulate. ^ Character for end. ^ Constructor for making tokens. Recognize string literals non-standard. ---------------------------------------------------------------------- Label an argument to a command. Label the command that this runs. Hide matcher from help system. Switch expression. Get map from strings to associated match Update switch match at a given identifier. Functions for building initial map. ---------------------------------------------------------------------- TokenPred | A token predicate recognizes tokens with a user-definable action. ---------------------------------------------------------------------- | List of token predicates in map. | Map of ground towns to switch matches. ---------------------------------------------------------------------- ---------------------------------------------------------------------- ---------------------------------------------------------------------- Parsing | Create a completion token from the target word and the following grammar. ^ Target word ^ Followup matcher | @spaceAfterToken t m@ holds if there may need to be a space between @t@ and the next token to be parsed. | Parse result when the user's command is incomplete. Arguments include an explanation, prefix if the user has entered a token, and a list of completions. ---------------------------------------------------------------------- Help system | Returns true if empty string may be argument. | Returns sequence of arguments that may appear. | Help for a specific command. and a list of commands if any. | Prints a list of commands for help purposes
# LANGUAGE KindSignatures # # LANGUAGE PatternGuards # # LANGUAGE ViewPatterns # | Module : $ Header$ Description : Symbolic execution tests License : BSD3 Stability : provisional Point - of - contact : acfoltzer Module : $Header$ Description : Symbolic execution tests License : BSD3 Stability : provisional Point-of-contact : acfoltzer -} module Verifier.LLVM.Debugger.Grammar ( Grammar , SwitchKey , switch , hide , cmdDef , keyword , argLabel , (<||>) , opt , nat , HelpResult , helpCmds , ppCmdHelp , matcherHelp , ParseResult(..) , resolveParse , parseString , parseCompletions ) where import Control.Lens import Control.Monad.State as MTL import Data.Char import qualified Data.Foldable as Fold import Data.Kind ( Type ) import Data.List.Compat import qualified Data.Map as Map import Data.Maybe import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.String import System.Console.Haskeline (Completion(..)) import Text.PrettyPrint.ANSI.Leijen hiding ((<$>), (</>)) import qualified Text.PrettyPrint.ANSI.Leijen as PP import Prelude () import Prelude.Compat hiding (mapM_) import Verifier.LLVM.Debugger.FreeApp import Verifier.LLVM.Utils.PrettyPrint Generic unionMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a unionMaybe u (Just x) y = Just (maybe x (u x) y) unionMaybe _ Nothing y = y | Split a list into the first elements and the last elemt . rcons :: [a] -> Maybe ([a], a) rcons l = case reverse l of [] -> Nothing (e:r) -> Just (reverse r,e) | @nonemptyPrefixes l@ returns non - empty prefixes of @l@. nonemptyPrefixes ::[a] -> [[a]] nonemptyPrefixes = tail . inits strictNonemptyPrefixes :: [a] -> [[a]] strictNonemptyPrefixes i = case rcons i of Nothing -> [] Just (r,_) -> nonemptyPrefixes r Token and Tokentype data Token = Keyword String | StringLit String | OpToken String | BadChar String deriving (Eq, Ord, Show) | A " type " for . Tokens with the same type need data TokenType = WordTokenType | OpTokenType | BadCharType deriving (Eq, Show) tokenType :: Token -> TokenType tokenType Keyword{} = WordTokenType tokenType StringLit{} = WordTokenType tokenType NatToken{} = WordTokenType tokenType OpToken{} = OpTokenType tokenType BadChar{} = BadCharType ppToken :: Token -> Doc ppToken (Keyword k) = text k ppToken (StringLit s) = dquotes (text s) ppToken (NatToken i) = integer i ppToken (OpToken k) = text k ppToken (BadChar s) = text s CharStream data CharStream = CSNext !Pos !Char !CharStream | CSEnd !Pos csString :: CharStream -> String csString (CSNext _ c cs) = c : csString cs csString (CSEnd _) = [] csEndPos :: CharStream -> Pos csEndPos (CSNext _ _ cs) = csEndPos cs csEndPos (CSEnd p) = p charStream :: String -> CharStream charStream = impl startPos where impl p (c:l) = CSNext p c $ impl (incPos p c) l impl p [] = CSEnd p type Pos = Int startPos :: Pos startPos = 0 incPos :: Pos -> Char -> Pos incPos p _ = p+1 data TokenSeq t = SeqCons Pos t (TokenSeq t) | SeqLast Pos t Pos | SeqEnd Pos tokenSeqPos :: TokenSeq t -> Pos tokenSeqPos (SeqCons p _ _) = p tokenSeqPos (SeqLast p _ _) = p tokenSeqPos (SeqEnd p) = p tokenSeqTokens :: Traversal (TokenSeq s) (TokenSeq t) s t tokenSeqTokens f (SeqCons p t s) = SeqCons p <$> f t <*> tokenSeqTokens f s tokenSeqTokens f (SeqLast p t pe) = (\ u -> SeqLast p u pe) <$> f t tokenSeqTokens _ (SeqEnd p) = pure (SeqEnd p) convertToTokens :: String -> TokenSeq Token convertToTokens = tokenize . charStream where tokenize :: CharStream -> TokenSeq Token tokenize (CSNext p c r) | isSpace c = tokenize r | c == '\"' = stringLit p [] r | c == '0' , CSNext p' 'x' r' <- r = charSeq isHexDigit isSpace (NatToken . read) p' ['x','0'] r' | c == '0' , CSNext p' 'b' r' <- r = charSeq isBinDigit isSpace (NatToken . readBinary) p' ['b','0'] r' | isDigit c = charSeq isDigit isSpace (NatToken . read) p [c] r | isToken1 c = charSeq isToken isSpace Keyword p [c] r | isOp c = charSeq isOp (\_ -> True) OpToken p [c] r | otherwise = badChar p [c] r tokenize (CSEnd p) = SeqEnd p badChar :: Pos -> String -> CharStream -> TokenSeq Token badChar p s r = SeqLast p (BadChar (s ++ csString r)) (csEndPos r) isToken1 c = isAlpha c || c `elem` ['_', '%'] isToken c = isAlphaNum c || c `elem` ['_', '%'] Recognize operator characters . isOp = (`elem` ['.', ':']) @charSeq whilePred endPred ctor pos p cs@ recognizes a word of the CharStream or a character satisfying endPred . -> Pos -> String -> CharStream -> TokenSeq Token charSeq accRec endRec ctor = go where go pos p cs@(CSNext _ c r) | accRec c = go pos (c:p) r | not (endRec c) = badChar pos (reverse p) cs go pos p r = resolve pos (ctor (reverse p)) r stringLit :: Pos -> String -> CharStream -> TokenSeq Token stringLit pos p r0@(CSNext _ '\\' r) = case r of CSNext _ '\\' s -> stringLit pos ('\\':p) s CSNext _ '\"' s -> stringLit pos ('\"':p) s _ -> badChar pos (reverse p) r0 stringLit pos p (CSNext _ '\"' r) = resolve pos (StringLit (reverse p)) r stringLit pos p (CSNext _ c r) = stringLit pos (c:p) r stringLit pos p (CSEnd p') = badChar pos (reverse p) (CSEnd p') resolve p k (CSEnd p') = SeqLast p k p' resolve p k r = SeqCons p k (tokenize r) Read a " 0b " prefixed binary literal like " 0b1010111 " . This succeeds on " 0b " returning zero , which is readBinary :: String -> Integer readBinary ('0':'b':bits) = foldl (\acc bit -> 2*acc + read [bit]) 0 bits readBinary lit = error $ "convertToTokens: bad binary literal: " ++ lit isBinDigit :: Char -> Bool isBinDigit = (`elem` ['0','1']) Grammar and type Grammar m a = App (Parser m) a data Parser (m :: Type -> Type) (a :: Type) where ArgumentLabel :: PP.Doc -> Parser m () CommandLabel :: PP.Doc -> Parser m () Hide :: Grammar m a -> Parser m a SwitchExpr :: SwitchMap m a -> Parser m a UnionGrammar :: Grammar m a -> Grammar m a -> Parser m a data SwitchKey = SwitchKey [Token] instance IsString SwitchKey where fromString s = SwitchKey (toListOf tokenSeqTokens tokens) where tokens = convertToTokens s switch :: forall m a . [(SwitchKey, Grammar m a)] -> Grammar m a switch = atom . SwitchExpr . impl impl cases = execState (mapM_ (uncurry addMatch) cases) emptySwitchMap alter :: Token -> (SwitchMatch (Grammar m a) -> SwitchMatch (Grammar m a)) -> MTL.State (SwitchMap m a) () alter k f = smWords . at k %= (\l -> Just (f (fromMaybe emptySwitchMatch l))) keywordSeq :: [Token] -> Grammar m a -> Grammar m a keywordSeq [] m = m keywordSeq (t:r) m = switch [(SwitchKey [t], keywordSeq r m)] addMatch :: SwitchKey -> Grammar m a -> MTL.State (SwitchMap m a) () addMatch (SwitchKey (k:r)) v = do let v' = keywordSeq r v alter k (switchExact ?~ v') case k of Keyword nm -> mapM_ addPrefix (strictNonemptyPrefixes nm) where addPrefix p = alter (Keyword p) (switchExtensions %~ (++[(k,v')])) _ -> return () addMatch (SwitchKey []) v = smEnd ?= v keyword :: SwitchKey -> Grammar m () keyword k = switch [(k,pure ())] argLabel :: PP.Doc -> Grammar m () argLabel = atom . ArgumentLabel cmdLabel :: String -> Grammar m () cmdLabel d = atom (CommandLabel (PP.text d)) cmdDef :: String -> a -> Grammar m a cmdDef d v = cmdLabel d *> pure v hide :: Grammar m a -> Grammar m a hide = atom . Hide (<||>) :: Grammar m a -> Grammar m a -> Grammar m a x <||> y = atom (UnionGrammar x y) infixl 3 <||> opt :: Grammar m a -> Grammar m (Maybe a) opt m = (Just <$> m) <||> pure Nothing nat :: Grammar m Integer nat = atom (SwitchExpr (fromTokenPred p)) where p = TokenPred (Just (text "<nat>")) WordTokenType f idCont f (NatToken i) = Just i f _ = Nothing data TokenPred m a where Includes what to show when printing , a predicate , . TokenPred :: (Maybe PP.Doc) -> TokenType -> (Token -> Maybe b) -> Cont (Parser m) b a -> TokenPred m a tokenPredType :: Simple Lens (TokenPred m a) TokenType tokenPredType f (TokenPred d tp p c) = (\tp' -> TokenPred d tp' p c) <$> f tp tokenPredAddCont :: TokenPred m a -> Cont (Parser m) a c -> TokenPred m c tokenPredAddCont (TokenPred d t f c) c' = TokenPred d t f (c `composeCont` c') fromTokenPred :: TokenPred m a -> SwitchMap m a fromTokenPred p = SwitchMap { _smWords = Map.empty , _smPreds = [p] , _smEnd = Nothing } SwitchMap data SwitchMap m a = SwitchMap { _smWords :: Map.Map Token (SwitchMatch (Grammar m a)) , _smPreds :: [TokenPred m a] , _smEnd :: Maybe (Grammar m a) } emptySwitchMap :: SwitchMap m a emptySwitchMap = SwitchMap { _smWords = Map.empty , _smPreds = [] , _smEnd = Nothing } smPreds :: Simple Lens (SwitchMap m a) [TokenPred m a] smPreds = lens _smPreds (\s v -> s { _smPreds = v }) smEnd :: Simple Lens (SwitchMap m a) (Maybe (Grammar m a)) smEnd = lens _smEnd (\s v -> s { _smEnd = v }) smWords :: Simple Lens (SwitchMap m a) (Map.Map Token (SwitchMatch (Grammar m a))) smWords = lens _smWords (\s v -> s { _smWords = v }) SwitchMatch data SwitchMatch a = SwitchMatch { _switchExact :: Maybe a , _switchExtensions :: [(Token, a)] } emptySwitchMatch :: SwitchMatch a emptySwitchMatch = SwitchMatch Nothing [] switchExact :: Simple Lens (SwitchMatch a) (Maybe a) switchExact = lens _switchExact (\s v -> s { _switchExact = v }) switchExtensions :: Simple Lens (SwitchMatch a) [(Token, a)] switchExtensions = lens _switchExtensions (\s v -> s { _switchExtensions = v }) switchMatchGrammars :: Traversal (SwitchMatch a) (SwitchMatch b) a b switchMatchGrammars f (SwitchMatch e x) = SwitchMatch <$> _Just f e <*> traverse (_2 f) x unionSwitchMatch :: (a -> a -> a) -> SwitchMatch a -> SwitchMatch a -> SwitchMatch a unionSwitchMatch u (SwitchMatch ex xx) (SwitchMatch ey xy) = SwitchMatch (unionMaybe u ex ey) (xx ++ xy) NextState data NextState m a = NextState { nsWords :: Map.Map Token (SwitchMatch (Grammar m a)) , nsPreds :: [TokenPred m a] , nsMatches :: [a] } pureNextState :: a -> NextState m a pureNextState v = NextState { nsWords = Map.empty , nsPreds = [] , nsMatches = [v] } composeNextState :: SwitchMap m a -> Cont (Parser m) a b -> NextState m b composeNextState m c = case m^.smEnd of Just a -> ns `unionNextState` ns' where ns' = resolveToNextState (a `runCont` c) Nothing -> ns where w = over switchMatchGrammars (`runCont` c) <$> m^.smWords ns = NextState { nsWords = w , nsPreds = (`tokenPredAddCont` c) <$> m^.smPreds , nsMatches = [] } unionNextState :: NextState m a -> NextState m a -> NextState m a unionNextState x y = NextState { nsWords = zw , nsPreds = zp , nsMatches = zm } where xw = nsWords x yw = nsWords y zw = Map.unionWith (unionSwitchMatch (<||>)) xw yw zp = nsPreds x ++ nsPreds y zm = nsMatches x ++ nsMatches y resolveToNextState :: Grammar m a -> NextState m a resolveToNextState (PureApp v) = pureNextState v resolveToNextState (NP u c) = case u of ArgumentLabel{} -> resolveToNextState (evalCont () c) CommandLabel{} -> resolveToNextState (evalCont () c) SwitchExpr m -> composeNextState m c Hide m -> resolveToNextState (runCont m c) UnionGrammar x y -> resolveToNextState (runCont x c) `unionNextState` resolveToNextState (runCont y c) nextStateChoices :: NextState m a -> [(Token, Grammar m a)] nextStateChoices m = [ (nm, a) | (nm,(^.switchExact) -> Just a) <- Map.toList (nsWords m) ] nextTokenTypes :: NextState m a -> [TokenType] nextTokenTypes m = wordTypes ++ predTypes where wordTypes = tokenType <$> Map.keys (nsWords m) predTypes = view tokenPredType <$> nsPreds m matchPred :: TokenPred m a -> Token -> Maybe (App (Parser m) a) matchPred (TokenPred _ _ f c) t = (`evalCont` c) <$> f t | A ParseResult consists of a data ParseResult a = ParseResult (Either Doc a) (Pos,[Completion]) resolveParse :: ParseResult r -> Either Doc r resolveParse (ParseResult v _) = v parseCompletions :: Simple Lens (ParseResult r) (Pos,[Completion]) parseCompletions f (ParseResult v cl) = ParseResult v <$> f cl parseValue :: Pos -> r -> [Completion] -> ParseResult r parseValue p v cl = ParseResult (Right v) (p, cl) parseFail :: Pos -> Doc -> [Completion] -> ParseResult r parseFail p d cl = ParseResult (Left d) (p,cl) addCompletions :: Pos -> [Completion] -> ParseResult r -> ParseResult r addCompletions p' cl = parseCompletions .~ (p',cl) -> Completion mkCompletion tgt g = Completion { replacement = show (ppToken tgt) , display = show (ppToken tgt) , isFinished = spaceAfterToken tgt (resolveToNextState g) } spaceAfterToken :: Token -> NextState m a -> Bool spaceAfterToken t m = any tokenCompat (nextTokenTypes m) where tokenCompat tp = tokenType t == tp expectedOneOf :: [(Token,a)] -> Doc expectedOneOf [] = text "." expectedOneOf [(x,_)] = text "; Expected:" <+> ppToken x expectedOneOf l = text "; Expected one of:" <+> commaSepList (ppToken . fst <$> l) incompleteParse :: Pos -> Doc -> [(Token,Grammar m a)] -> ParseResult b incompleteParse p msg cl = parseFail p d completions where d = msg PP.<> expectedOneOf cl completions = uncurry mkCompletion <$> cl parseString :: (Applicative m, Monad m) => Grammar m a -> String -> m (ParseResult a) parseString g s = runGrammar g (convertToTokens s) runGrammar :: (Applicative m, Monad m) => Grammar m a -> TokenSeq Token -> m (ParseResult a) runGrammar (PureApp a) ts = pure (parseValue (tokenSeqPos ts) a []) runGrammar m ts = parseSwitch (resolveToNextState m) ts parseSwitch :: (Applicative m, Monad m) => NextState m a -> TokenSeq Token -> m (ParseResult a) parseSwitch m ts = case ts of SeqCons p t ts' -> parseSwitchToken m p t ts' SeqLast p t pend -> parseSwitchToken m p t (SeqEnd pend) SeqEnd p -> case nsMatches m of [] -> pure (incompleteParse p msg cl) where msg = text "Unexpected end of command" cl = nextStateChoices m [v] -> pure $ parseValue p v [] _ -> pure $ parseFail p msg [] where msg = text "Internal error: Unexpected ambiguous command." parseSwitchToken :: (Applicative m, Monad m) => NextState m a -> Pos -> Token -> TokenSeq Token -> m (ParseResult a) parseSwitchToken m p t ts = case tokenMatches ++ predMatches of a:_ -> runGrammar a ts [] -> case mma of Nothing -> pure (parseFail p d []) where d = text "Unexpected symbol" <+> dquotes (ppToken t) PP.<> expectedOneOf cl cl = nextStateChoices m Just ma -> case ma^.switchExtensions of [] -> error "internal: parsing unexpectedly failed." [(t',a)] -> addCompletions p [mkCompletion t' a] <$> runGrammar a ts _ -> pure (incompleteParse p msg cl) where msg = text "Ambiguous input" <+> dquotes (ppToken t) cl = ma^.switchExtensions where mma = nsWords m^.at t tokenMatches = case mma of Nothing -> [] Just ma -> case ma^.switchExact of Just a -> [a] Nothing -> [] predMatches = mapMaybe (`matchPred` t) (nsPreds m) data ArgsI = NoArgs | EmptyArgs | SingleArg Doc | SeqArgs ArgsI ArgsI | UnionArgs (Seq ArgsI) | OptArgs ArgsI deriving (Show) emptyArgs :: ArgsI emptyArgs = EmptyArgs singleArg :: PP.Doc -> ArgsI singleArg = SingleArg seqArgs :: ArgsI -> ArgsI -> ArgsI seqArgs NoArgs _ = NoArgs seqArgs _ NoArgs = NoArgs seqArgs EmptyArgs x = x seqArgs x EmptyArgs = x seqArgs x y = SeqArgs x y allowEmpty :: ArgsI -> Bool allowEmpty EmptyArgs = True allowEmpty OptArgs{} = True allowEmpty _ = False asUnion :: ArgsI -> Seq ArgsI asUnion EmptyArgs = Seq.empty asUnion (OptArgs x) = asUnion x asUnion (UnionArgs x) = x asUnion x = Seq.singleton x unionArgs :: ArgsI -> ArgsI -> ArgsI unionArgs NoArgs y = y unionArgs x NoArgs = x unionArgs x y | Seq.null z = EmptyArgs | Seq.length z == 1 = OptArgs (z `Seq.index` 0) | allowEmpty x || allowEmpty y = OptArgs (UnionArgs z) | otherwise = UnionArgs z where z = asUnion x Seq.>< asUnion y ppArgsI :: ArgsI -> Doc ppArgsI NoArgs = PP.empty ppArgsI EmptyArgs = PP.empty ppArgsI (SingleArg d) = d ppArgsI (SeqArgs x y) = ppArgsI x PP.<+> ppArgsI y ppArgsI (UnionArgs s) = PP.encloseSep PP.lparen PP.rparen (PP.char '|') (Fold.toList (ppArgsI <$> s)) ppArgsI (OptArgs x) = ppArgsI x PP.<> PP.char '?' data CmdHelp = CmdHelp { _cmdHelpArgs :: ArgsI , cmdHelpDesc :: PP.Doc } deriving (Show) cmdHelpArgs :: Lens' CmdHelp ArgsI cmdHelpArgs = lens _cmdHelpArgs (\s v -> s { _cmdHelpArgs = v }) ppCmdHelp :: CmdHelp -> PP.Doc ppCmdHelp cmd = PP.indent 2 $ ppArgsI (cmd^.cmdHelpArgs) PP.<+> PP.char '-' PP.<+> cmdHelpDesc cmd | @HelpResult args cmds@ contains a doc with the arguments data HelpResult = HelpResult { _helpArgs :: ArgsI , _helpCmds :: [CmdHelp] } deriving (Show) helpCmds :: Lens' HelpResult [CmdHelp] helpCmds = lens _helpCmds (\s v -> s { _helpCmds = v }) emptyHelp :: HelpResult emptyHelp = HelpResult emptyArgs [] noHelp :: HelpResult noHelp = HelpResult NoArgs [] seqHelp :: HelpResult -> HelpResult -> HelpResult seqHelp (HelpResult xa xc) (HelpResult ya yc) = HelpResult (seqArgs xa ya) (xc ++ over cmdHelpArgs (seqArgs xa) `fmap` yc) unionHelp :: HelpResult -> HelpResult -> HelpResult unionHelp (HelpResult xa xc) (HelpResult ya yc) = HelpResult (xa `unionArgs` ya) (xc ++ yc) unionHelpList :: [HelpResult] -> HelpResult unionHelpList = foldr unionHelp noHelp matcherHelp :: Grammar m a -> HelpResult matcherHelp (PureApp _) = emptyHelp matcherHelp (NP u v) = parserHelp u `seqHelp` matcherHelp (contToApp v) switchHelp :: SwitchMap m a -> HelpResult switchHelp m = unionHelpList $ itemHelp <$> mapMaybe (_2 (^. switchExact)) matches where matches = Map.toList $ m^.smWords itemHelp (nm,k) = HelpResult (singleArg (ppToken nm)) [] `seqHelp` matcherHelp k parserHelp :: forall m a .Parser m a -> HelpResult parserHelp (ArgumentLabel d) = HelpResult (singleArg d) [] parserHelp (CommandLabel d) = HelpResult emptyArgs [CmdHelp emptyArgs d] parserHelp (SwitchExpr m) = switchHelp m parserHelp (Hide _) = emptyHelp parserHelp (UnionGrammar x y) = matcherHelp x `unionHelp` matcherHelp y
d528f5c664c0baa9a002bf69e8d95a50061a11ba028322aa97ca98eabcc9df61
racket/htdp
itunes.rkt
#lang racket (provide (all-from-out 2htdp/itunes)) (require 2htdp/itunes)
null
https://raw.githubusercontent.com/racket/htdp/aa78794fa1788358d6abd11dad54b3c9f4f5a80b/htdp-lib/teachpack/2htdp/itunes.rkt
racket
#lang racket (provide (all-from-out 2htdp/itunes)) (require 2htdp/itunes)
01e7fcdb1222659c966949be07d9600ea0f74be4e896808974a5235ac0d0e790
solita/mnt-teet
material_ui.cljs
(ns teet.ui.material-ui (:refer-clojure :exclude [List]) (:require [goog.object :as gobj] reagent.core ;; Require all MaterialUI components with "mui-" prefix ;; the define-mui-components will adapt them and provide ;; wrapper functions that can be used directly from reagent ["@material-ui/core/Card" :as mui-Card] ["@material-ui/core/CardActionArea" :as mui-CardActionArea] ["@material-ui/core/CardActions" :as mui-CardActions] ["@material-ui/core/CardContent" :as mui-CardContent] ["@material-ui/core/CardHeader" :as mui-CardHeader] ["@material-ui/core/CardMedia" :as mui-CardMedia] ["@material-ui/core/List" :as mui-List] ["@material-ui/core/ListItem" :as mui-ListItem] ["@material-ui/core/ListItemIcon" :as mui-ListItemIcon] ["@material-ui/core/ListItemText" :as mui-ListItemText] ["@material-ui/core/ListItemSecondaryAction" :as mui-ListItemSecondaryAction] ["@material-ui/core/Button" :as mui-Button] ["@material-ui/core/ButtonBase" :as mui-ButtonBase] ["@material-ui/core/Fab" :as mui-Fab] ["@material-ui/core/IconButton" :as mui-IconButton] ["@material-ui/core/Checkbox" :as mui-Checkbox] ["@material-ui/core/InputAdornment" :as mui-InputAdornment] ["@material-ui/core/FormControl" :as mui-FormControl] ["@material-ui/core/FormControlLabel" :as mui-FormControlLabel] ["@material-ui/core/InputLabel" :as mui-InputLabel] ["@material-ui/core/Input" :as mui-Input] ["@material-ui/core/Select" :as mui-Select] ["@material-ui/core/MenuItem" :as mui-MenuItem] ["@material-ui/core/MenuList" :as mui-MenuList] ["@material-ui/core/Menu" :as mui-Menu] ["@material-ui/core/ButtonGroup" :as mui-ButtonGroup] ["@material-ui/core/RadioGroup" :as mui-RadioGroup] ["@material-ui/core/Radio" :as mui-Radio] ["@material-ui/core/Paper" :as mui-Paper] ["@material-ui/core/Typography" :as mui-Typography] ["@material-ui/core/Divider" :as mui-Divider] ["@material-ui/core/CircularProgress" :as mui-CircularProgress] ["@material-ui/core/LinearProgress" :as mui-LinearProgress] ["@material-ui/core/Drawer" :as mui-Drawer] ["@material-ui/core/AppBar" :as mui-AppBar] ["@material-ui/core/Toolbar" :as mui-Toolbar] ["@material-ui/core/CssBaseline" :as mui-CssBaseline] ["@material-ui/core/Link" :as mui-Link] ["@material-ui/core/Breadcrumbs" :as mui-Breadcrumbs] ["@material-ui/core/ClickAwayListener" :as mui-ClickAwayListener] ["@material-ui/core/Switch" :as mui-Switch] ["@material-ui/core/Container" :as mui-Container] ["@material-ui/core/Grid" :as mui-Grid] ["@material-ui/core/Chip" :as mui-Chip] ["@material-ui/core/Avatar" :as mui-Avatar] ["@material-ui/core/Portal" :as mui-Portal] ["@material-ui/core/Icon" :as mui-Icon] ["@material-ui/core/Tabs" :as mui-Tabs] ["@material-ui/core/Tab" :as mui-Tab] ["@material-ui/core/Table" :as mui-Table] ["@material-ui/core/TableRow" :as mui-TableRow] ["@material-ui/core/TableHead" :as mui-TableHead] ["@material-ui/core/TableCell" :as mui-TableCell] ["@material-ui/core/TableSortLabel" :as mui-TableSortLabel] ["@material-ui/core/TableBody" :as mui-TableBody] ["@material-ui/core/TableFooter" :as mui-TableFooter] ["@material-ui/core/Zoom" :as mui-Zoom] ["@material-ui/core/Fade" :as mui-Fade] ["@material-ui/core/Collapse" :as mui-Collapse] ["@material-ui/core/Modal" :as mui-Modal] ["@material-ui/core/Dialog" :as mui-Dialog] ["@material-ui/core/DialogActions" :as mui-DialogActions] ["@material-ui/core/Backdrop" :as mui-Backdrop] ["@material-ui/core/DialogContentText" :as mui-DialogContentText] ["@material-ui/core/DialogTitle" :as mui-DialogTitle] ["@material-ui/core/DialogContent" :as mui-DialogContent] ["@material-ui/core/Popover" :as mui-Popover] ["@material-ui/core/Popper" :as mui-Popper] ["@material-ui/core/Snackbar" :as mui-Snackbar] ["@material-ui/core/SnackbarContent" :as mui-SnackbarContent] ["@material-ui/core/Badge" :as mui-Badge] ["@material-ui/core/TextField" :as mui-TextField] ["@material-ui/lab/Autocomplete" :as mui-Autocomplete] ["@material-ui/core/Slider" :as mui-Slider]) (:require-macros [teet.ui.material-ui-macros :refer [define-mui-components]])) ;; Cards (define-mui-components Card CardActionArea CardActions CardContent CardHeader CardMedia) ;; Listing (define-mui-components List ListItem ListItemIcon ListItemText ListItemSecondaryAction) ;; Form (define-mui-components Button ButtonBase Fab IconButton Checkbox InputAdornment FormControl FormControlLabel InputLabel Input TextField Select MenuItem MenuList Menu ButtonGroup) (def TextField-class (aget mui-TextField "default")) (define-mui-components RadioGroup Radio) (define-mui-components Paper Typography) ;; Common utility components (define-mui-components Divider CircularProgress LinearProgress Drawer AppBar Toolbar CssBaseline Link Breadcrumbs ClickAwayListener Switch) Layout (define-mui-components Container Grid) ;; Data display (define-mui-components Chip Avatar) ;; Icon (define-mui-components Icon) ;; Tabs (define-mui-components Tabs Tab) ;; Table (define-mui-components Table TableRow TableHead TableCell TableSortLabel TableBody TableFooter) Transitions (define-mui-components Zoom Fade Collapse) ;; Dialogs and modals (define-mui-components Modal Dialog DialogActions Backdrop DialogContentText DialogTitle DialogContent Popover Popper) ;; Snackbar (define-mui-components Snackbar SnackbarContent) ;; Badge (define-mui-components Badge) Portal (define-mui-components Portal) ;; Labs components (define-mui-components Autocomplete) (define-mui-components Slider)
null
https://raw.githubusercontent.com/solita/mnt-teet/19cc416f222d5079d5df63add1fa90620122de85/app/frontend/src/cljs/teet/ui/material_ui.cljs
clojure
Require all MaterialUI components with "mui-" prefix the define-mui-components will adapt them and provide wrapper functions that can be used directly from reagent Cards Listing Form Common utility components Data display Icon Tabs Table Dialogs and modals Snackbar Badge Labs components
(ns teet.ui.material-ui (:refer-clojure :exclude [List]) (:require [goog.object :as gobj] reagent.core ["@material-ui/core/Card" :as mui-Card] ["@material-ui/core/CardActionArea" :as mui-CardActionArea] ["@material-ui/core/CardActions" :as mui-CardActions] ["@material-ui/core/CardContent" :as mui-CardContent] ["@material-ui/core/CardHeader" :as mui-CardHeader] ["@material-ui/core/CardMedia" :as mui-CardMedia] ["@material-ui/core/List" :as mui-List] ["@material-ui/core/ListItem" :as mui-ListItem] ["@material-ui/core/ListItemIcon" :as mui-ListItemIcon] ["@material-ui/core/ListItemText" :as mui-ListItemText] ["@material-ui/core/ListItemSecondaryAction" :as mui-ListItemSecondaryAction] ["@material-ui/core/Button" :as mui-Button] ["@material-ui/core/ButtonBase" :as mui-ButtonBase] ["@material-ui/core/Fab" :as mui-Fab] ["@material-ui/core/IconButton" :as mui-IconButton] ["@material-ui/core/Checkbox" :as mui-Checkbox] ["@material-ui/core/InputAdornment" :as mui-InputAdornment] ["@material-ui/core/FormControl" :as mui-FormControl] ["@material-ui/core/FormControlLabel" :as mui-FormControlLabel] ["@material-ui/core/InputLabel" :as mui-InputLabel] ["@material-ui/core/Input" :as mui-Input] ["@material-ui/core/Select" :as mui-Select] ["@material-ui/core/MenuItem" :as mui-MenuItem] ["@material-ui/core/MenuList" :as mui-MenuList] ["@material-ui/core/Menu" :as mui-Menu] ["@material-ui/core/ButtonGroup" :as mui-ButtonGroup] ["@material-ui/core/RadioGroup" :as mui-RadioGroup] ["@material-ui/core/Radio" :as mui-Radio] ["@material-ui/core/Paper" :as mui-Paper] ["@material-ui/core/Typography" :as mui-Typography] ["@material-ui/core/Divider" :as mui-Divider] ["@material-ui/core/CircularProgress" :as mui-CircularProgress] ["@material-ui/core/LinearProgress" :as mui-LinearProgress] ["@material-ui/core/Drawer" :as mui-Drawer] ["@material-ui/core/AppBar" :as mui-AppBar] ["@material-ui/core/Toolbar" :as mui-Toolbar] ["@material-ui/core/CssBaseline" :as mui-CssBaseline] ["@material-ui/core/Link" :as mui-Link] ["@material-ui/core/Breadcrumbs" :as mui-Breadcrumbs] ["@material-ui/core/ClickAwayListener" :as mui-ClickAwayListener] ["@material-ui/core/Switch" :as mui-Switch] ["@material-ui/core/Container" :as mui-Container] ["@material-ui/core/Grid" :as mui-Grid] ["@material-ui/core/Chip" :as mui-Chip] ["@material-ui/core/Avatar" :as mui-Avatar] ["@material-ui/core/Portal" :as mui-Portal] ["@material-ui/core/Icon" :as mui-Icon] ["@material-ui/core/Tabs" :as mui-Tabs] ["@material-ui/core/Tab" :as mui-Tab] ["@material-ui/core/Table" :as mui-Table] ["@material-ui/core/TableRow" :as mui-TableRow] ["@material-ui/core/TableHead" :as mui-TableHead] ["@material-ui/core/TableCell" :as mui-TableCell] ["@material-ui/core/TableSortLabel" :as mui-TableSortLabel] ["@material-ui/core/TableBody" :as mui-TableBody] ["@material-ui/core/TableFooter" :as mui-TableFooter] ["@material-ui/core/Zoom" :as mui-Zoom] ["@material-ui/core/Fade" :as mui-Fade] ["@material-ui/core/Collapse" :as mui-Collapse] ["@material-ui/core/Modal" :as mui-Modal] ["@material-ui/core/Dialog" :as mui-Dialog] ["@material-ui/core/DialogActions" :as mui-DialogActions] ["@material-ui/core/Backdrop" :as mui-Backdrop] ["@material-ui/core/DialogContentText" :as mui-DialogContentText] ["@material-ui/core/DialogTitle" :as mui-DialogTitle] ["@material-ui/core/DialogContent" :as mui-DialogContent] ["@material-ui/core/Popover" :as mui-Popover] ["@material-ui/core/Popper" :as mui-Popper] ["@material-ui/core/Snackbar" :as mui-Snackbar] ["@material-ui/core/SnackbarContent" :as mui-SnackbarContent] ["@material-ui/core/Badge" :as mui-Badge] ["@material-ui/core/TextField" :as mui-TextField] ["@material-ui/lab/Autocomplete" :as mui-Autocomplete] ["@material-ui/core/Slider" :as mui-Slider]) (:require-macros [teet.ui.material-ui-macros :refer [define-mui-components]])) (define-mui-components Card CardActionArea CardActions CardContent CardHeader CardMedia) (define-mui-components List ListItem ListItemIcon ListItemText ListItemSecondaryAction) (define-mui-components Button ButtonBase Fab IconButton Checkbox InputAdornment FormControl FormControlLabel InputLabel Input TextField Select MenuItem MenuList Menu ButtonGroup) (def TextField-class (aget mui-TextField "default")) (define-mui-components RadioGroup Radio) (define-mui-components Paper Typography) (define-mui-components Divider CircularProgress LinearProgress Drawer AppBar Toolbar CssBaseline Link Breadcrumbs ClickAwayListener Switch) Layout (define-mui-components Container Grid) (define-mui-components Chip Avatar) (define-mui-components Icon) (define-mui-components Tabs Tab) (define-mui-components Table TableRow TableHead TableCell TableSortLabel TableBody TableFooter) Transitions (define-mui-components Zoom Fade Collapse) (define-mui-components Modal Dialog DialogActions Backdrop DialogContentText DialogTitle DialogContent Popover Popper) (define-mui-components Snackbar SnackbarContent) (define-mui-components Badge) Portal (define-mui-components Portal) (define-mui-components Autocomplete) (define-mui-components Slider)
d00e93b6e8f91f56dd2d5fef477d931ac2ff027c539a4b1b1155d276013883b8
tazjin/democrify
Queue.hs
# LANGUAGE ForeignFunctionInterface # {-# LANGUAGE OverloadedStrings #-} {-| This module contains the queue. -} module Queue where import Acid import Control.Applicative ((<$>)) import Control.Concurrent import Control.Monad (forM, forM_) import Control.Monad.IO.Class (liftIO) import Data.Acid import Data.Acid.Advanced (update', query') import Data.Acid.Local (createArchive, createCheckpointAndClose) import Data.Data (Data, Typeable) import Data.IORef import Data.Random (runRVar) import Data.Random.Extras (shuffleSeq) import Data.Random.Source.DevRandom (DevRandom (..)) import qualified Data.Sequence as SQ import Data.Text.Lazy (Text, unpack) import qualified Data.Text.Lazy as T import HSObjC import System.Directory (createDirectoryIfMissing, getHomeDirectory) import System.IO.Unsafe (unsafePerformIO) import WebAPI -- |This function runs an Acid Query and retrieves the state from the global IORef dfQuery u = liftIO (readIORef playQueue) >>= flip query' u -- |This function runs an Acid Update and retrieves the state from the global IORef dfUpdate u = liftIO (readIORef playQueue) >>= flip update' u initialPlayQueue :: PlayQueue initialPlayQueue = PlayQueue SQ.empty playQueue :: IORef (AcidState PlayQueue) playQueue = unsafePerformIO $ newIORef undefined currentTrack :: IORef (Maybe SpotifyTrack) currentTrack = unsafePerformIO $ newIORef Nothing getTrackData :: [Text] -> IO [Maybe SpotifyTrack] getTrackData trackIds = forM (map (T.drop 14) trackIds) $ \t -> do track <- identifyTrack t Evade Web API querying limit . Should be done with libspotify as well but ICBA right now return track -- |Shuffles the play queue through a weird combination of things :( shuffleQueue :: IO () shuffleQueue = do queue <- dfQuery GetQueue shuffled <- SQ.fromList <$> runRVar (shuffleSeq queue) DevURandom dfUpdate $ PutQueue shuffled dfUpdate SortQueue -- |Gracefully shuts down the state and archives gracefulQuit :: IO () gracefulQuit = do acid <- readIORef playQueue createArchive acid createCheckpointAndClose acid -- |Gets the folder @~/Library/Application Support/Democrify/queue@ and creates it if it doesn't exist statePath :: IO FilePath statePath = do path <- (++ "/Library/Application Support/Democrify/queue") <$> getHomeDirectory createDirectoryIfMissing True path return path -- |Gets the folder @~/Library/Application Support/Democrify@ and creates it if it doesn't exist prefsPath :: IO FilePath prefsPath = do path <- (++ "/Library/Application Support/Democrify") <$> getHomeDirectory createDirectoryIfMissing False path return $ path ++ "/democrify.config" -- |Part of the DB loop that sorts the queue loopPartSort :: AcidState PlayQueue -> IO () loopPartSort = flip update SortQueue |DB maintenance loop . Sorts the queue ( every 30 seconds ) dbLoop :: AcidState PlayQueue -> IO () dbLoop acid = do loopPartSort acid threadDelay 15000000 dbLoop acid -- |Sets the currently playing track by requesting it from the Spotify Lookup API -- based on the track ID. If the track is not found no track will be set. setCurrentTrack :: Text -> IO () setCurrentTrack track = do song <- identifyTrack track writeIORef currentTrack song foreign export ccall shuffleQueue :: IO () foreign export ccall gracefulQuit :: IO ()
null
https://raw.githubusercontent.com/tazjin/democrify/44d839428f881dff488d2e152ddb828dfd308dde/Democrify/Queue.hs
haskell
# LANGUAGE OverloadedStrings # | This module contains the queue.  |This function runs an Acid Query and retrieves the state from the global IORef |This function runs an Acid Update and retrieves the state from the global IORef |Shuffles the play queue through a weird combination of things :( |Gracefully shuts down the state and archives |Gets the folder @~/Library/Application Support/Democrify/queue@ and creates it if it doesn't exist |Gets the folder @~/Library/Application Support/Democrify@ and creates it if it doesn't exist |Part of the DB loop that sorts the queue |Sets the currently playing track by requesting it from the Spotify Lookup API based on the track ID. If the track is not found no track will be set.
# LANGUAGE ForeignFunctionInterface # module Queue where import Acid import Control.Applicative ((<$>)) import Control.Concurrent import Control.Monad (forM, forM_) import Control.Monad.IO.Class (liftIO) import Data.Acid import Data.Acid.Advanced (update', query') import Data.Acid.Local (createArchive, createCheckpointAndClose) import Data.Data (Data, Typeable) import Data.IORef import Data.Random (runRVar) import Data.Random.Extras (shuffleSeq) import Data.Random.Source.DevRandom (DevRandom (..)) import qualified Data.Sequence as SQ import Data.Text.Lazy (Text, unpack) import qualified Data.Text.Lazy as T import HSObjC import System.Directory (createDirectoryIfMissing, getHomeDirectory) import System.IO.Unsafe (unsafePerformIO) import WebAPI dfQuery u = liftIO (readIORef playQueue) >>= flip query' u dfUpdate u = liftIO (readIORef playQueue) >>= flip update' u initialPlayQueue :: PlayQueue initialPlayQueue = PlayQueue SQ.empty playQueue :: IORef (AcidState PlayQueue) playQueue = unsafePerformIO $ newIORef undefined currentTrack :: IORef (Maybe SpotifyTrack) currentTrack = unsafePerformIO $ newIORef Nothing getTrackData :: [Text] -> IO [Maybe SpotifyTrack] getTrackData trackIds = forM (map (T.drop 14) trackIds) $ \t -> do track <- identifyTrack t Evade Web API querying limit . Should be done with libspotify as well but ICBA right now return track shuffleQueue :: IO () shuffleQueue = do queue <- dfQuery GetQueue shuffled <- SQ.fromList <$> runRVar (shuffleSeq queue) DevURandom dfUpdate $ PutQueue shuffled dfUpdate SortQueue gracefulQuit :: IO () gracefulQuit = do acid <- readIORef playQueue createArchive acid createCheckpointAndClose acid statePath :: IO FilePath statePath = do path <- (++ "/Library/Application Support/Democrify/queue") <$> getHomeDirectory createDirectoryIfMissing True path return path prefsPath :: IO FilePath prefsPath = do path <- (++ "/Library/Application Support/Democrify") <$> getHomeDirectory createDirectoryIfMissing False path return $ path ++ "/democrify.config" loopPartSort :: AcidState PlayQueue -> IO () loopPartSort = flip update SortQueue |DB maintenance loop . Sorts the queue ( every 30 seconds ) dbLoop :: AcidState PlayQueue -> IO () dbLoop acid = do loopPartSort acid threadDelay 15000000 dbLoop acid setCurrentTrack :: Text -> IO () setCurrentTrack track = do song <- identifyTrack track writeIORef currentTrack song foreign export ccall shuffleQueue :: IO () foreign export ccall gracefulQuit :: IO ()
92b83d70416fea80a826702600e5b2ce11a50dac9b09d5963c51331fdf8c01b5
Perry961002/SICP
exe4.75.scm
; s是否只有一个元素 (define (singleton-stream? s) (and (not (stream-null? s)) (stream-null? (cdr s)))) (define (uniquely-asserted pattern frame-stream) (stream-flatmap (lambda (frame) (let ((stream (qeval pattern (singleton-stream frame)))) (if (singleton-stream? stream) stream the-empty-stream))) frame-stream))
null
https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap4/exercise/exe4.75.scm
scheme
s是否只有一个元素
(define (singleton-stream? s) (and (not (stream-null? s)) (stream-null? (cdr s)))) (define (uniquely-asserted pattern frame-stream) (stream-flatmap (lambda (frame) (let ((stream (qeval pattern (singleton-stream frame)))) (if (singleton-stream? stream) stream the-empty-stream))) frame-stream))
94ce3400f69f8d97461ec195230fbd84631e01b116a956abf9936af691c77061
fendor/hsimport
SymbolTest44.hs
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Control.Applicative (r, t, z) import Ugah.Blub ( a , b , c ) import Data.Text (Text(..)) f :: Int -> Int f = (+ 3) r :: Int -> Int r =
null
https://raw.githubusercontent.com/fendor/hsimport/9be9918b06545cfd7282e4db08c2b88f1d8162cd/tests/inputFiles/SymbolTest44.hs
haskell
# Language PatternGuards #
module Blub ( blub , foo , bar ) where import Control.Applicative (r, t, z) import Ugah.Blub ( a , b , c ) import Data.Text (Text(..)) f :: Int -> Int f = (+ 3) r :: Int -> Int r =
9942c6b668c2cea872ea680e01ade7d565a8cbae9d5733efd0eef3177a065f95
39aldo39/klfc
JsonComments.hs
# LANGUAGE UnicodeSyntax , NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module JsonComments ( removeJsonComments ) where import BasePrelude import Prelude.Unicode import qualified Data.ByteString.Lazy.Char8 as BL -- Preserve line numbers removeJsonComments ∷ BL.ByteString → BL.ByteString removeJsonComments = BL.unlines ∘ map removeJsonComment ∘ BL.lines removeJsonComment ∷ BL.ByteString → BL.ByteString removeJsonComment s | isCommentLine s = "" | otherwise = s isCommentLine ∷ BL.ByteString → Bool isCommentLine = BL.isPrefixOf "//" ∘ BL.dropWhile isSpace
null
https://raw.githubusercontent.com/39aldo39/klfc/83908c54c955b9c160b999bc8f0892401ba4adbf/src/JsonComments.hs
haskell
# LANGUAGE OverloadedStrings # Preserve line numbers
# LANGUAGE UnicodeSyntax , NoImplicitPrelude # module JsonComments ( removeJsonComments ) where import BasePrelude import Prelude.Unicode import qualified Data.ByteString.Lazy.Char8 as BL removeJsonComments ∷ BL.ByteString → BL.ByteString removeJsonComments = BL.unlines ∘ map removeJsonComment ∘ BL.lines removeJsonComment ∷ BL.ByteString → BL.ByteString removeJsonComment s | isCommentLine s = "" | otherwise = s isCommentLine ∷ BL.ByteString → Bool isCommentLine = BL.isPrefixOf "//" ∘ BL.dropWhile isSpace
699dfdd82f1f3e2ccebad87e7e870d7bc76cb824136226757a4484e260767508
borgeby/jarl
generator.clj
(ns test.compliance.generator "Generates compliance test files for both Clojure and ClojureScript" (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.pprint :as pprint] [clojure.string :as str] [jarl.builtins.registry :as registry] [zprint.core :as zp]) (:import (java.nio.file FileSystems) (java.io File))) (def ignored-tests {:clj can only read PKCS8 formatted private keys without bouncy castle , not "cryptox509parsersaprivatekey/valid" OPA allows patching sets using this built - in , which would require a custom implementation on our side . ; This does not seem terribly important at the moment. "jsonpatch/set"} :cljs #{; does not seem terribly important, ignoring for now "aggregates/count with invalid utf-8 chars (0xFFFD)" ; while BigInt isn't supported in ClojureScript right now, we could make this work if we're explicit... not sure ; that want all math operations to use BigInt though "arithmetic/big_int" "bitsshiftleft/shift of max int64 doesn't overflow and is not lossy" unicode not supported by goog.crypt . "cryptohmacmd5/crypto.hmac.md5_unicode" "cryptohmacsha1/crypto.hmac.sha1_unicode" "cryptohmacsha256/crypto.hmac.sha256_unicode" "cryptohmacsha512/crypto.hmac.sha512_unicode" ; cljs / javascript implementation not limited in this regard — arguably a feature and not a bug "time/parse_nanos_too_small" "time/parse_nanos_too_large" "time/add_date too small result" "time/add_date too large result" "time/parse_rfc3339_nanos_too_small" "time/parse_rfc3339_nanos_too_large" "time/clock too big" "time/date too big" "time/weekday too big" OPA allows patching sets using this built - in , which would require a custom implementation on our side . ; This does not seem terribly important at the moment. "jsonpatch/set"}}) (defn ignored? [target note] (contains? (get ignored-tests target) note)) (defn json->test-cases [^File file] (-> (slurp file) (json/read-str) (get "cases"))) (defn read-test-cases [] (let [is-json (-> (FileSystems/getDefault) (.getPathMatcher "glob:*.{json}"))] (->> (io/resource "compliance") io/file file-seq (filter #(.isFile ^File %)) (filter #(.matches is-json (.getFileName (.toPath ^File %)))) (mapv json->test-cases) flatten))) (defn note->test-name [note] (-> note (str/replace #"[/\s]" "-") (str/replace #"[\(\)\[\]\{\}\"\.,:]" "") (str/replace "'!¡'" "") (symbol) (vary-meta assoc :tag :compliance))) Deftest form templates - note the heavy use of ~ ' which unquotes a symbol using its name _ only _ , i.e. ; `deftest` rather than `clojure.test/deftest`, which would be the default behavior of syntax-quoted forms. ; While this make total sense for macros, the purpose here is readable code! (defn test-case-want-result [note data input entry-points want-result] (let [note (str/replace note #"\"" "") test-name (note->test-name note)] `(~'deftest ~test-name (~'let [~'plan (~'get ~'test-plans ~note) ~'info (~'parser/parse ~'plan ~'compliance-builtin-resolver) ~'data ~data ~'input ~input ~'result (~'eval-entry-points-for-results ~'info ~entry-points ~'input ~'data)] (~'is (~'= ~'result ~want-result)))))) (defn test-case-want-error [note data input entry-points want-error-code want-error strict-error] (let [note (str/replace note #"\"" "") test-name (note->test-name note)] `(~'deftest ~test-name (~'let [~'strict-error ~strict-error ~'plan (~'get ~'test-plans ~note) ~'info (~'cond-> (~'parser/parse ~'plan ~'compliance-builtin-resolver) (~'true? ~'strict-error) (~'assoc :strict-builtin-errors true)) ~'data ~data ~'input ~input ~'result (~'eval-entry-points-for-errors ~'info ~entry-points ~'input ~'data) ~'jarl-errors (~'filter (~'error-filter ~want-error-code ~want-error) ~'result)] ; There might be other errors generated than what is expected by the test case definition, but the test case does n't know we 're executing multiple entry - points , so we ca n't count unexpected JarlExceptions as violations (~'is (~'not-empty ~'jarl-errors) (~'str ~(str "Expected error code:" want-error-code "; message: " want-error ", got: ") ~'result)))))) (defn parse-input-term [_ term] ; note is unused for now - will be needed for graph.reachable_paths ; Some hacks to work around the fact that we can't parse non-JSON terms (condp = term "{\"foo\": {{1}}}" {"foo" #{#{1}}} "{\"x\": {1, 2, 3, \"a\"}}" {"x" #{1 2 3 "a"}} "{\"x\": {\"a\", {\"x\": 1}, {\"y\": 2}}}" {"x" #{"a" {"x" 1} {"y" 2}}} (json/read-str term))) (defn create-test "Creates a deftest form from an OPA compliance test plan" [{:strs [data note] entry-points "entrypoints" want-result "want_plan_result" want-error-code "want_error_code" want-error "want_error" strict-error "strict_error" :as test-case}] (let [input (if (contains? test-case "input_term") (parse-input-term note (test-case "input_term")) (test-case "input"))] (if (and (nil? want-error-code) (nil? want-error)) (test-case-want-result note data input entry-points want-result) (test-case-want-error note data input entry-points want-error-code want-error strict-error)))) (defn- builtin-names [ir] (let [builtins (get (get ir "static") "builtin_funcs")] (map #(get % "name") builtins))) (defn read-conditional [form target] (second (drop-while #(not= target %) (:form form)))) (defn read-string-as "Read form as given target (e.g. :clj or :cljs) parsing any reader conditionals found for target" [s target] (let [form (read-string {:read-cond :preserve} s)] (if (reader-conditional? form) (read-conditional form target) (map #(if (reader-conditional? %) (read-conditional % target) (identity %)) form)))) (defn read-cljs-registry [] (let [reg-path (str (System/getProperty "user.dir") "/src/main/cljc/jarl/builtins/registry.cljc") forms (str/split (slurp reg-path) #"\n\n") ; TODO Fix! we should not rely on whitespace here but find a way to read forms builtins-form (get forms 1) def-builtins (read-string-as builtins-form :cljs) builtins-map (nth def-builtins 2)] (into {} (for [[k, _] builtins-map] [k, (constantly nil)])))) (defn target-registry-builtins [target] (let [cljs-registry-reader (memoize read-cljs-registry)] (condp = target :clj registry/builtins :cljs (cljs-registry-reader) (println "unknown target" target)))) (defn- ir-supported? [ir target] (if (nil? ir) false (let [used-builtins (builtin-names ir) unsupported (remove #(contains? (target-registry-builtins target) %) used-builtins)] (if (empty? unsupported) true (do (println "Unsupported built-ins:" unsupported) false))))) (defn inc-note "Take note and return a new one with a dash and an incremented number appended if already exists in plans, else note.. i.e. if 'my-test' exists in plans, return 'my-test-2', if 'my-test-2' exists, return 'my-test-3', and so on" [note plans] (if (some? (get plans note)) (let [with-num (re-find #".*-(\d)" note) new-note (cond (vector? with-num) (str/replace note #"-(\d)" (str "-" (inc (parse-long (second with-num))))) :else (str note "-2"))] (inc-note new-note plans)) note)) (defn- generate-tests "Generate tests for provided target (:clj or :cljs)" [target] (loop [test-cases (read-test-cases) result {:plans {} :tests []}] (let [test-case (first test-cases)] (if (nil? test-case) result (let [{:strs [note plan]} test-case note (inc-note note (:plans result)) test-case (assoc test-case "note" note) ir-supported (ir-supported? plan target) ignored (ignored? target note)] (if (and ir-supported (not ignored)) (recur (rest test-cases) (-> result (assoc-in [:plans note] plan) (assoc :tests (conj (:tests result) (create-test test-case))))) (do (println "Ignoring" note "reason:" (cond (nil? plan) "no plan" (not ir-supported) "plan uses unsupported builtins" ignored "explicitly listed as ignored")) (recur (rest test-cases) result)))))))) (defn fmt-plans [plans] (str/triml (str/join "\n" (for [[name plan] plans] (str " \"" (str/replace name #"\"" "") "\" " plan))))) (def compliance-tests-ns-decl {:clj '(ns test.compliance.generated.tests (:require [clojure.test :refer [deftest is]] [jarl.parser :as parser] [test.compliance.runtime :refer [compliance-builtin-resolver eval-entry-points-for-results eval-entry-points-for-errors error-filter]] [test.compliance.generated.plans :refer [test-plans]])) :cljs '(ns test.compliance.generated.tests (:require [cljs.test :refer [deftest is]] [jarl.parser :as parser] [test.compliance.runtime :refer [compliance-builtin-resolver eval-entry-points-for-results eval-entry-points-for-errors error-filter]] [test.compliance.generated.plans :refer [test-plans]]))}) (defn compliance-tests-ns-str [tests target] (let [ns-decl (target compliance-tests-ns-decl)] (str (pprint/write ns-decl :dispatch clojure.pprint/code-dispatch :stream nil :pretty true) "\n\n" (binding [*print-meta* true] (zp/zprint-file-str (str/join "\n" (map prn-str tests)) "" {:width 120}))))) (defn generate-for-target [target] (let [{:keys [plans tests]} (generate-tests target) target-name (get {:clj "clj" :cljs "cljs"} target) dir (str "src/test/" target-name "/test/compliance/generated/") file (io/file dir)] (if (or (.exists file) (.mkdirs file)) (do (spit (str dir "plans." (name target)) (str "(ns test.compliance.generated.plans)" "\n\n(def test-plans \n {" (fmt-plans plans) "})")) (spit (str dir "tests." (name target)) (compliance-tests-ns-str tests target))) (println "ERROR: failed to create dir:" dir)))) (defn -main ([] (println "generating compliance tests for all targets") (time (do (generate-for-target :clj) (generate-for-target :cljs)))) ([target] (let [target (keyword (str/replace target #":" ""))] (println "generating compliance tests for target" target) (if (contains? #{:clj :cljs} target) (time (generate-for-target target)) (println "unsupported target" target)))))
null
https://raw.githubusercontent.com/borgeby/jarl/3783e3a383aadb74a123a6accc72d290451c9be5/core/src/test/clj/test/compliance/generator.clj
clojure
This does not seem terribly important at the moment. does not seem terribly important, ignoring for now while BigInt isn't supported in ClojureScript right now, we could make this work if we're explicit... not sure that want all math operations to use BigInt though cljs / javascript implementation not limited in this regard — arguably a feature and not a bug This does not seem terribly important at the moment. `deftest` rather than `clojure.test/deftest`, which would be the default behavior of syntax-quoted forms. While this make total sense for macros, the purpose here is readable code! There might be other errors generated than what is expected by the test case definition, but the test case note is unused for now - will be needed for graph.reachable_paths Some hacks to work around the fact that we can't parse non-JSON terms TODO Fix! we should not rely on whitespace here but find a way to read forms
(ns test.compliance.generator "Generates compliance test files for both Clojure and ClojureScript" (:require [clojure.data.json :as json] [clojure.java.io :as io] [clojure.pprint :as pprint] [clojure.string :as str] [jarl.builtins.registry :as registry] [zprint.core :as zp]) (:import (java.nio.file FileSystems) (java.io File))) (def ignored-tests {:clj can only read PKCS8 formatted private keys without bouncy castle , not "cryptox509parsersaprivatekey/valid" OPA allows patching sets using this built - in , which would require a custom implementation on our side . "jsonpatch/set"} :cljs "aggregates/count with invalid utf-8 chars (0xFFFD)" "arithmetic/big_int" "bitsshiftleft/shift of max int64 doesn't overflow and is not lossy" unicode not supported by goog.crypt . "cryptohmacmd5/crypto.hmac.md5_unicode" "cryptohmacsha1/crypto.hmac.sha1_unicode" "cryptohmacsha256/crypto.hmac.sha256_unicode" "cryptohmacsha512/crypto.hmac.sha512_unicode" "time/parse_nanos_too_small" "time/parse_nanos_too_large" "time/add_date too small result" "time/add_date too large result" "time/parse_rfc3339_nanos_too_small" "time/parse_rfc3339_nanos_too_large" "time/clock too big" "time/date too big" "time/weekday too big" OPA allows patching sets using this built - in , which would require a custom implementation on our side . "jsonpatch/set"}}) (defn ignored? [target note] (contains? (get ignored-tests target) note)) (defn json->test-cases [^File file] (-> (slurp file) (json/read-str) (get "cases"))) (defn read-test-cases [] (let [is-json (-> (FileSystems/getDefault) (.getPathMatcher "glob:*.{json}"))] (->> (io/resource "compliance") io/file file-seq (filter #(.isFile ^File %)) (filter #(.matches is-json (.getFileName (.toPath ^File %)))) (mapv json->test-cases) flatten))) (defn note->test-name [note] (-> note (str/replace #"[/\s]" "-") (str/replace #"[\(\)\[\]\{\}\"\.,:]" "") (str/replace "'!¡'" "") (symbol) (vary-meta assoc :tag :compliance))) Deftest form templates - note the heavy use of ~ ' which unquotes a symbol using its name _ only _ , i.e. (defn test-case-want-result [note data input entry-points want-result] (let [note (str/replace note #"\"" "") test-name (note->test-name note)] `(~'deftest ~test-name (~'let [~'plan (~'get ~'test-plans ~note) ~'info (~'parser/parse ~'plan ~'compliance-builtin-resolver) ~'data ~data ~'input ~input ~'result (~'eval-entry-points-for-results ~'info ~entry-points ~'input ~'data)] (~'is (~'= ~'result ~want-result)))))) (defn test-case-want-error [note data input entry-points want-error-code want-error strict-error] (let [note (str/replace note #"\"" "") test-name (note->test-name note)] `(~'deftest ~test-name (~'let [~'strict-error ~strict-error ~'plan (~'get ~'test-plans ~note) ~'info (~'cond-> (~'parser/parse ~'plan ~'compliance-builtin-resolver) (~'true? ~'strict-error) (~'assoc :strict-builtin-errors true)) ~'data ~data ~'input ~input ~'result (~'eval-entry-points-for-errors ~'info ~entry-points ~'input ~'data) ~'jarl-errors (~'filter (~'error-filter ~want-error-code ~want-error) ~'result)] does n't know we 're executing multiple entry - points , so we ca n't count unexpected JarlExceptions as violations (~'is (~'not-empty ~'jarl-errors) (~'str ~(str "Expected error code:" want-error-code "; message: " want-error ", got: ") ~'result)))))) (condp = term "{\"foo\": {{1}}}" {"foo" #{#{1}}} "{\"x\": {1, 2, 3, \"a\"}}" {"x" #{1 2 3 "a"}} "{\"x\": {\"a\", {\"x\": 1}, {\"y\": 2}}}" {"x" #{"a" {"x" 1} {"y" 2}}} (json/read-str term))) (defn create-test "Creates a deftest form from an OPA compliance test plan" [{:strs [data note] entry-points "entrypoints" want-result "want_plan_result" want-error-code "want_error_code" want-error "want_error" strict-error "strict_error" :as test-case}] (let [input (if (contains? test-case "input_term") (parse-input-term note (test-case "input_term")) (test-case "input"))] (if (and (nil? want-error-code) (nil? want-error)) (test-case-want-result note data input entry-points want-result) (test-case-want-error note data input entry-points want-error-code want-error strict-error)))) (defn- builtin-names [ir] (let [builtins (get (get ir "static") "builtin_funcs")] (map #(get % "name") builtins))) (defn read-conditional [form target] (second (drop-while #(not= target %) (:form form)))) (defn read-string-as "Read form as given target (e.g. :clj or :cljs) parsing any reader conditionals found for target" [s target] (let [form (read-string {:read-cond :preserve} s)] (if (reader-conditional? form) (read-conditional form target) (map #(if (reader-conditional? %) (read-conditional % target) (identity %)) form)))) (defn read-cljs-registry [] (let [reg-path (str (System/getProperty "user.dir") "/src/main/cljc/jarl/builtins/registry.cljc") builtins-form (get forms 1) def-builtins (read-string-as builtins-form :cljs) builtins-map (nth def-builtins 2)] (into {} (for [[k, _] builtins-map] [k, (constantly nil)])))) (defn target-registry-builtins [target] (let [cljs-registry-reader (memoize read-cljs-registry)] (condp = target :clj registry/builtins :cljs (cljs-registry-reader) (println "unknown target" target)))) (defn- ir-supported? [ir target] (if (nil? ir) false (let [used-builtins (builtin-names ir) unsupported (remove #(contains? (target-registry-builtins target) %) used-builtins)] (if (empty? unsupported) true (do (println "Unsupported built-ins:" unsupported) false))))) (defn inc-note "Take note and return a new one with a dash and an incremented number appended if already exists in plans, else note.. i.e. if 'my-test' exists in plans, return 'my-test-2', if 'my-test-2' exists, return 'my-test-3', and so on" [note plans] (if (some? (get plans note)) (let [with-num (re-find #".*-(\d)" note) new-note (cond (vector? with-num) (str/replace note #"-(\d)" (str "-" (inc (parse-long (second with-num))))) :else (str note "-2"))] (inc-note new-note plans)) note)) (defn- generate-tests "Generate tests for provided target (:clj or :cljs)" [target] (loop [test-cases (read-test-cases) result {:plans {} :tests []}] (let [test-case (first test-cases)] (if (nil? test-case) result (let [{:strs [note plan]} test-case note (inc-note note (:plans result)) test-case (assoc test-case "note" note) ir-supported (ir-supported? plan target) ignored (ignored? target note)] (if (and ir-supported (not ignored)) (recur (rest test-cases) (-> result (assoc-in [:plans note] plan) (assoc :tests (conj (:tests result) (create-test test-case))))) (do (println "Ignoring" note "reason:" (cond (nil? plan) "no plan" (not ir-supported) "plan uses unsupported builtins" ignored "explicitly listed as ignored")) (recur (rest test-cases) result)))))))) (defn fmt-plans [plans] (str/triml (str/join "\n" (for [[name plan] plans] (str " \"" (str/replace name #"\"" "") "\" " plan))))) (def compliance-tests-ns-decl {:clj '(ns test.compliance.generated.tests (:require [clojure.test :refer [deftest is]] [jarl.parser :as parser] [test.compliance.runtime :refer [compliance-builtin-resolver eval-entry-points-for-results eval-entry-points-for-errors error-filter]] [test.compliance.generated.plans :refer [test-plans]])) :cljs '(ns test.compliance.generated.tests (:require [cljs.test :refer [deftest is]] [jarl.parser :as parser] [test.compliance.runtime :refer [compliance-builtin-resolver eval-entry-points-for-results eval-entry-points-for-errors error-filter]] [test.compliance.generated.plans :refer [test-plans]]))}) (defn compliance-tests-ns-str [tests target] (let [ns-decl (target compliance-tests-ns-decl)] (str (pprint/write ns-decl :dispatch clojure.pprint/code-dispatch :stream nil :pretty true) "\n\n" (binding [*print-meta* true] (zp/zprint-file-str (str/join "\n" (map prn-str tests)) "" {:width 120}))))) (defn generate-for-target [target] (let [{:keys [plans tests]} (generate-tests target) target-name (get {:clj "clj" :cljs "cljs"} target) dir (str "src/test/" target-name "/test/compliance/generated/") file (io/file dir)] (if (or (.exists file) (.mkdirs file)) (do (spit (str dir "plans." (name target)) (str "(ns test.compliance.generated.plans)" "\n\n(def test-plans \n {" (fmt-plans plans) "})")) (spit (str dir "tests." (name target)) (compliance-tests-ns-str tests target))) (println "ERROR: failed to create dir:" dir)))) (defn -main ([] (println "generating compliance tests for all targets") (time (do (generate-for-target :clj) (generate-for-target :cljs)))) ([target] (let [target (keyword (str/replace target #":" ""))] (println "generating compliance tests for target" target) (if (contains? #{:clj :cljs} target) (time (generate-for-target target)) (println "unsupported target" target)))))
4c265d522be6c02ba3ba9764270c4d05c03470eb3f0cd7908244a4fe62cda179
xh4/web-toolkit
package.lisp
(in-package :cl-user) (defpackage :vendor (:nicknames :wt.vendor) (:use :cl) (:export :install))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/vendor/package.lisp
lisp
(in-package :cl-user) (defpackage :vendor (:nicknames :wt.vendor) (:use :cl) (:export :install))
3a85bbe2036350698222fcfeebe675bfb06844746c7aef61b9132b3996c0f5d0
RolfRolles/PandemicML
CFGBuild.mli
exception IndirectJump of int32 module type Language = sig type t val disasm : int32 -> t * ASMUtil.cfsuccessors val disasm_ex : int32 -> int32 -> t * ASMUtil.cfsuccessors * int32 end module type S = sig type lang module C : CFG.CFG with type language = lang list val merge_singleton_vertices : C.G.t -> C.G.t val remove_empty_vertices : C.G.t -> C.G.t val build : ?stopfun:(int32 -> bool) -> int32 -> C.G.t * (int32, unit) Hashtbl.t val build_ex : ?start_graph:C.G.t -> int32 -> int32 -> C.G.t val get_order : C.G.t -> C.G.V.t -> C.G.V.t list end module MakeGraphBuilder (Lang : Language) : S with type lang = Lang.t type 'a s = (module S with type lang = 'a)
null
https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/Graph/CFGBuild.mli
ocaml
exception IndirectJump of int32 module type Language = sig type t val disasm : int32 -> t * ASMUtil.cfsuccessors val disasm_ex : int32 -> int32 -> t * ASMUtil.cfsuccessors * int32 end module type S = sig type lang module C : CFG.CFG with type language = lang list val merge_singleton_vertices : C.G.t -> C.G.t val remove_empty_vertices : C.G.t -> C.G.t val build : ?stopfun:(int32 -> bool) -> int32 -> C.G.t * (int32, unit) Hashtbl.t val build_ex : ?start_graph:C.G.t -> int32 -> int32 -> C.G.t val get_order : C.G.t -> C.G.V.t -> C.G.V.t list end module MakeGraphBuilder (Lang : Language) : S with type lang = Lang.t type 'a s = (module S with type lang = 'a)
aa275e8a54af44cd9575179dc493ec7b644ae760ca9eb82ecc1dc17a5b556c3c
returntocorp/ocaml-tree-sitter-core
Backtrack_matcher.ml
(* A backtracking regular expression matcher. It promises to be simple and fast on simple regular expressions, but with an exponential asymptotic cost. *) open Printf let debug = false module Make (Token : Matcher.Token) : Matcher.Matcher with type token_kind = Token.kind and type token = Token.t = struct open Matcher type token_kind = Token.kind type token = Token.t let show_exp = Matcher.Exp.show Token.show_kind let show_capture = Matcher.Capture.show Token.show let show_match = Matcher.show_match Token.show (* Local type aliases for use in type annotations *) type nonrec exp = token_kind exp type nonrec capture = token capture type punct = | Enter_repeat | Enter_repeat1 | Enter_opt | Enter_alt of int | Enter_seq | Leave_repeat | Leave_repeat1 | Leave_opt | Leave_alt | Leave_seq | Nothing type path_elt = | Token of token | Punct of punct type path = path_elt list let show_path_elt path_elt = match path_elt with | Token tok -> Token.show tok | Punct x -> match x with | Enter_repeat -> "Enter_repeat" | Enter_repeat1 -> "Enter_repeat1" | Enter_opt -> "Enter_opt" | Enter_alt i -> sprintf "Enter_alt %i" i | Enter_seq -> "Enter_seq" | Leave_repeat -> "Leave_repeat" | Leave_repeat1 -> "Leave_repeat1" | Leave_opt -> "Leave_opt" | Leave_alt -> sprintf "Leave_alt" | Leave_seq -> "Leave_seq" | Nothing -> "Nothing" let show_path path = List.map (fun x -> sprintf " %s\n" (show_path_elt x)) path |> String.concat "" let match_end path tokens = match tokens with | [] -> Some (path, tokens) | _ -> None (* Match an expression against the beginning of the input sequence and match the rest of the input sequence. There may be several ways of matching an expression. Each way is tried sequentially until a match for the full sequence is found. *) let rec match_exp (path : path) (exp : exp) (tokens : token list) cont : (path * token list) option = match exp, tokens with | Token kind, tokens -> one way (match tokens with | tok :: tokens when kind = Token.kind tok -> cont (Token tok :: path) tokens | _ -> None ) | Repeat exp, tokens -> zero or more ways let cont path tokens = cont (Punct Leave_repeat :: path) tokens in match_repeat (Punct Enter_repeat :: path) exp tokens cont | Repeat1 exp, tokens -> one or more ways let cont path tokens = cont (Punct Leave_repeat1 :: path) tokens in match_repeat1 (Punct Enter_repeat1 :: path) exp tokens cont | Opt exp, tokens -> zero or one way let cont path tokens = cont (Punct Leave_opt :: path) tokens in match_opt (Punct Enter_opt :: path) exp tokens cont | Alt exps, tokens -> (* n ways *) match_cases path exps tokens cont | Seq exps, tokens -> one way match_seq (Punct Enter_seq :: path) exps tokens cont | Nothing, tokens -> one way cont (Punct Nothing :: path) tokens and match_repeat path exp tokens0 after_repeat = let after_exp path tokens = if tokens == tokens0 (* physical equality *) then (* avoid infinite loop if no input was consumed *) after_repeat path tokens else match_repeat path exp tokens after_repeat in match match_exp path exp tokens0 after_exp with | Some _ as res -> res | None -> after_repeat path tokens0 and match_repeat1 path exp tokens0 after_repeat = let after_exp path tokens = if tokens == tokens0 (* physical equality *) then (* avoid infinite loop if no input was consumed *) after_repeat path tokens else match_repeat path exp tokens after_repeat in match match_exp path exp tokens0 after_exp with | Some _ as res -> res | None -> None and match_opt path exp tokens after_opt = match match_exp path exp tokens after_opt with | Some _ as res -> res | None -> after_opt path tokens and match_cases path exps tokens cont = if Array.length exps = 0 then None else let cont path tokens = cont (Punct Leave_alt :: path) tokens in match_case path exps tokens cont 0 and match_case path exps tokens cont i = match match_exp (Punct (Enter_alt i) :: path) exps.(i) tokens cont with | Some _ as res -> res | None -> let i = i + 1 in if i < Array.length exps then match_case path exps tokens cont i else None and match_seq path exps tokens cont = match exps with | [] -> cont (Punct Leave_seq :: path) tokens | exp :: exps -> let cont path tokens = match_seq path exps tokens cont in match_exp path exp tokens cont let rec reconstruct_capture (exp : exp) (path : path) : capture * path = match exp, path with | Token _, (Token tok :: path) -> Token tok, path | Repeat exp, (Punct Enter_repeat :: path) -> let list, path = read_repeat exp path in Repeat list, path | Repeat1 exp, (Punct Enter_repeat1 :: path) -> let list, path = read_repeat exp path in Repeat1 list, path | Opt exp, (Punct Enter_opt :: path) -> let option, path = read_option exp path in Opt option, path | Alt cases, (Punct (Enter_alt i) :: path) -> let res, path = read_alt cases.(i) path in Alt (i, res), path | Seq exps, (Punct Enter_seq :: path) -> let list, path = read_seq exps path in Seq list, path | Nothing, (Punct Nothing :: path) -> Nothing, path | _ -> assert false used for both repeat and repeat1 and read_repeat exp path : _ list * path = match path with | Punct (Leave_repeat | Leave_repeat1) :: path -> [], path | _ -> let head, path = reconstruct_capture exp path in let tail, path = read_repeat exp path in (head :: tail), path and read_option exp path : _ option * path = match path with | Punct Leave_opt :: path -> None, path | _ -> let elt, path = reconstruct_capture exp path in let path = match path with | Punct Leave_opt :: path -> path | _ -> assert false in Some elt, path and read_alt exp path : _ * path = let elt, path = reconstruct_capture exp path in match path with | Punct Leave_alt :: path -> elt, path | _ -> assert false and read_seq exps path = match exps with | [] -> let path = match path with | Punct Leave_seq :: path -> path | _ -> assert false in [], path | exp :: exps -> let head, path = reconstruct_capture exp path in let tail, path = read_seq exps path in (head :: tail), path (* Match a regular expression against a sequence of tokens, return the path taken, which is a flat list of tokens and delimiters. Tokens must all be consumed for the match to be successful. *) let match_ exp tokens = match match_exp [] exp tokens match_end with | Some (path, tokens) -> assert (tokens = []); Some (List.rev path) | None -> None Construct a tree from a flat path returned by ' match _ ' . Construct a tree from a flat path returned by 'match_'. *) let reconstruct exp path = let res, path = reconstruct_capture exp path in assert (path = []); res (* Match and reconstruct. *) let match_tree exp tokens = match match_ exp tokens with | None -> None | Some path -> if debug then printf "path: [\n%s]\n%!" (show_path path); Some (reconstruct exp path) end
null
https://raw.githubusercontent.com/returntocorp/ocaml-tree-sitter-core/28f750bb894ea4c0a7f6b911e568ab9d731cc0b5/src/run/lib/Backtrack_matcher.ml
ocaml
A backtracking regular expression matcher. It promises to be simple and fast on simple regular expressions, but with an exponential asymptotic cost. Local type aliases for use in type annotations Match an expression against the beginning of the input sequence and match the rest of the input sequence. There may be several ways of matching an expression. Each way is tried sequentially until a match for the full sequence is found. n ways physical equality avoid infinite loop if no input was consumed physical equality avoid infinite loop if no input was consumed Match a regular expression against a sequence of tokens, return the path taken, which is a flat list of tokens and delimiters. Tokens must all be consumed for the match to be successful. Match and reconstruct.
open Printf let debug = false module Make (Token : Matcher.Token) : Matcher.Matcher with type token_kind = Token.kind and type token = Token.t = struct open Matcher type token_kind = Token.kind type token = Token.t let show_exp = Matcher.Exp.show Token.show_kind let show_capture = Matcher.Capture.show Token.show let show_match = Matcher.show_match Token.show type nonrec exp = token_kind exp type nonrec capture = token capture type punct = | Enter_repeat | Enter_repeat1 | Enter_opt | Enter_alt of int | Enter_seq | Leave_repeat | Leave_repeat1 | Leave_opt | Leave_alt | Leave_seq | Nothing type path_elt = | Token of token | Punct of punct type path = path_elt list let show_path_elt path_elt = match path_elt with | Token tok -> Token.show tok | Punct x -> match x with | Enter_repeat -> "Enter_repeat" | Enter_repeat1 -> "Enter_repeat1" | Enter_opt -> "Enter_opt" | Enter_alt i -> sprintf "Enter_alt %i" i | Enter_seq -> "Enter_seq" | Leave_repeat -> "Leave_repeat" | Leave_repeat1 -> "Leave_repeat1" | Leave_opt -> "Leave_opt" | Leave_alt -> sprintf "Leave_alt" | Leave_seq -> "Leave_seq" | Nothing -> "Nothing" let show_path path = List.map (fun x -> sprintf " %s\n" (show_path_elt x)) path |> String.concat "" let match_end path tokens = match tokens with | [] -> Some (path, tokens) | _ -> None let rec match_exp (path : path) (exp : exp) (tokens : token list) cont : (path * token list) option = match exp, tokens with | Token kind, tokens -> one way (match tokens with | tok :: tokens when kind = Token.kind tok -> cont (Token tok :: path) tokens | _ -> None ) | Repeat exp, tokens -> zero or more ways let cont path tokens = cont (Punct Leave_repeat :: path) tokens in match_repeat (Punct Enter_repeat :: path) exp tokens cont | Repeat1 exp, tokens -> one or more ways let cont path tokens = cont (Punct Leave_repeat1 :: path) tokens in match_repeat1 (Punct Enter_repeat1 :: path) exp tokens cont | Opt exp, tokens -> zero or one way let cont path tokens = cont (Punct Leave_opt :: path) tokens in match_opt (Punct Enter_opt :: path) exp tokens cont | Alt exps, tokens -> match_cases path exps tokens cont | Seq exps, tokens -> one way match_seq (Punct Enter_seq :: path) exps tokens cont | Nothing, tokens -> one way cont (Punct Nothing :: path) tokens and match_repeat path exp tokens0 after_repeat = let after_exp path tokens = after_repeat path tokens else match_repeat path exp tokens after_repeat in match match_exp path exp tokens0 after_exp with | Some _ as res -> res | None -> after_repeat path tokens0 and match_repeat1 path exp tokens0 after_repeat = let after_exp path tokens = after_repeat path tokens else match_repeat path exp tokens after_repeat in match match_exp path exp tokens0 after_exp with | Some _ as res -> res | None -> None and match_opt path exp tokens after_opt = match match_exp path exp tokens after_opt with | Some _ as res -> res | None -> after_opt path tokens and match_cases path exps tokens cont = if Array.length exps = 0 then None else let cont path tokens = cont (Punct Leave_alt :: path) tokens in match_case path exps tokens cont 0 and match_case path exps tokens cont i = match match_exp (Punct (Enter_alt i) :: path) exps.(i) tokens cont with | Some _ as res -> res | None -> let i = i + 1 in if i < Array.length exps then match_case path exps tokens cont i else None and match_seq path exps tokens cont = match exps with | [] -> cont (Punct Leave_seq :: path) tokens | exp :: exps -> let cont path tokens = match_seq path exps tokens cont in match_exp path exp tokens cont let rec reconstruct_capture (exp : exp) (path : path) : capture * path = match exp, path with | Token _, (Token tok :: path) -> Token tok, path | Repeat exp, (Punct Enter_repeat :: path) -> let list, path = read_repeat exp path in Repeat list, path | Repeat1 exp, (Punct Enter_repeat1 :: path) -> let list, path = read_repeat exp path in Repeat1 list, path | Opt exp, (Punct Enter_opt :: path) -> let option, path = read_option exp path in Opt option, path | Alt cases, (Punct (Enter_alt i) :: path) -> let res, path = read_alt cases.(i) path in Alt (i, res), path | Seq exps, (Punct Enter_seq :: path) -> let list, path = read_seq exps path in Seq list, path | Nothing, (Punct Nothing :: path) -> Nothing, path | _ -> assert false used for both repeat and repeat1 and read_repeat exp path : _ list * path = match path with | Punct (Leave_repeat | Leave_repeat1) :: path -> [], path | _ -> let head, path = reconstruct_capture exp path in let tail, path = read_repeat exp path in (head :: tail), path and read_option exp path : _ option * path = match path with | Punct Leave_opt :: path -> None, path | _ -> let elt, path = reconstruct_capture exp path in let path = match path with | Punct Leave_opt :: path -> path | _ -> assert false in Some elt, path and read_alt exp path : _ * path = let elt, path = reconstruct_capture exp path in match path with | Punct Leave_alt :: path -> elt, path | _ -> assert false and read_seq exps path = match exps with | [] -> let path = match path with | Punct Leave_seq :: path -> path | _ -> assert false in [], path | exp :: exps -> let head, path = reconstruct_capture exp path in let tail, path = read_seq exps path in (head :: tail), path let match_ exp tokens = match match_exp [] exp tokens match_end with | Some (path, tokens) -> assert (tokens = []); Some (List.rev path) | None -> None Construct a tree from a flat path returned by ' match _ ' . Construct a tree from a flat path returned by 'match_'. *) let reconstruct exp path = let res, path = reconstruct_capture exp path in assert (path = []); res let match_tree exp tokens = match match_ exp tokens with | None -> None | Some path -> if debug then printf "path: [\n%s]\n%!" (show_path path); Some (reconstruct exp path) end
ca28962d3524474030f4e0fa25bac0a32d1c21f778d789ff2b7487f95c132b61
sol/aeson-qq
Person.hs
# LANGUAGE OverloadedStrings , DeriveGeneric # module Person where import GHC.Generics import Data.Aeson data Person = Person { name :: String , age :: Int } deriving (Eq, Show, Generic) instance ToJSON Person
null
https://raw.githubusercontent.com/sol/aeson-qq/3b5acf994cb7ee452eb58a4733b21b7eca53132f/test/Person.hs
haskell
# LANGUAGE OverloadedStrings , DeriveGeneric # module Person where import GHC.Generics import Data.Aeson data Person = Person { name :: String , age :: Int } deriving (Eq, Show, Generic) instance ToJSON Person
7a9640d63ab31429dbab68bfe67001cf30179ef229990d6395356d7a073fe383
krcz/zygote
c-syntax-render.rkt
#lang typed/racket (require "c-syntax-defs.rkt") (require threading) (provide (all-defined-out)) (define-type token (U Symbol String integer-literal)) (struct Renderer ([output : Output-Port] [needs-separation? : Boolean]) #:transparent) (: ro-one (-> Renderer token Renderer)) (define (ro-one r t) (let*-values ([(o) (values (Renderer-output r))] [(str needs-separation?) (cond [(eq? t 'lparen) (values "(" #f)] [(eq? t 'rparen) (values ")" #f)] [(eq? t 'lbracket) (values "[" #f)] [(eq? t 'rbracket) (values "]" #f)] [(eq? t 'lbrace) (values "{" #f)] [(eq? t 'rbrace) (values "}" #f)] [(eq? t 'semicolon) (values ";" #t)] [(eq? t 'colon) (values "," #t)] [(eq? t 'comma) (values "." #f)] [(eq? t 'newline) (values "\n" #f)] [(integer-literal? t) (values (number->string (integer-literal-value t)) #t)] [(symbol? t) (values (symbol->string t) #t)] [(string? t) (values t #t)])] [(_) (if (and needs-separation? (Renderer-needs-separation? r)) (display " " o) '())]) (display str o) (struct-copy Renderer r [needs-separation? needs-separation?]))) (: ro (-> Renderer token * Renderer)) (: ro-list (-> Renderer (Listof token) Renderer)) (define (ro-list r tokens) (for/fold ([rr r]) ([t tokens]) (ro-one rr t))) (: ro (-> Renderer token * Renderer)) (define (ro r . tokens) (ro-list r tokens)) (: render-list-with (All (T) (-> Renderer (-> Renderer T Renderer) (Listof T) Renderer))) (define (render-list-with r f l) (for/fold ([rr r]) ([arg l]) (f rr arg))) (: render-list-with-sep (All (T) (-> Renderer (-> Renderer T Renderer) token (Listof T) Renderer))) (define (render-list-with-sep r f sep l) (if (empty? l) r (for/fold ([rr (f r (car l))]) ([arg (cdr l)]) (~> r (ro sep) (f arg))))) (: render-ex (-> Renderer expression+ Renderer)) (define (render-ex r ex) (match ex [(call-expression ex arguments) (~> r (render-ex ex) (ro 'lparen) (render-list-with-sep render-ex 'colon arguments) (ro 'rparen))] [(indexing-expression ex index) (~> r (render-ex ex) (ro 'lbracket) (render-ex index) (ro 'rbracket))] [(access-expression ex field) (~> r (render-ex ex) (ro 'comma) (render-ex field))] [(postfix-expression ex op) (~> r (render-ex ex) (ro op))] [(assignment-expression op left right) (~> r (render-ex left) (ro (assignment-operator-op op)) (render-ex right))] [(conditional-expression condition left right) (~> r (render-ex condition) (ro '?) (render-ex left) (ro ':) (render-ex right))] [(binary-expression op left right) (~> r (render-ex left) (ro op) (render-ex right))] [(cast-expression type exx) (~> r (ro 'lparen) (ro (type-name-name type)) (ro 'rparen) (render-ex exx))] [(unary-expression op exx) (~> r (ro op) (render-ex exx))] [(bracketed-expression exx) (~> r (ro 'lparen) (render-ex exx) (ro 'rparen))] [(expression prev last) (~> r (render-ex prev) (ro 'colon) (render-ex last))] [(var-name name) (ro r name)] [(integer-literal value) (ro r (integer-literal value))])) (: render-stat (-> Renderer statement Renderer)) (define (render-stat r stat) (match stat [(compound-statement items) (~> r (ro 'lbrace) (ro 'newline) (render-list-with render-block-item items) (ro 'rbrace))] [(expression-statement ex) (~> r (render-ex ex) (ro 'semicolon))] [(if-else-statement pred if-branch else-branch) (~> r (ro 'if) (ro 'lparen) (render-ex pred) (ro 'rparen) (render-stat if-branch) (ro 'else) (render-stat else-branch))] [(while-statement pred body) (~> r (ro 'while) (ro 'lparen) (render-ex pred) (ro 'rparen) (render-stat body))] [(do-while-statement body pred) (~> r (ro 'do) (render-stat body) (ro 'while) (ro 'lparen) (render-ex pred) (ro 'rparen))] [(for-statement init pred update body) (~> r (ro 'for) (ro 'lparen) (render-ex init) (ro 'semicolon) (render-ex pred) (ro 'semicolon) (render-ex update) (ro 'rparen) (render-stat body))])) (: render-block-item (-> Renderer block-item Renderer)) (define (render-block-item r b) (ro (match b [(? (make-predicate statement) bb) (render-stat r bb)] [(? (make-predicate declaration) bb) (render-decl r bb)]) 'newline)) (: render-decl (-> Renderer declaration Renderer)) (define (render-decl r decl) (let-values ([(specifiers declarators) (match decl [(var-declaration s d) (values s d)] [(type-declaration s d) (values s d)])]) (~> r (render-list-with render-specifier specifiers) (render-list-with-sep render-declarator 'colon declarators) (ro 'semicolon)))) (: render-specifier (-> Renderer declaration-specifier Renderer)) (define (render-specifier r spec) (match spec [(? symbol? s) (ro r s)])) (: ignore-null (All(T) (-> (-> Renderer T Renderer) (-> Renderer (U T Null) Renderer)))) (define (ignore-null f) (lambda (r v) (if (null? v) r (f r v)))) (: render-pointer (-> Renderer pointer Renderer)) (define (render-pointer r ptr) (let ([render-part (lambda ([r : Renderer] [part : (Listof type-qualifier)]) (~> r (ro '*) (render-list-with ro part)))] [parts (pointer-qualifiers ptr)]) (render-list-with r render-part parts))) (: render-declarator (-> Renderer (U declarator abstract-declarator) Renderer)) (define (render-declarator r declarator) (match declarator [(var-name name) (ro r name)] [(pointer-declarator p d) (~> r (render-pointer p) (render-declarator d))] [(bracketed-declarator d) (~> r (ro 'lparen) (render-declarator d) (ro 'rparen))] [(fun-declarator d params ellipsis?) (~> r (render-declarator d) (ro 'lparen) (render-list-with-sep render-parameter-decl 'colon params) (ro 'rparen))] [(bracketed-abstract-declarator d) (~> r (ro 'lparen) (render-declarator d) (ro 'rparen))] [(fun-abstract-declarator d params ellipsis?) (~> r ((ignore-null render-declarator) d) (ro 'lparen) (render-list-with-sep render-parameter-decl 'colon params) (ro 'rparen))])) (: render-parameter-decl (-> Renderer parameter-declaration Renderer)) (define (render-parameter-decl r decl) (~> r (render-list-with render-specifier (parameter-declaration-specifiers decl)) (render-declarator (parameter-declaration-target decl)))) (: render (-> Renderer external-declaration Renderer)) (define (render r ed) (match ed [(function-definition specs decl dl body) (~> r (render-list-with render-specifier specs) (render-declarator decl) (render-stat body))])) (: to-stdout (All (T U) (-> (-> Renderer T Any) T Void))) (define (to-stdout f v) (f (Renderer (current-output-port) #f) v) (newline (current-output-port)) (void))
null
https://raw.githubusercontent.com/krcz/zygote/1f6298f0a73fd0320bc3ba5abe5f00a805fed8fc/noizy/c-syntax-render.rkt
racket
#lang typed/racket (require "c-syntax-defs.rkt") (require threading) (provide (all-defined-out)) (define-type token (U Symbol String integer-literal)) (struct Renderer ([output : Output-Port] [needs-separation? : Boolean]) #:transparent) (: ro-one (-> Renderer token Renderer)) (define (ro-one r t) (let*-values ([(o) (values (Renderer-output r))] [(str needs-separation?) (cond [(eq? t 'lparen) (values "(" #f)] [(eq? t 'rparen) (values ")" #f)] [(eq? t 'lbracket) (values "[" #f)] [(eq? t 'rbracket) (values "]" #f)] [(eq? t 'lbrace) (values "{" #f)] [(eq? t 'rbrace) (values "}" #f)] [(eq? t 'semicolon) (values ";" #t)] [(eq? t 'colon) (values "," #t)] [(eq? t 'comma) (values "." #f)] [(eq? t 'newline) (values "\n" #f)] [(integer-literal? t) (values (number->string (integer-literal-value t)) #t)] [(symbol? t) (values (symbol->string t) #t)] [(string? t) (values t #t)])] [(_) (if (and needs-separation? (Renderer-needs-separation? r)) (display " " o) '())]) (display str o) (struct-copy Renderer r [needs-separation? needs-separation?]))) (: ro (-> Renderer token * Renderer)) (: ro-list (-> Renderer (Listof token) Renderer)) (define (ro-list r tokens) (for/fold ([rr r]) ([t tokens]) (ro-one rr t))) (: ro (-> Renderer token * Renderer)) (define (ro r . tokens) (ro-list r tokens)) (: render-list-with (All (T) (-> Renderer (-> Renderer T Renderer) (Listof T) Renderer))) (define (render-list-with r f l) (for/fold ([rr r]) ([arg l]) (f rr arg))) (: render-list-with-sep (All (T) (-> Renderer (-> Renderer T Renderer) token (Listof T) Renderer))) (define (render-list-with-sep r f sep l) (if (empty? l) r (for/fold ([rr (f r (car l))]) ([arg (cdr l)]) (~> r (ro sep) (f arg))))) (: render-ex (-> Renderer expression+ Renderer)) (define (render-ex r ex) (match ex [(call-expression ex arguments) (~> r (render-ex ex) (ro 'lparen) (render-list-with-sep render-ex 'colon arguments) (ro 'rparen))] [(indexing-expression ex index) (~> r (render-ex ex) (ro 'lbracket) (render-ex index) (ro 'rbracket))] [(access-expression ex field) (~> r (render-ex ex) (ro 'comma) (render-ex field))] [(postfix-expression ex op) (~> r (render-ex ex) (ro op))] [(assignment-expression op left right) (~> r (render-ex left) (ro (assignment-operator-op op)) (render-ex right))] [(conditional-expression condition left right) (~> r (render-ex condition) (ro '?) (render-ex left) (ro ':) (render-ex right))] [(binary-expression op left right) (~> r (render-ex left) (ro op) (render-ex right))] [(cast-expression type exx) (~> r (ro 'lparen) (ro (type-name-name type)) (ro 'rparen) (render-ex exx))] [(unary-expression op exx) (~> r (ro op) (render-ex exx))] [(bracketed-expression exx) (~> r (ro 'lparen) (render-ex exx) (ro 'rparen))] [(expression prev last) (~> r (render-ex prev) (ro 'colon) (render-ex last))] [(var-name name) (ro r name)] [(integer-literal value) (ro r (integer-literal value))])) (: render-stat (-> Renderer statement Renderer)) (define (render-stat r stat) (match stat [(compound-statement items) (~> r (ro 'lbrace) (ro 'newline) (render-list-with render-block-item items) (ro 'rbrace))] [(expression-statement ex) (~> r (render-ex ex) (ro 'semicolon))] [(if-else-statement pred if-branch else-branch) (~> r (ro 'if) (ro 'lparen) (render-ex pred) (ro 'rparen) (render-stat if-branch) (ro 'else) (render-stat else-branch))] [(while-statement pred body) (~> r (ro 'while) (ro 'lparen) (render-ex pred) (ro 'rparen) (render-stat body))] [(do-while-statement body pred) (~> r (ro 'do) (render-stat body) (ro 'while) (ro 'lparen) (render-ex pred) (ro 'rparen))] [(for-statement init pred update body) (~> r (ro 'for) (ro 'lparen) (render-ex init) (ro 'semicolon) (render-ex pred) (ro 'semicolon) (render-ex update) (ro 'rparen) (render-stat body))])) (: render-block-item (-> Renderer block-item Renderer)) (define (render-block-item r b) (ro (match b [(? (make-predicate statement) bb) (render-stat r bb)] [(? (make-predicate declaration) bb) (render-decl r bb)]) 'newline)) (: render-decl (-> Renderer declaration Renderer)) (define (render-decl r decl) (let-values ([(specifiers declarators) (match decl [(var-declaration s d) (values s d)] [(type-declaration s d) (values s d)])]) (~> r (render-list-with render-specifier specifiers) (render-list-with-sep render-declarator 'colon declarators) (ro 'semicolon)))) (: render-specifier (-> Renderer declaration-specifier Renderer)) (define (render-specifier r spec) (match spec [(? symbol? s) (ro r s)])) (: ignore-null (All(T) (-> (-> Renderer T Renderer) (-> Renderer (U T Null) Renderer)))) (define (ignore-null f) (lambda (r v) (if (null? v) r (f r v)))) (: render-pointer (-> Renderer pointer Renderer)) (define (render-pointer r ptr) (let ([render-part (lambda ([r : Renderer] [part : (Listof type-qualifier)]) (~> r (ro '*) (render-list-with ro part)))] [parts (pointer-qualifiers ptr)]) (render-list-with r render-part parts))) (: render-declarator (-> Renderer (U declarator abstract-declarator) Renderer)) (define (render-declarator r declarator) (match declarator [(var-name name) (ro r name)] [(pointer-declarator p d) (~> r (render-pointer p) (render-declarator d))] [(bracketed-declarator d) (~> r (ro 'lparen) (render-declarator d) (ro 'rparen))] [(fun-declarator d params ellipsis?) (~> r (render-declarator d) (ro 'lparen) (render-list-with-sep render-parameter-decl 'colon params) (ro 'rparen))] [(bracketed-abstract-declarator d) (~> r (ro 'lparen) (render-declarator d) (ro 'rparen))] [(fun-abstract-declarator d params ellipsis?) (~> r ((ignore-null render-declarator) d) (ro 'lparen) (render-list-with-sep render-parameter-decl 'colon params) (ro 'rparen))])) (: render-parameter-decl (-> Renderer parameter-declaration Renderer)) (define (render-parameter-decl r decl) (~> r (render-list-with render-specifier (parameter-declaration-specifiers decl)) (render-declarator (parameter-declaration-target decl)))) (: render (-> Renderer external-declaration Renderer)) (define (render r ed) (match ed [(function-definition specs decl dl body) (~> r (render-list-with render-specifier specs) (render-declarator decl) (render-stat body))])) (: to-stdout (All (T U) (-> (-> Renderer T Any) T Void))) (define (to-stdout f v) (f (Renderer (current-output-port) #f) v) (newline (current-output-port)) (void))
642ed8cdd304ec92b31374381200c2f0e40ea97e8da651c27d0c3146cd2a158f
CryptoKami/cryptokami-core
PureSpec.hs
| Specification for Pos . . . Toss . Pure module Test.Pos.Ssc.Toss.PureSpec ( spec ) where import Universum import qualified Crypto.Random as Rand import Data.Default (def) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck (Arbitrary (..), Gen, Property, forAll, listOf, suchThat, (===)) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Arbitrary.Core () import Pos.Arbitrary.Ssc () import Pos.Core (InnerSharesMap, EpochOrSlot, HasConfiguration, Opening, SignedCommitment, StakeholderId, VssCertificate (..), addressHash) import qualified Pos.Ssc.Toss.Class as Toss import qualified Pos.Ssc.Toss.Pure as Toss import qualified Pos.Ssc.Types as Toss import Test.Pos.Configuration (withDefConfiguration) spec :: Spec spec = withDefConfiguration $ describe "Toss" $ do let smaller n = modifyMaxSuccess (const n) describe "PureToss" $ smaller 30 $ do prop "Adding and deleting a signed commitment in the 'PureToss' monad is the\ \ same as doing nothing" putDelCommitment prop "Adding and deleting an opening in the 'PureToss' monad is the same as doing\ \ nothing" putDelOpening prop "Adding and deleting a share in the 'PureToss' monad is the same as doing\ \ nothing" putDelShare data TossAction = PutCommitment SignedCommitment | PutOpening StakeholderId Opening | PutShares StakeholderId InnerSharesMap | PutCertificate VssCertificate | ResetCO | ResetShares | DelCommitment StakeholderId | DelOpening StakeholderId | DelShares StakeholderId | SetEpochOrSlot EpochOrSlot deriving (Show, Eq, Generic) instance HasConfiguration => Arbitrary TossAction where arbitrary = genericArbitrary shrink = genericShrink actionToMonad :: Toss.MonadToss m => TossAction -> m () actionToMonad (PutCommitment sc) = Toss.putCommitment sc actionToMonad (PutOpening sid o) = Toss.putOpening sid o actionToMonad (PutShares sid ism) = Toss.putShares sid ism actionToMonad (PutCertificate v) = Toss.putCertificate v actionToMonad ResetCO = Toss.resetCO actionToMonad ResetShares = Toss.resetShares actionToMonad (DelCommitment sid) = Toss.delCommitment sid actionToMonad (DelOpening sid) = Toss.delOpening sid actionToMonad (DelShares sid) = Toss.delShares sid actionToMonad (SetEpochOrSlot eos) = Toss.setEpochOrSlot eos emptyTossSt :: Toss.SscGlobalState emptyTossSt = def perform :: HasConfiguration => [TossAction] -> Toss.PureToss () perform = mapM_ actionToMonad -- | Type synonym used for convenience. This quintuple is used to pass the randomness needed to run ' PureToss ' actions to the testing property . type TossTestInfo = (Word64, Word64, Word64, Word64, Word64) | Operational equivalence operator in the ' PureToss ' monad . To be used when equivalence between two sequences of actions in ' PureToss ' is to be tested / proved . (==^) :: HasConfiguration => [TossAction] -> [TossAction] -> Gen TossAction -> TossTestInfo -> Property t1 ==^ t2 = \prefixGen ttInfo -> forAll ((listOf prefixGen) :: Gen [TossAction]) $ \prefix -> forAll (arbitrary :: Gen [TossAction]) $ \suffix -> let applyAction x = view _2 . fst . Rand.withDRG (Rand.drgNewTest ttInfo) . Toss.runPureToss emptyTossSt $ (perform $ prefix ++ x ++ suffix) in applyAction t1 === applyAction t2 A note on the following tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to ' (= = ^ ) ' is that in each case , there is a particular sequence of actions for which the property does not hold . Using one of the following tests as an example : Let ' o , o ´ : : Opening ' such that ' o /= o ´ ' . This sequence of actions in the ' PureToss ' monad : [ o ´ , o , ] is not , in operational semantics terms , equal to the sequence [ o ´ ] It is instead equivalent to [ ] Because these actions are performed from left to right , performing an insertion with the same key several times without deleting it in between those insertions means only the last insertion actually matters for these tests . As such , prefixes with an insertion with the same key as the action being tested in the property will cause it to fail . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to '(==^)' is that in each case, there is a particular sequence of actions for which the property does not hold. Using one of the following tests as an example: Let 'o, o´ :: Opening' such that 'o /= o´'. This sequence of actions in the 'PureToss' monad: [PutOpening sid o´, PutOpening sid o, DelOpening sid] is not, in operational semantics terms, equal to the sequence [PutOpening sid o´] It is instead equivalent to [] Because these actions are performed from left to right, performing an insertion with the same key several times without deleting it in between those insertions means only the last insertion actually matters for these tests. As such, prefixes with an insertion with the same key as the action being tested in the property will cause it to fail. -} putDelCommitment :: HasConfiguration => SignedCommitment -> TossTestInfo -> Property putDelCommitment sc = let actionPrefixGen = arbitrary `suchThat` (\case PutCommitment sc' -> sc ^. _1 /= sc'^. _1 _ -> True) in ([PutCommitment sc, DelCommitment $ addressHash $ sc ^. _1] ==^ []) actionPrefixGen putDelOpening :: HasConfiguration => StakeholderId -> Opening -> TossTestInfo -> Property putDelOpening sid o = let actionPrefixGen = arbitrary `suchThat` (\case PutOpening sid' _ -> sid /= sid' _ -> True) in ([PutOpening sid o, DelOpening sid] ==^ []) actionPrefixGen putDelShare :: HasConfiguration => StakeholderId -> InnerSharesMap -> TossTestInfo -> Property putDelShare sid ism = let actionPrefixGen = arbitrary `suchThat` (\case PutShares sid' _ -> sid' /= sid _ -> True) in ([PutShares sid ism, DelShares sid] ==^ []) actionPrefixGen
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/lib/test/Test/Pos/Ssc/Toss/PureSpec.hs
haskell
| Type synonym used for convenience. This quintuple is used to pass the randomness
| Specification for Pos . . . Toss . Pure module Test.Pos.Ssc.Toss.PureSpec ( spec ) where import Universum import qualified Crypto.Random as Rand import Data.Default (def) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck (Arbitrary (..), Gen, Property, forAll, listOf, suchThat, (===)) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Arbitrary.Core () import Pos.Arbitrary.Ssc () import Pos.Core (InnerSharesMap, EpochOrSlot, HasConfiguration, Opening, SignedCommitment, StakeholderId, VssCertificate (..), addressHash) import qualified Pos.Ssc.Toss.Class as Toss import qualified Pos.Ssc.Toss.Pure as Toss import qualified Pos.Ssc.Types as Toss import Test.Pos.Configuration (withDefConfiguration) spec :: Spec spec = withDefConfiguration $ describe "Toss" $ do let smaller n = modifyMaxSuccess (const n) describe "PureToss" $ smaller 30 $ do prop "Adding and deleting a signed commitment in the 'PureToss' monad is the\ \ same as doing nothing" putDelCommitment prop "Adding and deleting an opening in the 'PureToss' monad is the same as doing\ \ nothing" putDelOpening prop "Adding and deleting a share in the 'PureToss' monad is the same as doing\ \ nothing" putDelShare data TossAction = PutCommitment SignedCommitment | PutOpening StakeholderId Opening | PutShares StakeholderId InnerSharesMap | PutCertificate VssCertificate | ResetCO | ResetShares | DelCommitment StakeholderId | DelOpening StakeholderId | DelShares StakeholderId | SetEpochOrSlot EpochOrSlot deriving (Show, Eq, Generic) instance HasConfiguration => Arbitrary TossAction where arbitrary = genericArbitrary shrink = genericShrink actionToMonad :: Toss.MonadToss m => TossAction -> m () actionToMonad (PutCommitment sc) = Toss.putCommitment sc actionToMonad (PutOpening sid o) = Toss.putOpening sid o actionToMonad (PutShares sid ism) = Toss.putShares sid ism actionToMonad (PutCertificate v) = Toss.putCertificate v actionToMonad ResetCO = Toss.resetCO actionToMonad ResetShares = Toss.resetShares actionToMonad (DelCommitment sid) = Toss.delCommitment sid actionToMonad (DelOpening sid) = Toss.delOpening sid actionToMonad (DelShares sid) = Toss.delShares sid actionToMonad (SetEpochOrSlot eos) = Toss.setEpochOrSlot eos emptyTossSt :: Toss.SscGlobalState emptyTossSt = def perform :: HasConfiguration => [TossAction] -> Toss.PureToss () perform = mapM_ actionToMonad needed to run ' PureToss ' actions to the testing property . type TossTestInfo = (Word64, Word64, Word64, Word64, Word64) | Operational equivalence operator in the ' PureToss ' monad . To be used when equivalence between two sequences of actions in ' PureToss ' is to be tested / proved . (==^) :: HasConfiguration => [TossAction] -> [TossAction] -> Gen TossAction -> TossTestInfo -> Property t1 ==^ t2 = \prefixGen ttInfo -> forAll ((listOf prefixGen) :: Gen [TossAction]) $ \prefix -> forAll (arbitrary :: Gen [TossAction]) $ \suffix -> let applyAction x = view _2 . fst . Rand.withDRG (Rand.drgNewTest ttInfo) . Toss.runPureToss emptyTossSt $ (perform $ prefix ++ x ++ suffix) in applyAction t1 === applyAction t2 A note on the following tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to ' (= = ^ ) ' is that in each case , there is a particular sequence of actions for which the property does not hold . Using one of the following tests as an example : Let ' o , o ´ : : Opening ' such that ' o /= o ´ ' . This sequence of actions in the ' PureToss ' monad : [ o ´ , o , ] is not , in operational semantics terms , equal to the sequence [ o ´ ] It is instead equivalent to [ ] Because these actions are performed from left to right , performing an insertion with the same key several times without deleting it in between those insertions means only the last insertion actually matters for these tests . As such , prefixes with an insertion with the same key as the action being tested in the property will cause it to fail . ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to '(==^)' is that in each case, there is a particular sequence of actions for which the property does not hold. Using one of the following tests as an example: Let 'o, o´ :: Opening' such that 'o /= o´'. This sequence of actions in the 'PureToss' monad: [PutOpening sid o´, PutOpening sid o, DelOpening sid] is not, in operational semantics terms, equal to the sequence [PutOpening sid o´] It is instead equivalent to [] Because these actions are performed from left to right, performing an insertion with the same key several times without deleting it in between those insertions means only the last insertion actually matters for these tests. As such, prefixes with an insertion with the same key as the action being tested in the property will cause it to fail. -} putDelCommitment :: HasConfiguration => SignedCommitment -> TossTestInfo -> Property putDelCommitment sc = let actionPrefixGen = arbitrary `suchThat` (\case PutCommitment sc' -> sc ^. _1 /= sc'^. _1 _ -> True) in ([PutCommitment sc, DelCommitment $ addressHash $ sc ^. _1] ==^ []) actionPrefixGen putDelOpening :: HasConfiguration => StakeholderId -> Opening -> TossTestInfo -> Property putDelOpening sid o = let actionPrefixGen = arbitrary `suchThat` (\case PutOpening sid' _ -> sid /= sid' _ -> True) in ([PutOpening sid o, DelOpening sid] ==^ []) actionPrefixGen putDelShare :: HasConfiguration => StakeholderId -> InnerSharesMap -> TossTestInfo -> Property putDelShare sid ism = let actionPrefixGen = arbitrary `suchThat` (\case PutShares sid' _ -> sid' /= sid _ -> True) in ([PutShares sid ism, DelShares sid] ==^ []) actionPrefixGen
a237a5dad5de102a65155bb9d04f839d9aade554881267a45d61f7c1fba6d22d
backtracking/astro
main.ml
open Format open Astro open Lib open Arg let soleil_o = ref false let lune_o = ref false let planetes_o = ref false let date_o = ref "" let _ = parse [ "-s", Set soleil_o, "coordonnées Soleil"; "-l", Set lune_o, "coordonnées Lune"; "-p", Set planetes_o, "coordonnées planètes"; "-d", String ((:=) date_o), "date" ] (fun _ -> ()) "" let jh = now () let date = if !date_o = "" then let msg = sprintf "date [%s = %s]: " (string_of_date jh) (natural_date jh) in input msg (function "" -> jh | s -> date_of_string s) else date_of_string !date_o let string_of_jour = function | Lundi -> "Lundi" | Mardi -> "Mardi" | Mercredi -> "Mercredi" | Jeudi -> "Jeudi" | Vendredi -> "Vendredi" | Samedi -> "Samedi" | Dimanche -> "Dimanche" let float_dec f = let s = sprintf "%.3f" f in String.sub s 1 (String.length s - 1) let degres f = let d = truncate f in let f = abs_float (f -. float d) *. 60. in let m = truncate f in let f = (f -. float m) *. 60. in let f,s = modf f in let f = if f = 0. then "" else float_dec f in sprintf "%d°%02d'%02d''%s" d m (truncate s) f let jj = jour_julien date let _ = printf "\ndate : %s = %s\n" (string_of_date date) (natural_date date); printf "jour julien : JJ = %f\n" jj; let js = jour_de_la_semaine date in printf "jour de la semaine : %s\n" (string_of_jour js); printf "jour de l'année : %d\n" (jour_de_l_annee date); let ts = temps_sideral date in let h,m,s = temps_sideral_hms date in printf "temps sidéral MOYEN : %f = %02d:%02d:%f" ts h m s let angle_hms a = let h,m,s = hms (a /. 360.) in sprintf "%dh %02dm %.3fs" h m s let massy = { obs_longitude = -2.2772; obs_latitude = 48.7314 } let print_ecliptiques fmt e = fprintf fmt "@[longitude : %f° = %s@\nlatitude : %f° = %s@]" e.longitude (degres e.longitude) e.latitude (degres e.latitude) let print_equatoriales fmt e = let a = e.ascension_droite in let d = e.declinaison in fprintf fmt "@[ascension droite : %f° = %s@\ndéclinaison : %f° = %s@]" a (angle_hms a) d (degres d) let print_horizontales fmt c = let a = c.azimut in let h = c.hauteur in fprintf fmt "@[azimut A = %f° = %s@\nhauteur h = %f° = %s@]" a (degres a) h (degres h) let soleil fmt () = let soleil = soleil jj in fprintf fmt "@[Soleil :@\n"; fprintf fmt " Position écliptique vraie :@\n %a@\n" print_ecliptiques soleil.pos_ecl_vraie; fprintf fmt " Position écliptique apparente :@\n %a@\n" print_ecliptiques soleil.pos_ecl_apparente; fprintf fmt " Position équatoriale vraie :@\n %a@\n" print_equatoriales soleil.pos_equ_vraie; fprintf fmt " Position équatoriale apparente :@\n %a@\n" print_equatoriales soleil.pos_equ_apparente; fprintf fmt " À Massy : %a@\n" print_horizontales (horizontales date massy soleil.pos_equ_apparente); fprintf fmt " Excentricité orbite terreste : %f@\n" soleil.excentricite_orbite_terrestre; fprintf fmt " Rayon vecteur : %f UA@\n" soleil.s_rayon_vecteur; fprintf fmt "@]" let _ = if !soleil_o then printf "@[%a@\n@]@?" soleil () let lune fmt () = let lune = lune jj in fprintf fmt "@[Lune :@\n"; fprintf fmt " Position écliptique :@\n %a@\n" print_ecliptiques lune.l_pos_ecl; fprintf fmt " Position équatoriale :@\n %a@\n" print_equatoriales lune.l_pos_equ; fprintf fmt " À Massy : %a@\n" print_horizontales (horizontales date massy lune.l_pos_equ); fprintf fmt " Fraction illuminée : %f@\n" lune.fraction_illuminee; fprintf fmt " Angle partie éclairée : %f°@\n" lune.angle_partie_eclairee; fprintf fmt " Parallaxe : %f° = %s@\n" lune.l_parallaxe (degres lune.l_parallaxe); fprintf fmt " Rayon vecteur : %f kms@\n" lune.l_rayon_vecteur; fprintf fmt "@]" let _ = if !lune_o then printf "@[%a@\n@]@?" lune () open Planets let planetes fmt () = fprintf fmt "@[Positions planètes / Soleil :@\n"; let planete fmt pl = let p = pl jj in fprintf fmt "@[Position héliocentrique :@\n"; let l = p.h_longitude in fprintf fmt " @[longitude = %f° = %s@\n" l (degres l); let l = p.h_latitude in fprintf fmt "latitude = %f° = %s@\n" l (degres l); fprintf fmt "distance = %f UA@]@\n" p.h_distance; if pl != earth then begin let g,r = geocentriques jj p in fprintf fmt "Position ecliptique :@\n @[%a@\ndistance = %f@]@\n" print_ecliptiques g r; fprintf fmt "À Massy :@\n %a@\n" print_horizontales (horizontales date massy (equatoriales jj g)) end; fprintf fmt "@]" in fprintf fmt "Mercure : %a@\n" planete mercury; fprintf fmt "Venus : %a@\n" planete venus; fprintf fmt "Terre : %a@\n" planete earth; fprintf fmt "Mars : %a@\n" planete mars; fprintf fmt "Jupiter : %a@\n" planete jupiter; fprintf fmt "Saturn : %a@\n" planete saturn; fprintf fmt "Uranus : %a@\n" planete uranus; fprintf fmt "Neptune : %a@\n" planete neptune; fprintf fmt "@]" let _ = if !planetes_o then printf "@[%a@\n@]@?" planetes ()
null
https://raw.githubusercontent.com/backtracking/astro/adb8020b8a56692f3d2b50d26dce2ccc442c6f39/main.ml
ocaml
open Format open Astro open Lib open Arg let soleil_o = ref false let lune_o = ref false let planetes_o = ref false let date_o = ref "" let _ = parse [ "-s", Set soleil_o, "coordonnées Soleil"; "-l", Set lune_o, "coordonnées Lune"; "-p", Set planetes_o, "coordonnées planètes"; "-d", String ((:=) date_o), "date" ] (fun _ -> ()) "" let jh = now () let date = if !date_o = "" then let msg = sprintf "date [%s = %s]: " (string_of_date jh) (natural_date jh) in input msg (function "" -> jh | s -> date_of_string s) else date_of_string !date_o let string_of_jour = function | Lundi -> "Lundi" | Mardi -> "Mardi" | Mercredi -> "Mercredi" | Jeudi -> "Jeudi" | Vendredi -> "Vendredi" | Samedi -> "Samedi" | Dimanche -> "Dimanche" let float_dec f = let s = sprintf "%.3f" f in String.sub s 1 (String.length s - 1) let degres f = let d = truncate f in let f = abs_float (f -. float d) *. 60. in let m = truncate f in let f = (f -. float m) *. 60. in let f,s = modf f in let f = if f = 0. then "" else float_dec f in sprintf "%d°%02d'%02d''%s" d m (truncate s) f let jj = jour_julien date let _ = printf "\ndate : %s = %s\n" (string_of_date date) (natural_date date); printf "jour julien : JJ = %f\n" jj; let js = jour_de_la_semaine date in printf "jour de la semaine : %s\n" (string_of_jour js); printf "jour de l'année : %d\n" (jour_de_l_annee date); let ts = temps_sideral date in let h,m,s = temps_sideral_hms date in printf "temps sidéral MOYEN : %f = %02d:%02d:%f" ts h m s let angle_hms a = let h,m,s = hms (a /. 360.) in sprintf "%dh %02dm %.3fs" h m s let massy = { obs_longitude = -2.2772; obs_latitude = 48.7314 } let print_ecliptiques fmt e = fprintf fmt "@[longitude : %f° = %s@\nlatitude : %f° = %s@]" e.longitude (degres e.longitude) e.latitude (degres e.latitude) let print_equatoriales fmt e = let a = e.ascension_droite in let d = e.declinaison in fprintf fmt "@[ascension droite : %f° = %s@\ndéclinaison : %f° = %s@]" a (angle_hms a) d (degres d) let print_horizontales fmt c = let a = c.azimut in let h = c.hauteur in fprintf fmt "@[azimut A = %f° = %s@\nhauteur h = %f° = %s@]" a (degres a) h (degres h) let soleil fmt () = let soleil = soleil jj in fprintf fmt "@[Soleil :@\n"; fprintf fmt " Position écliptique vraie :@\n %a@\n" print_ecliptiques soleil.pos_ecl_vraie; fprintf fmt " Position écliptique apparente :@\n %a@\n" print_ecliptiques soleil.pos_ecl_apparente; fprintf fmt " Position équatoriale vraie :@\n %a@\n" print_equatoriales soleil.pos_equ_vraie; fprintf fmt " Position équatoriale apparente :@\n %a@\n" print_equatoriales soleil.pos_equ_apparente; fprintf fmt " À Massy : %a@\n" print_horizontales (horizontales date massy soleil.pos_equ_apparente); fprintf fmt " Excentricité orbite terreste : %f@\n" soleil.excentricite_orbite_terrestre; fprintf fmt " Rayon vecteur : %f UA@\n" soleil.s_rayon_vecteur; fprintf fmt "@]" let _ = if !soleil_o then printf "@[%a@\n@]@?" soleil () let lune fmt () = let lune = lune jj in fprintf fmt "@[Lune :@\n"; fprintf fmt " Position écliptique :@\n %a@\n" print_ecliptiques lune.l_pos_ecl; fprintf fmt " Position équatoriale :@\n %a@\n" print_equatoriales lune.l_pos_equ; fprintf fmt " À Massy : %a@\n" print_horizontales (horizontales date massy lune.l_pos_equ); fprintf fmt " Fraction illuminée : %f@\n" lune.fraction_illuminee; fprintf fmt " Angle partie éclairée : %f°@\n" lune.angle_partie_eclairee; fprintf fmt " Parallaxe : %f° = %s@\n" lune.l_parallaxe (degres lune.l_parallaxe); fprintf fmt " Rayon vecteur : %f kms@\n" lune.l_rayon_vecteur; fprintf fmt "@]" let _ = if !lune_o then printf "@[%a@\n@]@?" lune () open Planets let planetes fmt () = fprintf fmt "@[Positions planètes / Soleil :@\n"; let planete fmt pl = let p = pl jj in fprintf fmt "@[Position héliocentrique :@\n"; let l = p.h_longitude in fprintf fmt " @[longitude = %f° = %s@\n" l (degres l); let l = p.h_latitude in fprintf fmt "latitude = %f° = %s@\n" l (degres l); fprintf fmt "distance = %f UA@]@\n" p.h_distance; if pl != earth then begin let g,r = geocentriques jj p in fprintf fmt "Position ecliptique :@\n @[%a@\ndistance = %f@]@\n" print_ecliptiques g r; fprintf fmt "À Massy :@\n %a@\n" print_horizontales (horizontales date massy (equatoriales jj g)) end; fprintf fmt "@]" in fprintf fmt "Mercure : %a@\n" planete mercury; fprintf fmt "Venus : %a@\n" planete venus; fprintf fmt "Terre : %a@\n" planete earth; fprintf fmt "Mars : %a@\n" planete mars; fprintf fmt "Jupiter : %a@\n" planete jupiter; fprintf fmt "Saturn : %a@\n" planete saturn; fprintf fmt "Uranus : %a@\n" planete uranus; fprintf fmt "Neptune : %a@\n" planete neptune; fprintf fmt "@]" let _ = if !planetes_o then printf "@[%a@\n@]@?" planetes ()
ca1925a2d9112640e7c1e69a2355dc06b6c475f15e91ac71b936c9608cf83f96
gabebw/haskell-upenn-cs194
Ring.hs
-- Define a class of mathematical rings -- See also (mathematics) module Ring where -- You can optionally include a list of symbols after an import statement -- to say exactly what you're importing from the other module. This is sometimes -- useful for documentation, and to avoid name clashes between modules. import Control.Arrow ( first ) import Data.Maybe ( listToMaybe ) class Ring a where addId :: a -- additive identity addInv :: a -> a -- additive inverse mulId :: a -- multiplicative identity add :: a -> a -> a -- addition mul :: a -> a -> a -- multiplication -- Something is parsable if there is a way to read it in from a string class Parsable a where -- | If successful, 'parse' returns the thing parsed along with the -- "leftover" string, containing all of the input string except what -- was parsed parse :: String -> Maybe (a, String) -- The canonical instance for integers: instance Ring Integer where addId = 0 addInv = negate mulId = 1 add = (+) mul = (*) instance Parsable Integer where parse = listToMaybe . reads -- Look up these functions online. Think about why this combination works. -- (It should work for any member of the `Read` class. Like `Integer`.) -- | A datatype for storing and manipulating ring expressions. data RingExpr a = Lit a | AddId | AddInv (RingExpr a) | MulId | Add (RingExpr a) (RingExpr a) | Mul (RingExpr a) (RingExpr a) deriving (Show, Eq) instance Ring (RingExpr a) where addId = AddId addInv = AddInv mulId = MulId add = Add mul = Mul instance Parsable a => Parsable (RingExpr a) where parse = fmap (first Lit) . parse | Evaluate a ' RingExpr a ' using the ring algebra of ' a ' . eval :: Ring a => RingExpr a -> a eval (Lit a) = a eval AddId = addId eval (AddInv x) = addInv (eval x) eval MulId = mulId eval (Add x y) = add (eval x) (eval y) eval (Mul x y) = mul (eval x) (eval y)
null
https://raw.githubusercontent.com/gabebw/haskell-upenn-cs194/94a27807de77df43f38ad8d044666548e9c849d4/fall-2014/hw5-typeclasses/Ring.hs
haskell
Define a class of mathematical rings See also (mathematics) You can optionally include a list of symbols after an import statement to say exactly what you're importing from the other module. This is sometimes useful for documentation, and to avoid name clashes between modules. additive identity additive inverse multiplicative identity addition multiplication Something is parsable if there is a way to read it in from a string | If successful, 'parse' returns the thing parsed along with the "leftover" string, containing all of the input string except what was parsed The canonical instance for integers: Look up these functions online. Think about why this combination works. (It should work for any member of the `Read` class. Like `Integer`.) | A datatype for storing and manipulating ring expressions.
module Ring where import Control.Arrow ( first ) import Data.Maybe ( listToMaybe ) class Ring a where class Parsable a where parse :: String -> Maybe (a, String) instance Ring Integer where addId = 0 addInv = negate mulId = 1 add = (+) mul = (*) instance Parsable Integer where parse = listToMaybe . reads data RingExpr a = Lit a | AddId | AddInv (RingExpr a) | MulId | Add (RingExpr a) (RingExpr a) | Mul (RingExpr a) (RingExpr a) deriving (Show, Eq) instance Ring (RingExpr a) where addId = AddId addInv = AddInv mulId = MulId add = Add mul = Mul instance Parsable a => Parsable (RingExpr a) where parse = fmap (first Lit) . parse | Evaluate a ' RingExpr a ' using the ring algebra of ' a ' . eval :: Ring a => RingExpr a -> a eval (Lit a) = a eval AddId = addId eval (AddInv x) = addInv (eval x) eval MulId = mulId eval (Add x y) = add (eval x) (eval y) eval (Mul x y) = mul (eval x) (eval y)
e7d4eab2bdce1b816a8dbf004a3915f46d7a7e452046c492936f98821d686e50
openbadgefactory/salava
db.clj
(ns salava.social.db (:require [yesql.core :refer [defqueries]] [clojure.set :refer [rename-keys]] [clojure.java.jdbc :as jdbc] [salava.core.helper :refer [dump]] [slingshot.slingshot :refer :all] [salava.core.util :as util :refer [get-db plugin-fun get-plugins]] [salava.admin.helper :as ah] [clojure.tools.logging :as log] [clojure.string :refer [blank? join]] [salava.core.time :refer [unix-time get-date-from-today]] [clojure.core.reducers :as r])) (defqueries "sql/social/queries.sql") #_(defn insert-social-event! [ctx data] (insert-social-event<! data (get-db ctx))) (defn get-all-owners [ctx data] (let [funs (plugin-fun (get-plugins ctx) "event" "owners")] (set (mapcat (fn [f] (try (f ctx data) (catch Throwable _ ()))) funs)))) (defn update-last-viewed [ctx events user_id] (let [event_ids (map #(:event_id %) events)] (update-last-checked-user-event-owner! {:user_id user_id :event_ids event_ids} (get-db ctx)))) (defn get-all-events [ctx user_id] (let [funs (plugin-fun (get-plugins ctx) "event" "events") events (flatten (pmap (fn [f] (try (f ctx user_id) (catch Throwable _ ()))) funs))] (sort-by :ctime > (set events)))) (defn insert-event-owners! "Creates event owners for event" [ctx data] (try (let [owners (get-all-owners ctx data) query (vec (map #(assoc % :event_id (:event-id data)) owners))] (jdbc/insert-multi! (:connection (get-db ctx)) :social_event_owners query)) (catch Exception ex (log/error "insert-event-owners!: failed to save event owners") (log/error (.toString ex))))) (defn insert-social-event! [ctx data] (let [id (-> (insert-social-event<! data (get-db ctx)) :generated_key)] (insert-event-owners! ctx (assoc data :event-id id)))) (defn get-all-events-add-viewed [ctx user_id] (let [events (get-all-events ctx user_id)] (if-not (empty? events) (update-last-viewed ctx events user_id)) events)) (defn messages-viewed "Save information about viewing messages." [ctx badge_id user_id] (try+ (let [gallery_id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (replace-badge-message-view! {:badge_id badge_id :user_id user_id :gallery_id gallery_id} (get-db ctx))) (catch Object _ "error"))) (defn is-connected? [ctx user_id badge_id] (-> (select-connection-badge {:user_id user_id :badge_id badge_id} (get-db ctx)) first boolean)) (defn insert-connection-badge! [ctx user_id badge_id] (let [gallery-id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (insert-connect-badge<! {:user_id user_id :badge_id badge_id :gallery_id gallery-id} (get-db ctx)) (util/event ctx user_id "follow" badge_id "badge") (messages-viewed ctx badge_id user_id))) (defn create-connection-badge! [ctx user_id badge_id] (try+ (insert-connection-badge! ctx user_id badge_id) {:status "success" :connected? (is-connected? ctx user_id badge_id)} (catch Object _ {:status "error" :connected? (is-connected? ctx user_id badge_id)}))) (defn create-connection-issuer! [ctx user_id issuer_content_id] (try+ (insert-connection-issuer<! {:user_id user_id :issuer_content_id issuer_content_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "false"}))) (defn delete-issuer-connection! [ctx user_id issuer_content_id] (try+ (delete-connection-issuer! {:user_id user_id :issuer_content_id issuer_content_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "error"}))) (defn issuer-connected? [ctx user_id issuer_content_id] (let [id (select-connection-issuer {:user_id user_id :issuer_content_id issuer_content_id} (into {:result-set-fn first :row-fn :issuer_content_id} (get-db ctx)))] (= issuer_content_id id))) ;; STREAM ;; (defn badge-events-reduce [events] (let [helper (fn [current item] (let [key [(:verb item) (:object item)]] (-> current (assoc key item)))) ;(assoc-in [key :count] (inc (get-in current [key :count ] 0))) reduced-events (vals (reduce helper {} (reverse events)))] (filter #(false? (:hidden %)) reduced-events))) (defn admin-events-reduce [events] (let [helper (fn [current item] (let [key [(:verb item)]] (-> current (assoc key item) (assoc-in [key :count] (inc (get-in current [key :count ] 0)))))) reduced-events (vals (reduce helper {} (reverse events)))] (filter #(false? (:hidden %)) reduced-events))) (defn badge-message-map "returns newest message and count new messages" [messages] (let [message-helper (fn [current item] (let [key (:badge_id item) new-messages-count (get-in current [key :new_messages] 0)] (-> current (assoc key item) (assoc-in [key :new_messages] (if (> (:ctime item) (:last_viewed item)) (inc new-messages-count) new-messages-count)))))] (reduce message-helper {} (reverse messages)))) (defn filter-badge-message-events [events] (filter #(= "message" (:verb %)) events)) (defn filter-own-events [events user_id] (filter #(and (= user_id (:subject %)) (= "follow" (:verb %))) events)) #_(defn get-user-admin-events [ctx user_id] (select-admin-events {:user_id user_id} (get-db ctx))) #_(defn get-user-admin-events-sorted [ctx user_id] (let [events (get-user-admin-events ctx user_id)] (if (not-empty events) (update-last-viewed ctx events user_id)) events)) (defn hide-user-event! [ctx user_id event_id] (try+ (update-hide-user-event! {:user_id user_id :event_id event_id} (get-db ctx)) "success" (catch Object _ "error"))) (defn hide-all-user-events! [ctx user_id] (try+ (hide-user-events-all! {:user_id user_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "error"}))) ;; MESSAGES ;; #_(defn message! [ctx badge_id user_id message] (try+ (if (not (blank? message)) (let [badge-connection (if (not (is-connected? ctx user_id badge_id)) (:status (create-connection-badge! ctx user_id badge_id)) "connected")] (do (insert-badge-message<! {:badge_id badge_id :user_id user_id :message message} (get-db ctx)) (util/event ctx user_id "message" badge_id "badge") {:status "success" :connected? badge-connection})) {:status "error" :connected? nil}) (catch Object _ {:status "error" :connected? nil}))) (defn message! ([ctx message-map] (let [{:keys [badge_id user_id message]} message-map] (if-not (blank? message) (let [badge-connection (if (not (is-connected? ctx user_id badge_id)) (:status (create-connection-badge! ctx user_id badge_id)) "connected") gallery_id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (do (insert-badge-message<! {:badge_id badge_id :gallery_id gallery_id :user_id user_id :message message} (get-db ctx)) (util/event ctx user_id "message" badge_id "badge")) {:connected? badge-connection})))) ([ctx badge_id user_id message] (if (blank? message) {:status "error" :connected? nil} (try+ (let [save-message (message! ctx {:badge_id badge_id :user_id user_id :message message})] (merge save-message {:status "success"})) (catch Object _ {:status "error" :connected? nil}))))) (defn get-badge-message-count [ctx badge_id user-id] (let [badge-messages-user-id-ctime (select-badge-messages-count {:badge_id badge_id} (get-db ctx)) last-viewed (select-badge-message-last-view {:badge_id badge_id :user_id user-id} (into {:result-set-fn first :row-fn :mtime} (get-db ctx))) new-messages (if last-viewed (filter #(and (not= user-id (:user_id %)) (< last-viewed (:ctime %))) badge-messages-user-id-ctime) ())] {:new-messages (count new-messages) :all-messages (count badge-messages-user-id-ctime)})) (defn get-badge-message-count-multi [ctx gallery-ids user-id] (let [badge-messages-user-id-ctime (->> (select-badge-messages-count-multi {:gallery_ids gallery-ids} (get-db ctx)) (remove #(= user-id (:user_id %)))) last-viewed (->> (select-badge-message-last-view-multi {:gallery_ids gallery-ids :user_id user-id} (get-db ctx)) (group-by :gallery_id) (reduce-kv (fn [r k v] (conj r (hash-map :gallery_id k :mtime (->> (map :mtime v) (apply max))))) [])) filtered-list (r/filter (fn [b] (some #(and (not= user-id (:user_id b)) (= (:gallery_id %) (:gallery_id b)) (< (:mtime %) (:ctime b))) last-viewed)) badge-messages-user-id-ctime)] (->> filtered-list (group-by :gallery_id) (reduce-kv (fn [r k v] (conj r (hash-map :gallery_id k :count (count v)))) [])))) (defn get-badge-messages-limit [ctx badge_id page_count user_id] (let [limit 10 offset (* limit page_count) badge-messages (select-badge-messages-limit {:badge_id badge_id :limit limit :offset offset} (get-db ctx)) messages-left (- (:all-messages (get-badge-message-count ctx badge_id user_id)) (* limit (+ page_count 1)))] (if (= 0 page_count) (messages-viewed ctx badge_id user_id)) {:messages badge-messages :messages_left (if (pos? messages-left) messages-left 0)})) (defn message-owner? [ctx message_id user_id] (let [message_owner (select-badge-message-owner {:message_id message_id} (into {:result-set-fn first :row-fn :user_id} (get-db ctx)))] (= user_id message_owner))) (defn delete-message! [ctx message_id user_id] (try+ (let [message-owner (message-owner? ctx message_id user_id) admin (ah/user-admin? ctx user_id)] (if (or message-owner admin) (update-badge-message-deleted! {:message_id message_id} (get-db ctx)))) "success" (catch Object _ "error"))) (defn create-connection-badge-by-badge-id! [ctx user_id user_badge_id] (let [badge_id (select-badge-id-by-user-badge-id {:user_badge_id user_badge_id} (into {:result-set-fn first :row-fn :badge_id} (get-db ctx)))] (try+ (insert-connection-badge! ctx user_id badge_id) (catch Object _)))) (defn delete-connection-badge-by-badge-id! [ctx user_id badge_id] (try+ (delete-connect-badge-by-badge-id! {:user_id user_id :badge_id badge_id} (get-db ctx)) (catch Object _))) (defn delete-connection-badge! [ctx user_id badge_id] (try+ (when-let [gallery-id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (delete-connect-badge! {:user_id user_id :badge_id badge_id :gallery_id gallery-id} (get-db ctx))) {:status "success" :connected? (is-connected? ctx user_id badge_id)} (catch Object _ {:status "error" :connected? (is-connected? ctx user_id badge_id)}))) (defn get-connections-badge [ctx user_id] (select-user-connections-badge {:user_id user_id} (get-db ctx))) (defn get-users-not-verified-emails [ctx user_id] (select-user-not-verified-emails {:user_id user_id} (get-db ctx))) (defn get-user-tips [ctx user_id] (let [welcome-tip (= 0 (select-user-badge-count {:user_id user_id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))) profile-picture-tip (if (not welcome-tip) (nil? (select-user-profile-picture {:user_id user_id} (into {:result-set-fn first :row-fn :profile_picture} (get-db ctx)))) false)] {:profile-picture-tip profile-picture-tip :welcome-tip welcome-tip :not-verified-emails (get-users-not-verified-emails ctx user_id)})) (defn get-all-user-events [ctx user_id] (get-all-user-event {:subject user_id} (get-db ctx))) (defn get-user-issuer-connections [ctx user_id] (select-user-connections-issuer {:user_id user_id} (get-db ctx)))
null
https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/clj/salava/social/db.clj
clojure
STREAM ;; (assoc-in [key :count] (inc (get-in current [key :count ] 0))) MESSAGES ;;
(ns salava.social.db (:require [yesql.core :refer [defqueries]] [clojure.set :refer [rename-keys]] [clojure.java.jdbc :as jdbc] [salava.core.helper :refer [dump]] [slingshot.slingshot :refer :all] [salava.core.util :as util :refer [get-db plugin-fun get-plugins]] [salava.admin.helper :as ah] [clojure.tools.logging :as log] [clojure.string :refer [blank? join]] [salava.core.time :refer [unix-time get-date-from-today]] [clojure.core.reducers :as r])) (defqueries "sql/social/queries.sql") #_(defn insert-social-event! [ctx data] (insert-social-event<! data (get-db ctx))) (defn get-all-owners [ctx data] (let [funs (plugin-fun (get-plugins ctx) "event" "owners")] (set (mapcat (fn [f] (try (f ctx data) (catch Throwable _ ()))) funs)))) (defn update-last-viewed [ctx events user_id] (let [event_ids (map #(:event_id %) events)] (update-last-checked-user-event-owner! {:user_id user_id :event_ids event_ids} (get-db ctx)))) (defn get-all-events [ctx user_id] (let [funs (plugin-fun (get-plugins ctx) "event" "events") events (flatten (pmap (fn [f] (try (f ctx user_id) (catch Throwable _ ()))) funs))] (sort-by :ctime > (set events)))) (defn insert-event-owners! "Creates event owners for event" [ctx data] (try (let [owners (get-all-owners ctx data) query (vec (map #(assoc % :event_id (:event-id data)) owners))] (jdbc/insert-multi! (:connection (get-db ctx)) :social_event_owners query)) (catch Exception ex (log/error "insert-event-owners!: failed to save event owners") (log/error (.toString ex))))) (defn insert-social-event! [ctx data] (let [id (-> (insert-social-event<! data (get-db ctx)) :generated_key)] (insert-event-owners! ctx (assoc data :event-id id)))) (defn get-all-events-add-viewed [ctx user_id] (let [events (get-all-events ctx user_id)] (if-not (empty? events) (update-last-viewed ctx events user_id)) events)) (defn messages-viewed "Save information about viewing messages." [ctx badge_id user_id] (try+ (let [gallery_id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (replace-badge-message-view! {:badge_id badge_id :user_id user_id :gallery_id gallery_id} (get-db ctx))) (catch Object _ "error"))) (defn is-connected? [ctx user_id badge_id] (-> (select-connection-badge {:user_id user_id :badge_id badge_id} (get-db ctx)) first boolean)) (defn insert-connection-badge! [ctx user_id badge_id] (let [gallery-id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (insert-connect-badge<! {:user_id user_id :badge_id badge_id :gallery_id gallery-id} (get-db ctx)) (util/event ctx user_id "follow" badge_id "badge") (messages-viewed ctx badge_id user_id))) (defn create-connection-badge! [ctx user_id badge_id] (try+ (insert-connection-badge! ctx user_id badge_id) {:status "success" :connected? (is-connected? ctx user_id badge_id)} (catch Object _ {:status "error" :connected? (is-connected? ctx user_id badge_id)}))) (defn create-connection-issuer! [ctx user_id issuer_content_id] (try+ (insert-connection-issuer<! {:user_id user_id :issuer_content_id issuer_content_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "false"}))) (defn delete-issuer-connection! [ctx user_id issuer_content_id] (try+ (delete-connection-issuer! {:user_id user_id :issuer_content_id issuer_content_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "error"}))) (defn issuer-connected? [ctx user_id issuer_content_id] (let [id (select-connection-issuer {:user_id user_id :issuer_content_id issuer_content_id} (into {:result-set-fn first :row-fn :issuer_content_id} (get-db ctx)))] (= issuer_content_id id))) (defn badge-events-reduce [events] (let [helper (fn [current item] (let [key [(:verb item) (:object item)]] (-> current (assoc key item)))) reduced-events (vals (reduce helper {} (reverse events)))] (filter #(false? (:hidden %)) reduced-events))) (defn admin-events-reduce [events] (let [helper (fn [current item] (let [key [(:verb item)]] (-> current (assoc key item) (assoc-in [key :count] (inc (get-in current [key :count ] 0)))))) reduced-events (vals (reduce helper {} (reverse events)))] (filter #(false? (:hidden %)) reduced-events))) (defn badge-message-map "returns newest message and count new messages" [messages] (let [message-helper (fn [current item] (let [key (:badge_id item) new-messages-count (get-in current [key :new_messages] 0)] (-> current (assoc key item) (assoc-in [key :new_messages] (if (> (:ctime item) (:last_viewed item)) (inc new-messages-count) new-messages-count)))))] (reduce message-helper {} (reverse messages)))) (defn filter-badge-message-events [events] (filter #(= "message" (:verb %)) events)) (defn filter-own-events [events user_id] (filter #(and (= user_id (:subject %)) (= "follow" (:verb %))) events)) #_(defn get-user-admin-events [ctx user_id] (select-admin-events {:user_id user_id} (get-db ctx))) #_(defn get-user-admin-events-sorted [ctx user_id] (let [events (get-user-admin-events ctx user_id)] (if (not-empty events) (update-last-viewed ctx events user_id)) events)) (defn hide-user-event! [ctx user_id event_id] (try+ (update-hide-user-event! {:user_id user_id :event_id event_id} (get-db ctx)) "success" (catch Object _ "error"))) (defn hide-all-user-events! [ctx user_id] (try+ (hide-user-events-all! {:user_id user_id} (get-db ctx)) {:status "success"} (catch Object _ {:status "error"}))) #_(defn message! [ctx badge_id user_id message] (try+ (if (not (blank? message)) (let [badge-connection (if (not (is-connected? ctx user_id badge_id)) (:status (create-connection-badge! ctx user_id badge_id)) "connected")] (do (insert-badge-message<! {:badge_id badge_id :user_id user_id :message message} (get-db ctx)) (util/event ctx user_id "message" badge_id "badge") {:status "success" :connected? badge-connection})) {:status "error" :connected? nil}) (catch Object _ {:status "error" :connected? nil}))) (defn message! ([ctx message-map] (let [{:keys [badge_id user_id message]} message-map] (if-not (blank? message) (let [badge-connection (if (not (is-connected? ctx user_id badge_id)) (:status (create-connection-badge! ctx user_id badge_id)) "connected") gallery_id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (do (insert-badge-message<! {:badge_id badge_id :gallery_id gallery_id :user_id user_id :message message} (get-db ctx)) (util/event ctx user_id "message" badge_id "badge")) {:connected? badge-connection})))) ([ctx badge_id user_id message] (if (blank? message) {:status "error" :connected? nil} (try+ (let [save-message (message! ctx {:badge_id badge_id :user_id user_id :message message})] (merge save-message {:status "success"})) (catch Object _ {:status "error" :connected? nil}))))) (defn get-badge-message-count [ctx badge_id user-id] (let [badge-messages-user-id-ctime (select-badge-messages-count {:badge_id badge_id} (get-db ctx)) last-viewed (select-badge-message-last-view {:badge_id badge_id :user_id user-id} (into {:result-set-fn first :row-fn :mtime} (get-db ctx))) new-messages (if last-viewed (filter #(and (not= user-id (:user_id %)) (< last-viewed (:ctime %))) badge-messages-user-id-ctime) ())] {:new-messages (count new-messages) :all-messages (count badge-messages-user-id-ctime)})) (defn get-badge-message-count-multi [ctx gallery-ids user-id] (let [badge-messages-user-id-ctime (->> (select-badge-messages-count-multi {:gallery_ids gallery-ids} (get-db ctx)) (remove #(= user-id (:user_id %)))) last-viewed (->> (select-badge-message-last-view-multi {:gallery_ids gallery-ids :user_id user-id} (get-db ctx)) (group-by :gallery_id) (reduce-kv (fn [r k v] (conj r (hash-map :gallery_id k :mtime (->> (map :mtime v) (apply max))))) [])) filtered-list (r/filter (fn [b] (some #(and (not= user-id (:user_id b)) (= (:gallery_id %) (:gallery_id b)) (< (:mtime %) (:ctime b))) last-viewed)) badge-messages-user-id-ctime)] (->> filtered-list (group-by :gallery_id) (reduce-kv (fn [r k v] (conj r (hash-map :gallery_id k :count (count v)))) [])))) (defn get-badge-messages-limit [ctx badge_id page_count user_id] (let [limit 10 offset (* limit page_count) badge-messages (select-badge-messages-limit {:badge_id badge_id :limit limit :offset offset} (get-db ctx)) messages-left (- (:all-messages (get-badge-message-count ctx badge_id user_id)) (* limit (+ page_count 1)))] (if (= 0 page_count) (messages-viewed ctx badge_id user_id)) {:messages badge-messages :messages_left (if (pos? messages-left) messages-left 0)})) (defn message-owner? [ctx message_id user_id] (let [message_owner (select-badge-message-owner {:message_id message_id} (into {:result-set-fn first :row-fn :user_id} (get-db ctx)))] (= user_id message_owner))) (defn delete-message! [ctx message_id user_id] (try+ (let [message-owner (message-owner? ctx message_id user_id) admin (ah/user-admin? ctx user_id)] (if (or message-owner admin) (update-badge-message-deleted! {:message_id message_id} (get-db ctx)))) "success" (catch Object _ "error"))) (defn create-connection-badge-by-badge-id! [ctx user_id user_badge_id] (let [badge_id (select-badge-id-by-user-badge-id {:user_badge_id user_badge_id} (into {:result-set-fn first :row-fn :badge_id} (get-db ctx)))] (try+ (insert-connection-badge! ctx user_id badge_id) (catch Object _)))) (defn delete-connection-badge-by-badge-id! [ctx user_id badge_id] (try+ (delete-connect-badge-by-badge-id! {:user_id user_id :badge_id badge_id} (get-db ctx)) (catch Object _))) (defn delete-connection-badge! [ctx user_id badge_id] (try+ (when-let [gallery-id (some-> (select-badge-gallery-id {:badge_id badge_id} (get-db ctx)) first :gallery_id)] (delete-connect-badge! {:user_id user_id :badge_id badge_id :gallery_id gallery-id} (get-db ctx))) {:status "success" :connected? (is-connected? ctx user_id badge_id)} (catch Object _ {:status "error" :connected? (is-connected? ctx user_id badge_id)}))) (defn get-connections-badge [ctx user_id] (select-user-connections-badge {:user_id user_id} (get-db ctx))) (defn get-users-not-verified-emails [ctx user_id] (select-user-not-verified-emails {:user_id user_id} (get-db ctx))) (defn get-user-tips [ctx user_id] (let [welcome-tip (= 0 (select-user-badge-count {:user_id user_id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))) profile-picture-tip (if (not welcome-tip) (nil? (select-user-profile-picture {:user_id user_id} (into {:result-set-fn first :row-fn :profile_picture} (get-db ctx)))) false)] {:profile-picture-tip profile-picture-tip :welcome-tip welcome-tip :not-verified-emails (get-users-not-verified-emails ctx user_id)})) (defn get-all-user-events [ctx user_id] (get-all-user-event {:subject user_id} (get-db ctx))) (defn get-user-issuer-connections [ctx user_id] (select-user-connections-issuer {:user_id user_id} (get-db ctx)))
69bb4d285639d2cc34131c1093306972c9241727a8f1e7ee02506a42cf55ad78
Enecuum/Node
NetworkSpec.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DuplicateRecordFields # module Enecuum.Tests.Integration.NetworkSpec where -- import Enecuum.Prelude import qualified Enecuum.Language as L import Test.Hspec import Test.Hspec.Contrib.HUnit (fromHUnitTest) import Test.HUnit import qualified Data.Map as M import qualified Enecuum.Domain as D import qualified Enecuum.Framework.Networking.Internal.Connection as Con import Enecuum.Interpreters import qualified Enecuum.Runtime as Rt import qualified Enecuum.Testing.Integrational as I import Enecuum.Tests.Helpers import Enecuum.Testing.Wrappers -- Tests disabled spec :: Spec spec = stableTest $ fastTest $ describe "Network tests" $ fromHUnitTest $ TestList [ TestLabel "tcp one message test" (oneMessageTest D.Tcp 3998 4998) , TestLabel "udp one message test" (oneMessageTest D.Udp 3999 4999) , TestLabel "udp ping-pong test" (pingPongTest D.Udp 4000 5000) , TestLabel "tcp ping-pong test" (pingPongTest D.Tcp 4001 5001) , TestLabel " fail sending too big msg by udp connect " ( testSendingBigMsgByConnect D.Udp 4002 5002 ) , TestLabel " fail sending too big msg by tcp connect " ( testSendingBigMsgByConnect D.Tcp 4003 5003 ) , TestLabel " fail sending too big udp msg by Address " ( testSendingBigUdpMsgByAddress 4004 5004 ) , TestLabel "fail sending msg by closed udp connect" (testSendingMsgToClosedConnection D.Udp 4005 5005) , TestLabel "fail sending msg by closed tcp connect" (testSendingMsgToClosedConnection D.Tcp 4006 5006) -- This functionality is not supported! , TestLabel " fail sending udp msg to nonexistent address " ( testSendingMsgToNonexistentAddress 5007 ) --, TestLabel "fail udp connecting to nonexistent address." (testConnectToNonexistentAddress D.Udp 5008) , TestLabel "fail tcp connecting to nonexistent address." (testConnectToNonexistentAddress D.Tcp 5009) -- This functionality is not supported! , TestLabel " fail udp connecting to tcp server . " ( testConnectFromTo D.Tcp D.Udp 4010 5010 ) , TestLabel "fail tcp connecting to udp server." (testConnectFromTo D.Udp D.Tcp 4011 5011) , TestLabel "release of udp serving resources" (testReleaseOfResources D.Udp 4012 5012) , TestLabel "release of tcp serving resources" (testReleaseOfResources D.Tcp 4013 5013) ] newtype Ping = Ping Int deriving (Generic, ToJSON, FromJSON) newtype Pong = Pong Int deriving (Generic, ToJSON, FromJSON) newtype BigMsg = BigMsg [Int] deriving (Generic, ToJSON, FromJSON) data Success = Success deriving (Generic, ToJSON, FromJSON) bigMsg :: BigMsg bigMsg = BigMsg [1..500000000] createNodeRuntime :: IO Rt.NodeRuntime createNodeRuntime = Rt.createVoidLoggerRuntime >>= Rt.createCoreRuntime >>= (\a -> Rt.createNodeRuntime a M.empty) ensureNetworkError (D.AddressNotExist _) (Left (D.AddressNotExist _)) = True ensureNetworkError (D.TooBigMessage _) (Left (D.TooBigMessage _)) = True ensureNetworkError (D.ConnectionClosed _) (Left (D.ConnectionClosed _)) = True ensureNetworkError _ _ = False testReleaseOfResources :: (Applicative f, L.Serving c (f ())) => c -> D.PortNumber -> D.PortNumber -> Test testReleaseOfResources protocol serverPort succPort = runServingScenarion serverPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do L.serving protocol serverPort $ pure () L.stopServing serverPort L.delay 5000 L.serving protocol serverPort $ pure () L.stopServing serverPort L.delay 5000 L.serving protocol serverPort $ pure () void $ L.notify succAddr Success testConnectFromTo :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving c (f ())) => c -> con -> D.PortNumber -> D.PortNumber -> Test testConnectFromTo prot1 prot2 serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving prot1 serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do conn <- L.open prot2 serverAddr $ pure () unless (isJust conn) $ void $ L.notify succAddr Success testConnectToNonexistentAddress :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con) => con -> D.PortNumber -> Test testConnectToNonexistentAddress protocol succPort = runServingScenarion succPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do conn <- L.open protocol (D.Address "127.0.0.1" 300) $ pure () unless (isJust conn) $ void $ L.notify succAddr Success testSendingMsgToNonexistentAddress :: D.PortNumber -> Test testSendingMsgToNonexistentAddress succPort = runServingScenarion succPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do res <- L.notify (D.Address "127.0.0.1" 300) Success when (ensureNetworkError (D.AddressNotExist "") res) $ void $ L.notify succAddr Success testSendingMsgToClosedConnection :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving con (f ())) => con -> D.PortNumber -> D.PortNumber -> Test testSendingMsgToClosedConnection protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () L.close conn res <- L.send conn Success when (ensureNetworkError (D.ConnectionClosed "") res) $ void $ L.notify succAddr Success testSendingBigMsgByConnect :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving con (f ())) => con -> D.PortNumber -> D.PortNumber -> Test testSendingBigMsgByConnect protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () res <- L.send conn bigMsg when (ensureNetworkError (D.TooBigMessage "") res) $ void $ L.notify succAddr Success testSendingBigUdpMsgByAddress :: D.PortNumber -> D.PortNumber -> Test testSendingBigUdpMsgByAddress serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving D.Tcp serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do res <- L.notify serverAddr bigMsg when (ensureNetworkError (D.TooBigMessage "") res) $ void $ L.notify succAddr Success pingPongTest :: (L.Send (D.Connection con1) (Free L.NetworkingF), L.Send (D.Connection con2) m, Typeable con1, Typeable con2, Typeable m, L.Connection (Free L.NodeF) con1, L.Connection m con2, L.SendUdp m, Monad m, L.Serving con1 (Free (L.NetworkHandlerF con2 m) ())) => con1 -> D.PortNumber -> D.PortNumber -> Test pingPongTest protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ do L.handler (pingHandle succAddr) L.handler (pongHandle succAddr) threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ do L.handler (pingHandle succAddr) L.handler (pongHandle succAddr) void $ L.send conn $ Ping 0 oneMessageTest protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ L.handler (accessSuccess succAddr) threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () res <- L.send conn Success case res of Left err -> L.logInfo $ "Error: " <> show err Right _ -> L.logInfo "Sending ok." accessSuccess succAddr Success conn = do void $ L.notify succAddr Success L.close conn runServingScenarion :: D.PortNumber -> D.PortNumber -> (D.Address -> D.Address -> Rt.NodeRuntime -> Rt.NodeRuntime -> IO ()) -> Test runServingScenarion serverPort succPort f = TestCase $ do let serverAddr = D.Address "127.0.0.1" serverPort succAddr = D.Address "127.0.0.1" succPort nodeRt1 <- createNodeRuntime --loger1 --loger2 <- Rt.createLoggerRuntime I.consoleLoggerConfig nodeRt2 <- createNodeRuntime --loger2 void $ forkIO $ f serverAddr succAddr nodeRt1 nodeRt2 ok <- succesServer succPort runNodeDefinitionL nodeRt1 $ L.stopServing serverPort assertBool "" ok pingHandle :: (L.Connection m con, L.SendUdp m, L.Send (D.Connection con) m, Monad m) => D.Address -> Ping -> D.Connection con -> m () pingHandle succAddr (Ping i) conn = do when (i < 10) $ void $ L.send conn (Pong $ i + 1) when (i == 10) $ do void $ L.notify succAddr Success L.close conn pongHandle :: (L.Connection m con, L.SendUdp m, L.Send (D.Connection con) m, Monad m) => D.Address -> Pong -> D.Connection con -> m () pongHandle succAddr (Pong i) conn = do when (i < 10) $ void $ L.send conn (Ping $ i + 1) when (i == 10) $ do void $ L.notify succAddr Success L.close conn emptFunc = Con.ConnectionRegister (\_ -> pure ()) (\_ -> pure ()) succesServer :: D.PortNumber -> IO Bool succesServer port = do let logger = Rt.RuntimeLogger { Rt.logMessage' = \lvl msg -> putStrLn $ "[" <> show lvl <> "] " <> msg } mvar <- newEmptyMVar void $ forkIO $ do threadDelay 1000000 putMVar mvar False counter <- newIORef 0 Just ch <- Con.startServer logger counter port (M.singleton (D.toTag Success) (\_ (_ :: D.Connection D.Udp) -> putMVar mvar True)) emptFunc ok <- takeMVar mvar Con.stopServer ch pure ok
null
https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/test/spec/Enecuum/Tests/Integration/NetworkSpec.hs
haskell
# LANGUAGE DeriveAnyClass # Tests disabled This functionality is not supported! , TestLabel "fail udp connecting to nonexistent address." (testConnectToNonexistentAddress D.Udp 5008) This functionality is not supported! loger1 loger2 <- Rt.createLoggerRuntime I.consoleLoggerConfig loger2
# LANGUAGE DuplicateRecordFields # module Enecuum.Tests.Integration.NetworkSpec where import Enecuum.Prelude import qualified Enecuum.Language as L import Test.Hspec import Test.Hspec.Contrib.HUnit (fromHUnitTest) import Test.HUnit import qualified Data.Map as M import qualified Enecuum.Domain as D import qualified Enecuum.Framework.Networking.Internal.Connection as Con import Enecuum.Interpreters import qualified Enecuum.Runtime as Rt import qualified Enecuum.Testing.Integrational as I import Enecuum.Tests.Helpers import Enecuum.Testing.Wrappers spec :: Spec spec = stableTest $ fastTest $ describe "Network tests" $ fromHUnitTest $ TestList [ TestLabel "tcp one message test" (oneMessageTest D.Tcp 3998 4998) , TestLabel "udp one message test" (oneMessageTest D.Udp 3999 4999) , TestLabel "udp ping-pong test" (pingPongTest D.Udp 4000 5000) , TestLabel "tcp ping-pong test" (pingPongTest D.Tcp 4001 5001) , TestLabel " fail sending too big msg by udp connect " ( testSendingBigMsgByConnect D.Udp 4002 5002 ) , TestLabel " fail sending too big msg by tcp connect " ( testSendingBigMsgByConnect D.Tcp 4003 5003 ) , TestLabel " fail sending too big udp msg by Address " ( testSendingBigUdpMsgByAddress 4004 5004 ) , TestLabel "fail sending msg by closed udp connect" (testSendingMsgToClosedConnection D.Udp 4005 5005) , TestLabel "fail sending msg by closed tcp connect" (testSendingMsgToClosedConnection D.Tcp 4006 5006) , TestLabel " fail sending udp msg to nonexistent address " ( testSendingMsgToNonexistentAddress 5007 ) , TestLabel "fail tcp connecting to nonexistent address." (testConnectToNonexistentAddress D.Tcp 5009) , TestLabel " fail udp connecting to tcp server . " ( testConnectFromTo D.Tcp D.Udp 4010 5010 ) , TestLabel "fail tcp connecting to udp server." (testConnectFromTo D.Udp D.Tcp 4011 5011) , TestLabel "release of udp serving resources" (testReleaseOfResources D.Udp 4012 5012) , TestLabel "release of tcp serving resources" (testReleaseOfResources D.Tcp 4013 5013) ] newtype Ping = Ping Int deriving (Generic, ToJSON, FromJSON) newtype Pong = Pong Int deriving (Generic, ToJSON, FromJSON) newtype BigMsg = BigMsg [Int] deriving (Generic, ToJSON, FromJSON) data Success = Success deriving (Generic, ToJSON, FromJSON) bigMsg :: BigMsg bigMsg = BigMsg [1..500000000] createNodeRuntime :: IO Rt.NodeRuntime createNodeRuntime = Rt.createVoidLoggerRuntime >>= Rt.createCoreRuntime >>= (\a -> Rt.createNodeRuntime a M.empty) ensureNetworkError (D.AddressNotExist _) (Left (D.AddressNotExist _)) = True ensureNetworkError (D.TooBigMessage _) (Left (D.TooBigMessage _)) = True ensureNetworkError (D.ConnectionClosed _) (Left (D.ConnectionClosed _)) = True ensureNetworkError _ _ = False testReleaseOfResources :: (Applicative f, L.Serving c (f ())) => c -> D.PortNumber -> D.PortNumber -> Test testReleaseOfResources protocol serverPort succPort = runServingScenarion serverPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do L.serving protocol serverPort $ pure () L.stopServing serverPort L.delay 5000 L.serving protocol serverPort $ pure () L.stopServing serverPort L.delay 5000 L.serving protocol serverPort $ pure () void $ L.notify succAddr Success testConnectFromTo :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving c (f ())) => c -> con -> D.PortNumber -> D.PortNumber -> Test testConnectFromTo prot1 prot2 serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving prot1 serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do conn <- L.open prot2 serverAddr $ pure () unless (isJust conn) $ void $ L.notify succAddr Success testConnectToNonexistentAddress :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con) => con -> D.PortNumber -> Test testConnectToNonexistentAddress protocol succPort = runServingScenarion succPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do conn <- L.open protocol (D.Address "127.0.0.1" 300) $ pure () unless (isJust conn) $ void $ L.notify succAddr Success testSendingMsgToNonexistentAddress :: D.PortNumber -> Test testSendingMsgToNonexistentAddress succPort = runServingScenarion succPort succPort $ \_ succAddr nodeRt1 _ -> runNodeDefinitionL nodeRt1 $ do res <- L.notify (D.Address "127.0.0.1" 300) Success when (ensureNetworkError (D.AddressNotExist "") res) $ void $ L.notify succAddr Success testSendingMsgToClosedConnection :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving con (f ())) => con -> D.PortNumber -> D.PortNumber -> Test testSendingMsgToClosedConnection protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () L.close conn res <- L.send conn Success when (ensureNetworkError (D.ConnectionClosed "") res) $ void $ L.notify succAddr Success testSendingBigMsgByConnect :: (L.Send (D.Connection con) (Free L.NetworkingF), L.Connection (Free L.NodeF) con, Applicative f, L.Serving con (f ())) => con -> D.PortNumber -> D.PortNumber -> Test testSendingBigMsgByConnect protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () res <- L.send conn bigMsg when (ensureNetworkError (D.TooBigMessage "") res) $ void $ L.notify succAddr Success testSendingBigUdpMsgByAddress :: D.PortNumber -> D.PortNumber -> Test testSendingBigUdpMsgByAddress serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving D.Tcp serverPort $ pure () threadDelay 5000 runNodeDefinitionL nodeRt2 $ do res <- L.notify serverAddr bigMsg when (ensureNetworkError (D.TooBigMessage "") res) $ void $ L.notify succAddr Success pingPongTest :: (L.Send (D.Connection con1) (Free L.NetworkingF), L.Send (D.Connection con2) m, Typeable con1, Typeable con2, Typeable m, L.Connection (Free L.NodeF) con1, L.Connection m con2, L.SendUdp m, Monad m, L.Serving con1 (Free (L.NetworkHandlerF con2 m) ())) => con1 -> D.PortNumber -> D.PortNumber -> Test pingPongTest protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ do L.handler (pingHandle succAddr) L.handler (pongHandle succAddr) threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ do L.handler (pingHandle succAddr) L.handler (pongHandle succAddr) void $ L.send conn $ Ping 0 oneMessageTest protocol serverPort succPort = runServingScenarion serverPort succPort $ \serverAddr succAddr nodeRt1 nodeRt2 -> do runNodeDefinitionL nodeRt1 $ L.serving protocol serverPort $ L.handler (accessSuccess succAddr) threadDelay 5000 runNodeDefinitionL nodeRt2 $ do Just conn <- L.open protocol serverAddr $ pure () res <- L.send conn Success case res of Left err -> L.logInfo $ "Error: " <> show err Right _ -> L.logInfo "Sending ok." accessSuccess succAddr Success conn = do void $ L.notify succAddr Success L.close conn runServingScenarion :: D.PortNumber -> D.PortNumber -> (D.Address -> D.Address -> Rt.NodeRuntime -> Rt.NodeRuntime -> IO ()) -> Test runServingScenarion serverPort succPort f = TestCase $ do let serverAddr = D.Address "127.0.0.1" serverPort succAddr = D.Address "127.0.0.1" succPort void $ forkIO $ f serverAddr succAddr nodeRt1 nodeRt2 ok <- succesServer succPort runNodeDefinitionL nodeRt1 $ L.stopServing serverPort assertBool "" ok pingHandle :: (L.Connection m con, L.SendUdp m, L.Send (D.Connection con) m, Monad m) => D.Address -> Ping -> D.Connection con -> m () pingHandle succAddr (Ping i) conn = do when (i < 10) $ void $ L.send conn (Pong $ i + 1) when (i == 10) $ do void $ L.notify succAddr Success L.close conn pongHandle :: (L.Connection m con, L.SendUdp m, L.Send (D.Connection con) m, Monad m) => D.Address -> Pong -> D.Connection con -> m () pongHandle succAddr (Pong i) conn = do when (i < 10) $ void $ L.send conn (Ping $ i + 1) when (i == 10) $ do void $ L.notify succAddr Success L.close conn emptFunc = Con.ConnectionRegister (\_ -> pure ()) (\_ -> pure ()) succesServer :: D.PortNumber -> IO Bool succesServer port = do let logger = Rt.RuntimeLogger { Rt.logMessage' = \lvl msg -> putStrLn $ "[" <> show lvl <> "] " <> msg } mvar <- newEmptyMVar void $ forkIO $ do threadDelay 1000000 putMVar mvar False counter <- newIORef 0 Just ch <- Con.startServer logger counter port (M.singleton (D.toTag Success) (\_ (_ :: D.Connection D.Udp) -> putMVar mvar True)) emptFunc ok <- takeMVar mvar Con.stopServer ch pure ok
ba4db8c016c096440a153fc9d2b8aa4ac869609aa7998cd6b24e183ae54f7e10
ryanpbrewster/haskell
P040Test.hs
module Problems.P040Test ( case_040_main ) where import Problems.P040 import Test.Tasty.Discover (Assertion, (@?=)) case_040_main :: Assertion case_040_main = solve @?= "210"
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/tests/Problems/P040Test.hs
haskell
module Problems.P040Test ( case_040_main ) where import Problems.P040 import Test.Tasty.Discover (Assertion, (@?=)) case_040_main :: Assertion case_040_main = solve @?= "210"
953069c0c6d2cdfb61931d4d806277c30102e6fb5a05989ca06d908434940f53
RRethy/nvim-treesitter-textsubjects
textsubjects-container-outer.scm
(([ (function_declaration) (lexical_declaration) (class_declaration) (method_definition) ] @_start @_end) (#make-range! "range" @_start @_end))
null
https://raw.githubusercontent.com/RRethy/nvim-treesitter-textsubjects/30c5aecd3b30d2f7d4d019c91b599b3df8c0b370/queries/javascript/textsubjects-container-outer.scm
scheme
(([ (function_declaration) (lexical_declaration) (class_declaration) (method_definition) ] @_start @_end) (#make-range! "range" @_start @_end))
d637c6f88ec393f39ce3bedfa4c6470e703fcb5dc17edd82ef4bdcdc2ed5712f
janestreet/universe
pdu_impl.mli
include Pdu_intf.S with module IO := Netsnmp_io_impl
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/netsnmp/src/raw_monad/pdu_impl.mli
ocaml
include Pdu_intf.S with module IO := Netsnmp_io_impl
65b0e545d562e02312c69ba674d320f5d56aa803013ca2779dc036636dcc8282
anmonteiro/lumo
core.cljs
(ns instrument.core "The entry point of this program" (:require [cljs.spec.test.alpha :as stest])) (stest/instrument) (defn -main [& args] (println "Hello world!") (process.exit 0)) (set! *main-cli-fn* `-main)
null
https://raw.githubusercontent.com/anmonteiro/lumo/6709c9f1b7b342c8108e6ed6e034e19dc786f00b/src/test/cljs_build/instrument/core.cljs
clojure
(ns instrument.core "The entry point of this program" (:require [cljs.spec.test.alpha :as stest])) (stest/instrument) (defn -main [& args] (println "Hello world!") (process.exit 0)) (set! *main-cli-fn* `-main)
f92ca7d22b131b5ce10332503307a8ea815fd5c9c1efe699de44d249c7e12bea
jhidding/chez-glfw
events.scm
(library (glfw events) (export event? event-type event-time mouse-button-event? mouse-button-event-button mouse-button-event-action mouse-move-event? mouse-move-event-x mouse-move-event-y key-event? key-event-key key-event-scancode key-event-action key-event-mods resize-event? resize-event-width resize-event-height mouse-button-callback cursor-position-callback key-callback resize-callback) (import (rnrs base (6)) (rnrs records syntactic (6)) (only (chezscheme) box unbox set-box!) (pfds queues)) #| Event queue ================================================================== |# (define-record-type event (fields type time)) (define-record-type mouse-button-event (parent event) (fields button action) (protocol (lambda (new) (lambda (time button action) ((new 'mouse-button time) button action))))) (define-record-type mouse-move-event (parent event) (fields x y) (protocol (lambda (new) (lambda (time x y) ((new 'mouse-move time) x y))))) (define-record-type key-event (parent event) (fields key scancode action mods) (protocol (lambda (new) (lambda (time key scancode action mods) ((new 'key time) key scancode action mods))))) (define-record-type resize-event (parent event) (fields width height) (protocol (lambda (new) (lambda (time width height) ((new 'resize time) width height))))) (define (mouse-button-callback event-queue) (lambda (window button action mods) (let ([action* (case action [(GLFW_PRESS) 'press] [(GLFW_RELEASE) 'release] [else 'other])] [button* (case button [(GLFW_MOUSE_BUTTON_LEFT) 'left] [(GLFW_MOUSE_BUTTON_RIGHT) 'right] [(GLFW_MOUSE_BUTTON_MIDDLE) 'middle] [else 'other])]) (set-box! event-queue (enqueue (unbox event-queue) (make-mouse-button-event (glfw-get-time) button* action*)))))) (define (cursor-position-callback event-queue) (lambda (window x y) (set-box! event-queue (enqueue (unbox event-queue) (make-mouse-move-event (glfw-get-time) x y))))) (define (key-callback event-queue) (lambda (window key scancode action mods) (set-box! event-queue (enqueue (unbox event-queue) (make-key-event (glfw-get-time) key scancode action mods))))) (define (resize-callback event-queue) (lambda (window width height) (set-box! event-queue (enqueue (unbox event-queue) (make-resize-event (glfw-get-time) width height))))) )
null
https://raw.githubusercontent.com/jhidding/chez-glfw/fe53b5d8915c1c0b9f6a07446a0399a430d09851/glfw/events.scm
scheme
Event queue ==================================================================
(library (glfw events) (export event? event-type event-time mouse-button-event? mouse-button-event-button mouse-button-event-action mouse-move-event? mouse-move-event-x mouse-move-event-y key-event? key-event-key key-event-scancode key-event-action key-event-mods resize-event? resize-event-width resize-event-height mouse-button-callback cursor-position-callback key-callback resize-callback) (import (rnrs base (6)) (rnrs records syntactic (6)) (only (chezscheme) box unbox set-box!) (pfds queues)) (define-record-type event (fields type time)) (define-record-type mouse-button-event (parent event) (fields button action) (protocol (lambda (new) (lambda (time button action) ((new 'mouse-button time) button action))))) (define-record-type mouse-move-event (parent event) (fields x y) (protocol (lambda (new) (lambda (time x y) ((new 'mouse-move time) x y))))) (define-record-type key-event (parent event) (fields key scancode action mods) (protocol (lambda (new) (lambda (time key scancode action mods) ((new 'key time) key scancode action mods))))) (define-record-type resize-event (parent event) (fields width height) (protocol (lambda (new) (lambda (time width height) ((new 'resize time) width height))))) (define (mouse-button-callback event-queue) (lambda (window button action mods) (let ([action* (case action [(GLFW_PRESS) 'press] [(GLFW_RELEASE) 'release] [else 'other])] [button* (case button [(GLFW_MOUSE_BUTTON_LEFT) 'left] [(GLFW_MOUSE_BUTTON_RIGHT) 'right] [(GLFW_MOUSE_BUTTON_MIDDLE) 'middle] [else 'other])]) (set-box! event-queue (enqueue (unbox event-queue) (make-mouse-button-event (glfw-get-time) button* action*)))))) (define (cursor-position-callback event-queue) (lambda (window x y) (set-box! event-queue (enqueue (unbox event-queue) (make-mouse-move-event (glfw-get-time) x y))))) (define (key-callback event-queue) (lambda (window key scancode action mods) (set-box! event-queue (enqueue (unbox event-queue) (make-key-event (glfw-get-time) key scancode action mods))))) (define (resize-callback event-queue) (lambda (window width height) (set-box! event-queue (enqueue (unbox event-queue) (make-resize-event (glfw-get-time) width height))))) )
ed036cb35989f8f2741d2efaf0d3dbab08beb20d96f9341cbdfc8f6087b0fb06
yallop/ocaml-ctypes
test_errno.ml
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes let us x = if Sys.os_type <> "Win32" then x else "_" ^ x (* Call close() with a bogus file descriptor and check that an exception is raised. *) let test_errno_exception_raised _ = let close = Foreign.foreign (us "close") ~check_errno:true (int @-> returning int) in assert_raises (Unix.Unix_error(Unix.EBADF, us "close", "")) (fun () -> close (-300)) Call chdir ( ) with a valid directory path and check that zero is returned . Call chdir() with a valid directory path and check that zero is returned. *) let test_int_return_errno_exception_raised _ = let unlikely_to_exist = if Sys.os_type <> "Win32" then "/unlikely_to_exist" else "C:\\unlikely_to_exist" in let chdir = Foreign.foreign (us "chdir") ~check_errno:true (string @-> returning int) in assert_raises (Unix.Unix_error(Unix.ENOENT, us "chdir", "")) (fun () -> chdir unlikely_to_exist) Call chdir ( ) with a valid directory path and check that zero is returned . Call chdir() with a valid directory path and check that zero is returned. *) let test_errno_no_exception_raised _ = let chdir = Foreign.foreign (us "chdir") ~check_errno:true (string @-> returning int) in assert_equal 0 (chdir (Sys.getcwd ())) let suite = "foreign+errno tests" >::: ["Exception from close" >:: test_errno_exception_raised; "Exception from chdir" >:: test_int_return_errno_exception_raised; "No exception from chdir" >:: test_errno_no_exception_raised; ] let _ = if Sys.os_type = "Win32" then Ugly workaround because oUnit raises an error , if there are any changes in the environment . There are two ways to access the environments on windows : - through the native Windows API . - through the lib . The uses the environment for interprocess communication , but hides it from the end user . Since OCaml 4.07 the native Windows API is used by Unix.environment , therefore the tricks of the lib are visible . Ugly workaround because oUnit raises an error, if there are any changes in the environment. There are two ways to access the environments on windows: - through the native Windows API. - through the crt lib. The crt uses the environment for interprocess communication, but hides it from the end user. Since OCaml 4.07 the native Windows API is used by Unix.environment, therefore the tricks of the crt lib are visible. *) Sys.chdir "."; (* udpate environment *) run_test_tt_main suite
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-foreign-errno/test_errno.ml
ocaml
Call close() with a bogus file descriptor and check that an exception is raised. udpate environment
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open OUnit2 open Ctypes let us x = if Sys.os_type <> "Win32" then x else "_" ^ x let test_errno_exception_raised _ = let close = Foreign.foreign (us "close") ~check_errno:true (int @-> returning int) in assert_raises (Unix.Unix_error(Unix.EBADF, us "close", "")) (fun () -> close (-300)) Call chdir ( ) with a valid directory path and check that zero is returned . Call chdir() with a valid directory path and check that zero is returned. *) let test_int_return_errno_exception_raised _ = let unlikely_to_exist = if Sys.os_type <> "Win32" then "/unlikely_to_exist" else "C:\\unlikely_to_exist" in let chdir = Foreign.foreign (us "chdir") ~check_errno:true (string @-> returning int) in assert_raises (Unix.Unix_error(Unix.ENOENT, us "chdir", "")) (fun () -> chdir unlikely_to_exist) Call chdir ( ) with a valid directory path and check that zero is returned . Call chdir() with a valid directory path and check that zero is returned. *) let test_errno_no_exception_raised _ = let chdir = Foreign.foreign (us "chdir") ~check_errno:true (string @-> returning int) in assert_equal 0 (chdir (Sys.getcwd ())) let suite = "foreign+errno tests" >::: ["Exception from close" >:: test_errno_exception_raised; "Exception from chdir" >:: test_int_return_errno_exception_raised; "No exception from chdir" >:: test_errno_no_exception_raised; ] let _ = if Sys.os_type = "Win32" then Ugly workaround because oUnit raises an error , if there are any changes in the environment . There are two ways to access the environments on windows : - through the native Windows API . - through the lib . The uses the environment for interprocess communication , but hides it from the end user . Since OCaml 4.07 the native Windows API is used by Unix.environment , therefore the tricks of the lib are visible . Ugly workaround because oUnit raises an error, if there are any changes in the environment. There are two ways to access the environments on windows: - through the native Windows API. - through the crt lib. The crt uses the environment for interprocess communication, but hides it from the end user. Since OCaml 4.07 the native Windows API is used by Unix.environment, therefore the tricks of the crt lib are visible. *) run_test_tt_main suite
84c0124a309e3e2ca7059f1410c556d55a986b0bc1a284fab784dcd028311064
ocaml/dune
main.ml
open! Stdune open Import let all : _ Cmdliner.Cmd.t list = let terms = [ Installed_libraries.command ; External_lib_deps.command ; Build_cmd.build ; Build_cmd.runtest ; Build_cmd.fmt ; command_alias Build_cmd.runtest Build_cmd.runtest_term "test" ; Clean.command ; Install_uninstall.install ; Install_uninstall.uninstall ; Exec.command ; Subst.command ; Print_rules.command ; Utop.command ; Promotion.promote ; Printenv.command ; Help.command ; Format_dune_file.command ; Upgrade.command ; Cache.command ; Describe.command ; Top.command ; Ocaml_merlin.command ; Shutdown.command ; Diagnostics.command ] in let groups = [ Ocaml_cmd.group ; Coq.group ; Rpc.group ; Internal.group ; Init.group ; Promotion.group ] in terms @ groups (* Short reminders for the most used and useful commands *) let common_commands_synopsis = Common.command_synopsis [ "build [--watch]" ; "runtest [--watch]" ; "exec NAME" ; "utop [DIR]" ; "install" ; "init project NAME [PATH] [--libs=l1,l2 --ppx=p1,p2 --inline-tests]" ] let info = let doc = "composable build system for OCaml" in Cmd.info "dune" ~doc ~envs:Common.envs ~version: (match Build_info.V1.version () with | None -> "n/a" | Some v -> Build_info.V1.Version.to_string v) ~man: [ `Blocks common_commands_synopsis ; `S "DESCRIPTION" ; `P {|Dune is a build system designed for OCaml projects only. It focuses on providing the user with a consistent experience and takes care of most of the low-level details of OCaml compilation. All you have to do is provide a description of your project and Dune will do the rest. |} ; `P {|The scheme it implements is inspired from the one used inside Jane Street and adapted to the open source world. It has matured over a long time and is used daily by hundreds of developers, which means that it is highly tested and productive. |} ; `Blocks Common.help_secs ; Common.examples [ ("Initialise a new project named `foo'", "dune init project foo") ; ("Build all targets in the current source tree", "dune build") ; ("Run the executable named `bar'", "dune exec bar") ; ("Run all tests in the current source tree", "dune runtest") ; ("Install all components defined in the project", "dune install") ; ("Remove all build artefacts", "dune clean") ] ] let cmd = Cmd.group info all let exit_and_flush code = Console.finish (); exit code let () = Dune_rules.Colors.setup_err_formatter_colors (); try match Cmd.eval_value cmd ~catch:false with | Ok _ -> exit_and_flush 0 | Error _ -> exit_and_flush 1 with | Scheduler.Run.Shutdown.E Requested -> exit_and_flush 0 | Scheduler.Run.Shutdown.E (Signal _) -> exit_and_flush 130 | exn -> let exn = Exn_with_backtrace.capture exn in Dune_util.Report_error.report exn; exit_and_flush 1
null
https://raw.githubusercontent.com/ocaml/dune/3eaf83cd678009c586a0a506bc4755a3896be0f8/bin/main.ml
ocaml
Short reminders for the most used and useful commands
open! Stdune open Import let all : _ Cmdliner.Cmd.t list = let terms = [ Installed_libraries.command ; External_lib_deps.command ; Build_cmd.build ; Build_cmd.runtest ; Build_cmd.fmt ; command_alias Build_cmd.runtest Build_cmd.runtest_term "test" ; Clean.command ; Install_uninstall.install ; Install_uninstall.uninstall ; Exec.command ; Subst.command ; Print_rules.command ; Utop.command ; Promotion.promote ; Printenv.command ; Help.command ; Format_dune_file.command ; Upgrade.command ; Cache.command ; Describe.command ; Top.command ; Ocaml_merlin.command ; Shutdown.command ; Diagnostics.command ] in let groups = [ Ocaml_cmd.group ; Coq.group ; Rpc.group ; Internal.group ; Init.group ; Promotion.group ] in terms @ groups let common_commands_synopsis = Common.command_synopsis [ "build [--watch]" ; "runtest [--watch]" ; "exec NAME" ; "utop [DIR]" ; "install" ; "init project NAME [PATH] [--libs=l1,l2 --ppx=p1,p2 --inline-tests]" ] let info = let doc = "composable build system for OCaml" in Cmd.info "dune" ~doc ~envs:Common.envs ~version: (match Build_info.V1.version () with | None -> "n/a" | Some v -> Build_info.V1.Version.to_string v) ~man: [ `Blocks common_commands_synopsis ; `S "DESCRIPTION" ; `P {|Dune is a build system designed for OCaml projects only. It focuses on providing the user with a consistent experience and takes care of most of the low-level details of OCaml compilation. All you have to do is provide a description of your project and Dune will do the rest. |} ; `P {|The scheme it implements is inspired from the one used inside Jane Street and adapted to the open source world. It has matured over a long time and is used daily by hundreds of developers, which means that it is highly tested and productive. |} ; `Blocks Common.help_secs ; Common.examples [ ("Initialise a new project named `foo'", "dune init project foo") ; ("Build all targets in the current source tree", "dune build") ; ("Run the executable named `bar'", "dune exec bar") ; ("Run all tests in the current source tree", "dune runtest") ; ("Install all components defined in the project", "dune install") ; ("Remove all build artefacts", "dune clean") ] ] let cmd = Cmd.group info all let exit_and_flush code = Console.finish (); exit code let () = Dune_rules.Colors.setup_err_formatter_colors (); try match Cmd.eval_value cmd ~catch:false with | Ok _ -> exit_and_flush 0 | Error _ -> exit_and_flush 1 with | Scheduler.Run.Shutdown.E Requested -> exit_and_flush 0 | Scheduler.Run.Shutdown.E (Signal _) -> exit_and_flush 130 | exn -> let exn = Exn_with_backtrace.capture exn in Dune_util.Report_error.report exn; exit_and_flush 1
340985c2c125e5b5afe90789c76665b56d426512be19071dbe252dcd762d0506
shop-planner/shop3
p10.lisp
(in-package :shop-openstacks) #.(make-problem 'OS-SEQUENCEDSTRIPS-P20_1 'OPENSTACKS-SEQUENCEDSTRIPS-ADL-INCLUDED '((NEXT-COUNT N0 N1) (NEXT-COUNT N1 N2) (NEXT-COUNT N2 N3) (NEXT-COUNT N3 N4) (NEXT-COUNT N4 N5) (NEXT-COUNT N5 N6) (NEXT-COUNT N6 N7) (NEXT-COUNT N7 N8) (NEXT-COUNT N8 N9) (NEXT-COUNT N9 N10) (NEXT-COUNT N10 N11) (NEXT-COUNT N11 N12) (NEXT-COUNT N12 N13) (NEXT-COUNT N13 N14) (NEXT-COUNT N14 N15) (NEXT-COUNT N15 N16) (NEXT-COUNT N16 N17) (NEXT-COUNT N17 N18) (NEXT-COUNT N18 N19) (NEXT-COUNT N19 N20) (STACKS-AVAIL N0) (WAITING O1) (INCLUDES O1 P2) (WAITING O2) (INCLUDES O2 P3) (INCLUDES O2 P4) (INCLUDES O2 P5) (INCLUDES O2 P7) (WAITING O3) (INCLUDES O3 P5) (INCLUDES O3 P6) (INCLUDES O3 P8) (WAITING O4) (INCLUDES O4 P16) (WAITING O5) (INCLUDES O5 P10) (WAITING O6) (INCLUDES O6 P16) (WAITING O7) (INCLUDES O7 P12) (WAITING O8) (INCLUDES O8 P4) (INCLUDES O8 P12) (INCLUDES O8 P13) (INCLUDES O8 P17) (WAITING O9) (INCLUDES O9 P4) (WAITING O10) (INCLUDES O10 P4) (INCLUDES O10 P10) (WAITING O11) (INCLUDES O11 P12) (WAITING O12) (INCLUDES O12 P3) (WAITING O13) (INCLUDES O13 P6) (WAITING O14) (INCLUDES O14 P18) (WAITING O15) (INCLUDES O15 P12) (INCLUDES O15 P14) (INCLUDES O15 P16) (INCLUDES O15 P18) (WAITING O16) (INCLUDES O16 P11) (INCLUDES O16 P20) (WAITING O17) (INCLUDES O17 P1) (WAITING O18) (INCLUDES O18 P9) (WAITING O19) (INCLUDES O19 P15) (WAITING O20) (INCLUDES O20 P15) (INCLUDES O20 P19) (= (TOTAL-COST) 0) (COUNT N0) (COUNT N1) (COUNT N2) (COUNT N3) (COUNT N4) (COUNT N5) (COUNT N6) (COUNT N7) (COUNT N8) (COUNT N9) (COUNT N10) (COUNT N11) (COUNT N12) (COUNT N13) (COUNT N14) (COUNT N15) (COUNT N16) (COUNT N17) (COUNT N18) (COUNT N19) (COUNT N20) (ORDER O1) (ORDER O2) (ORDER O3) (ORDER O4) (ORDER O5) (ORDER O6) (ORDER O7) (ORDER O8) (ORDER O9) (ORDER O10) (ORDER O11) (ORDER O12) (ORDER O13) (ORDER O14) (ORDER O15) (ORDER O16) (ORDER O17) (ORDER O18) (ORDER O19) (ORDER O20) (PRODUCT P1) (PRODUCT P2) (PRODUCT P3) (PRODUCT P4) (PRODUCT P5) (PRODUCT P6) (PRODUCT P7) (PRODUCT P8) (PRODUCT P9) (PRODUCT P10) (PRODUCT P11) (PRODUCT P12) (PRODUCT P13) (PRODUCT P14) (PRODUCT P15) (PRODUCT P16) (PRODUCT P17) (PRODUCT P18) (PRODUCT P19) (PRODUCT P20) (:GOAL (AND (SHIPPED O1) (SHIPPED O2) (SHIPPED O3) (SHIPPED O4) (SHIPPED O5) (SHIPPED O6) (SHIPPED O7) (SHIPPED O8) (SHIPPED O9) (SHIPPED O10) (SHIPPED O11) (SHIPPED O12) (SHIPPED O13) (SHIPPED O14) (SHIPPED O15) (SHIPPED O16) (SHIPPED O17) (SHIPPED O18) (SHIPPED O19) (SHIPPED O20)))) '(:TASK PLAN))
null
https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/examples/openstacks-adl/p10.lisp
lisp
(in-package :shop-openstacks) #.(make-problem 'OS-SEQUENCEDSTRIPS-P20_1 'OPENSTACKS-SEQUENCEDSTRIPS-ADL-INCLUDED '((NEXT-COUNT N0 N1) (NEXT-COUNT N1 N2) (NEXT-COUNT N2 N3) (NEXT-COUNT N3 N4) (NEXT-COUNT N4 N5) (NEXT-COUNT N5 N6) (NEXT-COUNT N6 N7) (NEXT-COUNT N7 N8) (NEXT-COUNT N8 N9) (NEXT-COUNT N9 N10) (NEXT-COUNT N10 N11) (NEXT-COUNT N11 N12) (NEXT-COUNT N12 N13) (NEXT-COUNT N13 N14) (NEXT-COUNT N14 N15) (NEXT-COUNT N15 N16) (NEXT-COUNT N16 N17) (NEXT-COUNT N17 N18) (NEXT-COUNT N18 N19) (NEXT-COUNT N19 N20) (STACKS-AVAIL N0) (WAITING O1) (INCLUDES O1 P2) (WAITING O2) (INCLUDES O2 P3) (INCLUDES O2 P4) (INCLUDES O2 P5) (INCLUDES O2 P7) (WAITING O3) (INCLUDES O3 P5) (INCLUDES O3 P6) (INCLUDES O3 P8) (WAITING O4) (INCLUDES O4 P16) (WAITING O5) (INCLUDES O5 P10) (WAITING O6) (INCLUDES O6 P16) (WAITING O7) (INCLUDES O7 P12) (WAITING O8) (INCLUDES O8 P4) (INCLUDES O8 P12) (INCLUDES O8 P13) (INCLUDES O8 P17) (WAITING O9) (INCLUDES O9 P4) (WAITING O10) (INCLUDES O10 P4) (INCLUDES O10 P10) (WAITING O11) (INCLUDES O11 P12) (WAITING O12) (INCLUDES O12 P3) (WAITING O13) (INCLUDES O13 P6) (WAITING O14) (INCLUDES O14 P18) (WAITING O15) (INCLUDES O15 P12) (INCLUDES O15 P14) (INCLUDES O15 P16) (INCLUDES O15 P18) (WAITING O16) (INCLUDES O16 P11) (INCLUDES O16 P20) (WAITING O17) (INCLUDES O17 P1) (WAITING O18) (INCLUDES O18 P9) (WAITING O19) (INCLUDES O19 P15) (WAITING O20) (INCLUDES O20 P15) (INCLUDES O20 P19) (= (TOTAL-COST) 0) (COUNT N0) (COUNT N1) (COUNT N2) (COUNT N3) (COUNT N4) (COUNT N5) (COUNT N6) (COUNT N7) (COUNT N8) (COUNT N9) (COUNT N10) (COUNT N11) (COUNT N12) (COUNT N13) (COUNT N14) (COUNT N15) (COUNT N16) (COUNT N17) (COUNT N18) (COUNT N19) (COUNT N20) (ORDER O1) (ORDER O2) (ORDER O3) (ORDER O4) (ORDER O5) (ORDER O6) (ORDER O7) (ORDER O8) (ORDER O9) (ORDER O10) (ORDER O11) (ORDER O12) (ORDER O13) (ORDER O14) (ORDER O15) (ORDER O16) (ORDER O17) (ORDER O18) (ORDER O19) (ORDER O20) (PRODUCT P1) (PRODUCT P2) (PRODUCT P3) (PRODUCT P4) (PRODUCT P5) (PRODUCT P6) (PRODUCT P7) (PRODUCT P8) (PRODUCT P9) (PRODUCT P10) (PRODUCT P11) (PRODUCT P12) (PRODUCT P13) (PRODUCT P14) (PRODUCT P15) (PRODUCT P16) (PRODUCT P17) (PRODUCT P18) (PRODUCT P19) (PRODUCT P20) (:GOAL (AND (SHIPPED O1) (SHIPPED O2) (SHIPPED O3) (SHIPPED O4) (SHIPPED O5) (SHIPPED O6) (SHIPPED O7) (SHIPPED O8) (SHIPPED O9) (SHIPPED O10) (SHIPPED O11) (SHIPPED O12) (SHIPPED O13) (SHIPPED O14) (SHIPPED O15) (SHIPPED O16) (SHIPPED O17) (SHIPPED O18) (SHIPPED O19) (SHIPPED O20)))) '(:TASK PLAN))
84a5dbf785f407db56aab4f11837a34b963a06bf0ee4af8e64c97f9db2e5df8f
NoRedInk/haskell-libraries
List.hs
{-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - redundant - constraints # -- | A simple Redis library providing high level access to Redis features we use here at NoRedInk -- As with our Ruby Redis access , we enforce working within a " namespace " . module Redis.List ( -- * Creating a redis handler Real.handler, Real.handlerAutoExtendExpire, Internal.Handler, Internal.HandlerAutoExtendExpire, Settings.Settings (..), Settings.decoder, -- * Creating a redis API jsonApi, textApi, byteStringApi, Api, -- * Creating redis queries del, exists, expire, ping, lrange, rpush, -- * Running Redis queries Internal.query, Internal.transaction, Internal.Query, Internal.Error (..), Internal.map, Internal.map2, Internal.map3, Internal.sequence, ) where import qualified Data.Aeson as Aeson import qualified Data.ByteString as ByteString import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NonEmpty import qualified Redis.Codec as Codec import qualified Redis.Internal as Internal import qualified Redis.Real as Real import qualified Redis.Settings as Settings import qualified Prelude -- | a API type can be used to enforce a mapping of keys to values. -- without an API type, it can be easy to naiively serialize the wrong type -- into a redis key. -- -- Out of the box, we have helpers to support -- - 'jsonApi' for json-encodable and decodable values -- - 'textApi' for 'Text' values - ' byteStringApi ' for ' ByteString ' values data Api key a = Api { -- | Removes the specified keys. A key is ignored if it does not exist. -- -- del :: NonEmpty key -> Internal.Query Int, -- | Returns if key exists. -- -- exists :: key -> Internal.Query Bool, -- | Set a timeout on key. After the timeout has expired, the key will -- automatically be deleted. A key with an associated timeout is often said to -- be volatile in Redis terminology. -- -- expire :: key -> Int -> Internal.Query (), -- | Returns PONG if no argument is provided, otherwise return a copy of the -- argument as a bulk. This command is often used to test if a connection is -- still alive, or to measure latency. -- -- ping :: Internal.Query (), -- | Returns the specified elements of the list stored at key. The offsets start and stop are zero - based indexes , with 0 being the first element of the list ( the head of the list ) , 1 being the next -- element and so on. -- -- These offsets can also be negative numbers indicating offsets -- starting at the end of the list. For example, -1 is the last element -- of the list, -2 the penultimate, and so on. lrange :: key -> Int -> Int -> Internal.Query [a], -- | Insert all the specified values at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation. When key holds a value that is not a list, an error is returned. -- -- rpush :: key -> NonEmpty a -> Internal.Query Int } -- | Creates a json API mapping a 'key' to a json-encodable-decodable type -- -- > data Key = Key { fieldA: Text, fieldB: Text } > data = Val { ... } -- > -- > myJsonApi :: Redis.Api Key Val -- > myJsonApi = Redis.jsonApi (\Key {fieldA, jsonApi :: forall a key. (Aeson.ToJSON a, Aeson.FromJSON a) => (key -> Text) -> Api key a jsonApi = makeApi Codec.jsonCodec -- | Creates a Redis API mapping a 'key' to Text textApi :: (key -> Text) -> Api key Text textApi = makeApi Codec.textCodec | Creates a Redis API mapping a ' key ' to a ByteString byteStringApi :: (key -> Text) -> Api key ByteString.ByteString byteStringApi = makeApi Codec.byteStringCodec makeApi :: Codec.Codec a -> (key -> Text) -> Api key a makeApi Codec.Codec {Codec.codecEncoder, Codec.codecDecoder} toKey = Api { del = Internal.Del << NonEmpty.map toKey, exists = Internal.Exists << toKey, expire = \key secs -> Internal.Expire (toKey key) secs, ping = Internal.Ping |> map (\_ -> ()), lrange = \key lower upper -> Internal.Lrange (toKey key) lower upper |> Internal.WithResult (Prelude.traverse codecDecoder), rpush = \key vals -> Internal.Rpush (toKey key) (NonEmpty.map codecEncoder vals) }
null
https://raw.githubusercontent.com/NoRedInk/haskell-libraries/8a0ea7e1a80fc711810e5d225328826ac82393ea/nri-redis/src/Redis/List.hs
haskell
# LANGUAGE RankNTypes # | A simple Redis library providing high level access to Redis features we * Creating a redis handler * Creating a redis API * Creating redis queries * Running Redis queries | a API type can be used to enforce a mapping of keys to values. without an API type, it can be easy to naiively serialize the wrong type into a redis key. Out of the box, we have helpers to support - 'jsonApi' for json-encodable and decodable values - 'textApi' for 'Text' values | Removes the specified keys. A key is ignored if it does not exist. | Returns if key exists. | Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. | Returns PONG if no argument is provided, otherwise return a copy of the argument as a bulk. This command is often used to test if a connection is still alive, or to measure latency. | Returns the specified elements of the list stored at key. The element and so on. These offsets can also be negative numbers indicating offsets starting at the end of the list. For example, -1 is the last element of the list, -2 the penultimate, and so on. | Insert all the specified values at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation. When key holds a value that is not a list, an error is returned. | Creates a json API mapping a 'key' to a json-encodable-decodable type > data Key = Key { fieldA: Text, fieldB: Text } > > myJsonApi :: Redis.Api Key Val > myJsonApi = Redis.jsonApi (\Key {fieldA, | Creates a Redis API mapping a 'key' to Text
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -fno - warn - redundant - constraints # use here at NoRedInk As with our Ruby Redis access , we enforce working within a " namespace " . module Redis.List Real.handler, Real.handlerAutoExtendExpire, Internal.Handler, Internal.HandlerAutoExtendExpire, Settings.Settings (..), Settings.decoder, jsonApi, textApi, byteStringApi, Api, del, exists, expire, ping, lrange, rpush, Internal.query, Internal.transaction, Internal.Query, Internal.Error (..), Internal.map, Internal.map2, Internal.map3, Internal.sequence, ) where import qualified Data.Aeson as Aeson import qualified Data.ByteString as ByteString import Data.List.NonEmpty (NonEmpty) import qualified Data.List.NonEmpty as NonEmpty import qualified Redis.Codec as Codec import qualified Redis.Internal as Internal import qualified Redis.Real as Real import qualified Redis.Settings as Settings import qualified Prelude - ' byteStringApi ' for ' ByteString ' values data Api key a = Api del :: NonEmpty key -> Internal.Query Int, exists :: key -> Internal.Query Bool, expire :: key -> Int -> Internal.Query (), ping :: Internal.Query (), offsets start and stop are zero - based indexes , with 0 being the first element of the list ( the head of the list ) , 1 being the next lrange :: key -> Int -> Int -> Internal.Query [a], rpush :: key -> NonEmpty a -> Internal.Query Int } > data = Val { ... } jsonApi :: forall a key. (Aeson.ToJSON a, Aeson.FromJSON a) => (key -> Text) -> Api key a jsonApi = makeApi Codec.jsonCodec textApi :: (key -> Text) -> Api key Text textApi = makeApi Codec.textCodec | Creates a Redis API mapping a ' key ' to a ByteString byteStringApi :: (key -> Text) -> Api key ByteString.ByteString byteStringApi = makeApi Codec.byteStringCodec makeApi :: Codec.Codec a -> (key -> Text) -> Api key a makeApi Codec.Codec {Codec.codecEncoder, Codec.codecDecoder} toKey = Api { del = Internal.Del << NonEmpty.map toKey, exists = Internal.Exists << toKey, expire = \key secs -> Internal.Expire (toKey key) secs, ping = Internal.Ping |> map (\_ -> ()), lrange = \key lower upper -> Internal.Lrange (toKey key) lower upper |> Internal.WithResult (Prelude.traverse codecDecoder), rpush = \key vals -> Internal.Rpush (toKey key) (NonEmpty.map codecEncoder vals) }
b6fcf719b3fe8d055dd01b82ad7dcf3d51dbb1516e359d4ca59770138d34d538
hexlet-codebattle/battle_asserts
cube_sum.clj
(ns battle-asserts.issues.cube-sum (:require [clojure.test.check.generators :as gen])) (def level :elementary) (def tags ["math"]) (def description {:en "Calculate sum of cubes in array from 1 to `n`." :ru "Рассчитайте сумму кубов в массиве от 1 до `n`."}) (def signature {:input [{:argument-name "num" :type {:name "integer"}}] :output {:type {:name "integer"}}}) (defn arguments-generator [] (gen/tuple (gen/choose 1 30))) (def test-data [{:expected 1 :arguments [1]} {:expected 9 :arguments [2]} {:expected 44100 :arguments [20]} {:expected 216225 :arguments [30]}]) (defn solution [n] (letfn [(cube [num] (* num num num))] (reduce (fn [acc elem] (+ acc (cube elem))) 0 (range 1 (inc n)))))
null
https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/51a10801cac8cc09f82252bdcaaf8d0def6eabb1/src/battle_asserts/issues/cube_sum.clj
clojure
(ns battle-asserts.issues.cube-sum (:require [clojure.test.check.generators :as gen])) (def level :elementary) (def tags ["math"]) (def description {:en "Calculate sum of cubes in array from 1 to `n`." :ru "Рассчитайте сумму кубов в массиве от 1 до `n`."}) (def signature {:input [{:argument-name "num" :type {:name "integer"}}] :output {:type {:name "integer"}}}) (defn arguments-generator [] (gen/tuple (gen/choose 1 30))) (def test-data [{:expected 1 :arguments [1]} {:expected 9 :arguments [2]} {:expected 44100 :arguments [20]} {:expected 216225 :arguments [30]}]) (defn solution [n] (letfn [(cube [num] (* num num num))] (reduce (fn [acc elem] (+ acc (cube elem))) 0 (range 1 (inc n)))))
8b133c5bd08e727010a97421cd3198171f0019a523305b7381a866e59f130ac9
ohua-dev/ohua-core
Seq.hs
| Module : $ Header$ Description : Implementation for basic tail recrusion support . Copyright : ( c ) , 2017 . All Rights Reserved . License : EPL-1.0 Maintainer : , Stability : experimental Portability : portable This source code is licensed under the terms described in the associated LICENSE.TXT file = = Design : It is the very same rewrite as for the true branch of the ` ifRewrite ` . In fact , we could turn the ` seq ` into an if that is always true . We just would need a new function ` trueC : : a - > Bool ` that always returns ` True ` . Instead , we do a more performant version and introduce a ` seqFun ` operator that does this and also creates the control signal ( saving the ` if ` node ) . Note that ` seq ` is about sequencing side - effects to I / O. Module : $Header$ Description : Implementation for basic tail recrusion support. Copyright : (c) Sebastian Ertel, Justus Adam 2017. All Rights Reserved. License : EPL-1.0 Maintainer : , Stability : experimental Portability : portable This source code is licensed under the terms described in the associated LICENSE.TXT file == Design: It is the very same rewrite as for the true branch of the `ifRewrite`. In fact, we could turn the `seq` into an if that is always true. We just would need a new function `trueC :: a -> Bool` that always returns `True`. Instead, we do a more performant version and introduce a `seqFun` operator that does this and also creates the control signal (saving the `if` node). Note that `seq` is about sequencing side-effects to I/O. -} module Ohua.ALang.Passes.Seq where import Ohua.Prelude import Ohua.ALang.Lang import Ohua.ALang.Passes.Control import qualified Ohua.ALang.Refs as Refs (seq, seqFun) import Ohua.ALang.Util (lambdaArgsAndBody) seqFunSf :: Expression seqFunSf = Lit $ FunRefLit $ FunRef Refs.seqFun Nothing seqRewrite :: (Monad m, MonadGenBnd m, MonadReadEnvironment m) => Expression -> m Expression seqRewrite (Let v a b) = Let v <$> seqRewrite a <*> seqRewrite b seqRewrite (Lambda v e) = Lambda v <$> seqRewrite e seqRewrite (Apply (Apply (Lit (FunRefLit (FunRef "ohua.lang/seq" Nothing))) dep) expr) = do expr' <- seqRewrite expr -- post traversal optimization ctrl <- generateBindingWith "ctrl" expr'' <- liftIntoCtrlCtxt ctrl expr' TODO verify that this arg is actually ( ) let ((_:[]), expr''') = lambdaArgsAndBody expr'' -- return $ -- [ohualang| -- let $var:ctrl = ohua.lang/seqFun $var:dep in -- let result = $expr:expr' in -- result -- |] result <- generateBindingWith "result" return $ Let ctrl (Apply seqFunSf dep) $ Let result expr''' $ Var result seqRewrite e = return e
null
https://raw.githubusercontent.com/ohua-dev/ohua-core/8fe0ee90f4a1aea0c5bfabe922b290fed668a7da/core/src/Ohua/ALang/Passes/Seq.hs
haskell
post traversal optimization return $ [ohualang| let $var:ctrl = ohua.lang/seqFun $var:dep in let result = $expr:expr' in result |]
| Module : $ Header$ Description : Implementation for basic tail recrusion support . Copyright : ( c ) , 2017 . All Rights Reserved . License : EPL-1.0 Maintainer : , Stability : experimental Portability : portable This source code is licensed under the terms described in the associated LICENSE.TXT file = = Design : It is the very same rewrite as for the true branch of the ` ifRewrite ` . In fact , we could turn the ` seq ` into an if that is always true . We just would need a new function ` trueC : : a - > Bool ` that always returns ` True ` . Instead , we do a more performant version and introduce a ` seqFun ` operator that does this and also creates the control signal ( saving the ` if ` node ) . Note that ` seq ` is about sequencing side - effects to I / O. Module : $Header$ Description : Implementation for basic tail recrusion support. Copyright : (c) Sebastian Ertel, Justus Adam 2017. All Rights Reserved. License : EPL-1.0 Maintainer : , Stability : experimental Portability : portable This source code is licensed under the terms described in the associated LICENSE.TXT file == Design: It is the very same rewrite as for the true branch of the `ifRewrite`. In fact, we could turn the `seq` into an if that is always true. We just would need a new function `trueC :: a -> Bool` that always returns `True`. Instead, we do a more performant version and introduce a `seqFun` operator that does this and also creates the control signal (saving the `if` node). Note that `seq` is about sequencing side-effects to I/O. -} module Ohua.ALang.Passes.Seq where import Ohua.Prelude import Ohua.ALang.Lang import Ohua.ALang.Passes.Control import qualified Ohua.ALang.Refs as Refs (seq, seqFun) import Ohua.ALang.Util (lambdaArgsAndBody) seqFunSf :: Expression seqFunSf = Lit $ FunRefLit $ FunRef Refs.seqFun Nothing seqRewrite :: (Monad m, MonadGenBnd m, MonadReadEnvironment m) => Expression -> m Expression seqRewrite (Let v a b) = Let v <$> seqRewrite a <*> seqRewrite b seqRewrite (Lambda v e) = Lambda v <$> seqRewrite e seqRewrite (Apply (Apply (Lit (FunRefLit (FunRef "ohua.lang/seq" Nothing))) dep) expr) = do expr' <- seqRewrite expr ctrl <- generateBindingWith "ctrl" expr'' <- liftIntoCtrlCtxt ctrl expr' TODO verify that this arg is actually ( ) let ((_:[]), expr''') = lambdaArgsAndBody expr'' result <- generateBindingWith "result" return $ Let ctrl (Apply seqFunSf dep) $ Let result expr''' $ Var result seqRewrite e = return e
37dda189e6f0a273710de77e4a2974befcc973e106dff85bf691bf77531c4b36
RefactoringTools/HaRe
HsKindPretty.hs
-- Pretty printing for the K functor -- module HsKindPretty where import PrettyPrint import HsKindStruct import PrettySymbols instance Printable x => Printable (K x) where ppi (Kfun k1 k2) = wrap k1 <> rarrow <> k2 ppi k = wrap k wrap Kstar = star wrap Kpred = moon wrap Kprop = kw "P" wrap k = parens (ppi k)
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/AST/HsKindPretty.hs
haskell
Pretty printing for the K functor --
module HsKindPretty where import PrettyPrint import HsKindStruct import PrettySymbols instance Printable x => Printable (K x) where ppi (Kfun k1 k2) = wrap k1 <> rarrow <> k2 ppi k = wrap k wrap Kstar = star wrap Kpred = moon wrap Kprop = kw "P" wrap k = parens (ppi k)
25879732a880a298a2ba7e973de00a4ddd5983d4b0450218be4ac877b16741d0
mput/sicp-solutions
1_23.test.rkt
#lang racket (require rackunit/text-ui) (require rackunit "../solutions/1_23.rkt") (define better-prime?-test (test-suite "Test for (better-prime?)" (test-case "Tests for truzy" (check-true (better-prime? 7)) (check-true (better-prime? 199)) (check-true (better-prime? 900307))) (test-case "Tests for falsy" (check-false (better-prime? 19999)) (check-false (better-prime? 15)) (check-false (better-prime? 900309))))) (run-tests better-prime?-test 'verbose)
null
https://raw.githubusercontent.com/mput/sicp-solutions/fe12ad2b6f17c99978c8fe04b2495005986b8496/tests/1_23.test.rkt
racket
#lang racket (require rackunit/text-ui) (require rackunit "../solutions/1_23.rkt") (define better-prime?-test (test-suite "Test for (better-prime?)" (test-case "Tests for truzy" (check-true (better-prime? 7)) (check-true (better-prime? 199)) (check-true (better-prime? 900307))) (test-case "Tests for falsy" (check-false (better-prime? 19999)) (check-false (better-prime? 15)) (check-false (better-prime? 900309))))) (run-tests better-prime?-test 'verbose)
6cbae0dcfa213b708bccbb232d95e9d446a530547336ae7a7fc9e5b29d975c1a
hdgarrood/qq-literals
Spec.hs
# LANGUAGE QuasiQuotes # import Spec.Example (uri) import Network.URI (URI(..)) main :: IO () main = do let exampleDotCom = [uri||] putStrLn ("scheme: " ++ uriScheme exampleDotCom) putStrLn ("authority: " ++ show (uriAuthority exampleDotCom)) putStrLn ("path: " ++ uriPath exampleDotCom)
null
https://raw.githubusercontent.com/hdgarrood/qq-literals/19f3dfae03623b6ea6898096c1e6fa4cf1e749bb/test/Spec.hs
haskell
# LANGUAGE QuasiQuotes # import Spec.Example (uri) import Network.URI (URI(..)) main :: IO () main = do let exampleDotCom = [uri||] putStrLn ("scheme: " ++ uriScheme exampleDotCom) putStrLn ("authority: " ++ show (uriAuthority exampleDotCom)) putStrLn ("path: " ++ uriPath exampleDotCom)
bfbb5af71c4f986ecffeb55112328c3a629e66bbda7455896bccb1140bf8fcd6
GaloisInc/daedalus
Layout.hs
{-# Language OverloadedStrings #-} module Daedalus.Parser.Layout where import Daedalus.Parser.Tokens import AlexTools virtual :: Token -> Lexeme Token -> Lexeme Token virtual t l = l { lexemeToken = t, lexemeText = "" } layout :: [Lexeme Token] -> [Lexeme Token] layout tokIn = go False [] (error "Last token") tokIn where dbg = [ trace ( show ( lexemeToken x ) ) x | x < - toks ] col = sourceColumn . sourceFrom . lexemeRange startBlock t next = case lexemeToken t of KWOf | nonBrace -> True KWChoose | nonBrace -> True KWFirst -> True KWblock -> True KWWhere -> True KWstruct -> True KWunion -> True _ -> False where nonBrace = case next of Lexeme { lexemeToken = OpenBrace } : _ -> False _ -> True isEOF t = case lexemeToken t of TokEOF -> True _ -> False go first stack lastTok toks = case stack of c : cs -> case toks of [] -> virtual VClose lastTok : go first cs lastTok toks t : ts | col t < c || isEOF t -> virtual VClose t : go False cs lastTok toks | not first && col t == c -> virtual VSemi t : emitTok stack t ts | otherwise -> emitTok stack t ts [] -> case toks of [] -> [] t : ts -> emitTok stack t ts emitTok stack t ts = t : checkStrtBlock stack t ts checkStrtBlock stack t toks | startBlock t toks = virtual VOpen t : go True (newBlock : stack) t toks | otherwise = go False stack t toks where newBlock = case toks of [] -> col t t1 : _ -> col t1
null
https://raw.githubusercontent.com/GaloisInc/daedalus/036a79404cb2cac266aa54dd9820280616724c33/src/Daedalus/Parser/Layout.hs
haskell
# Language OverloadedStrings #
module Daedalus.Parser.Layout where import Daedalus.Parser.Tokens import AlexTools virtual :: Token -> Lexeme Token -> Lexeme Token virtual t l = l { lexemeToken = t, lexemeText = "" } layout :: [Lexeme Token] -> [Lexeme Token] layout tokIn = go False [] (error "Last token") tokIn where dbg = [ trace ( show ( lexemeToken x ) ) x | x < - toks ] col = sourceColumn . sourceFrom . lexemeRange startBlock t next = case lexemeToken t of KWOf | nonBrace -> True KWChoose | nonBrace -> True KWFirst -> True KWblock -> True KWWhere -> True KWstruct -> True KWunion -> True _ -> False where nonBrace = case next of Lexeme { lexemeToken = OpenBrace } : _ -> False _ -> True isEOF t = case lexemeToken t of TokEOF -> True _ -> False go first stack lastTok toks = case stack of c : cs -> case toks of [] -> virtual VClose lastTok : go first cs lastTok toks t : ts | col t < c || isEOF t -> virtual VClose t : go False cs lastTok toks | not first && col t == c -> virtual VSemi t : emitTok stack t ts | otherwise -> emitTok stack t ts [] -> case toks of [] -> [] t : ts -> emitTok stack t ts emitTok stack t ts = t : checkStrtBlock stack t ts checkStrtBlock stack t toks | startBlock t toks = virtual VOpen t : go True (newBlock : stack) t toks | otherwise = go False stack t toks where newBlock = case toks of [] -> col t t1 : _ -> col t1
587b30b5414415cbc6543b99bd68ac89b6ca63c96ebee7f53591e59ed7661a84
magnusjonsson/unitc
Unit.hs
module Unit where import Prelude hiding (div, recip) import Data.Ratio import Data.List as List import Data.Map.Strict as Map type Q = Ratio Integer newtype Unit = Unit (Map String Q) deriving (Eq) nonzero :: Q -> Maybe Q nonzero 0 = Nothing nonzero x = Just x one :: Unit one = Unit Map.empty fundamental :: String -> Unit fundamental name = Unit (Map.singleton name 1) mul :: Unit -> Unit -> Unit mul (Unit u1) (Unit u2) = Unit (Map.mergeWithKey (\_k p1 p2 -> nonzero (p1 + p2)) id id u1 u2) recip :: Unit -> Unit recip (Unit u) = Unit (Map.map negate u) div :: Unit -> Unit -> Unit div (Unit u1) (Unit u2) = Unit (Map.mergeWithKey (\_k p1 p2 -> nonzero (p1 - p2)) id (Map.map negate) u1 u2) pow :: Unit -> Q -> Unit pow (Unit u) q = Unit (Map.map (q *) u) sqrt :: Unit -> Unit sqrt u = pow u (1%2) instance Show Unit where show (Unit u) = let (positive, negative) = List.partition (\(k,p) -> p >= 0) (Map.toList u) in (if List.null positive then "1" else intercalate " * " (List.map (\ (k, p) -> showPower k p) positive) ) ++ List.concatMap (\ (k, p) -> " / " ++ showPower k (-p)) negative showPower :: String -> Q -> String showPower name power = case (numerator power, denominator power) of (1, 1) -> name (n, 1) -> name ++ "**" ++ show n (n, d) -> name ++ "**(" ++ show n ++ "/" ++ show d ++ ")"
null
https://raw.githubusercontent.com/magnusjonsson/unitc/9b837d87b9ea4ebc430b1c5572346818080b7e49/app/Unit.hs
haskell
module Unit where import Prelude hiding (div, recip) import Data.Ratio import Data.List as List import Data.Map.Strict as Map type Q = Ratio Integer newtype Unit = Unit (Map String Q) deriving (Eq) nonzero :: Q -> Maybe Q nonzero 0 = Nothing nonzero x = Just x one :: Unit one = Unit Map.empty fundamental :: String -> Unit fundamental name = Unit (Map.singleton name 1) mul :: Unit -> Unit -> Unit mul (Unit u1) (Unit u2) = Unit (Map.mergeWithKey (\_k p1 p2 -> nonzero (p1 + p2)) id id u1 u2) recip :: Unit -> Unit recip (Unit u) = Unit (Map.map negate u) div :: Unit -> Unit -> Unit div (Unit u1) (Unit u2) = Unit (Map.mergeWithKey (\_k p1 p2 -> nonzero (p1 - p2)) id (Map.map negate) u1 u2) pow :: Unit -> Q -> Unit pow (Unit u) q = Unit (Map.map (q *) u) sqrt :: Unit -> Unit sqrt u = pow u (1%2) instance Show Unit where show (Unit u) = let (positive, negative) = List.partition (\(k,p) -> p >= 0) (Map.toList u) in (if List.null positive then "1" else intercalate " * " (List.map (\ (k, p) -> showPower k p) positive) ) ++ List.concatMap (\ (k, p) -> " / " ++ showPower k (-p)) negative showPower :: String -> Q -> String showPower name power = case (numerator power, denominator power) of (1, 1) -> name (n, 1) -> name ++ "**" ++ show n (n, d) -> name ++ "**(" ++ show n ++ "/" ++ show d ++ ")"
69fe7eadcf6710c60d52a38b97b8295440ded063138c46a97abbe6e6c9225af1
openbadgefactory/salava
handler.clj
(ns salava.core.handler (:import (java.io FileNotFoundException)) (:require [clojure.tools.logging :as log] [compojure.api.sweet :refer :all] [compojure.route :as route] [salava.core.session :refer [wrap-app-session]] [salava.core.util :refer [get-base-path get-data-dir]] [salava.core.routes :refer [legacy-routes]] [salava.core.helper :refer [dump plugin-str]] [slingshot.slingshot :refer :all] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.flash :refer [wrap-flash]] [ring.middleware.session.cookie :refer [cookie-store]] [ring.middleware.webjars :refer [wrap-webjars]])) (defn- get-route-def [ctx plugin] (let [nspace (symbol (str "salava." (clojure.string/replace (plugin-str plugin) #"/" ".") ".routes"))] (if (try (require nspace :reload) true (catch FileNotFoundException _ false)) ((get (ns-map nspace) 'route-def) ctx) (log/info (str "no routes in plugin " plugin))))) (defn- resolve-routes [ctx] (apply routes (map (fn [p] (get-route-def ctx p)) (conj (get-in ctx [:config :core :plugins]) :core)))) (defn ignore-trailing-slash "Modifies the request uri before calling the handler. Removes a single trailing slash from the end of the uri if present. Useful for handling optional trailing slashes until Compojure's route matching syntax supports regex. Adapted from -regex-for-matching-a-trailing-slash" [handler] (fn [request] (let [uri (:uri request)] (handler (assoc request :uri (if (and (not (= "/" uri)) (.endsWith uri "/")) (subs uri 0 (dec (count uri))) uri)))))) (defn remove-x-frame-options [handler] "Remove X-Frame-Options header if route ends with '/embed'" (fn [request] (let [uri (:uri request)] (if-let [response (handler request)] (if (re-find (re-pattern "/embed$") (str uri)) (update-in response [:headers] dissoc "X-Frame-Options") response))))) (defn wrap-middlewares [ctx routes] (let [config (get-in ctx [:config :core])] (-> routes (ignore-trailing-slash) (wrap-webjars) (wrap-defaults (-> site-defaults (assoc-in [:security :anti-forgery] false) (assoc-in [:session] false) (assoc-in [:responses :absolute-redirects] false) ;; Disabled for OAuth2 custom redirect_uri schemes (assoc-in [:static :files] (get-data-dir ctx)))) (remove-x-frame-options) (wrap-flash) (wrap-app-session config)))) (defn handler [ctx] (let [main-routes (resolve-routes ctx)] (wrap-middlewares ctx (api (swagger-routes {:ui "/swagger-ui" :info {:version "0.1.0" :title "Salava REST API" :description "" :contact {:name "Discendum Oy" :email "" :url ""} :license {:name "Apache 2.0" :url "-2.0"}} :tags [{:name "badge", :description "plugin"} {:name "file", :description "plugin"} {:name "gallery", :description "plugin"} {:name "page", :description "plugin"} {:name "translator", :description "plugin"} {:name "user", :description "plugin"}]}) (context (get-base-path ctx) [] main-routes) (legacy-routes ctx) (ANY "*" [] (route/not-found "404 Not found"))))))
null
https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/src/clj/salava/core/handler.clj
clojure
Disabled for OAuth2 custom redirect_uri schemes
(ns salava.core.handler (:import (java.io FileNotFoundException)) (:require [clojure.tools.logging :as log] [compojure.api.sweet :refer :all] [compojure.route :as route] [salava.core.session :refer [wrap-app-session]] [salava.core.util :refer [get-base-path get-data-dir]] [salava.core.routes :refer [legacy-routes]] [salava.core.helper :refer [dump plugin-str]] [slingshot.slingshot :refer :all] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] [ring.middleware.session :refer [wrap-session]] [ring.middleware.flash :refer [wrap-flash]] [ring.middleware.session.cookie :refer [cookie-store]] [ring.middleware.webjars :refer [wrap-webjars]])) (defn- get-route-def [ctx plugin] (let [nspace (symbol (str "salava." (clojure.string/replace (plugin-str plugin) #"/" ".") ".routes"))] (if (try (require nspace :reload) true (catch FileNotFoundException _ false)) ((get (ns-map nspace) 'route-def) ctx) (log/info (str "no routes in plugin " plugin))))) (defn- resolve-routes [ctx] (apply routes (map (fn [p] (get-route-def ctx p)) (conj (get-in ctx [:config :core :plugins]) :core)))) (defn ignore-trailing-slash "Modifies the request uri before calling the handler. Removes a single trailing slash from the end of the uri if present. Useful for handling optional trailing slashes until Compojure's route matching syntax supports regex. Adapted from -regex-for-matching-a-trailing-slash" [handler] (fn [request] (let [uri (:uri request)] (handler (assoc request :uri (if (and (not (= "/" uri)) (.endsWith uri "/")) (subs uri 0 (dec (count uri))) uri)))))) (defn remove-x-frame-options [handler] "Remove X-Frame-Options header if route ends with '/embed'" (fn [request] (let [uri (:uri request)] (if-let [response (handler request)] (if (re-find (re-pattern "/embed$") (str uri)) (update-in response [:headers] dissoc "X-Frame-Options") response))))) (defn wrap-middlewares [ctx routes] (let [config (get-in ctx [:config :core])] (-> routes (ignore-trailing-slash) (wrap-webjars) (wrap-defaults (-> site-defaults (assoc-in [:security :anti-forgery] false) (assoc-in [:session] false) (assoc-in [:static :files] (get-data-dir ctx)))) (remove-x-frame-options) (wrap-flash) (wrap-app-session config)))) (defn handler [ctx] (let [main-routes (resolve-routes ctx)] (wrap-middlewares ctx (api (swagger-routes {:ui "/swagger-ui" :info {:version "0.1.0" :title "Salava REST API" :description "" :contact {:name "Discendum Oy" :email "" :url ""} :license {:name "Apache 2.0" :url "-2.0"}} :tags [{:name "badge", :description "plugin"} {:name "file", :description "plugin"} {:name "gallery", :description "plugin"} {:name "page", :description "plugin"} {:name "translator", :description "plugin"} {:name "user", :description "plugin"}]}) (context (get-base-path ctx) [] main-routes) (legacy-routes ctx) (ANY "*" [] (route/not-found "404 Not found"))))))
3ea0fb95005de40381a327190fcca4729447809a7a8534b88e79bec7aab278bf
patricoferris/ocaml-multicore-monorepo
test_date.ml
--------------------------------------------------------------------------- Copyright ( c ) 2015 The ptime programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2015 The ptime programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) open Testing open Testing_ptime let stamp_of_date_time d = (Ptime.of_date_time $ raw_date_time @-> ret_get_option stamp) d let valid_date d = ignore ((Ptime.of_date $ raw_date @-> ret_some stamp) d) let wrong_date d = ignore ((Ptime.of_date $ raw_date @-> ret_none stamp) d) let bounds = test "Testing calendar date field bounds" @@ fun () -> (* Check year bounds *) wrong_date (-1, 01, 01); valid_date (0, 01, 01); valid_date (1, 01, 01); valid_date (9999, 01, 01); wrong_date (10000, 01, 01); wrong_date (10001, 01, 01); (* Check month bounds *) wrong_date (0, 00, 01); valid_date (0, 01, 01); valid_date (0, 12, 01); wrong_date (0, 13, 01); Check day bounds in 2015 ( month lengths ) Jan 2015 wrong_date (2015, 01, -1); valid_date (2015, 01, 01); valid_date (2015, 01, 31); wrong_date (2015, 01, 32); Feb 2015 , is not leap wrong_date (2015, 02, -1); valid_date (2015, 02, 01); valid_date (2015, 02, 28); wrong_date (2015, 02, 29); Mar 2015 wrong_date (2015, 03, -1); valid_date (2015, 03, 01); valid_date (2015, 03, 31); wrong_date (2015, 03, 32); Apr 2015 wrong_date (2015, 04, -1); valid_date (2015, 04, 01); valid_date (2015, 04, 30); wrong_date (2015, 04, 31); May 2015 wrong_date (2015, 05, -1); valid_date (2015, 05, 01); valid_date (2015, 05, 31); wrong_date (2015, 05, 32); June 2015 wrong_date (2015, 06, -1); valid_date (2015, 06, 01); valid_date (2015, 06, 30); wrong_date (2015, 06, 31); July 2015 wrong_date (2015, 07, -1); valid_date (2015, 07, 01); valid_date (2015, 07, 31); wrong_date (2015, 07, 32); Aug 2015 wrong_date (2015, 08, -1); valid_date (2015, 08, 01); valid_date (2015, 08, 31); wrong_date (2015, 08, 32); Sept 2015 wrong_date (2015, 09, -1); valid_date (2015, 09, 01); valid_date (2015, 09, 30); wrong_date (2015, 09, 31); Oct 2015 wrong_date (2015, 10, -1); valid_date (2015, 10, 01); valid_date (2015, 10, 31); wrong_date (2015, 10, 32); Nov 2015 wrong_date (2015, 11, -1); valid_date (2015, 11, 01); valid_date (2015, 11, 30); wrong_date (2015, 11, 31); Dec 2015 wrong_date (2015, 12, -1); valid_date (2015, 12, 01); valid_date (2015, 12, 31); wrong_date (2015, 12, 32); 1500 is not leap valid_date (1500, 02, 28); wrong_date (1500, 02, 29); (* 1700 is not leap *) valid_date (1700, 02, 28); wrong_date (1700, 02, 29); 1800 is not leap valid_date (1800, 02, 28); wrong_date (1800, 02, 29); 1900 is not leap , Lotus 1 - 2 - 3 & Excel bug valid_date (1900, 02, 28); wrong_date (1900, 02, 29); 2000 is leap valid_date (2000, 02, 28); valid_date (2000, 02, 29); wrong_date (2000, 02, 30); 2010 is not leap valid_date (2010, 02, 28); wrong_date (2010, 02, 29); 2012 is leap valid_date (2012, 02, 29); valid_date (2012, 02, 29); wrong_date (2012, 02, 30); (* 2100 is not leap *) valid_date (2100, 02, 28); wrong_date (2100, 02, 29); () let stamp_trips = test "Random valid dates to stamps round trips" @@ fun () -> let of_date = Ptime.of_date $ raw_date @-> ret_get_option stamp in for i = 1 to Test_rand.loop_len () do let date = Test_rand.date () in let trip = Ptime.to_date (of_date date) in eq_date date trip done; () let suite = suite "Ptime date tests" [ bounds; stamp_trips; ] --------------------------------------------------------------------------- Copyright ( c ) 2015 The ptime programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2015 The ptime programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/ptime/test/test_date.ml
ocaml
Check year bounds Check month bounds 1700 is not leap 2100 is not leap
--------------------------------------------------------------------------- Copyright ( c ) 2015 The ptime programmers . All rights reserved . Distributed under the ISC license , see terms at the end of the file . % % NAME%% % % --------------------------------------------------------------------------- Copyright (c) 2015 The ptime programmers. All rights reserved. Distributed under the ISC license, see terms at the end of the file. %%NAME%% %%VERSION%% ---------------------------------------------------------------------------*) open Testing open Testing_ptime let stamp_of_date_time d = (Ptime.of_date_time $ raw_date_time @-> ret_get_option stamp) d let valid_date d = ignore ((Ptime.of_date $ raw_date @-> ret_some stamp) d) let wrong_date d = ignore ((Ptime.of_date $ raw_date @-> ret_none stamp) d) let bounds = test "Testing calendar date field bounds" @@ fun () -> wrong_date (-1, 01, 01); valid_date (0, 01, 01); valid_date (1, 01, 01); valid_date (9999, 01, 01); wrong_date (10000, 01, 01); wrong_date (10001, 01, 01); wrong_date (0, 00, 01); valid_date (0, 01, 01); valid_date (0, 12, 01); wrong_date (0, 13, 01); Check day bounds in 2015 ( month lengths ) Jan 2015 wrong_date (2015, 01, -1); valid_date (2015, 01, 01); valid_date (2015, 01, 31); wrong_date (2015, 01, 32); Feb 2015 , is not leap wrong_date (2015, 02, -1); valid_date (2015, 02, 01); valid_date (2015, 02, 28); wrong_date (2015, 02, 29); Mar 2015 wrong_date (2015, 03, -1); valid_date (2015, 03, 01); valid_date (2015, 03, 31); wrong_date (2015, 03, 32); Apr 2015 wrong_date (2015, 04, -1); valid_date (2015, 04, 01); valid_date (2015, 04, 30); wrong_date (2015, 04, 31); May 2015 wrong_date (2015, 05, -1); valid_date (2015, 05, 01); valid_date (2015, 05, 31); wrong_date (2015, 05, 32); June 2015 wrong_date (2015, 06, -1); valid_date (2015, 06, 01); valid_date (2015, 06, 30); wrong_date (2015, 06, 31); July 2015 wrong_date (2015, 07, -1); valid_date (2015, 07, 01); valid_date (2015, 07, 31); wrong_date (2015, 07, 32); Aug 2015 wrong_date (2015, 08, -1); valid_date (2015, 08, 01); valid_date (2015, 08, 31); wrong_date (2015, 08, 32); Sept 2015 wrong_date (2015, 09, -1); valid_date (2015, 09, 01); valid_date (2015, 09, 30); wrong_date (2015, 09, 31); Oct 2015 wrong_date (2015, 10, -1); valid_date (2015, 10, 01); valid_date (2015, 10, 31); wrong_date (2015, 10, 32); Nov 2015 wrong_date (2015, 11, -1); valid_date (2015, 11, 01); valid_date (2015, 11, 30); wrong_date (2015, 11, 31); Dec 2015 wrong_date (2015, 12, -1); valid_date (2015, 12, 01); valid_date (2015, 12, 31); wrong_date (2015, 12, 32); 1500 is not leap valid_date (1500, 02, 28); wrong_date (1500, 02, 29); valid_date (1700, 02, 28); wrong_date (1700, 02, 29); 1800 is not leap valid_date (1800, 02, 28); wrong_date (1800, 02, 29); 1900 is not leap , Lotus 1 - 2 - 3 & Excel bug valid_date (1900, 02, 28); wrong_date (1900, 02, 29); 2000 is leap valid_date (2000, 02, 28); valid_date (2000, 02, 29); wrong_date (2000, 02, 30); 2010 is not leap valid_date (2010, 02, 28); wrong_date (2010, 02, 29); 2012 is leap valid_date (2012, 02, 29); valid_date (2012, 02, 29); wrong_date (2012, 02, 30); valid_date (2100, 02, 28); wrong_date (2100, 02, 29); () let stamp_trips = test "Random valid dates to stamps round trips" @@ fun () -> let of_date = Ptime.of_date $ raw_date @-> ret_get_option stamp in for i = 1 to Test_rand.loop_len () do let date = Test_rand.date () in let trip = Ptime.to_date (of_date date) in eq_date date trip done; () let suite = suite "Ptime date tests" [ bounds; stamp_trips; ] --------------------------------------------------------------------------- Copyright ( c ) 2015 The ptime programmers Permission to use , copy , modify , and/or distribute this software for any purpose with or without fee is hereby granted , provided that the above copyright notice and this permission notice appear in all copies . THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . --------------------------------------------------------------------------- Copyright (c) 2015 The ptime programmers Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---------------------------------------------------------------------------*)
17769c358abaf4ad0967ddd9994a44f530c03ba09927fa05b2a043e2fd3eab20
GaloisInc/HaNS
Packet.hs
# LANGUAGE RecordWildCards # module Tests.IP4.Packet where import Tests.Ethernet (arbitraryMac) import Tests.Network (arbitraryProtocol) import Tests.Utils (encodeDecodeIdentity,showReadIdentity) import Hans.IP4.Packet import Hans.Lens import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Short as Sh import Data.Word (Word8) import Test.QuickCheck import Test.Tasty (testGroup,TestTree) import Test.Tasty.QuickCheck (testProperty) Packet Generator Support ---------------------------------------------------- arbitraryIP4 :: Gen IP4 arbitraryIP4 = do a <- arbitraryBoundedRandom b <- arbitraryBoundedRandom c <- arbitraryBoundedRandom d <- arbitraryBoundedRandom return $! packIP4 a b c d arbitraryIP4Mask :: Gen IP4Mask arbitraryIP4Mask = do addr <- arbitraryIP4 bits <- choose (0,32) return (IP4Mask addr bits) arbitraryIdent :: Gen IP4Ident arbitraryIdent = arbitraryBoundedRandom arbitraryPayload :: Int -> Gen L.ByteString arbitraryPayload len = do bytes <- vectorOf len arbitraryBoundedRandom return (L.pack bytes) arbitraryOptionPayload :: Word8 -> Gen Sh.ShortByteString arbitraryOptionPayload len = do bytes <- vectorOf (fromIntegral len) arbitraryBoundedRandom return (Sh.pack bytes) arbitraryIP4Header :: Gen IP4Header arbitraryIP4Header = do ip4TypeOfService <- arbitraryBoundedRandom ip4Ident <- arbitraryIdent ip4TimeToLive <- arbitraryBoundedRandom ip4Protocol <- arbitraryProtocol ip4SourceAddr <- arbitraryIP4 ip4DestAddr <- arbitraryIP4 -- checksum processing is validated by a different property let ip4Checksum = 0 XXX need to generate options that fit within the additional 40 bytes -- available let ip4Options = [] -- set the members of the ip4Fragment_ field on the final header df <- arbitraryBoundedRandom mf <- arbitraryBoundedRandom off <- choose (0,0x1fff) let hdr = IP4Header { ip4Fragment_ = 0, .. } return $! set ip4DontFragment df $! set ip4MoreFragments mf $! set ip4FragmentOffset off hdr arbitraryIP4Option :: Gen IP4Option arbitraryIP4Option = do ip4OptionCopied <- arbitraryBoundedRandom ip4OptionClass <- choose (0,0x3) ip4OptionNum <- choose (0,0x1f) ip4OptionData <- if ip4OptionNum < 2 then return Sh.empty else do len <- choose (0, 0xff - 2) arbitraryOptionPayload len return IP4Option { .. } arbitraryArpPacket :: Gen ArpPacket arbitraryArpPacket = do arpOper <- elements [ArpRequest,ArpReply] arpSHA <- arbitraryMac arpSPA <- arbitraryIP4 arpTHA <- arbitraryMac arpTPA <- arbitraryIP4 return ArpPacket { .. } -- Packet Properties ----------------------------------------------------------- packetTests :: TestTree packetTests = testGroup "Packet" [ testProperty "IP4 Address encode/decode" $ encodeDecodeIdentity putIP4 getIP4 arbitraryIP4 , let get = do (hdr,20,0) <- getIP4Packet return hdr put hdr = putIP4Header hdr 0 in testProperty "Header encode/decode" $ encodeDecodeIdentity put get arbitraryIP4Header , testProperty "Option encode/decode" $ encodeDecodeIdentity putIP4Option getIP4Option arbitraryIP4Option , testProperty "Arp Message encode/decode" $ encodeDecodeIdentity putArpPacket getArpPacket arbitraryArpPacket , testProperty "IP4 Addr read/show" $ showReadIdentity showIP4 readIP4 arbitraryIP4 , testProperty "IP4 Mask read/show" $ showReadIdentity showIP4Mask readIP4Mask arbitraryIP4Mask ]
null
https://raw.githubusercontent.com/GaloisInc/HaNS/2af19397dbb4f828192f896b223ed2b77dd9a055/tests/Tests/IP4/Packet.hs
haskell
-------------------------------------------------- checksum processing is validated by a different property available set the members of the ip4Fragment_ field on the final header Packet Properties -----------------------------------------------------------
# LANGUAGE RecordWildCards # module Tests.IP4.Packet where import Tests.Ethernet (arbitraryMac) import Tests.Network (arbitraryProtocol) import Tests.Utils (encodeDecodeIdentity,showReadIdentity) import Hans.IP4.Packet import Hans.Lens import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Short as Sh import Data.Word (Word8) import Test.QuickCheck import Test.Tasty (testGroup,TestTree) import Test.Tasty.QuickCheck (testProperty) arbitraryIP4 :: Gen IP4 arbitraryIP4 = do a <- arbitraryBoundedRandom b <- arbitraryBoundedRandom c <- arbitraryBoundedRandom d <- arbitraryBoundedRandom return $! packIP4 a b c d arbitraryIP4Mask :: Gen IP4Mask arbitraryIP4Mask = do addr <- arbitraryIP4 bits <- choose (0,32) return (IP4Mask addr bits) arbitraryIdent :: Gen IP4Ident arbitraryIdent = arbitraryBoundedRandom arbitraryPayload :: Int -> Gen L.ByteString arbitraryPayload len = do bytes <- vectorOf len arbitraryBoundedRandom return (L.pack bytes) arbitraryOptionPayload :: Word8 -> Gen Sh.ShortByteString arbitraryOptionPayload len = do bytes <- vectorOf (fromIntegral len) arbitraryBoundedRandom return (Sh.pack bytes) arbitraryIP4Header :: Gen IP4Header arbitraryIP4Header = do ip4TypeOfService <- arbitraryBoundedRandom ip4Ident <- arbitraryIdent ip4TimeToLive <- arbitraryBoundedRandom ip4Protocol <- arbitraryProtocol ip4SourceAddr <- arbitraryIP4 ip4DestAddr <- arbitraryIP4 let ip4Checksum = 0 XXX need to generate options that fit within the additional 40 bytes let ip4Options = [] df <- arbitraryBoundedRandom mf <- arbitraryBoundedRandom off <- choose (0,0x1fff) let hdr = IP4Header { ip4Fragment_ = 0, .. } return $! set ip4DontFragment df $! set ip4MoreFragments mf $! set ip4FragmentOffset off hdr arbitraryIP4Option :: Gen IP4Option arbitraryIP4Option = do ip4OptionCopied <- arbitraryBoundedRandom ip4OptionClass <- choose (0,0x3) ip4OptionNum <- choose (0,0x1f) ip4OptionData <- if ip4OptionNum < 2 then return Sh.empty else do len <- choose (0, 0xff - 2) arbitraryOptionPayload len return IP4Option { .. } arbitraryArpPacket :: Gen ArpPacket arbitraryArpPacket = do arpOper <- elements [ArpRequest,ArpReply] arpSHA <- arbitraryMac arpSPA <- arbitraryIP4 arpTHA <- arbitraryMac arpTPA <- arbitraryIP4 return ArpPacket { .. } packetTests :: TestTree packetTests = testGroup "Packet" [ testProperty "IP4 Address encode/decode" $ encodeDecodeIdentity putIP4 getIP4 arbitraryIP4 , let get = do (hdr,20,0) <- getIP4Packet return hdr put hdr = putIP4Header hdr 0 in testProperty "Header encode/decode" $ encodeDecodeIdentity put get arbitraryIP4Header , testProperty "Option encode/decode" $ encodeDecodeIdentity putIP4Option getIP4Option arbitraryIP4Option , testProperty "Arp Message encode/decode" $ encodeDecodeIdentity putArpPacket getArpPacket arbitraryArpPacket , testProperty "IP4 Addr read/show" $ showReadIdentity showIP4 readIP4 arbitraryIP4 , testProperty "IP4 Mask read/show" $ showReadIdentity showIP4Mask readIP4Mask arbitraryIP4Mask ]
78042bdbd9e063ce2de828f89fcd0d3957af3b39967a32c5b0d2ffdf84314c6a
marcoonroad/hieroglyphs
bench.ml
open Core_bench.Bench module Command = Core.Command let suite = Hiero.suite @ Rsa_pss.suite @ Secp.suite let _ = Command.run (make_command suite)
null
https://raw.githubusercontent.com/marcoonroad/hieroglyphs/03050bcf78b2871591752a696a16587989065163/test/bench/bench.ml
ocaml
open Core_bench.Bench module Command = Core.Command let suite = Hiero.suite @ Rsa_pss.suite @ Secp.suite let _ = Command.run (make_command suite)
7587995b71ddfdbb4a9a9226bd2146ddf626d98eadf68b1f322e5ae6af040f7e
processone/ejabberd
mod_push_opt.erl
%% Generated automatically %% DO NOT EDIT: run `make options` instead -module(mod_push_opt). -export([cache_life_time/1]). -export([cache_missed/1]). -export([cache_size/1]). -export([db_type/1]). -export([include_body/1]). -export([include_sender/1]). -export([use_cache/1]). -spec cache_life_time(gen_mod:opts() | global | binary()) -> 'infinity' | pos_integer(). cache_life_time(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_life_time, Opts); cache_life_time(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_life_time). -spec cache_missed(gen_mod:opts() | global | binary()) -> boolean(). cache_missed(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_missed, Opts); cache_missed(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_missed). -spec cache_size(gen_mod:opts() | global | binary()) -> 'infinity' | pos_integer(). cache_size(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_size, Opts); cache_size(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_size). -spec db_type(gen_mod:opts() | global | binary()) -> atom(). db_type(Opts) when is_map(Opts) -> gen_mod:get_opt(db_type, Opts); db_type(Host) -> gen_mod:get_module_opt(Host, mod_push, db_type). -spec include_body(gen_mod:opts() | global | binary()) -> boolean() | binary(). include_body(Opts) when is_map(Opts) -> gen_mod:get_opt(include_body, Opts); include_body(Host) -> gen_mod:get_module_opt(Host, mod_push, include_body). -spec include_sender(gen_mod:opts() | global | binary()) -> boolean(). include_sender(Opts) when is_map(Opts) -> gen_mod:get_opt(include_sender, Opts); include_sender(Host) -> gen_mod:get_module_opt(Host, mod_push, include_sender). -spec use_cache(gen_mod:opts() | global | binary()) -> boolean(). use_cache(Opts) when is_map(Opts) -> gen_mod:get_opt(use_cache, Opts); use_cache(Host) -> gen_mod:get_module_opt(Host, mod_push, use_cache).
null
https://raw.githubusercontent.com/processone/ejabberd/b860a25c82515ba51b044e13ea4e040e3b9bbc41/src/mod_push_opt.erl
erlang
Generated automatically DO NOT EDIT: run `make options` instead
-module(mod_push_opt). -export([cache_life_time/1]). -export([cache_missed/1]). -export([cache_size/1]). -export([db_type/1]). -export([include_body/1]). -export([include_sender/1]). -export([use_cache/1]). -spec cache_life_time(gen_mod:opts() | global | binary()) -> 'infinity' | pos_integer(). cache_life_time(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_life_time, Opts); cache_life_time(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_life_time). -spec cache_missed(gen_mod:opts() | global | binary()) -> boolean(). cache_missed(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_missed, Opts); cache_missed(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_missed). -spec cache_size(gen_mod:opts() | global | binary()) -> 'infinity' | pos_integer(). cache_size(Opts) when is_map(Opts) -> gen_mod:get_opt(cache_size, Opts); cache_size(Host) -> gen_mod:get_module_opt(Host, mod_push, cache_size). -spec db_type(gen_mod:opts() | global | binary()) -> atom(). db_type(Opts) when is_map(Opts) -> gen_mod:get_opt(db_type, Opts); db_type(Host) -> gen_mod:get_module_opt(Host, mod_push, db_type). -spec include_body(gen_mod:opts() | global | binary()) -> boolean() | binary(). include_body(Opts) when is_map(Opts) -> gen_mod:get_opt(include_body, Opts); include_body(Host) -> gen_mod:get_module_opt(Host, mod_push, include_body). -spec include_sender(gen_mod:opts() | global | binary()) -> boolean(). include_sender(Opts) when is_map(Opts) -> gen_mod:get_opt(include_sender, Opts); include_sender(Host) -> gen_mod:get_module_opt(Host, mod_push, include_sender). -spec use_cache(gen_mod:opts() | global | binary()) -> boolean(). use_cache(Opts) when is_map(Opts) -> gen_mod:get_opt(use_cache, Opts); use_cache(Host) -> gen_mod:get_module_opt(Host, mod_push, use_cache).
6126784d56f4ddbf890b87ba9ad4b5e4e6854b3d6df75bdc5cb7be6f29db1831
simplegeo/erlang
typer_info.erl
-*- erlang - indent - level : 2 -*- %% %% %CopyrightBegin% %% Copyright Ericsson AB 2006 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(typer_info). -export([collect/1]). -type func_info() :: {non_neg_integer(), atom(), arity()}. -type inc_file_info() :: {string(), func_info()}. -record(tmpAcc, {file :: string(), module :: atom(), funcAcc=[] :: [func_info()], incFuncAcc=[] :: [inc_file_info()], dialyzerObj=[] :: [{mfa(), {_, _}}]}). -include("typer.hrl"). -spec collect(#typer_analysis{}) -> #typer_analysis{}. collect(Analysis) -> NewPlt = try get_dialyzer_plt(Analysis) of DialyzerPlt -> dialyzer_plt:merge_plts([Analysis#typer_analysis.trust_plt, DialyzerPlt]) catch throw:{dialyzer_error,_Reason} -> typer:error("Dialyzer's PLT is missing or is not up-to-date; please (re)create it") end, NewAnalysis = lists:foldl(fun collect_one_file_info/2, Analysis#typer_analysis{trust_plt = NewPlt}, Analysis#typer_analysis.ana_files), Process Remote Types TmpCServer = NewAnalysis#typer_analysis.code_server, NewCServer = try NewRecords = dialyzer_codeserver:get_temp_records(TmpCServer), OldRecords = dialyzer_plt:get_types(NewPlt), MergedRecords = dialyzer_utils:merge_records(NewRecords, OldRecords), io : format("Merged Records ~p",[MergedRecords ] ) , TmpCServer1 = dialyzer_codeserver:set_temp_records(MergedRecords, TmpCServer), TmpCServer2 = dialyzer_utils:process_record_remote_types(TmpCServer1), dialyzer_contracts:process_contract_remote_types(TmpCServer2) catch throw:{error, ErrorMsg} -> typer:error(ErrorMsg) end, NewAnalysis#typer_analysis{code_server = NewCServer}. collect_one_file_info(File, Analysis) -> Ds = [{d,Name,Val} || {Name,Val} <- Analysis#typer_analysis.macros], %% Current directory should also be included in "Includes". Includes = [filename:dirname(File)|Analysis#typer_analysis.includes], Is = [{i,Dir} || Dir <- Includes], Options = dialyzer_utils:src_compiler_opts() ++ Is ++ Ds, case dialyzer_utils:get_abstract_code_from_src(File, Options) of {error, Reason} -> io : format("File=~p\n , Options=~p\n , Error=~p\n " , [ File , Options , Reason ] ) , typer:compile_error(Reason); {ok, AbstractCode} -> case dialyzer_utils:get_core_from_abstract_code(AbstractCode, Options) of error -> typer:compile_error(["Could not get core erlang for "++File]); {ok, Core} -> case dialyzer_utils:get_record_and_type_info(AbstractCode) of {error, Reason} -> typer:compile_error([Reason]); {ok, Records} -> Mod = list_to_atom(filename:basename(File, ".erl")), case dialyzer_utils:get_spec_info(Mod, AbstractCode, Records) of {error, Reason} -> typer:compile_error([Reason]); {ok, SpecInfo} -> analyze_core_tree(Core, Records, SpecInfo, Analysis, File) end end end end. analyze_core_tree(Core, Records, SpecInfo, Analysis, File) -> Module = list_to_atom(filename:basename(File, ".erl")), TmpTree = cerl:from_records(Core), CS1 = Analysis#typer_analysis.code_server, NextLabel = dialyzer_codeserver:get_next_core_label(CS1), {Tree, NewLabel} = cerl_trees:label(TmpTree, NextLabel), CS2 = dialyzer_codeserver:insert(Module, Tree, CS1), CS3 = dialyzer_codeserver:set_next_core_label(NewLabel, CS2), CS4 = dialyzer_codeserver:store_temp_records(Module, Records, CS3), CS5 = dialyzer_codeserver:store_temp_contracts(Module, SpecInfo, CS4), Ex_Funcs = [{0,F,A} || {_,_,{F,A}} <- cerl:module_exports(Tree)], TmpCG = Analysis#typer_analysis.callgraph, CG = dialyzer_callgraph:scan_core_tree(Tree, TmpCG), Fun = fun analyze_one_function/2, All_Defs = cerl:module_defs(Tree), Acc = lists:foldl(Fun, #tmpAcc{file=File, module=Module}, All_Defs), Exported_FuncMap = typer_map:insert({File, Ex_Funcs}, Analysis#typer_analysis.ex_func), %% NOTE: we must sort all functions in the file which %% originate from this file by *numerical order* of lineNo Sorted_Functions = lists:keysort(1, Acc#tmpAcc.funcAcc), FuncMap = typer_map:insert({File, Sorted_Functions}, Analysis#typer_analysis.func), %% NOTE: However we do not need to sort functions %% which are imported from included files. IncFuncMap = typer_map:insert({File, Acc#tmpAcc.incFuncAcc}, Analysis#typer_analysis.inc_func), Final_Files = Analysis#typer_analysis.final_files ++ [{File, Module}], RecordMap = typer_map:insert({File, Records}, Analysis#typer_analysis.record), Analysis#typer_analysis{final_files=Final_Files, callgraph=CG, code_server=CS5, ex_func=Exported_FuncMap, inc_func=IncFuncMap, record=RecordMap, func=FuncMap}. analyze_one_function({Var, FunBody} = Function, Acc) -> F = cerl:fname_id(Var), A = cerl:fname_arity(Var), TmpDialyzerObj = {{Acc#tmpAcc.module, F, A}, Function}, NewDialyzerObj = Acc#tmpAcc.dialyzerObj ++ [TmpDialyzerObj], [_, LineNo, {file, FileName}] = cerl:get_ann(FunBody), BaseName = filename:basename(FileName), FuncInfo = {LineNo, F, A}, OriginalName = Acc#tmpAcc.file, {FuncAcc, IncFuncAcc} = case (FileName =:= OriginalName) orelse (BaseName =:= OriginalName) of true -> %% Coming from original file %% io:format("Added function ~p\n", [{LineNo, F, A}]), {Acc#tmpAcc.funcAcc ++ [FuncInfo], Acc#tmpAcc.incFuncAcc}; false -> %% Coming from other sourses, including: %% -- .yrl (yecc-generated file) %% -- yeccpre.hrl (yecc-generated file) %% -- other cases {Acc#tmpAcc.funcAcc, Acc#tmpAcc.incFuncAcc ++ [{FileName, FuncInfo}]} end, Acc#tmpAcc{funcAcc = FuncAcc, incFuncAcc = IncFuncAcc, dialyzerObj = NewDialyzerObj}. get_dialyzer_plt(#typer_analysis{plt = PltFile0}) -> PltFile = case PltFile0 =:= none of true -> dialyzer_plt:get_default_plt(); false -> PltFile0 end, dialyzer_plt:from_file(PltFile).
null
https://raw.githubusercontent.com/simplegeo/erlang/15eda8de27ba73d176c7eeb3a70a64167f50e2c4/lib/typer/src/typer_info.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% Current directory should also be included in "Includes". NOTE: we must sort all functions in the file which originate from this file by *numerical order* of lineNo NOTE: However we do not need to sort functions which are imported from included files. Coming from original file io:format("Added function ~p\n", [{LineNo, F, A}]), Coming from other sourses, including: -- .yrl (yecc-generated file) -- yeccpre.hrl (yecc-generated file) -- other cases
-*- erlang - indent - level : 2 -*- Copyright Ericsson AB 2006 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(typer_info). -export([collect/1]). -type func_info() :: {non_neg_integer(), atom(), arity()}. -type inc_file_info() :: {string(), func_info()}. -record(tmpAcc, {file :: string(), module :: atom(), funcAcc=[] :: [func_info()], incFuncAcc=[] :: [inc_file_info()], dialyzerObj=[] :: [{mfa(), {_, _}}]}). -include("typer.hrl"). -spec collect(#typer_analysis{}) -> #typer_analysis{}. collect(Analysis) -> NewPlt = try get_dialyzer_plt(Analysis) of DialyzerPlt -> dialyzer_plt:merge_plts([Analysis#typer_analysis.trust_plt, DialyzerPlt]) catch throw:{dialyzer_error,_Reason} -> typer:error("Dialyzer's PLT is missing or is not up-to-date; please (re)create it") end, NewAnalysis = lists:foldl(fun collect_one_file_info/2, Analysis#typer_analysis{trust_plt = NewPlt}, Analysis#typer_analysis.ana_files), Process Remote Types TmpCServer = NewAnalysis#typer_analysis.code_server, NewCServer = try NewRecords = dialyzer_codeserver:get_temp_records(TmpCServer), OldRecords = dialyzer_plt:get_types(NewPlt), MergedRecords = dialyzer_utils:merge_records(NewRecords, OldRecords), io : format("Merged Records ~p",[MergedRecords ] ) , TmpCServer1 = dialyzer_codeserver:set_temp_records(MergedRecords, TmpCServer), TmpCServer2 = dialyzer_utils:process_record_remote_types(TmpCServer1), dialyzer_contracts:process_contract_remote_types(TmpCServer2) catch throw:{error, ErrorMsg} -> typer:error(ErrorMsg) end, NewAnalysis#typer_analysis{code_server = NewCServer}. collect_one_file_info(File, Analysis) -> Ds = [{d,Name,Val} || {Name,Val} <- Analysis#typer_analysis.macros], Includes = [filename:dirname(File)|Analysis#typer_analysis.includes], Is = [{i,Dir} || Dir <- Includes], Options = dialyzer_utils:src_compiler_opts() ++ Is ++ Ds, case dialyzer_utils:get_abstract_code_from_src(File, Options) of {error, Reason} -> io : format("File=~p\n , Options=~p\n , Error=~p\n " , [ File , Options , Reason ] ) , typer:compile_error(Reason); {ok, AbstractCode} -> case dialyzer_utils:get_core_from_abstract_code(AbstractCode, Options) of error -> typer:compile_error(["Could not get core erlang for "++File]); {ok, Core} -> case dialyzer_utils:get_record_and_type_info(AbstractCode) of {error, Reason} -> typer:compile_error([Reason]); {ok, Records} -> Mod = list_to_atom(filename:basename(File, ".erl")), case dialyzer_utils:get_spec_info(Mod, AbstractCode, Records) of {error, Reason} -> typer:compile_error([Reason]); {ok, SpecInfo} -> analyze_core_tree(Core, Records, SpecInfo, Analysis, File) end end end end. analyze_core_tree(Core, Records, SpecInfo, Analysis, File) -> Module = list_to_atom(filename:basename(File, ".erl")), TmpTree = cerl:from_records(Core), CS1 = Analysis#typer_analysis.code_server, NextLabel = dialyzer_codeserver:get_next_core_label(CS1), {Tree, NewLabel} = cerl_trees:label(TmpTree, NextLabel), CS2 = dialyzer_codeserver:insert(Module, Tree, CS1), CS3 = dialyzer_codeserver:set_next_core_label(NewLabel, CS2), CS4 = dialyzer_codeserver:store_temp_records(Module, Records, CS3), CS5 = dialyzer_codeserver:store_temp_contracts(Module, SpecInfo, CS4), Ex_Funcs = [{0,F,A} || {_,_,{F,A}} <- cerl:module_exports(Tree)], TmpCG = Analysis#typer_analysis.callgraph, CG = dialyzer_callgraph:scan_core_tree(Tree, TmpCG), Fun = fun analyze_one_function/2, All_Defs = cerl:module_defs(Tree), Acc = lists:foldl(Fun, #tmpAcc{file=File, module=Module}, All_Defs), Exported_FuncMap = typer_map:insert({File, Ex_Funcs}, Analysis#typer_analysis.ex_func), Sorted_Functions = lists:keysort(1, Acc#tmpAcc.funcAcc), FuncMap = typer_map:insert({File, Sorted_Functions}, Analysis#typer_analysis.func), IncFuncMap = typer_map:insert({File, Acc#tmpAcc.incFuncAcc}, Analysis#typer_analysis.inc_func), Final_Files = Analysis#typer_analysis.final_files ++ [{File, Module}], RecordMap = typer_map:insert({File, Records}, Analysis#typer_analysis.record), Analysis#typer_analysis{final_files=Final_Files, callgraph=CG, code_server=CS5, ex_func=Exported_FuncMap, inc_func=IncFuncMap, record=RecordMap, func=FuncMap}. analyze_one_function({Var, FunBody} = Function, Acc) -> F = cerl:fname_id(Var), A = cerl:fname_arity(Var), TmpDialyzerObj = {{Acc#tmpAcc.module, F, A}, Function}, NewDialyzerObj = Acc#tmpAcc.dialyzerObj ++ [TmpDialyzerObj], [_, LineNo, {file, FileName}] = cerl:get_ann(FunBody), BaseName = filename:basename(FileName), FuncInfo = {LineNo, F, A}, OriginalName = Acc#tmpAcc.file, {FuncAcc, IncFuncAcc} = case (FileName =:= OriginalName) orelse (BaseName =:= OriginalName) of {Acc#tmpAcc.funcAcc ++ [FuncInfo], Acc#tmpAcc.incFuncAcc}; false -> {Acc#tmpAcc.funcAcc, Acc#tmpAcc.incFuncAcc ++ [{FileName, FuncInfo}]} end, Acc#tmpAcc{funcAcc = FuncAcc, incFuncAcc = IncFuncAcc, dialyzerObj = NewDialyzerObj}. get_dialyzer_plt(#typer_analysis{plt = PltFile0}) -> PltFile = case PltFile0 =:= none of true -> dialyzer_plt:get_default_plt(); false -> PltFile0 end, dialyzer_plt:from_file(PltFile).
52c3f1a3a407ac7c1fd95d14eeaacca2ccaff2abf4f7e04a262b3e4dfc28f280
NaaS/motto
crisp_type_annotation.ml
Serialisation - related annotations for types in , Cambridge University Computer Lab , March 2015 Use of this source code is governed by the Apache 2.0 license ; see LICENSE Serialisation-related annotations for types in Crisp Nik Sultana, Cambridge University Computer Lab, March 2015 Use of this source code is governed by the Apache 2.0 license; see LICENSE *) open General (*NOTE we allow the annotation to talk about a value that won't be used in the program -- but that will be represented in the input (and whose value is preserved in the output.) By this I mean things like anonymous field names that have type annotations -- being anonymous, we cannot read, use, or change their value in the program, since we have no way of referring to their value. Their value must be preserved however, if, say, we output the (possibly otherwise modified) record to the network. In order to indicate that a field is anonymous -- i.e., its value is not important to the program -- then we use dummy names in type specs -- such as in records, in which case the syntax is: type bla : record a : integer { ... } _ : integer # Anonymous field. { ... } b : integer { ... } *) type type_annotation_op = | Plus | Minus type type_annotation_kind = | Ann_Str of string | Ann_Int of int | Ann_Ident of string | Ann_BinaryExp of type_annotation_op * type_annotation_kind * type_annotation_kind type type_annotation = (string * type_annotation_kind) list let empty_type_annotation : type_annotation = [] let hadoop_vint_ann_key = "hadoop_vint" let true_ann_value = Ann_Ident "true" let is_hadoop_vint = List.exists (fun (k, v) -> k = hadoop_vint_ann_key && v = true_ann_value) let k_v_string indent (l, e) = let rec e_s e = match e with | Ann_Str s -> "\"" ^ s ^ "\"" | Ann_Int i -> string_of_int i | Ann_Ident s -> s | Ann_BinaryExp (op, e1, e2) -> let op_s = match op with | Plus -> "+" | Minus -> "-" in "(" ^ e_s e1 ^ ")" ^ op_s ^ "(" ^ e_s e2 ^ ")" in indn indent ^ l ^ " = " ^ e_s e let ann_string indent indentation ann = match ann with | [] -> "" | k_v :: xs -> let indent' = indent + indentation in let k_v_string' indent x = FIXME use endline instead of ? k_v_string indent x in FIXME check that this agrees with endline "{" ^ k_v_string 0 k_v ^ FIXME instruct mk_block to use endline ?
null
https://raw.githubusercontent.com/NaaS/motto/8ff3eba534be816d861dcfced93b68d593a12e2b/syntax/crisp_type_annotation.ml
ocaml
NOTE we allow the annotation to talk about a value that won't be used in the program -- but that will be represented in the input (and whose value is preserved in the output.) By this I mean things like anonymous field names that have type annotations -- being anonymous, we cannot read, use, or change their value in the program, since we have no way of referring to their value. Their value must be preserved however, if, say, we output the (possibly otherwise modified) record to the network. In order to indicate that a field is anonymous -- i.e., its value is not important to the program -- then we use dummy names in type specs -- such as in records, in which case the syntax is: type bla : record a : integer { ... } _ : integer # Anonymous field. { ... } b : integer { ... }
Serialisation - related annotations for types in , Cambridge University Computer Lab , March 2015 Use of this source code is governed by the Apache 2.0 license ; see LICENSE Serialisation-related annotations for types in Crisp Nik Sultana, Cambridge University Computer Lab, March 2015 Use of this source code is governed by the Apache 2.0 license; see LICENSE *) open General type type_annotation_op = | Plus | Minus type type_annotation_kind = | Ann_Str of string | Ann_Int of int | Ann_Ident of string | Ann_BinaryExp of type_annotation_op * type_annotation_kind * type_annotation_kind type type_annotation = (string * type_annotation_kind) list let empty_type_annotation : type_annotation = [] let hadoop_vint_ann_key = "hadoop_vint" let true_ann_value = Ann_Ident "true" let is_hadoop_vint = List.exists (fun (k, v) -> k = hadoop_vint_ann_key && v = true_ann_value) let k_v_string indent (l, e) = let rec e_s e = match e with | Ann_Str s -> "\"" ^ s ^ "\"" | Ann_Int i -> string_of_int i | Ann_Ident s -> s | Ann_BinaryExp (op, e1, e2) -> let op_s = match op with | Plus -> "+" | Minus -> "-" in "(" ^ e_s e1 ^ ")" ^ op_s ^ "(" ^ e_s e2 ^ ")" in indn indent ^ l ^ " = " ^ e_s e let ann_string indent indentation ann = match ann with | [] -> "" | k_v :: xs -> let indent' = indent + indentation in let k_v_string' indent x = FIXME use endline instead of ? k_v_string indent x in FIXME check that this agrees with endline "{" ^ k_v_string 0 k_v ^ FIXME instruct mk_block to use endline ?
97202bfc50f53c88b899f07a5c58d39015812f403542810f5d0b785e58b1761d
cucapra/diospyros
backend-utils.rkt
#lang rosette (require "../c-ast.rkt") (provide suppress-git-info git-info-comment) ; Suppress the git information header (define suppress-git-info (make-parameter #f)) ; Return the non-error string output of a system command (define (get-command-output cmd) (with-output-to-string (lambda () (system cmd)))) ; Get the current git revision (define (get-git-revision) (get-command-output "git rev-parse --short HEAD")) ; Check the current git status (define (get-git-status) (define stat (get-command-output "git diff --stat")) (define clean? (equal? stat "")) (if (not clean?) (let ([warning (format "Warning: dirty git status:\n~a" stat)]) warning) "Git status clean")) ; Produce git info (revision and status) as a C-style block comment (define (git-info-comment) (define rev (get-git-revision)) (define status (get-git-status)) (c-comment (format "Git revision: ~a\n~a" rev status)))
null
https://raw.githubusercontent.com/cucapra/diospyros/5c9fb6d3bda40d7bb395546aaefc78e6813b729f/src/backend/backend-utils.rkt
racket
Suppress the git information header Return the non-error string output of a system command Get the current git revision Check the current git status Produce git info (revision and status) as a C-style block comment
#lang rosette (require "../c-ast.rkt") (provide suppress-git-info git-info-comment) (define suppress-git-info (make-parameter #f)) (define (get-command-output cmd) (with-output-to-string (lambda () (system cmd)))) (define (get-git-revision) (get-command-output "git rev-parse --short HEAD")) (define (get-git-status) (define stat (get-command-output "git diff --stat")) (define clean? (equal? stat "")) (if (not clean?) (let ([warning (format "Warning: dirty git status:\n~a" stat)]) warning) "Git status clean")) (define (git-info-comment) (define rev (get-git-revision)) (define status (get-git-status)) (c-comment (format "Git revision: ~a\n~a" rev status)))
b64c7f56c907d4957e09602d27661a500fc6489670ede429b9426859f63a683a
ghc/packages-haskeline
DumbTerm.hs
module System.Console.Haskeline.Backend.DumbTerm where import System.Console.Haskeline.Backend.Posix import System.Console.Haskeline.Backend.WCWidth import System.Console.Haskeline.Term import System.Console.Haskeline.LineState import System.Console.Haskeline.Monads as Monads import System.IO import Control.Applicative(Applicative) import Control.Monad(liftM) import Control.Monad.Catch -- TODO: ---- Put "<" and ">" at end of term if scrolls off. ---- Have a margin at the ends data Window = Window {pos :: Int -- ^ # of visible chars to left of cursor } initWindow :: Window initWindow = Window {pos=0} newtype DumbTerm m a = DumbTerm {unDumbTerm :: StateT Window (PosixT m) a} deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask, MonadState Window, MonadReader Handles) type DumbTermM a = forall m . (MonadIO m, MonadReader Layout m) => DumbTerm m a instance MonadTrans DumbTerm where lift = DumbTerm . lift . lift evalDumb :: (MonadReader Layout m, CommandMonad m) => EvalTerm (PosixT m) evalDumb = EvalTerm (evalStateT' initWindow . unDumbTerm) (DumbTerm . lift) runDumbTerm :: Handles -> MaybeT IO RunTerm runDumbTerm h = liftIO $ posixRunTerm h (posixLayouts h) [] id evalDumb instance (MonadIO m, MonadMask m, MonadReader Layout m) => Term (DumbTerm m) where reposition _ s = refitLine s drawLineDiff x y = drawLineDiff' x y printLines = mapM_ (printText . (++ crlf)) moveToNextLine _ = printText crlf clearLayout = clearLayoutD ringBell True = printText "\a" ringBell False = return () printText :: MonadIO m => String -> DumbTerm m () printText str = do h <- liftM ehOut ask liftIO $ hPutStr h str liftIO $ hFlush h -- Things we can assume a dumb terminal knows how to do cr,crlf :: String crlf = "\r\n" cr = "\r" backs,spaces :: Int -> String backs n = replicate n '\b' spaces n = replicate n ' ' clearLayoutD :: DumbTermM () clearLayoutD = do w <- maxWidth printText (cr ++ spaces w ++ cr) -- Don't want to print in the last column, as that may wrap to the next line. maxWidth :: DumbTermM Int maxWidth = asks (\lay -> width lay - 1) drawLineDiff' :: LineChars -> LineChars -> DumbTermM () drawLineDiff' (xs1,ys1) (xs2,ys2) = do Window {pos=p} <- get w <- maxWidth let (xs1',xs2') = matchInit xs1 xs2 let (xw1, xw2) = (gsWidth xs1', gsWidth xs2') let newP = p + xw2 - xw1 let (ys2', yw2) = takeWidth (w-newP) ys2 if xw1 > p || newP >= w then refitLine (xs2,ys2) else do -- we haven't moved outside the margins put Window {pos=newP} case (xs1',xs2') of ([],[]) | ys1 == ys2 -> return () -- no change (_,[]) | xs1' ++ ys1 == ys2 -> -- moved left printText $ backs xw1 ([],_) | ys1 == xs2' ++ ys2 -> -- moved right printText (graphemesToString xs2') _ -> let extraLength = xw1 + snd (takeWidth (w-p) ys1) - xw2 - yw2 in printText $ backs xw1 ++ graphemesToString (xs2' ++ ys2') ++ clearDeadText extraLength ++ backs yw2 refitLine :: ([Grapheme],[Grapheme]) -> DumbTermM () refitLine (xs,ys) = do w <- maxWidth let (xs',p) = dropFrames w xs put Window {pos=p} let (ys',k) = takeWidth (w - p) ys printText $ cr ++ graphemesToString (xs' ++ ys') ++ spaces (w-k-p) ++ backs (w-p) where -- returns the width of the returned characters. dropFrames w zs = case splitAtWidth w zs of (_,[],l) -> (zs,l) (_,zs',_) -> dropFrames w zs' clearDeadText :: Int -> String clearDeadText n | n > 0 = spaces n ++ backs n | otherwise = ""
null
https://raw.githubusercontent.com/ghc/packages-haskeline/5f16b76168f13c6413413386efc44fb1152048d5/System/Console/Haskeline/Backend/DumbTerm.hs
haskell
TODO: -- Put "<" and ">" at end of term if scrolls off. -- Have a margin at the ends ^ # of visible chars to left of cursor Things we can assume a dumb terminal knows how to do Don't want to print in the last column, as that may wrap to the next line. we haven't moved outside the margins no change moved left moved right returns the width of the returned characters.
module System.Console.Haskeline.Backend.DumbTerm where import System.Console.Haskeline.Backend.Posix import System.Console.Haskeline.Backend.WCWidth import System.Console.Haskeline.Term import System.Console.Haskeline.LineState import System.Console.Haskeline.Monads as Monads import System.IO import Control.Applicative(Applicative) import Control.Monad(liftM) import Control.Monad.Catch } initWindow :: Window initWindow = Window {pos=0} newtype DumbTerm m a = DumbTerm {unDumbTerm :: StateT Window (PosixT m) a} deriving (Functor, Applicative, Monad, MonadIO, MonadThrow, MonadCatch, MonadMask, MonadState Window, MonadReader Handles) type DumbTermM a = forall m . (MonadIO m, MonadReader Layout m) => DumbTerm m a instance MonadTrans DumbTerm where lift = DumbTerm . lift . lift evalDumb :: (MonadReader Layout m, CommandMonad m) => EvalTerm (PosixT m) evalDumb = EvalTerm (evalStateT' initWindow . unDumbTerm) (DumbTerm . lift) runDumbTerm :: Handles -> MaybeT IO RunTerm runDumbTerm h = liftIO $ posixRunTerm h (posixLayouts h) [] id evalDumb instance (MonadIO m, MonadMask m, MonadReader Layout m) => Term (DumbTerm m) where reposition _ s = refitLine s drawLineDiff x y = drawLineDiff' x y printLines = mapM_ (printText . (++ crlf)) moveToNextLine _ = printText crlf clearLayout = clearLayoutD ringBell True = printText "\a" ringBell False = return () printText :: MonadIO m => String -> DumbTerm m () printText str = do h <- liftM ehOut ask liftIO $ hPutStr h str liftIO $ hFlush h cr,crlf :: String crlf = "\r\n" cr = "\r" backs,spaces :: Int -> String backs n = replicate n '\b' spaces n = replicate n ' ' clearLayoutD :: DumbTermM () clearLayoutD = do w <- maxWidth printText (cr ++ spaces w ++ cr) maxWidth :: DumbTermM Int maxWidth = asks (\lay -> width lay - 1) drawLineDiff' :: LineChars -> LineChars -> DumbTermM () drawLineDiff' (xs1,ys1) (xs2,ys2) = do Window {pos=p} <- get w <- maxWidth let (xs1',xs2') = matchInit xs1 xs2 let (xw1, xw2) = (gsWidth xs1', gsWidth xs2') let newP = p + xw2 - xw1 let (ys2', yw2) = takeWidth (w-newP) ys2 if xw1 > p || newP >= w then refitLine (xs2,ys2) put Window {pos=newP} case (xs1',xs2') of printText $ backs xw1 printText (graphemesToString xs2') _ -> let extraLength = xw1 + snd (takeWidth (w-p) ys1) - xw2 - yw2 in printText $ backs xw1 ++ graphemesToString (xs2' ++ ys2') ++ clearDeadText extraLength ++ backs yw2 refitLine :: ([Grapheme],[Grapheme]) -> DumbTermM () refitLine (xs,ys) = do w <- maxWidth let (xs',p) = dropFrames w xs put Window {pos=p} let (ys',k) = takeWidth (w - p) ys printText $ cr ++ graphemesToString (xs' ++ ys') ++ spaces (w-k-p) ++ backs (w-p) where dropFrames w zs = case splitAtWidth w zs of (_,[],l) -> (zs,l) (_,zs',_) -> dropFrames w zs' clearDeadText :: Int -> String clearDeadText n | n > 0 = spaces n ++ backs n | otherwise = ""
f0a563bdd5fb87c7bf704c6001dd00b41ca1fba9f7e5038305648cd1003bbef0
Beluga-lang/Beluga
version.ml
* Gets the version of from the dune-build.info library . let get () = match Build_info.V1.version () with | None -> "n/a" | Some v -> Build_info.V1.Version.to_string v
null
https://raw.githubusercontent.com/Beluga-lang/Beluga/1d39095c99dc255d972a339d447dc04286d8c13f/src/beluga/version.ml
ocaml
* Gets the version of from the dune-build.info library . let get () = match Build_info.V1.version () with | None -> "n/a" | Some v -> Build_info.V1.Version.to_string v
2f75fde2db97f1452f086d695c7ecffd90508a4e902fde28868b1bdaa4997442
MyDataFlow/ttalk-server
cow_http.erl
Copyright ( c ) 2013 - 2014 , < > %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -module(cow_http). @todo parse_request_line -export([parse_status_line/1]). -export([parse_headers/1]). -export([parse_fullhost/1]). -export([parse_fullpath/1]). -export([parse_version/1]). -export([request/4]). -export([version/1]). -type version() :: 'HTTP/1.0' | 'HTTP/1.1'. -type status() :: 100..999. -type headers() :: [{binary(), iodata()}]. -include("cow_inline.hrl"). %% @doc Parse the status line. -spec parse_status_line(binary()) -> {version(), status(), binary(), binary()}. parse_status_line(<< "HTTP/1.1 200 OK\r\n", Rest/bits >>) -> {'HTTP/1.1', 200, <<"OK">>, Rest}; parse_status_line(<< "HTTP/1.1 404 Not Found\r\n", Rest/bits >>) -> {'HTTP/1.1', 404, <<"Not Found">>, Rest}; parse_status_line(<< "HTTP/1.1 500 Internal Server Error\r\n", Rest/bits >>) -> {'HTTP/1.1', 500, <<"Internal Server Error">>, Rest}; parse_status_line(<< "HTTP/1.1 ", Status/bits >>) -> parse_status_line(Status, 'HTTP/1.1'); parse_status_line(<< "HTTP/1.0 ", Status/bits >>) -> parse_status_line(Status, 'HTTP/1.0'). parse_status_line(<< H, T, U, " ", Rest/bits >>, Version) when $0 =< H, H =< $9, $0 =< T, T =< $9, $0 =< U, U =< $9 -> Status = (H - $0) * 100 + (T - $0) * 10 + (U - $0), {Pos, _} = binary:match(Rest, <<"\r">>), << StatusStr:Pos/binary, "\r\n", Rest2/bits >> = Rest, {Version, Status, StatusStr, Rest2}. -ifdef(TEST). parse_status_line_test_() -> Tests = [ {<<"HTTP/1.1 200 OK\r\nRest">>, {'HTTP/1.1', 200, <<"OK">>, <<"Rest">>}}, {<<"HTTP/1.0 404 Not Found\r\nRest">>, {'HTTP/1.0', 404, <<"Not Found">>, <<"Rest">>}}, {<<"HTTP/1.1 500 Something very funny here\r\nRest">>, {'HTTP/1.1', 500, <<"Something very funny here">>, <<"Rest">>}}, {<<"HTTP/1.1 200 \r\nRest">>, {'HTTP/1.1', 200, <<>>, <<"Rest">>}} ], [{V, fun() -> R = parse_status_line(V) end} || {V, R} <- Tests]. parse_status_line_error_test_() -> Tests = [ <<>>, <<"HTTP/1.1">>, <<"HTTP/1.1 200\r\n">>, <<"HTTP/1.1 200 OK">>, <<"HTTP/1.1 200 OK\r">>, <<"HTTP/1.1 200 OK\n">>, <<"HTTP/0.9 200 OK\r\n">>, <<"HTTP/1.1 42 Answer\r\n">>, <<"HTTP/1.1 999999999 More than OK\r\n">>, <<"content-type: text/plain\r\n">>, <<0:80, "\r\n">> ], [{V, fun() -> {'EXIT', _} = (catch parse_status_line(V)) end} || V <- Tests]. -endif. -ifdef(PERF). horse_parse_status_line_200() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 200 OK\r\n">>) ). horse_parse_status_line_404() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 404 Not Found\r\n">>) ). horse_parse_status_line_500() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 500 Internal Server Error\r\n">>) ). horse_parse_status_line_other() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 416 Requested range not satisfiable\r\n">>) ). -endif. %% @doc Parse the list of headers. -spec parse_headers(binary()) -> {[{binary(), binary()}], binary()}. parse_headers(Data) -> parse_header(Data, []). parse_header(<< $\r, $\n, Rest/bits >>, Acc) -> {lists:reverse(Acc), Rest}; parse_header(Data, Acc) -> parse_hd_name(Data, Acc, <<>>). parse_hd_name(<< C, Rest/bits >>, Acc, SoFar) -> case C of $: -> parse_hd_before_value(Rest, Acc, SoFar); $\s -> parse_hd_name_ws(Rest, Acc, SoFar); $\t -> parse_hd_name_ws(Rest, Acc, SoFar); ?INLINE_LOWERCASE(parse_hd_name, Rest, Acc, SoFar) end. parse_hd_name_ws(<< C, Rest/bits >>, Acc, Name) -> case C of $: -> parse_hd_before_value(Rest, Acc, Name); $\s -> parse_hd_name_ws(Rest, Acc, Name); $\t -> parse_hd_name_ws(Rest, Acc, Name) end. parse_hd_before_value(<< $\s, Rest/bits >>, Acc, Name) -> parse_hd_before_value(Rest, Acc, Name); parse_hd_before_value(<< $\t, Rest/bits >>, Acc, Name) -> parse_hd_before_value(Rest, Acc, Name); parse_hd_before_value(Data, Acc, Name) -> parse_hd_value(Data, Acc, Name, <<>>). parse_hd_value(<< $\r, Rest/bits >>, Acc, Name, SoFar) -> case Rest of << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t -> parse_hd_value(Rest2, Acc, Name, << SoFar/binary, C >>); << $\n, Rest2/bits >> -> parse_header(Rest2, [{Name, SoFar}|Acc]) end; parse_hd_value(<< C, Rest/bits >>, Acc, Name, SoFar) -> parse_hd_value(Rest, Acc, Name, << SoFar/binary, C >>). -ifdef(TEST). parse_headers_test_() -> Tests = [ {<<"\r\nRest">>, {[], <<"Rest">>}}, {<<"Server: Erlang/R17\r\n" "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n" "Multiline-Header: why hello!\r\n" " I didn't see you all the way over there!\r\n" "Content-Length: 12\r\n" "Content-Type: text/plain\r\n" "\r\nRest">>, {[{<<"server">>, <<"Erlang/R17">>}, {<<"date">>, <<"Sun, 23 Feb 2014 09:30:39 GMT">>}, {<<"multiline-header">>, <<"why hello! I didn't see you all the way over there!">>}, {<<"content-length">>, <<"12">>}, {<<"content-type">>, <<"text/plain">>}], <<"Rest">>}} ], [{V, fun() -> R = parse_headers(V) end} || {V, R} <- Tests]. parse_headers_error_test_() -> Tests = [ <<>>, <<"\r">>, <<"Malformed\r\n\r\n">>, <<"content-type: text/plain\r\nMalformed\r\n\r\n">>, <<"HTTP/1.1 200 OK\r\n\r\n">>, <<0:80, "\r\n\r\n">>, <<"content-type: text/plain\r\ncontent-length: 12\r\n">> ], [{V, fun() -> {'EXIT', _} = (catch parse_headers(V)) end} || V <- Tests]. -endif. -ifdef(PERF). horse_parse_headers() -> horse:repeat(50000, parse_headers(<<"Server: Erlang/R17\r\n" "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n" "Multiline-Header: why hello!\r\n" " I didn't see you all the way over there!\r\n" "Content-Length: 12\r\n" "Content-Type: text/plain\r\n" "\r\nRest">>) ). -endif. %% @doc Extract host and port from a binary. %% %% Because the hostname is case insensitive it is converted %% to lowercase. -spec parse_fullhost(binary()) -> {binary(), undefined | non_neg_integer()}. parse_fullhost(Fullhost) -> parse_fullhost(Fullhost, false, <<>>). parse_fullhost(<< $[, Rest/bits >>, false, <<>>) -> parse_fullhost(Rest, true, << $[ >>); parse_fullhost(<<>>, false, Acc) -> {Acc, undefined}; @todo Optimize . parse_fullhost(<< $:, Rest/bits >>, false, Acc) -> {Acc, list_to_integer(binary_to_list(Rest))}; parse_fullhost(<< $], Rest/bits >>, true, Acc) -> parse_fullhost(Rest, false, << Acc/binary, $] >>); parse_fullhost(<< C, Rest/bits >>, E, Acc) -> case C of ?INLINE_LOWERCASE(parse_fullhost, Rest, E, Acc) end. -ifdef(TEST). parse_fullhost_test() -> {<<"example.org">>, 8080} = parse_fullhost(<<"example.org:8080">>), {<<"example.org">>, undefined} = parse_fullhost(<<"example.org">>), {<<"192.0.2.1">>, 8080} = parse_fullhost(<<"192.0.2.1:8080">>), {<<"192.0.2.1">>, undefined} = parse_fullhost(<<"192.0.2.1">>), {<<"[2001:db8::1]">>, 8080} = parse_fullhost(<<"[2001:db8::1]:8080">>), {<<"[2001:db8::1]">>, undefined} = parse_fullhost(<<"[2001:db8::1]">>), {<<"[::ffff:192.0.2.1]">>, 8080} = parse_fullhost(<<"[::ffff:192.0.2.1]:8080">>), {<<"[::ffff:192.0.2.1]">>, undefined} = parse_fullhost(<<"[::ffff:192.0.2.1]">>), ok. -endif. %% @doc Extract path and query string from a binary. -spec parse_fullpath(binary()) -> {binary(), binary()}. parse_fullpath(Fullpath) -> parse_fullpath(Fullpath, <<>>). parse_fullpath(<<>>, Path) -> {Path, <<>>}; parse_fullpath(<< $?, Qs/binary >>, Path) -> {Path, Qs}; parse_fullpath(<< C, Rest/binary >>, SoFar) -> parse_fullpath(Rest, << SoFar/binary, C >>). -ifdef(TEST). parse_fullpath_test() -> {<<"*">>, <<>>} = parse_fullpath(<<"*">>), {<<"/">>, <<>>} = parse_fullpath(<<"/">>), {<<"/path/to/resource">>, <<>>} = parse_fullpath(<<"/path/to/resource">>), {<<"/">>, <<>>} = parse_fullpath(<<"/?">>), {<<"/">>, <<"q=cowboy">>} = parse_fullpath(<<"/?q=cowboy">>), {<<"/path/to/resource">>, <<"q=cowboy">>} = parse_fullpath(<<"/path/to/resource?q=cowboy">>), ok. -endif. %% @doc Convert an HTTP version to atom. -spec parse_version(binary()) -> version(). parse_version(<<"HTTP/1.1">>) -> 'HTTP/1.1'; parse_version(<<"HTTP/1.0">>) -> 'HTTP/1.0'. -ifdef(TEST). parse_version_test() -> 'HTTP/1.1' = parse_version(<<"HTTP/1.1">>), 'HTTP/1.0' = parse_version(<<"HTTP/1.0">>), {'EXIT', _} = (catch parse_version(<<"HTTP/1.2">>)), ok. -endif. %% @doc Return formatted request-line and headers. %% @todo Add tests when the corresponding reverse functions are added. -spec request(binary(), iodata(), version(), headers()) -> iodata(). request(Method, Path, Version, Headers) -> [Method, <<" ">>, Path, <<" ">>, version(Version), <<"\r\n">>, [[N, <<": ">>, V, <<"\r\n">>] || {N, V} <- Headers], <<"\r\n">>]. %% @doc Return the version as a binary. -spec version(version()) -> binary(). version('HTTP/1.1') -> <<"HTTP/1.1">>; version('HTTP/1.0') -> <<"HTTP/1.0">>. -ifdef(TEST). version_test() -> <<"HTTP/1.1">> = version('HTTP/1.1'), <<"HTTP/1.0">> = version('HTTP/1.0'), {'EXIT', _} = (catch version('HTTP/1.2')), ok. -endif.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowlib/src/cow_http.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. @doc Parse the status line. @doc Parse the list of headers. @doc Extract host and port from a binary. Because the hostname is case insensitive it is converted to lowercase. @doc Extract path and query string from a binary. @doc Convert an HTTP version to atom. @doc Return formatted request-line and headers. @todo Add tests when the corresponding reverse functions are added. @doc Return the version as a binary.
Copyright ( c ) 2013 - 2014 , < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(cow_http). @todo parse_request_line -export([parse_status_line/1]). -export([parse_headers/1]). -export([parse_fullhost/1]). -export([parse_fullpath/1]). -export([parse_version/1]). -export([request/4]). -export([version/1]). -type version() :: 'HTTP/1.0' | 'HTTP/1.1'. -type status() :: 100..999. -type headers() :: [{binary(), iodata()}]. -include("cow_inline.hrl"). -spec parse_status_line(binary()) -> {version(), status(), binary(), binary()}. parse_status_line(<< "HTTP/1.1 200 OK\r\n", Rest/bits >>) -> {'HTTP/1.1', 200, <<"OK">>, Rest}; parse_status_line(<< "HTTP/1.1 404 Not Found\r\n", Rest/bits >>) -> {'HTTP/1.1', 404, <<"Not Found">>, Rest}; parse_status_line(<< "HTTP/1.1 500 Internal Server Error\r\n", Rest/bits >>) -> {'HTTP/1.1', 500, <<"Internal Server Error">>, Rest}; parse_status_line(<< "HTTP/1.1 ", Status/bits >>) -> parse_status_line(Status, 'HTTP/1.1'); parse_status_line(<< "HTTP/1.0 ", Status/bits >>) -> parse_status_line(Status, 'HTTP/1.0'). parse_status_line(<< H, T, U, " ", Rest/bits >>, Version) when $0 =< H, H =< $9, $0 =< T, T =< $9, $0 =< U, U =< $9 -> Status = (H - $0) * 100 + (T - $0) * 10 + (U - $0), {Pos, _} = binary:match(Rest, <<"\r">>), << StatusStr:Pos/binary, "\r\n", Rest2/bits >> = Rest, {Version, Status, StatusStr, Rest2}. -ifdef(TEST). parse_status_line_test_() -> Tests = [ {<<"HTTP/1.1 200 OK\r\nRest">>, {'HTTP/1.1', 200, <<"OK">>, <<"Rest">>}}, {<<"HTTP/1.0 404 Not Found\r\nRest">>, {'HTTP/1.0', 404, <<"Not Found">>, <<"Rest">>}}, {<<"HTTP/1.1 500 Something very funny here\r\nRest">>, {'HTTP/1.1', 500, <<"Something very funny here">>, <<"Rest">>}}, {<<"HTTP/1.1 200 \r\nRest">>, {'HTTP/1.1', 200, <<>>, <<"Rest">>}} ], [{V, fun() -> R = parse_status_line(V) end} || {V, R} <- Tests]. parse_status_line_error_test_() -> Tests = [ <<>>, <<"HTTP/1.1">>, <<"HTTP/1.1 200\r\n">>, <<"HTTP/1.1 200 OK">>, <<"HTTP/1.1 200 OK\r">>, <<"HTTP/1.1 200 OK\n">>, <<"HTTP/0.9 200 OK\r\n">>, <<"HTTP/1.1 42 Answer\r\n">>, <<"HTTP/1.1 999999999 More than OK\r\n">>, <<"content-type: text/plain\r\n">>, <<0:80, "\r\n">> ], [{V, fun() -> {'EXIT', _} = (catch parse_status_line(V)) end} || V <- Tests]. -endif. -ifdef(PERF). horse_parse_status_line_200() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 200 OK\r\n">>) ). horse_parse_status_line_404() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 404 Not Found\r\n">>) ). horse_parse_status_line_500() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 500 Internal Server Error\r\n">>) ). horse_parse_status_line_other() -> horse:repeat(200000, parse_status_line(<<"HTTP/1.1 416 Requested range not satisfiable\r\n">>) ). -endif. -spec parse_headers(binary()) -> {[{binary(), binary()}], binary()}. parse_headers(Data) -> parse_header(Data, []). parse_header(<< $\r, $\n, Rest/bits >>, Acc) -> {lists:reverse(Acc), Rest}; parse_header(Data, Acc) -> parse_hd_name(Data, Acc, <<>>). parse_hd_name(<< C, Rest/bits >>, Acc, SoFar) -> case C of $: -> parse_hd_before_value(Rest, Acc, SoFar); $\s -> parse_hd_name_ws(Rest, Acc, SoFar); $\t -> parse_hd_name_ws(Rest, Acc, SoFar); ?INLINE_LOWERCASE(parse_hd_name, Rest, Acc, SoFar) end. parse_hd_name_ws(<< C, Rest/bits >>, Acc, Name) -> case C of $: -> parse_hd_before_value(Rest, Acc, Name); $\s -> parse_hd_name_ws(Rest, Acc, Name); $\t -> parse_hd_name_ws(Rest, Acc, Name) end. parse_hd_before_value(<< $\s, Rest/bits >>, Acc, Name) -> parse_hd_before_value(Rest, Acc, Name); parse_hd_before_value(<< $\t, Rest/bits >>, Acc, Name) -> parse_hd_before_value(Rest, Acc, Name); parse_hd_before_value(Data, Acc, Name) -> parse_hd_value(Data, Acc, Name, <<>>). parse_hd_value(<< $\r, Rest/bits >>, Acc, Name, SoFar) -> case Rest of << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t -> parse_hd_value(Rest2, Acc, Name, << SoFar/binary, C >>); << $\n, Rest2/bits >> -> parse_header(Rest2, [{Name, SoFar}|Acc]) end; parse_hd_value(<< C, Rest/bits >>, Acc, Name, SoFar) -> parse_hd_value(Rest, Acc, Name, << SoFar/binary, C >>). -ifdef(TEST). parse_headers_test_() -> Tests = [ {<<"\r\nRest">>, {[], <<"Rest">>}}, {<<"Server: Erlang/R17\r\n" "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n" "Multiline-Header: why hello!\r\n" " I didn't see you all the way over there!\r\n" "Content-Length: 12\r\n" "Content-Type: text/plain\r\n" "\r\nRest">>, {[{<<"server">>, <<"Erlang/R17">>}, {<<"date">>, <<"Sun, 23 Feb 2014 09:30:39 GMT">>}, {<<"multiline-header">>, <<"why hello! I didn't see you all the way over there!">>}, {<<"content-length">>, <<"12">>}, {<<"content-type">>, <<"text/plain">>}], <<"Rest">>}} ], [{V, fun() -> R = parse_headers(V) end} || {V, R} <- Tests]. parse_headers_error_test_() -> Tests = [ <<>>, <<"\r">>, <<"Malformed\r\n\r\n">>, <<"content-type: text/plain\r\nMalformed\r\n\r\n">>, <<"HTTP/1.1 200 OK\r\n\r\n">>, <<0:80, "\r\n\r\n">>, <<"content-type: text/plain\r\ncontent-length: 12\r\n">> ], [{V, fun() -> {'EXIT', _} = (catch parse_headers(V)) end} || V <- Tests]. -endif. -ifdef(PERF). horse_parse_headers() -> horse:repeat(50000, parse_headers(<<"Server: Erlang/R17\r\n" "Date: Sun, 23 Feb 2014 09:30:39 GMT\r\n" "Multiline-Header: why hello!\r\n" " I didn't see you all the way over there!\r\n" "Content-Length: 12\r\n" "Content-Type: text/plain\r\n" "\r\nRest">>) ). -endif. -spec parse_fullhost(binary()) -> {binary(), undefined | non_neg_integer()}. parse_fullhost(Fullhost) -> parse_fullhost(Fullhost, false, <<>>). parse_fullhost(<< $[, Rest/bits >>, false, <<>>) -> parse_fullhost(Rest, true, << $[ >>); parse_fullhost(<<>>, false, Acc) -> {Acc, undefined}; @todo Optimize . parse_fullhost(<< $:, Rest/bits >>, false, Acc) -> {Acc, list_to_integer(binary_to_list(Rest))}; parse_fullhost(<< $], Rest/bits >>, true, Acc) -> parse_fullhost(Rest, false, << Acc/binary, $] >>); parse_fullhost(<< C, Rest/bits >>, E, Acc) -> case C of ?INLINE_LOWERCASE(parse_fullhost, Rest, E, Acc) end. -ifdef(TEST). parse_fullhost_test() -> {<<"example.org">>, 8080} = parse_fullhost(<<"example.org:8080">>), {<<"example.org">>, undefined} = parse_fullhost(<<"example.org">>), {<<"192.0.2.1">>, 8080} = parse_fullhost(<<"192.0.2.1:8080">>), {<<"192.0.2.1">>, undefined} = parse_fullhost(<<"192.0.2.1">>), {<<"[2001:db8::1]">>, 8080} = parse_fullhost(<<"[2001:db8::1]:8080">>), {<<"[2001:db8::1]">>, undefined} = parse_fullhost(<<"[2001:db8::1]">>), {<<"[::ffff:192.0.2.1]">>, 8080} = parse_fullhost(<<"[::ffff:192.0.2.1]:8080">>), {<<"[::ffff:192.0.2.1]">>, undefined} = parse_fullhost(<<"[::ffff:192.0.2.1]">>), ok. -endif. -spec parse_fullpath(binary()) -> {binary(), binary()}. parse_fullpath(Fullpath) -> parse_fullpath(Fullpath, <<>>). parse_fullpath(<<>>, Path) -> {Path, <<>>}; parse_fullpath(<< $?, Qs/binary >>, Path) -> {Path, Qs}; parse_fullpath(<< C, Rest/binary >>, SoFar) -> parse_fullpath(Rest, << SoFar/binary, C >>). -ifdef(TEST). parse_fullpath_test() -> {<<"*">>, <<>>} = parse_fullpath(<<"*">>), {<<"/">>, <<>>} = parse_fullpath(<<"/">>), {<<"/path/to/resource">>, <<>>} = parse_fullpath(<<"/path/to/resource">>), {<<"/">>, <<>>} = parse_fullpath(<<"/?">>), {<<"/">>, <<"q=cowboy">>} = parse_fullpath(<<"/?q=cowboy">>), {<<"/path/to/resource">>, <<"q=cowboy">>} = parse_fullpath(<<"/path/to/resource?q=cowboy">>), ok. -endif. -spec parse_version(binary()) -> version(). parse_version(<<"HTTP/1.1">>) -> 'HTTP/1.1'; parse_version(<<"HTTP/1.0">>) -> 'HTTP/1.0'. -ifdef(TEST). parse_version_test() -> 'HTTP/1.1' = parse_version(<<"HTTP/1.1">>), 'HTTP/1.0' = parse_version(<<"HTTP/1.0">>), {'EXIT', _} = (catch parse_version(<<"HTTP/1.2">>)), ok. -endif. -spec request(binary(), iodata(), version(), headers()) -> iodata(). request(Method, Path, Version, Headers) -> [Method, <<" ">>, Path, <<" ">>, version(Version), <<"\r\n">>, [[N, <<": ">>, V, <<"\r\n">>] || {N, V} <- Headers], <<"\r\n">>]. -spec version(version()) -> binary(). version('HTTP/1.1') -> <<"HTTP/1.1">>; version('HTTP/1.0') -> <<"HTTP/1.0">>. -ifdef(TEST). version_test() -> <<"HTTP/1.1">> = version('HTTP/1.1'), <<"HTTP/1.0">> = version('HTTP/1.0'), {'EXIT', _} = (catch version('HTTP/1.2')), ok. -endif.
fcf9e4425cae6b5d582a536e1f7b3d33c6a99ab6a15db60d6653c6376838aaf9
mtolly/onyxite-customs
Freetar.hs
# LANGUAGE DuplicateRecordFields # {-# LANGUAGE NoFieldSelectors #-} {-# LANGUAGE OverloadedRecordDot #-} # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} module Onyx.Import.Freetar where import Control.Monad.Codec import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Reader (runReaderT) import qualified Data.ByteString as B import Data.Default.Class (def) import qualified Data.EventList.Absolute.TimeBody as ATB import qualified Data.EventList.Relative.TimeBody as RTB import Data.Foldable (toList) import qualified Data.HashMap.Strict as HM import Data.List (sort) import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map import Data.Maybe (catMaybes) import qualified Data.Text as T import qualified Data.Vector as V import Onyx.Audio import Onyx.Codec.XML import Onyx.Guitar (HOPOsAlgorithm (..), emit5', strumHOPOTap) import Onyx.Import.Base import Onyx.MIDI.Common (Difficulty (..)) import qualified Onyx.MIDI.Track.File as F import qualified Onyx.MIDI.Track.FiveFret as Five import Onyx.Project import Onyx.StackTrace import Onyx.Util.Handle (fileReadable) import Onyx.Util.Text.Decode (decodeGeneral) import qualified Sound.MIDI.Util as U import System.FilePath (takeDirectory, takeExtension, (<.>), (</>)) import Text.Read (readMaybe) import Text.XML.Light (parseXMLDoc) data Properties = Properties { version :: Maybe T.Text , title :: Maybe T.Text , artist :: Maybe T.Text , album :: Maybe T.Text , year :: Maybe T.Text , beatsPerSecond :: Maybe Double , beatOffset :: Maybe Double , hammerOnTime :: Maybe Double , pullOffTime :: Maybe Double , difficulty :: Maybe T.Text , allowableErrorTime :: Maybe Double , length_ :: Maybe Double , musicFileName :: Maybe T.Text , musicDirectoryHint :: Maybe T.Text } deriving (Show) instance IsInside Properties where insideCodec = do version <- (.version) =. childTagOpt "Version" (parseInside' childText) title <- (.title) =. childTagOpt "Title" (parseInside' childText) artist <- (.artist) =. childTagOpt "Artist" (parseInside' childText) album <- (.album) =. childTagOpt "Album" (parseInside' childText) year <- (.year) =. childTagOpt "Year" (parseInside' childText) beatsPerSecond <- (.beatsPerSecond) =. childTagOpt "BeatsPerSecond" (parseInside' $ milliText childText) beatOffset <- (.beatOffset) =. childTagOpt "BeatOffset" (parseInside' $ milliText childText) hammerOnTime <- (.hammerOnTime) =. childTagOpt "HammerOnTime" (parseInside' $ milliText childText) pullOffTime <- (.pullOffTime) =. childTagOpt "PullOffTime" (parseInside' $ milliText childText) difficulty <- (.difficulty) =. childTagOpt "Difficulty" (parseInside' childText) allowableErrorTime <- (.allowableErrorTime) =. childTagOpt "AllowableErrorTime" (parseInside' $ milliText childText) length_ <- (.length_) =. childTagOpt "Length" (parseInside' $ milliText childText) musicFileName <- (.musicFileName) =. childTagOpt "MusicFileName" (parseInside' childText) musicDirectoryHint <- (.musicDirectoryHint) =. childTagOpt "MusicDirectoryHint" (parseInside' childText) return Properties{..} data Note = Note { time :: Double , duration :: Double , track :: Int -- TODO HammerOnAllowed } deriving (Show) instance IsInside Note where insideCodec = do time <- (.time) =. milliText (reqAttr "time") duration <- (.duration) =. milliText (reqAttr "duration") track <- (.track) =. intText (reqAttr "track") return Note{..} data Song = Song { properties :: Properties , data_ :: V.Vector Note } deriving (Show) instance IsInside Song where insideCodec = do properties <- (.properties) =. childTag "Properties" (parseInside' insideCodec) data_ <- (.data_) =. childTag "Data" (parseInside' $ bareList $ isTag "Note" $ parseInside' insideCodec) return Song{..} parseSong :: (SendMessage m) => T.Text -> StackTraceT m Song parseSong xml = do elt <- maybe (fatal "Couldn't parse XML") return $ parseXMLDoc xml mapStackTraceT (`runReaderT` elt) $ codecIn $ isTag "Song" $ parseInside' insideCodec songToMidi :: Song -> F.Song (F.OnyxFile U.Beats) songToMidi song = let " BeatsPerSecond " is probably useless sigs = U.measureMapFromTimeSigs U.Truncate RTB.empty threshold :: U.Seconds threshold = case NE.nonEmpty $ catMaybes [song.properties.hammerOnTime, song.properties.pullOffTime] of Nothing -> 0.25 Just ne -> realToFrac $ maximum ne gtr = emit5' $ U.unapplyTempoTrack tempos $ strumHOPOTap HOPOsRBGuitar threshold $ RTB.fromAbsoluteEventList $ ATB.fromPairList $ sort $ map (\n -> let time = realToFrac n.time fret = Just $ toEnum n.track len = case n.duration of 0 -> Nothing d -> Just $ realToFrac d in (time, (fret, len)) ) $ V.toList song.data_ in F.Song { s_tempos = tempos , s_signatures = sigs , s_tracks = mempty { F.onyxParts = Map.singleton F.FlexGuitar mempty { F.onyxPartGuitar = mempty { Five.fiveDifficulties = Map.singleton Expert gtr } } } } importFreetar :: (SendMessage m, MonadIO m) => FilePath -> Import m importFreetar sng level = do song <- stackIO (B.readFile sng) >>= parseSong . decodeGeneral let props = song.properties return SongYaml { metadata = def' { title = props.title , artist = props.artist , album = props.album , year = props.year >>= readMaybe . T.unpack , comments = [] , fileAlbumArt = Nothing } , jammit = mempty , global = def' { backgroundVideo = Nothing , fileBackgroundImage = Nothing , fileMidi = SoftFile "notes.mid" $ SoftChart $ case level of ImportFull -> songToMidi song ImportQuick -> emptyChart , fileSongAnim = Nothing } , audio = HM.fromList $ toList $ flip fmap props.musicFileName $ \f -> let f' = takeDirectory sng </> T.unpack f audio = AudioFile AudioInfo { md5 = Nothing , frames = Nothing , commands = [] , filePath = Just $ SoftFile ("audio" <.> takeExtension f') $ SoftReadable $ fileReadable f' , rate = Nothing , channels = 2 -- just assuming } in ("song", audio) , plans = HM.fromList $ toList $ flip fmap props.musicFileName $ \_ -> let plan = StandardPlan StandardPlanInfo { song = Just $ PlanAudio (Input $ Named "song") [] [] , parts = Parts HM.empty , crowd = Nothing , comments = [] , tuningCents = 0 , fileTempo = Nothing } in ("freetar", plan) , targets = HM.empty , parts = Parts $ HM.singleton F.FlexGuitar emptyPart { grybo = Just def } }
null
https://raw.githubusercontent.com/mtolly/onyxite-customs/0c8acd6248fe92ea0d994b18b551973816adf85b/haskell/packages/onyx-lib/src/Onyx/Import/Freetar.hs
haskell
# LANGUAGE NoFieldSelectors # # LANGUAGE OverloadedRecordDot # # LANGUAGE StrictData # TODO HammerOnAllowed just assuming
# LANGUAGE DuplicateRecordFields # # LANGUAGE OverloadedStrings # # LANGUAGE RecordWildCards # module Onyx.Import.Freetar where import Control.Monad.Codec import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Reader (runReaderT) import qualified Data.ByteString as B import Data.Default.Class (def) import qualified Data.EventList.Absolute.TimeBody as ATB import qualified Data.EventList.Relative.TimeBody as RTB import Data.Foldable (toList) import qualified Data.HashMap.Strict as HM import Data.List (sort) import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map import Data.Maybe (catMaybes) import qualified Data.Text as T import qualified Data.Vector as V import Onyx.Audio import Onyx.Codec.XML import Onyx.Guitar (HOPOsAlgorithm (..), emit5', strumHOPOTap) import Onyx.Import.Base import Onyx.MIDI.Common (Difficulty (..)) import qualified Onyx.MIDI.Track.File as F import qualified Onyx.MIDI.Track.FiveFret as Five import Onyx.Project import Onyx.StackTrace import Onyx.Util.Handle (fileReadable) import Onyx.Util.Text.Decode (decodeGeneral) import qualified Sound.MIDI.Util as U import System.FilePath (takeDirectory, takeExtension, (<.>), (</>)) import Text.Read (readMaybe) import Text.XML.Light (parseXMLDoc) data Properties = Properties { version :: Maybe T.Text , title :: Maybe T.Text , artist :: Maybe T.Text , album :: Maybe T.Text , year :: Maybe T.Text , beatsPerSecond :: Maybe Double , beatOffset :: Maybe Double , hammerOnTime :: Maybe Double , pullOffTime :: Maybe Double , difficulty :: Maybe T.Text , allowableErrorTime :: Maybe Double , length_ :: Maybe Double , musicFileName :: Maybe T.Text , musicDirectoryHint :: Maybe T.Text } deriving (Show) instance IsInside Properties where insideCodec = do version <- (.version) =. childTagOpt "Version" (parseInside' childText) title <- (.title) =. childTagOpt "Title" (parseInside' childText) artist <- (.artist) =. childTagOpt "Artist" (parseInside' childText) album <- (.album) =. childTagOpt "Album" (parseInside' childText) year <- (.year) =. childTagOpt "Year" (parseInside' childText) beatsPerSecond <- (.beatsPerSecond) =. childTagOpt "BeatsPerSecond" (parseInside' $ milliText childText) beatOffset <- (.beatOffset) =. childTagOpt "BeatOffset" (parseInside' $ milliText childText) hammerOnTime <- (.hammerOnTime) =. childTagOpt "HammerOnTime" (parseInside' $ milliText childText) pullOffTime <- (.pullOffTime) =. childTagOpt "PullOffTime" (parseInside' $ milliText childText) difficulty <- (.difficulty) =. childTagOpt "Difficulty" (parseInside' childText) allowableErrorTime <- (.allowableErrorTime) =. childTagOpt "AllowableErrorTime" (parseInside' $ milliText childText) length_ <- (.length_) =. childTagOpt "Length" (parseInside' $ milliText childText) musicFileName <- (.musicFileName) =. childTagOpt "MusicFileName" (parseInside' childText) musicDirectoryHint <- (.musicDirectoryHint) =. childTagOpt "MusicDirectoryHint" (parseInside' childText) return Properties{..} data Note = Note { time :: Double , duration :: Double , track :: Int } deriving (Show) instance IsInside Note where insideCodec = do time <- (.time) =. milliText (reqAttr "time") duration <- (.duration) =. milliText (reqAttr "duration") track <- (.track) =. intText (reqAttr "track") return Note{..} data Song = Song { properties :: Properties , data_ :: V.Vector Note } deriving (Show) instance IsInside Song where insideCodec = do properties <- (.properties) =. childTag "Properties" (parseInside' insideCodec) data_ <- (.data_) =. childTag "Data" (parseInside' $ bareList $ isTag "Note" $ parseInside' insideCodec) return Song{..} parseSong :: (SendMessage m) => T.Text -> StackTraceT m Song parseSong xml = do elt <- maybe (fatal "Couldn't parse XML") return $ parseXMLDoc xml mapStackTraceT (`runReaderT` elt) $ codecIn $ isTag "Song" $ parseInside' insideCodec songToMidi :: Song -> F.Song (F.OnyxFile U.Beats) songToMidi song = let " BeatsPerSecond " is probably useless sigs = U.measureMapFromTimeSigs U.Truncate RTB.empty threshold :: U.Seconds threshold = case NE.nonEmpty $ catMaybes [song.properties.hammerOnTime, song.properties.pullOffTime] of Nothing -> 0.25 Just ne -> realToFrac $ maximum ne gtr = emit5' $ U.unapplyTempoTrack tempos $ strumHOPOTap HOPOsRBGuitar threshold $ RTB.fromAbsoluteEventList $ ATB.fromPairList $ sort $ map (\n -> let time = realToFrac n.time fret = Just $ toEnum n.track len = case n.duration of 0 -> Nothing d -> Just $ realToFrac d in (time, (fret, len)) ) $ V.toList song.data_ in F.Song { s_tempos = tempos , s_signatures = sigs , s_tracks = mempty { F.onyxParts = Map.singleton F.FlexGuitar mempty { F.onyxPartGuitar = mempty { Five.fiveDifficulties = Map.singleton Expert gtr } } } } importFreetar :: (SendMessage m, MonadIO m) => FilePath -> Import m importFreetar sng level = do song <- stackIO (B.readFile sng) >>= parseSong . decodeGeneral let props = song.properties return SongYaml { metadata = def' { title = props.title , artist = props.artist , album = props.album , year = props.year >>= readMaybe . T.unpack , comments = [] , fileAlbumArt = Nothing } , jammit = mempty , global = def' { backgroundVideo = Nothing , fileBackgroundImage = Nothing , fileMidi = SoftFile "notes.mid" $ SoftChart $ case level of ImportFull -> songToMidi song ImportQuick -> emptyChart , fileSongAnim = Nothing } , audio = HM.fromList $ toList $ flip fmap props.musicFileName $ \f -> let f' = takeDirectory sng </> T.unpack f audio = AudioFile AudioInfo { md5 = Nothing , frames = Nothing , commands = [] , filePath = Just $ SoftFile ("audio" <.> takeExtension f') $ SoftReadable $ fileReadable f' , rate = Nothing } in ("song", audio) , plans = HM.fromList $ toList $ flip fmap props.musicFileName $ \_ -> let plan = StandardPlan StandardPlanInfo { song = Just $ PlanAudio (Input $ Named "song") [] [] , parts = Parts HM.empty , crowd = Nothing , comments = [] , tuningCents = 0 , fileTempo = Nothing } in ("freetar", plan) , targets = HM.empty , parts = Parts $ HM.singleton F.FlexGuitar emptyPart { grybo = Just def } }
9e3c250608f593f400d3df15b2e71f4c78ab777fe18e81c25fd5b059060f54bb
grin-compiler/ghc-wpc-sample-programs
Main.hs
| Module : . REPL Description : Main function to decide ' mode of use . License : : The Idris Community . Module : Idris.REPL Description : Main function to decide Idris' mode of use. License : BSD3 Maintainer : The Idris Community. -} module Idris.Main ( idrisMain , idris , runMain taken from . REPL . taken from . ModeCommon ) where import Idris.AbsSyntax import Idris.Core.Execute (execute) import Idris.Core.TT import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error import Idris.IBC import Idris.Info import Idris.ModeCommon import Idris.Options import Idris.Output import Idris.Parser hiding (indent) import Idris.REPL import Idris.REPL.Commands import Idris.REPL.Parser import IRTS.CodegenCommon import Util.System import Control.Category import Control.DeepSeq import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Trans.Except (runExceptT) import Control.Monad.Trans.State.Strict (execStateT) import Data.List import Data.Maybe import Prelude hiding (id, (.), (<$>)) import System.Console.Haskeline as H import System.Directory import System.Exit import System.FilePath import System.IO import System.IO.CodePage (withCP65001) | How to run programs . runMain :: Idris () -> IO () runMain prog = withCP65001 $ do Run in codepage 65001 on Windows so that UTF-8 characters can be displayed properly . See # 3000 . res <- runExceptT $ execStateT prog idrisInit case res of Left err -> do putStrLn $ "Uncaught error: " ++ show err exitFailure Right _ -> return () | The main function of that when given a set of Options will launch into the desired interaction mode either : REPL ; Compiler ; Script execution ; or IDE Mode . idrisMain :: [Opt] -> Idris () idrisMain opts = do mapM_ setWidth (opt getConsoleWidth opts) let inputs = opt getFile opts let quiet = Quiet `elem` opts let nobanner = NoBanner `elem` opts let idesl = Idemode `elem` opts || IdemodeSocket `elem` opts let runrepl = not (NoREPL `elem` opts) let output = opt getOutput opts let ibcsubdir = opt getIBCSubDir opts let importdirs = opt getImportDir opts let sourcedirs = opt getSourceDir opts setSourceDirs sourcedirs let bcs = opt getBC opts let pkgdirs = opt getPkgDir opts -- Set default optimisations let optimise = case opt getOptLevel opts of [] -> 1 xs -> last xs setOptLevel optimise let outty = case opt getOutputTy opts of [] -> if Interface `elem` opts then Object else Executable xs -> last xs let cgn = case opt getCodegen opts of [] -> Via IBCFormat "c" xs -> last xs let cgFlags = opt getCodegenArgs opts -- Now set/unset specifically chosen optimisations let os = opt getOptimisation opts mapM_ processOptimisation os script <- case opt getExecScript opts of [] -> return Nothing x:y:xs -> do iputStrLn "More than one interpreter expression found." runIO $ exitWith (ExitFailure 1) [expr] -> return (Just expr) let immediate = opt getEvalExpr opts let port = case getPort opts of Nothing -> ListenPort defaultPort Just p -> p when (DefaultTotal `elem` opts) $ do i <- getIState putIState (i { default_total = DefaultCheckingTotal }) tty <- runIO isATTY setColourise $ not quiet && last (tty : opt getColour opts) runIO $ hSetBuffering stdout LineBuffering mapM_ addLangExt (opt getLanguageExt opts) setREPL runrepl setQuiet (quiet || isJust script || not (null immediate)) setCmdLine opts setOutputTy outty setNoBanner nobanner setCodegen cgn mapM_ (addFlag cgn) cgFlags mapM_ makeOption opts vlevel <- verbose when (runrepl && vlevel == 0) $ setVerbose 1 -- if we have the --bytecode flag, drop into the bytecode assembler case bcs of [] -> return () runIO $ mapM _ bcAsm xs case ibcsubdir of [] -> setIBCSubDir "" (d:_) -> setIBCSubDir d setImportDirs importdirs setNoBanner nobanner -- Check if listed packages are actually installed idrisCatch (do ipkgs <- runIO $ getIdrisInstalledPackages let diff_pkgs = (\\) pkgdirs ipkgs when (not $ null diff_pkgs) $ do iputStrLn "The following packages were specified but cannot be found:" iputStr $ unlines $ map (\x -> unwords ["-", x]) diff_pkgs runIO $ exitWith (ExitFailure 1)) (\e -> return ()) when (not (NoBasePkgs `elem` opts)) $ do addPkgDir "prelude" addPkgDir "base" mapM_ addPkgDir pkgdirs elabPrims when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" (IBC_REPL False) addAutoImport "Builtins" return () when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" (IBC_REPL False) addAutoImport "Prelude" return () when (runrepl && not idesl) initScript nobanner <- getNoBanner when (runrepl && not quiet && not idesl && not (isJust script) && not nobanner && null immediate) $ iputStrLn banner orig <- getIState mods <- if idesl then return [] else loadInputs inputs Nothing let efile = case inputs of [] -> "" (f:_) -> f ok <- noErrors when ok $ case output of [] -> return () (o:_) -> idrisCatch (process "" (Compile cgn o)) (\e -> do ist <- getIState ; iputStrLn $ pshow ist e) case immediate of [] -> return () exprs -> do setWidth InfinitelyWide mapM_ (\str -> do ist <- getIState c <- colourise case parseExpr ist str of Left err -> do emitWarning err runIO $ exitWith (ExitFailure 1) Right e -> process "" (Eval e)) exprs runIO exitSuccess case script of Nothing -> return () Just expr -> execScript expr Create data dir + repl history and config dir idrisCatch (do dir <- runIO $ getIdrisUserDataDir exists <- runIO $ doesDirectoryExist dir unless exists $ logLvl 1 ("Creating " ++ dir) runIO $ createDirectoryIfMissing True (dir </> "repl")) (\e -> return ()) historyFile <- runIO $ getIdrisHistoryFile when ok $ case opt getPkgIndex opts of (f : _) -> writePkgIndex f _ -> return () when (runrepl && not idesl) $ do -- clearOrigPats case port of DontListen -> return () ListenPort port' -> startServer port' orig mods runInputT (replSettings (Just historyFile)) $ repl (force orig) mods efile let idesock = IdemodeSocket `elem` opts when (idesl) $ idemodeStart idesock orig inputs ok <- noErrors when (not ok) $ runIO (exitWith (ExitFailure 1)) where makeOption (OLogging i) = setLogLevel i makeOption (OLogCats cs) = setLogCats cs makeOption (Verbose v) = setVerbose v makeOption TypeCase = setTypeCase True makeOption TypeInType = setTypeInType True makeOption NoCoverage = setCoverage False makeOption ErrContext = setErrContext True makeOption (IndentWith n) = setIndentWith n makeOption (IndentClause n) = setIndentClause n makeOption _ = return () processOptimisation :: (Bool,Optimisation) -> Idris () processOptimisation (True, p) = addOptimise p processOptimisation (False, p) = removeOptimise p addPkgDir :: String -> Idris () addPkgDir p = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> p) addIBC (IBCImportDir (ddir </> p)) -- | Invoke as if from command line. It is an error if there are -- unresolved totality problems. idris :: [Opt] -> IO (Maybe IState) idris opts = do res <- runExceptT $ execStateT totalMain idrisInit case res of Left err -> do putStrLn $ pshow idrisInit err return Nothing Right ist -> return (Just ist) where totalMain = do idrisMain opts ist <- getIState case idris_totcheckfail ist of ((fc, msg):_) -> ierror . At fc . Msg $ "Could not build: "++ msg [] -> return () | Execute the provided expression . execScript :: String -> Idris () execScript expr = do i <- getIState c <- colourise case parseExpr i expr of Left err -> do emitWarning err runIO $ exitWith (ExitFailure 1) Right term -> do ctxt <- getContext (tm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS term res <- execute tm runIO $ exitSuccess -- | Run the initialisation script initScript :: Idris () initScript = do script <- runIO $ getIdrisInitScript idrisCatch (do go <- runIO $ doesFileExist script when go $ do h <- runIO $ openFile script ReadMode runInit h runIO $ hClose h) (\e -> iPrintError $ "Error reading init file: " ++ show e) where runInit :: Handle -> Idris () runInit h = do eof <- lift . lift $ hIsEOF h ist <- getIState unless eof $ do line <- runIO $ hGetLine h script <- runIO $ getIdrisInitScript c <- colourise processLine ist line script c runInit h processLine i cmd input clr = case parseCmd i input cmd of Left err -> emitWarning err Right (Right Reload) -> iPrintError "Init scripts cannot reload the file" Right (Right (Load f _)) -> iPrintError "Init scripts cannot load files" Right (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules" Right (Right Edit) -> iPrintError "Init scripts cannot invoke the editor" Right (Right Proofs) -> proofs i Right (Right Quit) -> iPrintError "Init scripts cannot quit Idris" Right (Right cmd ) -> process [] cmd Right (Left err) -> runIO $ print err
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/idris-1.3.3/src/Idris/Main.hs
haskell
Set default optimisations Now set/unset specifically chosen optimisations if we have the --bytecode flag, drop into the bytecode assembler Check if listed packages are actually installed clearOrigPats | Invoke as if from command line. It is an error if there are unresolved totality problems. | Run the initialisation script
| Module : . REPL Description : Main function to decide ' mode of use . License : : The Idris Community . Module : Idris.REPL Description : Main function to decide Idris' mode of use. License : BSD3 Maintainer : The Idris Community. -} module Idris.Main ( idrisMain , idris , runMain taken from . REPL . taken from . ModeCommon ) where import Idris.AbsSyntax import Idris.Core.Execute (execute) import Idris.Core.TT import Idris.Elab.Term import Idris.Elab.Value import Idris.ElabDecls import Idris.Error import Idris.IBC import Idris.Info import Idris.ModeCommon import Idris.Options import Idris.Output import Idris.Parser hiding (indent) import Idris.REPL import Idris.REPL.Commands import Idris.REPL.Parser import IRTS.CodegenCommon import Util.System import Control.Category import Control.DeepSeq import Control.Monad import Control.Monad.Trans (lift) import Control.Monad.Trans.Except (runExceptT) import Control.Monad.Trans.State.Strict (execStateT) import Data.List import Data.Maybe import Prelude hiding (id, (.), (<$>)) import System.Console.Haskeline as H import System.Directory import System.Exit import System.FilePath import System.IO import System.IO.CodePage (withCP65001) | How to run programs . runMain :: Idris () -> IO () runMain prog = withCP65001 $ do Run in codepage 65001 on Windows so that UTF-8 characters can be displayed properly . See # 3000 . res <- runExceptT $ execStateT prog idrisInit case res of Left err -> do putStrLn $ "Uncaught error: " ++ show err exitFailure Right _ -> return () | The main function of that when given a set of Options will launch into the desired interaction mode either : REPL ; Compiler ; Script execution ; or IDE Mode . idrisMain :: [Opt] -> Idris () idrisMain opts = do mapM_ setWidth (opt getConsoleWidth opts) let inputs = opt getFile opts let quiet = Quiet `elem` opts let nobanner = NoBanner `elem` opts let idesl = Idemode `elem` opts || IdemodeSocket `elem` opts let runrepl = not (NoREPL `elem` opts) let output = opt getOutput opts let ibcsubdir = opt getIBCSubDir opts let importdirs = opt getImportDir opts let sourcedirs = opt getSourceDir opts setSourceDirs sourcedirs let bcs = opt getBC opts let pkgdirs = opt getPkgDir opts let optimise = case opt getOptLevel opts of [] -> 1 xs -> last xs setOptLevel optimise let outty = case opt getOutputTy opts of [] -> if Interface `elem` opts then Object else Executable xs -> last xs let cgn = case opt getCodegen opts of [] -> Via IBCFormat "c" xs -> last xs let cgFlags = opt getCodegenArgs opts let os = opt getOptimisation opts mapM_ processOptimisation os script <- case opt getExecScript opts of [] -> return Nothing x:y:xs -> do iputStrLn "More than one interpreter expression found." runIO $ exitWith (ExitFailure 1) [expr] -> return (Just expr) let immediate = opt getEvalExpr opts let port = case getPort opts of Nothing -> ListenPort defaultPort Just p -> p when (DefaultTotal `elem` opts) $ do i <- getIState putIState (i { default_total = DefaultCheckingTotal }) tty <- runIO isATTY setColourise $ not quiet && last (tty : opt getColour opts) runIO $ hSetBuffering stdout LineBuffering mapM_ addLangExt (opt getLanguageExt opts) setREPL runrepl setQuiet (quiet || isJust script || not (null immediate)) setCmdLine opts setOutputTy outty setNoBanner nobanner setCodegen cgn mapM_ (addFlag cgn) cgFlags mapM_ makeOption opts vlevel <- verbose when (runrepl && vlevel == 0) $ setVerbose 1 case bcs of [] -> return () runIO $ mapM _ bcAsm xs case ibcsubdir of [] -> setIBCSubDir "" (d:_) -> setIBCSubDir d setImportDirs importdirs setNoBanner nobanner idrisCatch (do ipkgs <- runIO $ getIdrisInstalledPackages let diff_pkgs = (\\) pkgdirs ipkgs when (not $ null diff_pkgs) $ do iputStrLn "The following packages were specified but cannot be found:" iputStr $ unlines $ map (\x -> unwords ["-", x]) diff_pkgs runIO $ exitWith (ExitFailure 1)) (\e -> return ()) when (not (NoBasePkgs `elem` opts)) $ do addPkgDir "prelude" addPkgDir "base" mapM_ addPkgDir pkgdirs elabPrims when (not (NoBuiltins `elem` opts)) $ do x <- loadModule "Builtins" (IBC_REPL False) addAutoImport "Builtins" return () when (not (NoPrelude `elem` opts)) $ do x <- loadModule "Prelude" (IBC_REPL False) addAutoImport "Prelude" return () when (runrepl && not idesl) initScript nobanner <- getNoBanner when (runrepl && not quiet && not idesl && not (isJust script) && not nobanner && null immediate) $ iputStrLn banner orig <- getIState mods <- if idesl then return [] else loadInputs inputs Nothing let efile = case inputs of [] -> "" (f:_) -> f ok <- noErrors when ok $ case output of [] -> return () (o:_) -> idrisCatch (process "" (Compile cgn o)) (\e -> do ist <- getIState ; iputStrLn $ pshow ist e) case immediate of [] -> return () exprs -> do setWidth InfinitelyWide mapM_ (\str -> do ist <- getIState c <- colourise case parseExpr ist str of Left err -> do emitWarning err runIO $ exitWith (ExitFailure 1) Right e -> process "" (Eval e)) exprs runIO exitSuccess case script of Nothing -> return () Just expr -> execScript expr Create data dir + repl history and config dir idrisCatch (do dir <- runIO $ getIdrisUserDataDir exists <- runIO $ doesDirectoryExist dir unless exists $ logLvl 1 ("Creating " ++ dir) runIO $ createDirectoryIfMissing True (dir </> "repl")) (\e -> return ()) historyFile <- runIO $ getIdrisHistoryFile when ok $ case opt getPkgIndex opts of (f : _) -> writePkgIndex f _ -> return () when (runrepl && not idesl) $ do case port of DontListen -> return () ListenPort port' -> startServer port' orig mods runInputT (replSettings (Just historyFile)) $ repl (force orig) mods efile let idesock = IdemodeSocket `elem` opts when (idesl) $ idemodeStart idesock orig inputs ok <- noErrors when (not ok) $ runIO (exitWith (ExitFailure 1)) where makeOption (OLogging i) = setLogLevel i makeOption (OLogCats cs) = setLogCats cs makeOption (Verbose v) = setVerbose v makeOption TypeCase = setTypeCase True makeOption TypeInType = setTypeInType True makeOption NoCoverage = setCoverage False makeOption ErrContext = setErrContext True makeOption (IndentWith n) = setIndentWith n makeOption (IndentClause n) = setIndentClause n makeOption _ = return () processOptimisation :: (Bool,Optimisation) -> Idris () processOptimisation (True, p) = addOptimise p processOptimisation (False, p) = removeOptimise p addPkgDir :: String -> Idris () addPkgDir p = do ddir <- runIO getIdrisLibDir addImportDir (ddir </> p) addIBC (IBCImportDir (ddir </> p)) idris :: [Opt] -> IO (Maybe IState) idris opts = do res <- runExceptT $ execStateT totalMain idrisInit case res of Left err -> do putStrLn $ pshow idrisInit err return Nothing Right ist -> return (Just ist) where totalMain = do idrisMain opts ist <- getIState case idris_totcheckfail ist of ((fc, msg):_) -> ierror . At fc . Msg $ "Could not build: "++ msg [] -> return () | Execute the provided expression . execScript :: String -> Idris () execScript expr = do i <- getIState c <- colourise case parseExpr i expr of Left err -> do emitWarning err runIO $ exitWith (ExitFailure 1) Right term -> do ctxt <- getContext (tm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS term res <- execute tm runIO $ exitSuccess initScript :: Idris () initScript = do script <- runIO $ getIdrisInitScript idrisCatch (do go <- runIO $ doesFileExist script when go $ do h <- runIO $ openFile script ReadMode runInit h runIO $ hClose h) (\e -> iPrintError $ "Error reading init file: " ++ show e) where runInit :: Handle -> Idris () runInit h = do eof <- lift . lift $ hIsEOF h ist <- getIState unless eof $ do line <- runIO $ hGetLine h script <- runIO $ getIdrisInitScript c <- colourise processLine ist line script c runInit h processLine i cmd input clr = case parseCmd i input cmd of Left err -> emitWarning err Right (Right Reload) -> iPrintError "Init scripts cannot reload the file" Right (Right (Load f _)) -> iPrintError "Init scripts cannot load files" Right (Right (ModImport f)) -> iPrintError "Init scripts cannot import modules" Right (Right Edit) -> iPrintError "Init scripts cannot invoke the editor" Right (Right Proofs) -> proofs i Right (Right Quit) -> iPrintError "Init scripts cannot quit Idris" Right (Right cmd ) -> process [] cmd Right (Left err) -> runIO $ print err
a4bfe367668c38ccd893556286713be40530cfa3c9dbd794afa381837b985fd1
EFanZh/EOPL-Exercises
exercise-1.24-test.rkt
#lang racket/base (require rackunit) (require "../solutions/exercise-1.24.rkt") (check-false (every? number? '(a b c 3 e))) (check-true (every? number? '(1 2 3 5 4))) (check-true (every? number? '()))
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/tests/exercise-1.24-test.rkt
racket
#lang racket/base (require rackunit) (require "../solutions/exercise-1.24.rkt") (check-false (every? number? '(a b c 3 e))) (check-true (every? number? '(1 2 3 5 4))) (check-true (every? number? '()))
60f2224e40af733bbbc4fd36991ed8d69ccb323e77ebe0c7585b75844627958f
sellout/haskerwaul
Lax.hs
# language UndecidableSuperClasses # module Haskerwaul.Functor.Closed.Lax ( module Haskerwaul.Functor.Closed.Lax -- * extended modules , module Haskerwaul.Functor ) where import Data.Proxy (Proxy) import Haskerwaul.Category.Monoidal.Closed import Haskerwaul.Functor -- | [nLab](+functor) class (ClosedCategory c, ClosedCategory d, Functor c d f) => LaxClosedFunctor c d f where fHat :: Proxy c -> f (InternalHom c x y) `d` InternalHom d (f x) (f y) -- -- | Every `LaxMonoidalFunctor` between `ClosedMonoidalCategories` gives rise to -- -- a `LaxClosedFunctor`. -- instance ( ClosedMonoidalCategory c , ClosedMonoidalCategory d , LaxMonoidalFunctor c d f ) = > -- LaxClosedFunctor c d f where fHat =
null
https://raw.githubusercontent.com/sellout/haskerwaul/cf54bd7ce5bf4f3d1fd0d9d991dc733785b66a73/src/Haskerwaul/Functor/Closed/Lax.hs
haskell
* extended modules | [nLab](+functor) -- | Every `LaxMonoidalFunctor` between `ClosedMonoidalCategories` gives rise to -- a `LaxClosedFunctor`. instance ( ClosedMonoidalCategory c LaxClosedFunctor c d f where
# language UndecidableSuperClasses # module Haskerwaul.Functor.Closed.Lax ( module Haskerwaul.Functor.Closed.Lax , module Haskerwaul.Functor ) where import Data.Proxy (Proxy) import Haskerwaul.Category.Monoidal.Closed import Haskerwaul.Functor class (ClosedCategory c, ClosedCategory d, Functor c d f) => LaxClosedFunctor c d f where fHat :: Proxy c -> f (InternalHom c x y) `d` InternalHom d (f x) (f y) , ClosedMonoidalCategory d , LaxMonoidalFunctor c d f ) = > fHat =
598990cc471477621cf125d4f6ce945196bc8c16bbd1972722c2f8afe986710b
clckwrks/clckwrks
Monad.hs
# LANGUAGE CPP , DeriveDataTypeable , GeneralizedNewtypeDeriving , MultiParamTypeClasses , FlexibleInstances , TypeSynonymInstances , FlexibleContexts , TypeFamilies , RankNTypes , RecordWildCards , ScopedTypeVariables , UndecidableInstances , OverloadedStrings , TemplateHaskell # module Clckwrks.Monad ( Clck , ClckPlugins , ClckPluginsSt(cpsAcid) , initialClckPluginsSt , ClckT(..) , ClckForm , ClckFormT , ClckFormError(..) , ChildType(..) , ClckwrksConfig(..) , TLSSettings(..) , AttributeType(..) , Theme(..) , ThemeStyle(..) , ThemeStyleId(..) , ThemeName , getThemeStyles , themeTemplate , calcBaseURI , calcTLSBaseURI , evalClckT , execClckT , runClckT , mapClckT , withRouteClckT , ClckState(..) , Content(..) -- , markupToContent , addPreProcessor , addAdminMenu , appendRequestInit , getNavBarLinks , addPreProc , addNavBarCallback , getPreProcessors , , getEnableAnalytics , googleAnalytics , getUnique , setUnique , setRedirectCookie , getRedirectCookie , query , update , nestURL , isSecure , withAbs , withAbs' , segments , transform , module HSP.XML , module HSP.XMLGenerator ) where import Clckwrks.Admin.URL (AdminURL(..)) import Clckwrks.Acid (Acid(..), CoreState, GetAcidState(..), GetUACCT(..)) import Clckwrks.ProfileData.Acid (ProfileDataState, GetRoles(..), HasRole(..)) import Clckwrks.ProfileData.Types (Role(..)) import Clckwrks.NavBar.Acid (NavBarState) import Clckwrks.NavBar.Types (NavBarLinks(..)) import Clckwrks.Types (NamedLink(..), Prefix, Trust(Trusted)) import Clckwrks.Unauthorized (unauthorizedPage) import Clckwrks.URL (ClckURL(..)) import Control.Applicative (Alternative, Applicative, (<$>), (<|>), many, optional) #if MIN_VERSION_base (4,9,0) && !MIN_VERSION_base (4,13,0) import Control.Monad.Fail (MonadFail) #endif import Control.Monad (MonadPlus, foldM) import Control.Monad.State (MonadState, StateT, evalStateT, execStateT, get, mapStateT, modify, put, runStateT) import Control.Monad.Reader (MonadReader, ReaderT, mapReaderT) import Control.Monad.Trans (MonadIO(liftIO), MonadTrans(lift)) import Control.Concurrent.STM (TVar, readTVar, writeTVar, atomically) import Data.Acid (AcidState, EventState, EventResult, QueryEvent, UpdateEvent) import Data.Acid.Advanced (query', update') import Data.Attoparsec.Text.Lazy (Parser, parseOnly, char, asciiCI, try, takeWhile, takeWhile1) import qualified Data.HashMap.Lazy as HashMap import qualified Data.List as List import qualified Data.Map as Map import Data.Monoid ((<>), mappend, mconcat) import qualified Data.Serialize as S import Data.Traversable (sequenceA) import qualified Data.Vector as Vector import Data.ByteString.Lazy as LB (ByteString) import Data.ByteString.Lazy.UTF8 as LB (toString) import Data.Data (Data, Typeable) import Data.Map (Map) import Data.Maybe (fromJust) import Data.SafeCopy (SafeCopy(..), Contained, deriveSafeCopy, base, contain) import Data.Set (Set) import qualified Data.Set as Set import Data.Sequence (Seq) import qualified Data.Text as T import qualified Data.Text as Text import qualified Data.Text.Lazy as TL import Data.Text.Lazy.Builder (Builder, fromText) import qualified Data.Text.Lazy.Builder as B import Data.Time.Clock (UTCTime) import Data.Time.Format (formatTime) import Data.UserId (UserId(..)) import Happstack.Server ( CookieLife(Session), Happstack, ServerMonad(..), FilterMonad(..) , WebMonad(..), Input, Request(..), Response, HasRqData(..) , ServerPart, ServerPartT, UnWebT, addCookie, expireCookie, escape , internalServerError, lookCookieValue, mapServerPartT, mkCookie , toResponse, getHeaderUnsafe ) ToMessage XML instance instance import Happstack.Server.Internal.Monads (FilterFun) import HSP hiding ( Request , escape ) import HSP.Google.Analytics (UACCT, universalAnalytics) -- import HSP.ServerPartT () import HSP.XML import HSP.XMLGenerator import HSP.JMacro (IntegerSupply(..)) import Language.Javascript.JMacro import Prelude hiding (takeWhile) can import from time directly when time-1.4 / ghc 7.8 is not important anymore import Text.Blaze.Html (Html) import Text.Blaze.Html.Renderer.Text (renderHtml) import Text.Reform (CommonFormError, Form, FormError(..)) import Web.Routes (URL, MonadRoute(askRouteFn), RouteT(RouteT, unRouteT), mapRouteT, showURL, withRouteT) import Web.Plugins.Core (Plugins, getConfig, getPluginsSt, modifyPluginsSt, getTheme) import qualified Web.Routes as R import Web.Routes.Happstack (seeOtherURL) -- imported so that instances are scope even though we do not use them here import Web.Routes.XMLGenT () -- imported so that instances are scope even though we do not use them here ------------------------------------------------------------------------------ -- Theme ------------------------------------------------------------------------------ type ThemeName = T.Text newtype ThemeStyleId = ThemeStyleId { unThemeStyleId :: Int } deriving (Eq, Ord, Read, Show, Data, Typeable) instance SafeCopy ThemeStyleId where getCopy = contain $ ThemeStyleId <$> S.get putCopy (ThemeStyleId i) = contain $ S.put i errorTypeName _ = "ThemeStyleId" data ThemeStyle = ThemeStyle { themeStyleName :: T.Text , themeStyleDescription :: T.Text , themeStylePreview :: Maybe FilePath , themeStyleTemplate :: forall headers body. ( EmbedAsChild (ClckT ClckURL (ServerPartT IO)) headers , EmbedAsChild (ClckT ClckURL (ServerPartT IO)) body) => T.Text -> headers -> body -> XMLGenT (ClckT ClckURL (ServerPartT IO)) XML } data Theme = Theme { themeName :: ThemeName , themeStyles :: [ThemeStyle] , themeDataDir :: IO FilePath } themeTemplate :: ( EmbedAsChild (ClckT ClckURL (ServerPartT IO)) headers , EmbedAsChild (ClckT ClckURL (ServerPartT IO)) body ) => ClckPlugins -> ThemeStyleId -> T.Text -> headers -> body -> ClckT ClckURL (ServerPartT IO) Response themeTemplate plugins tsid ttl hdrs bdy = do mTheme <- getTheme plugins case mTheme of Nothing -> escape $ internalServerError $ toResponse $ ("No theme package is loaded." :: T.Text) (Just theme) -> case lookupThemeStyle tsid (themeStyles theme) of Nothing -> escape $ internalServerError $ toResponse $ ("The current theme does not seem to contain any theme styles." :: T.Text) (Just themeStyle) -> fmap toResponse $ unXMLGenT $ ((themeStyleTemplate themeStyle) ttl hdrs bdy) lookupThemeStyle :: ThemeStyleId -> [a] -> Maybe a lookupThemeStyle _ [] = Nothing lookupThemeStyle (ThemeStyleId 0) (t:_) = Just t lookupThemeStyle (ThemeStyleId n) (t':ts) = lookupThemeStyle' (n - 1) ts where lookupThemeStyle' _ [] = Just t' lookupThemeStyle' 0 (t:ts) = Just t lookupThemeStyle' n (_:ts) = lookupThemeStyle' (n - 1) ts getThemeStyles :: (MonadIO m) => ClckPlugins -> m [(ThemeStyleId, ThemeStyle)] getThemeStyles plugins = do mTheme <- getTheme plugins case mTheme of Nothing -> return [] (Just theme) -> return $ zip (map ThemeStyleId [0..]) (themeStyles theme) ------------------------------------------------------------------------------ ClckwrksConfig ------------------------------------------------------------------------------ data TLSSettings = TLSSettings { clckTLSPort :: Int , clckTLSCert :: Maybe FilePath , clckTLSKey :: Maybe FilePath , clckTLSCA :: Maybe FilePath , clckTLSRev :: Bool } data ClckwrksConfig = ClckwrksConfig { clckHostname :: String -- ^ external name of the host , clckPort :: Int -- ^ port to listen on , clckTLS :: Maybe TLSSettings -- ^ HTTPS , clckHidePort :: Bool -- ^ hide port number in URL (useful when running behind a reverse proxy) , clckJQueryPath :: FilePath -- ^ path to @jquery.js@ on disk ^ path to @jquery - ui.js@ on disk ^ path to on disk , clckJSON2Path :: FilePath -- ^ path to @JSON2.js@ on disk , clckTopDir :: Maybe FilePath -- ^ path to top-level directory for all acid-state files/file uploads/etc ^ enable google analytics , clckInitHook :: T.Text -> ClckState -> ClckwrksConfig -> IO (ClckState, ClckwrksConfig) -- ^ init hook } -- | calculate the baseURI from the 'clckHostname', 'clckPort' and 'clckHidePort' options calcBaseURI :: ClckwrksConfig -> T.Text calcBaseURI c = Text.pack $ "http://" ++ (clckHostname c) ++ if ((clckPort c /= 80) && (clckHidePort c == False)) then (':' : show (clckPort c)) else "" calcTLSBaseURI :: ClckwrksConfig -> Maybe T.Text calcTLSBaseURI c = case clckTLS c of Nothing -> Nothing (Just tlsSettings) -> Just $ Text.pack $ "https://" ++ (clckHostname c) ++ if ((clckPort c /= 443) && (clckHidePort c == False)) then (':' : show (clckTLSPort tlsSettings)) else "" ------------------------------------------------------------------------------ ClckState ------------------------------------------------------------------------------ data ClckState = ClckState { acidState :: Acid , uniqueId :: TVar Integer -- only unique for this request , adminMenus :: [(T.Text, [(Set Role, T.Text, T.Text)])] ^ enable Google Analytics , plugins :: ClckPlugins , requestInit :: ServerPart () -- ^ an action which gets called at the beginning of each request } ------------------------------------------------------------------------------ ClckT ------------------------------------------------------------------------------ newtype ClckT url m a = ClckT { unClckT :: RouteT url (StateT ClckState m) a } #if MIN_VERSION_base(4,9,0) deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadFail, MonadPlus, ServerMonad, HasRqData, FilterMonad r, WebMonad r, MonadState ClckState) #else deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadPlus, ServerMonad, HasRqData, FilterMonad r, WebMonad r, MonadState ClckState) #endif instance (Happstack m) => Happstack (ClckT url m) instance MonadTrans (ClckT url) where lift = ClckT . lift . lift | evaluate a ' ClckT ' returning the inner monad -- -- similar to 'evalStateT'. evalClckT :: (Monad m) => (url -> [(Text.Text, Maybe Text.Text)] -> Text.Text) -- ^ function to act as 'showURLParams' ^ initial ' ClckState ' -> ClckT url m a -- ^ 'ClckT' to evaluate -> m a evalClckT showFn clckState m = evalStateT (unRouteT (unClckT m) showFn) clckState | execute a ' ClckT ' returning the final ' ClckState ' -- -- similar to 'execStateT'. execClckT :: (Monad m) => (url -> [(Text.Text, Maybe Text.Text)] -> Text.Text) -- ^ function to act as 'showURLParams' ^ initial ' ClckState ' -> ClckT url m a -- ^ 'ClckT' to evaluate -> m ClckState execClckT showFn clckState m = execStateT (unRouteT (unClckT m) showFn) clckState | run a ' ClckT ' -- -- similar to 'runStateT'. runClckT :: (Monad m) => (url -> [(Text.Text, Maybe Text.Text)] -> Text.Text) -- ^ function to act as 'showURLParams' ^ initial ' ClckState ' -> ClckT url m a -- ^ 'ClckT' to evaluate -> m (a, ClckState) runClckT showFn clckState m = runStateT (unRouteT (unClckT m) showFn) clckState -- | map a transformation function over the inner monad -- -- similar to 'mapStateT' mapClckT :: (m (a, ClckState) -> n (b, ClckState)) -- ^ transformation function -> ClckT url m a -- ^ initial monad -> ClckT url n b mapClckT f (ClckT r) = ClckT $ mapRouteT (mapStateT f) r -- | error returned when a reform 'Form' fails to validate data ClckFormError = ClckCFE (CommonFormError [Input]) | EmptyUsername | InvalidDecimal T.Text deriving (Show) instance FormError ClckFormError where type ErrorInputType ClckFormError = [Input] commonFormError = ClckCFE | ClckForm - type for reform forms type ClckFormT error m = Form m [Input] error [XMLGenT m XML] () type ClckForm url = Form (ClckT url (ServerPartT IO)) [Input] ClckFormError [XMLGenT (ClckT url (ServerPartT IO)) XML] () ------------------------------------------------------------------------------ ClckPlugins / ClckPluginsSt ------------------------------------------------------------------------------ data ClckPluginsSt = ClckPluginsSt { cpsPreProcessors :: forall m. (Functor m, MonadIO m, Happstack m) => [TL.Text -> ClckT ClckURL m TL.Text] , cpsNavBarLinks :: [ClckT ClckURL IO (String, [NamedLink])] ^ this value is also in ClckState , but it is sometimes needed by plugins during initPlugin } initialClckPluginsSt :: Acid -> ClckPluginsSt initialClckPluginsSt acid = ClckPluginsSt { cpsPreProcessors = [] , cpsNavBarLinks = [] , cpsAcid = acid } -- | ClckPlugins -- -- newtype Plugins theme m hook config st type ClckPlugins = Plugins Theme (ClckT ClckURL (ServerPartT IO) Response) (ClckT ClckURL IO ()) ClckwrksConfig ClckPluginsSt setUnique :: (Functor m, MonadIO m) => Integer -> ClckT url m () setUnique i = do u <- uniqueId <$> get liftIO $ atomically $ writeTVar u i -- | get a unique 'Integer'. -- -- Only unique for the current request getUnique :: (Functor m, MonadIO m) => ClckT url m Integer getUnique = do u <- uniqueId <$> get liftIO $ atomically $ do i <- readTVar u writeTVar u (succ i) return i | get the ' Bool ' value indicating if Google Analytics should be enabled or not getEnableAnalytics :: (Functor m, MonadState ClckState m) => m Bool getEnableAnalytics = enableAnalytics <$> get -- | add an Admin menu addAdminMenu :: (Monad m) => (T.Text, [(Set Role, T.Text, T.Text)]) -> ClckT url m () addAdminMenu (category, entries) = modify $ \cs -> let oldMenus = adminMenus cs newMenus = Map.toAscList $ Map.insertWith List.union category entries $ Map.fromList oldMenus in cs { adminMenus = newMenus } -- | append an action to the request init appendRequestInit :: (Monad m) => ServerPart () -> ClckT url m () appendRequestInit action = modify $ \cs -> cs { requestInit = (requestInit cs) >> action } -- | change the route url withRouteClckT :: ((url' -> [(T.Text, Maybe T.Text)] -> T.Text) -> url -> [(T.Text, Maybe T.Text)] -> T.Text) -> ClckT url m a -> ClckT url' m a withRouteClckT f (ClckT routeT) = (ClckT $ withRouteT f routeT) type Clck url = ClckT url (ServerPartT IO) instance (Functor m, MonadIO m) => IntegerSupply (ClckT url m) where nextInteger = getUnique nestURL :: (url1 -> url2) -> ClckT url1 m a -> ClckT url2 m a nestURL f (ClckT r) = ClckT $ R.nestURL f r isSecure :: ClckwrksConfig -> Request -> Bool isSecure cc req = case rqSecure req of True -> True False -> case clckTLS cc of Nothing -> False Just tlsSettings -> case clckTLSRev tlsSettings of False -> False True -> case getHeaderUnsafe "x-forwarded-proto" req of Nothing -> False Just proto -> proto == "https" withAbs :: (Happstack m) => ClckT url m a -> ClckT url m a withAbs m = do clckState <- get cc <- getConfig (plugins clckState) secure <- isSecure cc <$> askRq let base = if secure then (fromJust $ calcTLSBaseURI cc) else calcBaseURI cc withAbs' base m withAbs' :: T.Text -> ClckT url m a -> ClckT url m a withAbs' prefix (ClckT (RouteT r)) = ClckT $ RouteT $ \showFn -> r (\url params -> prefix <> showFn url params) instance (Monad m) => MonadRoute (ClckT url m) where type URL (ClckT url m) = url askRouteFn = ClckT $ askRouteFn | similar to the normal acid - state ' query ' except it automatically gets the correct ' AcidState ' handle from the environment query :: forall event m. (QueryEvent event, GetAcidState m (EventState event), Functor m, MonadIO m, MonadState ClckState m) => event -> m (EventResult event) query event = do as <- getAcidState query' (as :: AcidState (EventState event)) event | similar to the normal acid - state ' update ' except it automatically gets the correct ' AcidState ' handle from the environment update :: forall event m. (UpdateEvent event, GetAcidState m (EventState event), Functor m, MonadIO m, MonadState ClckState m) => event -> m (EventResult event) update event = do as <- getAcidState update' (as :: AcidState (EventState event)) event instance (GetAcidState m st) => GetAcidState (XMLGenT m) st where getAcidState = XMLGenT getAcidState instance (Functor m, Monad m) => GetAcidState (ClckT url m) CoreState where getAcidState = (acidCore . acidState) <$> get instance (Functor m, Monad m) => GetAcidState (ClckT url m) NavBarState where getAcidState = (acidNavBar . acidState) <$> get instance (Functor m, Monad m) => GetAcidState (ClckT url m) ProfileDataState where getAcidState = (acidProfileData . acidState) <$> get * XMLGen / XMLGenerator instances for instance (Functor m, Monad m) => XMLGen (ClckT url m) where type XMLType (ClckT url m) = XML type StringType (ClckT url m) = TL.Text newtype ChildType (ClckT url m) = ClckChild { unClckChild :: XML } newtype AttributeType (ClckT url m) = ClckAttr { unClckAttr :: Attribute } genElement n attrs children = do attribs <- map unClckAttr <$> asAttr attrs childer <- flattenCDATA . map (unClckChild) <$> asChild children XMLGenT $ return (Element (toName n) attribs childer ) xmlToChild = ClckChild pcdataToChild = xmlToChild . pcdata flattenCDATA :: [XML] -> [XML] flattenCDATA cxml = case flP cxml [] of [] -> [] [CDATA _ ""] -> [] xs -> xs where flP :: [XML] -> [XML] -> [XML] flP [] bs = reverse bs flP [x] bs = reverse (x:bs) flP (x:y:xs) bs = case (x,y) of (CDATA e1 s1, CDATA e2 s2) | e1 == e2 -> flP (CDATA e1 (s1<>s2) : xs) bs _ -> flP (y:xs) (x:bs) instance ( Functor m , ) = > IsAttrValue ( ClckT url m ) T.Text where toAttrValue = toAttrValue . T.unpack instance ( Functor m , ) = > IsAttrValue ( ClckT url m ) TL.Text where toAttrValue = toAttrValue . TL.unpack instance (Functor m, Monad m) => IsAttrValue (ClckT url m) T.Text where toAttrValue = toAttrValue . T.unpack instance (Functor m, Monad m) => IsAttrValue (ClckT url m) TL.Text where toAttrValue = toAttrValue . TL.unpack -} instance (Functor m, Monad m) => EmbedAsAttr (ClckT url m) Attribute where asAttr = return . (:[]) . ClckAttr instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n String) where asAttr (n := str) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack str) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Char) where asAttr (n := c) = asAttr (n := TL.singleton c) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Bool) where asAttr (n := True) = asAttr $ MkAttr (toName n, pAttrVal "true") asAttr (n := False) = asAttr $ MkAttr (toName n, pAttrVal "false") instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Int) where asAttr (n := i) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack (show i)) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Integer) where asAttr (n := i) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack (show i)) instance (IsName n TL.Text) => EmbedAsAttr (Clck ClckURL) (Attr n ClckURL) where asAttr (n := u) = do url <- showURL u asAttr $ MkAttr (toName n, pAttrVal $ TL.fromStrict url) instance (IsName n TL.Text) => EmbedAsAttr (Clck AdminURL) (Attr n AdminURL) where asAttr (n := u) = do url <- showURL u asAttr $ MkAttr (toName n, pAttrVal (TL.fromStrict url)) instance (Functor m, Monad m, IsName n TL.Text) => (EmbedAsAttr (ClckT url m) (Attr n TL.Text)) where asAttr (n := a) = asAttr $ MkAttr (toName n, pAttrVal $ a) instance (Functor m, Monad m, IsName n TL.Text) => (EmbedAsAttr (ClckT url m) (Attr n T.Text)) where asAttr (n := a) = asAttr $ MkAttr (toName n, pAttrVal $ TL.fromStrict a) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Char where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.singleton instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) String where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Int where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Integer where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Double where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Float where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) TL.Text where asChild = asChild . TL.unpack instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) T.Text where asChild = asChild . T.unpack instance (EmbedAsChild (ClckT url1 m) a, url1 ~ url2) => EmbedAsChild (ClckT url1 m) (ClckT url2 m a) where asChild c = do a <- XMLGenT c asChild a instance (Functor m, MonadIO m, EmbedAsChild (ClckT url m) a) => EmbedAsChild (ClckT url m) (IO a) where asChild c = do a <- XMLGenT (liftIO c) asChild a instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) XML where asChild = XMLGenT . return . (:[]) . ClckChild instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Html where asChild = XMLGenT . return . (:[]) . ClckChild . cdata . renderHtml instance (Functor m, MonadIO m, Happstack m) => EmbedAsChild (ClckT url m) ClckFormError where asChild formError = asChild (show formError) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) () where asChild () = return [] instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) UTCTime where asChild = asChild . formatTime defaultTimeLocale "%a, %F @ %r" instance (Functor m, Monad m, EmbedAsChild (ClckT url m) a) => EmbedAsChild (ClckT url m) (Maybe a) where asChild Nothing = asChild () asChild (Just a) = asChild a instance (Functor m, Monad m) => AppendChild (ClckT url m) XML where appAll xml children = do chs <- children case xml of CDATA _ _ -> return xml Element n as cs -> return $ Element n as (cs ++ (map unClckChild chs)) instance (Functor m, Monad m) => SetAttr (ClckT url m) XML where setAll xml hats = do attrs <- hats case xml of CDATA _ _ -> return xml Element n as cs -> return $ Element n (foldr (:) as (map unClckAttr attrs)) cs instance (Functor m, Monad m) => XMLGenerator (ClckT url m) -- | a wrapper which identifies how to treat different 'Text' values when attempting to embed them. -- -- In general 'Content' values have already been -- flatten/preprocessed/etc and are now basic formats like @text / plain@ , @text / html@ , etc data Content = TrustedHtml T.Text | PlainText T.Text deriving (Eq, Ord, Read, Show, Data, Typeable) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Content where asChild (TrustedHtml html) = asChild $ cdata (TL.fromStrict html) asChild (PlainText txt) = asChild $ pcdata (TL.fromStrict txt) addPreProc :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> (forall mm. (Functor mm, MonadIO mm, Happstack mm) => TL.Text -> ClckT ClckURL mm TL.Text) -> m () addPreProc plugins p = modifyPluginsSt plugins $ \cps -> cps { cpsPreProcessors = p : (cpsPreProcessors cps) } -- * Preprocess data Segment cmd = TextBlock T.Text | Cmd cmd deriving Show instance Functor Segment where fmap f (TextBlock t) = TextBlock t fmap f (Cmd c) = Cmd (f c) transform :: (Monad m) => (cmd -> m Builder) -> [Segment cmd] -> m Builder transform f segments = do bs <- mapM (transformSegment f) segments return (mconcat bs) transformSegment :: (Monad m) => (cmd -> m Builder) -> Segment cmd -> m Builder transformSegment f (TextBlock t) = return (B.fromText t) transformSegment f (Cmd cmd) = f cmd segments :: T.Text -> Parser a -> Parser [Segment a] segments name p = many (cmd name p <|> plainText) cmd :: T.Text -> Parser cmd -> Parser (Segment cmd) cmd n p = do char '{' ((try $ do asciiCI n char '|' r <- p char '}' return (Cmd r)) <|> (do t <- takeWhile1 (/= '{') return $ TextBlock (T.cons '{' t))) plainText :: Parser (Segment cmd) plainText = do t <- takeWhile1 (/= '{') return $ TextBlock t -- * Require Role setRedirectCookie :: (Happstack m) => String -> m () setRedirectCookie url = addCookie Session (mkCookie "clckwrks-authenticate-redirect" url) getRedirectCookie :: (Happstack m) => m (Maybe String) getRedirectCookie = do expireCookie "clckwrks-authenticate-redirect" optional $ lookCookieValue "clckwrks-authenticate-redirect" ------------------------------------------------------------------------------ NavBar callback ------------------------------------------------------------------------------ addNavBarCallback :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> ClckT ClckURL IO (String, [NamedLink]) -> m () addNavBarCallback plugins ml = modifyPluginsSt plugins $ \cps -> cps { cpsNavBarLinks = (cpsNavBarLinks cps) ++ [ml] } getNavBarLinks :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> ClckT ClckURL m NavBarLinks getNavBarLinks plugins = mapClckT liftIO $ do genNavBarLinks <- (cpsNavBarLinks <$> getPluginsSt plugins) NavBarLinks <$> sequenceA genNavBarLinks getPreProcessors :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> (forall mm. (Functor mm, MonadIO mm, Happstack mm) => ClckT url m [TL.Text -> ClckT ClckURL mm TL.Text]) getPreProcessors plugins = do st <- liftIO $ getPluginsSt plugins pure (cpsPreProcessors st) -- | create a google analytics tracking code block -- This will under two different conditions : -- * the ' enableAnalytics ' field in ' ClckState ' is ' False ' -- * the ' uacct ' field in ' PageState ' is ' Nothing ' googleAnalytics :: XMLGenT (Clck url) XML googleAnalytics = do enabled <- getEnableAnalytics case enabled of False -> return $ cdata "" True -> do muacct <- query GetUACCT case muacct of Nothing -> return $ cdata "" (Just uacct) -> universalAnalytics uacct
null
https://raw.githubusercontent.com/clckwrks/clckwrks/a0e3f5e29b24cdb2cc63f8b662cc457384d7104a/Clckwrks/Monad.hs
haskell
, markupToContent import HSP.ServerPartT () imported so that instances are scope even though we do not use them here imported so that instances are scope even though we do not use them here ---------------------------------------------------------------------------- Theme ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ^ external name of the host ^ port to listen on ^ HTTPS ^ hide port number in URL (useful when running behind a reverse proxy) ^ path to @jquery.js@ on disk ^ path to @JSON2.js@ on disk ^ path to top-level directory for all acid-state files/file uploads/etc ^ init hook | calculate the baseURI from the 'clckHostname', 'clckPort' and 'clckHidePort' options ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- only unique for this request ^ an action which gets called at the beginning of each request ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- similar to 'evalStateT'. ^ function to act as 'showURLParams' ^ 'ClckT' to evaluate similar to 'execStateT'. ^ function to act as 'showURLParams' ^ 'ClckT' to evaluate similar to 'runStateT'. ^ function to act as 'showURLParams' ^ 'ClckT' to evaluate | map a transformation function over the inner monad similar to 'mapStateT' ^ transformation function ^ initial monad | error returned when a reform 'Form' fails to validate ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | ClckPlugins newtype Plugins theme m hook config st | get a unique 'Integer'. Only unique for the current request | add an Admin menu | append an action to the request init | change the route url | a wrapper which identifies how to treat different 'Text' values when attempting to embed them. In general 'Content' values have already been flatten/preprocessed/etc and are now basic formats like * Preprocess * Require Role ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- | create a google analytics tracking code block
# LANGUAGE CPP , DeriveDataTypeable , GeneralizedNewtypeDeriving , MultiParamTypeClasses , FlexibleInstances , TypeSynonymInstances , FlexibleContexts , TypeFamilies , RankNTypes , RecordWildCards , ScopedTypeVariables , UndecidableInstances , OverloadedStrings , TemplateHaskell # module Clckwrks.Monad ( Clck , ClckPlugins , ClckPluginsSt(cpsAcid) , initialClckPluginsSt , ClckT(..) , ClckForm , ClckFormT , ClckFormError(..) , ChildType(..) , ClckwrksConfig(..) , TLSSettings(..) , AttributeType(..) , Theme(..) , ThemeStyle(..) , ThemeStyleId(..) , ThemeName , getThemeStyles , themeTemplate , calcBaseURI , calcTLSBaseURI , evalClckT , execClckT , runClckT , mapClckT , withRouteClckT , ClckState(..) , Content(..) , addPreProcessor , addAdminMenu , appendRequestInit , getNavBarLinks , addPreProc , addNavBarCallback , getPreProcessors , , getEnableAnalytics , googleAnalytics , getUnique , setUnique , setRedirectCookie , getRedirectCookie , query , update , nestURL , isSecure , withAbs , withAbs' , segments , transform , module HSP.XML , module HSP.XMLGenerator ) where import Clckwrks.Admin.URL (AdminURL(..)) import Clckwrks.Acid (Acid(..), CoreState, GetAcidState(..), GetUACCT(..)) import Clckwrks.ProfileData.Acid (ProfileDataState, GetRoles(..), HasRole(..)) import Clckwrks.ProfileData.Types (Role(..)) import Clckwrks.NavBar.Acid (NavBarState) import Clckwrks.NavBar.Types (NavBarLinks(..)) import Clckwrks.Types (NamedLink(..), Prefix, Trust(Trusted)) import Clckwrks.Unauthorized (unauthorizedPage) import Clckwrks.URL (ClckURL(..)) import Control.Applicative (Alternative, Applicative, (<$>), (<|>), many, optional) #if MIN_VERSION_base (4,9,0) && !MIN_VERSION_base (4,13,0) import Control.Monad.Fail (MonadFail) #endif import Control.Monad (MonadPlus, foldM) import Control.Monad.State (MonadState, StateT, evalStateT, execStateT, get, mapStateT, modify, put, runStateT) import Control.Monad.Reader (MonadReader, ReaderT, mapReaderT) import Control.Monad.Trans (MonadIO(liftIO), MonadTrans(lift)) import Control.Concurrent.STM (TVar, readTVar, writeTVar, atomically) import Data.Acid (AcidState, EventState, EventResult, QueryEvent, UpdateEvent) import Data.Acid.Advanced (query', update') import Data.Attoparsec.Text.Lazy (Parser, parseOnly, char, asciiCI, try, takeWhile, takeWhile1) import qualified Data.HashMap.Lazy as HashMap import qualified Data.List as List import qualified Data.Map as Map import Data.Monoid ((<>), mappend, mconcat) import qualified Data.Serialize as S import Data.Traversable (sequenceA) import qualified Data.Vector as Vector import Data.ByteString.Lazy as LB (ByteString) import Data.ByteString.Lazy.UTF8 as LB (toString) import Data.Data (Data, Typeable) import Data.Map (Map) import Data.Maybe (fromJust) import Data.SafeCopy (SafeCopy(..), Contained, deriveSafeCopy, base, contain) import Data.Set (Set) import qualified Data.Set as Set import Data.Sequence (Seq) import qualified Data.Text as T import qualified Data.Text as Text import qualified Data.Text.Lazy as TL import Data.Text.Lazy.Builder (Builder, fromText) import qualified Data.Text.Lazy.Builder as B import Data.Time.Clock (UTCTime) import Data.Time.Format (formatTime) import Data.UserId (UserId(..)) import Happstack.Server ( CookieLife(Session), Happstack, ServerMonad(..), FilterMonad(..) , WebMonad(..), Input, Request(..), Response, HasRqData(..) , ServerPart, ServerPartT, UnWebT, addCookie, expireCookie, escape , internalServerError, lookCookieValue, mapServerPartT, mkCookie , toResponse, getHeaderUnsafe ) ToMessage XML instance instance import Happstack.Server.Internal.Monads (FilterFun) import HSP hiding ( Request , escape ) import HSP.Google.Analytics (UACCT, universalAnalytics) import HSP.XML import HSP.XMLGenerator import HSP.JMacro (IntegerSupply(..)) import Language.Javascript.JMacro import Prelude hiding (takeWhile) can import from time directly when time-1.4 / ghc 7.8 is not important anymore import Text.Blaze.Html (Html) import Text.Blaze.Html.Renderer.Text (renderHtml) import Text.Reform (CommonFormError, Form, FormError(..)) import Web.Routes (URL, MonadRoute(askRouteFn), RouteT(RouteT, unRouteT), mapRouteT, showURL, withRouteT) import Web.Plugins.Core (Plugins, getConfig, getPluginsSt, modifyPluginsSt, getTheme) import qualified Web.Routes as R type ThemeName = T.Text newtype ThemeStyleId = ThemeStyleId { unThemeStyleId :: Int } deriving (Eq, Ord, Read, Show, Data, Typeable) instance SafeCopy ThemeStyleId where getCopy = contain $ ThemeStyleId <$> S.get putCopy (ThemeStyleId i) = contain $ S.put i errorTypeName _ = "ThemeStyleId" data ThemeStyle = ThemeStyle { themeStyleName :: T.Text , themeStyleDescription :: T.Text , themeStylePreview :: Maybe FilePath , themeStyleTemplate :: forall headers body. ( EmbedAsChild (ClckT ClckURL (ServerPartT IO)) headers , EmbedAsChild (ClckT ClckURL (ServerPartT IO)) body) => T.Text -> headers -> body -> XMLGenT (ClckT ClckURL (ServerPartT IO)) XML } data Theme = Theme { themeName :: ThemeName , themeStyles :: [ThemeStyle] , themeDataDir :: IO FilePath } themeTemplate :: ( EmbedAsChild (ClckT ClckURL (ServerPartT IO)) headers , EmbedAsChild (ClckT ClckURL (ServerPartT IO)) body ) => ClckPlugins -> ThemeStyleId -> T.Text -> headers -> body -> ClckT ClckURL (ServerPartT IO) Response themeTemplate plugins tsid ttl hdrs bdy = do mTheme <- getTheme plugins case mTheme of Nothing -> escape $ internalServerError $ toResponse $ ("No theme package is loaded." :: T.Text) (Just theme) -> case lookupThemeStyle tsid (themeStyles theme) of Nothing -> escape $ internalServerError $ toResponse $ ("The current theme does not seem to contain any theme styles." :: T.Text) (Just themeStyle) -> fmap toResponse $ unXMLGenT $ ((themeStyleTemplate themeStyle) ttl hdrs bdy) lookupThemeStyle :: ThemeStyleId -> [a] -> Maybe a lookupThemeStyle _ [] = Nothing lookupThemeStyle (ThemeStyleId 0) (t:_) = Just t lookupThemeStyle (ThemeStyleId n) (t':ts) = lookupThemeStyle' (n - 1) ts where lookupThemeStyle' _ [] = Just t' lookupThemeStyle' 0 (t:ts) = Just t lookupThemeStyle' n (_:ts) = lookupThemeStyle' (n - 1) ts getThemeStyles :: (MonadIO m) => ClckPlugins -> m [(ThemeStyleId, ThemeStyle)] getThemeStyles plugins = do mTheme <- getTheme plugins case mTheme of Nothing -> return [] (Just theme) -> return $ zip (map ThemeStyleId [0..]) (themeStyles theme) ClckwrksConfig data TLSSettings = TLSSettings { clckTLSPort :: Int , clckTLSCert :: Maybe FilePath , clckTLSKey :: Maybe FilePath , clckTLSCA :: Maybe FilePath , clckTLSRev :: Bool } data ClckwrksConfig = ClckwrksConfig ^ path to @jquery - ui.js@ on disk ^ path to on disk ^ enable google analytics } calcBaseURI :: ClckwrksConfig -> T.Text calcBaseURI c = Text.pack $ "http://" ++ (clckHostname c) ++ if ((clckPort c /= 80) && (clckHidePort c == False)) then (':' : show (clckPort c)) else "" calcTLSBaseURI :: ClckwrksConfig -> Maybe T.Text calcTLSBaseURI c = case clckTLS c of Nothing -> Nothing (Just tlsSettings) -> Just $ Text.pack $ "https://" ++ (clckHostname c) ++ if ((clckPort c /= 443) && (clckHidePort c == False)) then (':' : show (clckTLSPort tlsSettings)) else "" ClckState data ClckState = ClckState { acidState :: Acid , adminMenus :: [(T.Text, [(Set Role, T.Text, T.Text)])] ^ enable Google Analytics , plugins :: ClckPlugins } ClckT newtype ClckT url m a = ClckT { unClckT :: RouteT url (StateT ClckState m) a } #if MIN_VERSION_base(4,9,0) deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadFail, MonadPlus, ServerMonad, HasRqData, FilterMonad r, WebMonad r, MonadState ClckState) #else deriving (Functor, Applicative, Alternative, Monad, MonadIO, MonadPlus, ServerMonad, HasRqData, FilterMonad r, WebMonad r, MonadState ClckState) #endif instance (Happstack m) => Happstack (ClckT url m) instance MonadTrans (ClckT url) where lift = ClckT . lift . lift | evaluate a ' ClckT ' returning the inner monad evalClckT :: (Monad m) => ^ initial ' ClckState ' -> m a evalClckT showFn clckState m = evalStateT (unRouteT (unClckT m) showFn) clckState | execute a ' ClckT ' returning the final ' ClckState ' execClckT :: (Monad m) => ^ initial ' ClckState ' -> m ClckState execClckT showFn clckState m = execStateT (unRouteT (unClckT m) showFn) clckState | run a ' ClckT ' runClckT :: (Monad m) => ^ initial ' ClckState ' -> m (a, ClckState) runClckT showFn clckState m = runStateT (unRouteT (unClckT m) showFn) clckState -> ClckT url n b mapClckT f (ClckT r) = ClckT $ mapRouteT (mapStateT f) r data ClckFormError = ClckCFE (CommonFormError [Input]) | EmptyUsername | InvalidDecimal T.Text deriving (Show) instance FormError ClckFormError where type ErrorInputType ClckFormError = [Input] commonFormError = ClckCFE | ClckForm - type for reform forms type ClckFormT error m = Form m [Input] error [XMLGenT m XML] () type ClckForm url = Form (ClckT url (ServerPartT IO)) [Input] ClckFormError [XMLGenT (ClckT url (ServerPartT IO)) XML] () ClckPlugins / ClckPluginsSt data ClckPluginsSt = ClckPluginsSt { cpsPreProcessors :: forall m. (Functor m, MonadIO m, Happstack m) => [TL.Text -> ClckT ClckURL m TL.Text] , cpsNavBarLinks :: [ClckT ClckURL IO (String, [NamedLink])] ^ this value is also in ClckState , but it is sometimes needed by plugins during initPlugin } initialClckPluginsSt :: Acid -> ClckPluginsSt initialClckPluginsSt acid = ClckPluginsSt { cpsPreProcessors = [] , cpsNavBarLinks = [] , cpsAcid = acid } type ClckPlugins = Plugins Theme (ClckT ClckURL (ServerPartT IO) Response) (ClckT ClckURL IO ()) ClckwrksConfig ClckPluginsSt setUnique :: (Functor m, MonadIO m) => Integer -> ClckT url m () setUnique i = do u <- uniqueId <$> get liftIO $ atomically $ writeTVar u i getUnique :: (Functor m, MonadIO m) => ClckT url m Integer getUnique = do u <- uniqueId <$> get liftIO $ atomically $ do i <- readTVar u writeTVar u (succ i) return i | get the ' Bool ' value indicating if Google Analytics should be enabled or not getEnableAnalytics :: (Functor m, MonadState ClckState m) => m Bool getEnableAnalytics = enableAnalytics <$> get addAdminMenu :: (Monad m) => (T.Text, [(Set Role, T.Text, T.Text)]) -> ClckT url m () addAdminMenu (category, entries) = modify $ \cs -> let oldMenus = adminMenus cs newMenus = Map.toAscList $ Map.insertWith List.union category entries $ Map.fromList oldMenus in cs { adminMenus = newMenus } appendRequestInit :: (Monad m) => ServerPart () -> ClckT url m () appendRequestInit action = modify $ \cs -> cs { requestInit = (requestInit cs) >> action } withRouteClckT :: ((url' -> [(T.Text, Maybe T.Text)] -> T.Text) -> url -> [(T.Text, Maybe T.Text)] -> T.Text) -> ClckT url m a -> ClckT url' m a withRouteClckT f (ClckT routeT) = (ClckT $ withRouteT f routeT) type Clck url = ClckT url (ServerPartT IO) instance (Functor m, MonadIO m) => IntegerSupply (ClckT url m) where nextInteger = getUnique nestURL :: (url1 -> url2) -> ClckT url1 m a -> ClckT url2 m a nestURL f (ClckT r) = ClckT $ R.nestURL f r isSecure :: ClckwrksConfig -> Request -> Bool isSecure cc req = case rqSecure req of True -> True False -> case clckTLS cc of Nothing -> False Just tlsSettings -> case clckTLSRev tlsSettings of False -> False True -> case getHeaderUnsafe "x-forwarded-proto" req of Nothing -> False Just proto -> proto == "https" withAbs :: (Happstack m) => ClckT url m a -> ClckT url m a withAbs m = do clckState <- get cc <- getConfig (plugins clckState) secure <- isSecure cc <$> askRq let base = if secure then (fromJust $ calcTLSBaseURI cc) else calcBaseURI cc withAbs' base m withAbs' :: T.Text -> ClckT url m a -> ClckT url m a withAbs' prefix (ClckT (RouteT r)) = ClckT $ RouteT $ \showFn -> r (\url params -> prefix <> showFn url params) instance (Monad m) => MonadRoute (ClckT url m) where type URL (ClckT url m) = url askRouteFn = ClckT $ askRouteFn | similar to the normal acid - state ' query ' except it automatically gets the correct ' AcidState ' handle from the environment query :: forall event m. (QueryEvent event, GetAcidState m (EventState event), Functor m, MonadIO m, MonadState ClckState m) => event -> m (EventResult event) query event = do as <- getAcidState query' (as :: AcidState (EventState event)) event | similar to the normal acid - state ' update ' except it automatically gets the correct ' AcidState ' handle from the environment update :: forall event m. (UpdateEvent event, GetAcidState m (EventState event), Functor m, MonadIO m, MonadState ClckState m) => event -> m (EventResult event) update event = do as <- getAcidState update' (as :: AcidState (EventState event)) event instance (GetAcidState m st) => GetAcidState (XMLGenT m) st where getAcidState = XMLGenT getAcidState instance (Functor m, Monad m) => GetAcidState (ClckT url m) CoreState where getAcidState = (acidCore . acidState) <$> get instance (Functor m, Monad m) => GetAcidState (ClckT url m) NavBarState where getAcidState = (acidNavBar . acidState) <$> get instance (Functor m, Monad m) => GetAcidState (ClckT url m) ProfileDataState where getAcidState = (acidProfileData . acidState) <$> get * XMLGen / XMLGenerator instances for instance (Functor m, Monad m) => XMLGen (ClckT url m) where type XMLType (ClckT url m) = XML type StringType (ClckT url m) = TL.Text newtype ChildType (ClckT url m) = ClckChild { unClckChild :: XML } newtype AttributeType (ClckT url m) = ClckAttr { unClckAttr :: Attribute } genElement n attrs children = do attribs <- map unClckAttr <$> asAttr attrs childer <- flattenCDATA . map (unClckChild) <$> asChild children XMLGenT $ return (Element (toName n) attribs childer ) xmlToChild = ClckChild pcdataToChild = xmlToChild . pcdata flattenCDATA :: [XML] -> [XML] flattenCDATA cxml = case flP cxml [] of [] -> [] [CDATA _ ""] -> [] xs -> xs where flP :: [XML] -> [XML] -> [XML] flP [] bs = reverse bs flP [x] bs = reverse (x:bs) flP (x:y:xs) bs = case (x,y) of (CDATA e1 s1, CDATA e2 s2) | e1 == e2 -> flP (CDATA e1 (s1<>s2) : xs) bs _ -> flP (y:xs) (x:bs) instance ( Functor m , ) = > IsAttrValue ( ClckT url m ) T.Text where toAttrValue = toAttrValue . T.unpack instance ( Functor m , ) = > IsAttrValue ( ClckT url m ) TL.Text where toAttrValue = toAttrValue . TL.unpack instance (Functor m, Monad m) => IsAttrValue (ClckT url m) T.Text where toAttrValue = toAttrValue . T.unpack instance (Functor m, Monad m) => IsAttrValue (ClckT url m) TL.Text where toAttrValue = toAttrValue . TL.unpack -} instance (Functor m, Monad m) => EmbedAsAttr (ClckT url m) Attribute where asAttr = return . (:[]) . ClckAttr instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n String) where asAttr (n := str) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack str) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Char) where asAttr (n := c) = asAttr (n := TL.singleton c) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Bool) where asAttr (n := True) = asAttr $ MkAttr (toName n, pAttrVal "true") asAttr (n := False) = asAttr $ MkAttr (toName n, pAttrVal "false") instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Int) where asAttr (n := i) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack (show i)) instance (Functor m, Monad m, IsName n TL.Text) => EmbedAsAttr (ClckT url m) (Attr n Integer) where asAttr (n := i) = asAttr $ MkAttr (toName n, pAttrVal $ TL.pack (show i)) instance (IsName n TL.Text) => EmbedAsAttr (Clck ClckURL) (Attr n ClckURL) where asAttr (n := u) = do url <- showURL u asAttr $ MkAttr (toName n, pAttrVal $ TL.fromStrict url) instance (IsName n TL.Text) => EmbedAsAttr (Clck AdminURL) (Attr n AdminURL) where asAttr (n := u) = do url <- showURL u asAttr $ MkAttr (toName n, pAttrVal (TL.fromStrict url)) instance (Functor m, Monad m, IsName n TL.Text) => (EmbedAsAttr (ClckT url m) (Attr n TL.Text)) where asAttr (n := a) = asAttr $ MkAttr (toName n, pAttrVal $ a) instance (Functor m, Monad m, IsName n TL.Text) => (EmbedAsAttr (ClckT url m) (Attr n T.Text)) where asAttr (n := a) = asAttr $ MkAttr (toName n, pAttrVal $ TL.fromStrict a) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Char where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.singleton instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) String where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Int where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Integer where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Double where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Float where asChild = XMLGenT . return . (:[]) . ClckChild . pcdata . TL.pack . show instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) TL.Text where asChild = asChild . TL.unpack instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) T.Text where asChild = asChild . T.unpack instance (EmbedAsChild (ClckT url1 m) a, url1 ~ url2) => EmbedAsChild (ClckT url1 m) (ClckT url2 m a) where asChild c = do a <- XMLGenT c asChild a instance (Functor m, MonadIO m, EmbedAsChild (ClckT url m) a) => EmbedAsChild (ClckT url m) (IO a) where asChild c = do a <- XMLGenT (liftIO c) asChild a instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) XML where asChild = XMLGenT . return . (:[]) . ClckChild instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Html where asChild = XMLGenT . return . (:[]) . ClckChild . cdata . renderHtml instance (Functor m, MonadIO m, Happstack m) => EmbedAsChild (ClckT url m) ClckFormError where asChild formError = asChild (show formError) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) () where asChild () = return [] instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) UTCTime where asChild = asChild . formatTime defaultTimeLocale "%a, %F @ %r" instance (Functor m, Monad m, EmbedAsChild (ClckT url m) a) => EmbedAsChild (ClckT url m) (Maybe a) where asChild Nothing = asChild () asChild (Just a) = asChild a instance (Functor m, Monad m) => AppendChild (ClckT url m) XML where appAll xml children = do chs <- children case xml of CDATA _ _ -> return xml Element n as cs -> return $ Element n as (cs ++ (map unClckChild chs)) instance (Functor m, Monad m) => SetAttr (ClckT url m) XML where setAll xml hats = do attrs <- hats case xml of CDATA _ _ -> return xml Element n as cs -> return $ Element n (foldr (:) as (map unClckAttr attrs)) cs instance (Functor m, Monad m) => XMLGenerator (ClckT url m) @text / plain@ , @text / html@ , etc data Content = TrustedHtml T.Text | PlainText T.Text deriving (Eq, Ord, Read, Show, Data, Typeable) instance (Functor m, Monad m) => EmbedAsChild (ClckT url m) Content where asChild (TrustedHtml html) = asChild $ cdata (TL.fromStrict html) asChild (PlainText txt) = asChild $ pcdata (TL.fromStrict txt) addPreProc :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> (forall mm. (Functor mm, MonadIO mm, Happstack mm) => TL.Text -> ClckT ClckURL mm TL.Text) -> m () addPreProc plugins p = modifyPluginsSt plugins $ \cps -> cps { cpsPreProcessors = p : (cpsPreProcessors cps) } data Segment cmd = TextBlock T.Text | Cmd cmd deriving Show instance Functor Segment where fmap f (TextBlock t) = TextBlock t fmap f (Cmd c) = Cmd (f c) transform :: (Monad m) => (cmd -> m Builder) -> [Segment cmd] -> m Builder transform f segments = do bs <- mapM (transformSegment f) segments return (mconcat bs) transformSegment :: (Monad m) => (cmd -> m Builder) -> Segment cmd -> m Builder transformSegment f (TextBlock t) = return (B.fromText t) transformSegment f (Cmd cmd) = f cmd segments :: T.Text -> Parser a -> Parser [Segment a] segments name p = many (cmd name p <|> plainText) cmd :: T.Text -> Parser cmd -> Parser (Segment cmd) cmd n p = do char '{' ((try $ do asciiCI n char '|' r <- p char '}' return (Cmd r)) <|> (do t <- takeWhile1 (/= '{') return $ TextBlock (T.cons '{' t))) plainText :: Parser (Segment cmd) plainText = do t <- takeWhile1 (/= '{') return $ TextBlock t setRedirectCookie :: (Happstack m) => String -> m () setRedirectCookie url = addCookie Session (mkCookie "clckwrks-authenticate-redirect" url) getRedirectCookie :: (Happstack m) => m (Maybe String) getRedirectCookie = do expireCookie "clckwrks-authenticate-redirect" optional $ lookCookieValue "clckwrks-authenticate-redirect" NavBar callback addNavBarCallback :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> ClckT ClckURL IO (String, [NamedLink]) -> m () addNavBarCallback plugins ml = modifyPluginsSt plugins $ \cps -> cps { cpsNavBarLinks = (cpsNavBarLinks cps) ++ [ml] } getNavBarLinks :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> ClckT ClckURL m NavBarLinks getNavBarLinks plugins = mapClckT liftIO $ do genNavBarLinks <- (cpsNavBarLinks <$> getPluginsSt plugins) NavBarLinks <$> sequenceA genNavBarLinks getPreProcessors :: (MonadIO m) => Plugins theme n hook config ClckPluginsSt -> (forall mm. (Functor mm, MonadIO mm, Happstack mm) => ClckT url m [TL.Text -> ClckT ClckURL mm TL.Text]) getPreProcessors plugins = do st <- liftIO $ getPluginsSt plugins pure (cpsPreProcessors st) This will under two different conditions : * the ' enableAnalytics ' field in ' ClckState ' is ' False ' * the ' uacct ' field in ' PageState ' is ' Nothing ' googleAnalytics :: XMLGenT (Clck url) XML googleAnalytics = do enabled <- getEnableAnalytics case enabled of False -> return $ cdata "" True -> do muacct <- query GetUACCT case muacct of Nothing -> return $ cdata "" (Just uacct) -> universalAnalytics uacct
0d8c96d89f28c172197bb9acaef596d0d5af4377b615adec1b6c7749e2f37bfd
magnars/zombie-clj
prep_test.clj
(ns zombieclj.prep-test (:require [zombieclj.prep :refer :all] [zombieclj.game :refer [create-game reveal-tile tick]] [midje.sweet :refer :all])) (fact "Concealed tiles have no faces" (->> (create-game) prep :tiles (map #(dissoc % :id))) => (repeat 16 {})) (fact "Revealed tiles has faces" (->> (create-game) (reveal-tile 1) prep :tiles (filter :face) count) => 1) (fact "After three ticks, it still has a face" (->> (create-game) (reveal-tile 1) (reveal-tile 2) tick tick tick prep :tiles (filter :face) count) => 2) (fact "No ticks" (:ticks (prep (create-game))) => nil) (fact "No remaining-ticks" (->> (create-game) (reveal-tile 1) (reveal-tile 2) prep :tiles (filter :remaining-ticks)) => []) (fact "Provides id for each tile" (->> (create-game) prep :tiles (map :id)) => (range 0 16))
null
https://raw.githubusercontent.com/magnars/zombie-clj/822820967a3e046f334e37bd3a4ecdc283c3e66b/test/zombieclj/prep_test.clj
clojure
(ns zombieclj.prep-test (:require [zombieclj.prep :refer :all] [zombieclj.game :refer [create-game reveal-tile tick]] [midje.sweet :refer :all])) (fact "Concealed tiles have no faces" (->> (create-game) prep :tiles (map #(dissoc % :id))) => (repeat 16 {})) (fact "Revealed tiles has faces" (->> (create-game) (reveal-tile 1) prep :tiles (filter :face) count) => 1) (fact "After three ticks, it still has a face" (->> (create-game) (reveal-tile 1) (reveal-tile 2) tick tick tick prep :tiles (filter :face) count) => 2) (fact "No ticks" (:ticks (prep (create-game))) => nil) (fact "No remaining-ticks" (->> (create-game) (reveal-tile 1) (reveal-tile 2) prep :tiles (filter :remaining-ticks)) => []) (fact "Provides id for each tile" (->> (create-game) prep :tiles (map :id)) => (range 0 16))
392f5b08a00c4d8f515f5d1535efae1c2e9811199e97d1fa3f6215b15ace5b7f
picty/parsifal
enum-11.ml
enum test (8, Exception) = | 0 -> A, "First constructor A" | 1 -> B, "BBB" | 2 -> C | 3 -> D
null
https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/syntax/unit/enum-11.ml
ocaml
enum test (8, Exception) = | 0 -> A, "First constructor A" | 1 -> B, "BBB" | 2 -> C | 3 -> D
3d9a91dd19b891d18200a1c2e0529fc21f999e81d6fc0199063f11e24221fef4
spurious/chibi-scheme-mirror
system-tests.scm
(cond-expand (modules (import (chibi system) (only (chibi test) test-begin test test-end))) (else #f)) (test-begin "system") (test #t (user? (user-information (current-user-id)))) (test #f (user? #f)) (test #f (user? (list #f))) (test #t (string? (user-name (user-information (current-user-id))))) (test #t (string? (user-password (user-information (current-user-id))))) (test #t (integer? (user-id (user-information (current-user-id))))) (test #t (integer? (user-group-id (user-information (current-user-id))))) (test #t (string? (user-gecos (user-information (current-user-id))))) (test #t (string? (user-home (user-information (current-user-id))))) (test #t (string? (user-shell (user-information (current-user-id))))) (test (current-user-id) (user-id (user-information (current-user-id)))) (test (current-group-id) (user-group-id (user-information (current-user-id)))) (test (user-id (user-information (current-user-id))) (user-id (user-information (user-name (user-information (current-user-id)))))) (test #t (integer? (current-session-id))) ;; stress test user-name (test (user-name (user-information (current-user-id))) (user-name (user-information (current-user-id)))) (define u (user-information (current-user-id))) (test (user-name u) (user-name (user-information (current-user-id)))) (define un (user-name (user-information (current-user-id)))) (test un (user-name (user-information (current-user-id)))) (test-end)
null
https://raw.githubusercontent.com/spurious/chibi-scheme-mirror/49168ab073f64a95c834b5f584a9aaea3469594d/tests/system-tests.scm
scheme
stress test user-name
(cond-expand (modules (import (chibi system) (only (chibi test) test-begin test test-end))) (else #f)) (test-begin "system") (test #t (user? (user-information (current-user-id)))) (test #f (user? #f)) (test #f (user? (list #f))) (test #t (string? (user-name (user-information (current-user-id))))) (test #t (string? (user-password (user-information (current-user-id))))) (test #t (integer? (user-id (user-information (current-user-id))))) (test #t (integer? (user-group-id (user-information (current-user-id))))) (test #t (string? (user-gecos (user-information (current-user-id))))) (test #t (string? (user-home (user-information (current-user-id))))) (test #t (string? (user-shell (user-information (current-user-id))))) (test (current-user-id) (user-id (user-information (current-user-id)))) (test (current-group-id) (user-group-id (user-information (current-user-id)))) (test (user-id (user-information (current-user-id))) (user-id (user-information (user-name (user-information (current-user-id)))))) (test #t (integer? (current-session-id))) (test (user-name (user-information (current-user-id))) (user-name (user-information (current-user-id)))) (define u (user-information (current-user-id))) (test (user-name u) (user-name (user-information (current-user-id)))) (define un (user-name (user-information (current-user-id)))) (test un (user-name (user-information (current-user-id)))) (test-end)
c3fdef5b0d778c3f01b3eaa4d8b8c7c2237ece62ac5cb6c465b5486d939334e8
8c6794b6/guile-tjit
t-make-long-long-immediate-01.scm
;; Nested loop containing `make-long-long-immediate'. (define (loop1 n) (let lp ((n n) (acc '())) (if (= n 0) acc (lp (- n 1) (cons 2305843009213693951 acc))))) (define (loop2 n) (let lp ((n n) (acc '())) (if (= n 0) acc (lp (- n 1) (cons (loop1 n) acc))))) (loop2 50)
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/t-make-long-long-immediate-01.scm
scheme
Nested loop containing `make-long-long-immediate'.
(define (loop1 n) (let lp ((n n) (acc '())) (if (= n 0) acc (lp (- n 1) (cons 2305843009213693951 acc))))) (define (loop2 n) (let lp ((n n) (acc '())) (if (= n 0) acc (lp (- n 1) (cons (loop1 n) acc))))) (loop2 50)
d959e09cd8c6717fc4ccabb2e1e57b599ea22e4836b3260eebbd2e193086ff13
danoctavian/bit-smuggler
Main.hs
module Main where import Prelude as P import Data.Torrent import Data.ByteString as BS import Data.ByteString.Char8 as BSC import Data.ByteString.Lazy as BSL import Control.Applicative import System.Environment import Control.Monad.Trans.Resource import Data.Conduit import Data.Conduit.Binary import Network.BitSmuggler.Server import Network.BitSmuggler.Client import Network.BitSmuggler.TorrentFile import Network.BitSmuggler.Utils import Network.BitSmuggler.Common -- currently tiny commandline app to run some manual tests main = do P.putStrLn "0 server, 1 client, 2 make cache, 3 generate file" args <- getArgs case read (P.head args) :: Int of 0 -> return () -- runRealDemoServer 1 -> return () --runRealDemoClient initCache $ P.tail args -- seed, size, filename 3 -> genRandFile $ P.tail args return () initCache a = setupFileCache ( a ! ! 0 ) ( a ! ! 1 ) ( a ! ! 2 ) sends a bittorrent handshake message to see how a bittorrent clien -- responds to it genRandFile a = runResourceT $ genRandBytes (read (a !! 0) ::Int) (read (a !! 1) :: Int) $$ sinkFile (a !! 2)
null
https://raw.githubusercontent.com/danoctavian/bit-smuggler/4385ed67f1fec4ed441832fc9a119de632b796aa/BitSmuggler/bit-smuggler-app/Main.hs
haskell
currently tiny commandline app to run some manual tests runRealDemoServer runRealDemoClient seed, size, filename responds to it
module Main where import Prelude as P import Data.Torrent import Data.ByteString as BS import Data.ByteString.Char8 as BSC import Data.ByteString.Lazy as BSL import Control.Applicative import System.Environment import Control.Monad.Trans.Resource import Data.Conduit import Data.Conduit.Binary import Network.BitSmuggler.Server import Network.BitSmuggler.Client import Network.BitSmuggler.TorrentFile import Network.BitSmuggler.Utils import Network.BitSmuggler.Common main = do P.putStrLn "0 server, 1 client, 2 make cache, 3 generate file" args <- getArgs case read (P.head args) :: Int of initCache $ P.tail args 3 -> genRandFile $ P.tail args return () initCache a = setupFileCache ( a ! ! 0 ) ( a ! ! 1 ) ( a ! ! 2 ) sends a bittorrent handshake message to see how a bittorrent clien genRandFile a = runResourceT $ genRandBytes (read (a !! 0) ::Int) (read (a !! 1) :: Int) $$ sinkFile (a !! 2)
4953d4daefa0e4c65b2bcc0665074e24748c46c1c06b7f5c1af57f8e9ca213da
lazamar/nix-package-versions
DatabaseSpec.hs
module DatabaseSpec (spec) where import App.Main (run) import Control.Monad.SQL (MonadSQLT) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Log2 (runLoggerT, discard) import Data.Time.Calendar (Day(ModifiedJulianDay)) import Nix.Revision (Revision(..), Package(..), Channel(..), RevisionPackages) import Nix.Versions.Types (DBFile(..), CachePath(..), Hash(..), Version(..), KeyName(..), FullName(..), Name(..), Commit(..), GitHubUser(..), Config(..)) import System.IO.Temp (withSystemTempDirectory) import Test.Hspec (Spec, describe, it) import Test.Hspec.Expectations (HasCallStack) import qualified Test.Hspec as Hspec import qualified Data.HashMap.Strict as HM import qualified Nix.Versions.Database as P -- | Create a temporary database file and connect to it to perform tests. Erases the file after tests are finished overDatabase :: MonadSQLT IO a -> IO a overDatabase f = withSystemTempDirectory "NIX_TEST" $ \dirPath -> P.withConnection (CachePath dirPath) (DBFile "Test.db") f defaultChannel :: Channel defaultChannel = Nixpkgs_unstable day :: Day day = read "2020-03-31" shouldBe :: (MonadIO m, HasCallStack, Show a, Eq a) => a -> a -> m () shouldBe a b = liftIO $ Hspec.shouldBe a b shouldNotBe :: (MonadIO m, HasCallStack, Show a, Eq a) => a -> a -> m () shouldNotBe a b = liftIO $ Hspec.shouldNotBe a b spec :: Spec spec = do describe "Database" $ do let pname = Name "my-package" keyName = KeyName "my-package" fullName = FullName "my-package" pkg = Package pname (Version "1.0") keyName fullName Nothing commit = Commit (Hash "hash") (ModifiedJulianDay 10) packages = [pkg] revision = Revision defaultChannel commit it "can save and load a revision" $ do overDatabase $ runLoggerT discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname liftIO $ length v1 `shouldBe` 1 -- We can add the same thing over and over again and we won't get duplicates it "Adding revisions is idempotent" $ do overDatabase $ runLoggerT discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages day revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` v2 length v1 `shouldBe` 1 it "Searching a package in a channel doesn't return results from a different channel" $ do overDatabase $ runLoggerT discard $ do let otherPkg = Package pname (Version "other-version") keyName fullName Nothing otherChannel = succ defaultChannel otherCommit = Commit (Hash "otherHash") (ModifiedJulianDay 10) otherRevision = Revision otherChannel otherCommit otherPackages = [otherPkg] -- Even though the packages have the same name, -- because they point to revisions with different commits -- they only appear in the respective revision search () <- P.saveRevisionWithPackages day revision packages () <- P.saveRevisionWithPackages day otherRevision otherPackages v1 <- P.versions defaultChannel pname v2 <- P.versions otherChannel pname (getPackage <$> v1) `shouldBe` [pkg] (getPackage <$> v2) `shouldBe` [otherPkg] pkg `shouldNotBe` otherPkg it "When inserting the same package version with a more recent revision, the record is overriden" $ do overDatabase $ runLoggerT discard $ do let newDay = succ day Commit hash _ = commit () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages newDay revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` [(pkg, hash, day)] v2 `shouldBe` [(pkg, hash, newDay)] it "When inserting the same package version with an older revision, the record is not overriden" $ do overDatabase $ runLoggerT discard $ do let newDay = succ day Commit hash _ = commit () <- P.saveRevisionWithPackages newDay revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages day revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` [(pkg, hash, newDay)] v2 `shouldBe` [(pkg, hash, newDay)] it "Works with main transformer stack" $ do withSystemTempDirectory "NIX_TEST" $ \dirPath -> let config = Config (DBFile "Test.db") (CachePath dirPath) (GitHubUser "" "") in run config discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname liftIO $ length v1 `shouldBe` 1 getPackage :: (Package, Hash, Day) -> Package getPackage (p,_,_) = p
null
https://raw.githubusercontent.com/lazamar/nix-package-versions/3b2caa78b7e130619818e5afa8b549b23377ac30/test/DatabaseSpec.hs
haskell
| Create a temporary database file and connect to it to perform tests. We can add the same thing over and over again and we won't get duplicates Even though the packages have the same name, because they point to revisions with different commits they only appear in the respective revision search
module DatabaseSpec (spec) where import App.Main (run) import Control.Monad.SQL (MonadSQLT) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Log2 (runLoggerT, discard) import Data.Time.Calendar (Day(ModifiedJulianDay)) import Nix.Revision (Revision(..), Package(..), Channel(..), RevisionPackages) import Nix.Versions.Types (DBFile(..), CachePath(..), Hash(..), Version(..), KeyName(..), FullName(..), Name(..), Commit(..), GitHubUser(..), Config(..)) import System.IO.Temp (withSystemTempDirectory) import Test.Hspec (Spec, describe, it) import Test.Hspec.Expectations (HasCallStack) import qualified Test.Hspec as Hspec import qualified Data.HashMap.Strict as HM import qualified Nix.Versions.Database as P Erases the file after tests are finished overDatabase :: MonadSQLT IO a -> IO a overDatabase f = withSystemTempDirectory "NIX_TEST" $ \dirPath -> P.withConnection (CachePath dirPath) (DBFile "Test.db") f defaultChannel :: Channel defaultChannel = Nixpkgs_unstable day :: Day day = read "2020-03-31" shouldBe :: (MonadIO m, HasCallStack, Show a, Eq a) => a -> a -> m () shouldBe a b = liftIO $ Hspec.shouldBe a b shouldNotBe :: (MonadIO m, HasCallStack, Show a, Eq a) => a -> a -> m () shouldNotBe a b = liftIO $ Hspec.shouldNotBe a b spec :: Spec spec = do describe "Database" $ do let pname = Name "my-package" keyName = KeyName "my-package" fullName = FullName "my-package" pkg = Package pname (Version "1.0") keyName fullName Nothing commit = Commit (Hash "hash") (ModifiedJulianDay 10) packages = [pkg] revision = Revision defaultChannel commit it "can save and load a revision" $ do overDatabase $ runLoggerT discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname liftIO $ length v1 `shouldBe` 1 it "Adding revisions is idempotent" $ do overDatabase $ runLoggerT discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages day revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` v2 length v1 `shouldBe` 1 it "Searching a package in a channel doesn't return results from a different channel" $ do overDatabase $ runLoggerT discard $ do let otherPkg = Package pname (Version "other-version") keyName fullName Nothing otherChannel = succ defaultChannel otherCommit = Commit (Hash "otherHash") (ModifiedJulianDay 10) otherRevision = Revision otherChannel otherCommit otherPackages = [otherPkg] () <- P.saveRevisionWithPackages day revision packages () <- P.saveRevisionWithPackages day otherRevision otherPackages v1 <- P.versions defaultChannel pname v2 <- P.versions otherChannel pname (getPackage <$> v1) `shouldBe` [pkg] (getPackage <$> v2) `shouldBe` [otherPkg] pkg `shouldNotBe` otherPkg it "When inserting the same package version with a more recent revision, the record is overriden" $ do overDatabase $ runLoggerT discard $ do let newDay = succ day Commit hash _ = commit () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages newDay revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` [(pkg, hash, day)] v2 `shouldBe` [(pkg, hash, newDay)] it "When inserting the same package version with an older revision, the record is not overriden" $ do overDatabase $ runLoggerT discard $ do let newDay = succ day Commit hash _ = commit () <- P.saveRevisionWithPackages newDay revision packages v1 <- P.versions defaultChannel pname () <- P.saveRevisionWithPackages day revision packages v2 <- P.versions defaultChannel pname v1 `shouldBe` [(pkg, hash, newDay)] v2 `shouldBe` [(pkg, hash, newDay)] it "Works with main transformer stack" $ do withSystemTempDirectory "NIX_TEST" $ \dirPath -> let config = Config (DBFile "Test.db") (CachePath dirPath) (GitHubUser "" "") in run config discard $ do () <- P.saveRevisionWithPackages day revision packages v1 <- P.versions defaultChannel pname liftIO $ length v1 `shouldBe` 1 getPackage :: (Package, Hash, Day) -> Package getPackage (p,_,_) = p
633dca6eb724f4ef2918edb3ca8be0dbe2551b888839ab262c50bdaad59d8e11
exercism/babashka
run_length_encoding_test.clj
(ns run-length-encoding-test (:require [clojure.test :refer :all] [run-length-encoding :as rle])) ;;Tests for run-length-encoding exercise (deftest encode-empty-string (testing "encode an empty string" (is (= (rle/run-length-encode "") "")))) (deftest encode-single-characters-without-count (testing "encode single characters without count" (is (= (rle/run-length-encode "XYZ") "XYZ")))) (deftest encode-string-with-no-single-characters (testing "encode string with no single characters" (is (= (rle/run-length-encode "AABBBCCCC") "2A3B4C")))) (deftest encode-string-with-single-and-mixed-characters (testing "encode string with single and mixed characters" (is (= (rle/run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB") "12WB12W3B24WB")))) (deftest encode-multiple-whitespace (testing "encode string with whitespace characters mixed in it" (is (= (rle/run-length-encode " hsqq qww ") "2 hs2q q2w2 ")))) (deftest encode-lowercase (testing "encode string with lowercase characters" (is (= (rle/run-length-encode "aabbbcccc") "2a3b4c")))) (deftest decode-empty-string (testing "decode empty string" (is (= (rle/run-length-decode "") "")))) (deftest decode-single-characters (testing "decode string with single characters only" (is (= (rle/run-length-decode "XYZ") "XYZ")))) (deftest decode-no-single-characters (testing "decode string with no single characters" (is (= (rle/run-length-decode "2A3B4C") "AABBBCCCC")))) (deftest decode-single-and-repeated-characters (testing "decode string with single and repeated characters" (is (= (rle/run-length-decode "12WB12W3B24WB") "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")))) (deftest decode-lowercase (testing "decode string with lowercase characters" (is (= (rle/run-length-decode "2a3b4c") "aabbbcccc")))) (deftest decode-mixed-whitespace (testing "decode string with mixed whitespace characters in it" (is (= (rle/run-length-decode "2 hs2q q2w2 ") " hsqq qww ")))) (deftest consistency (testing "Encode a string and then decode it. Should return the same one." (is (= (rle/run-length-decode (rle/run-length-encode "zzz ZZ zZ")) "zzz ZZ zZ"))))
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/run-length-encoding/test/run_length_encoding_test.clj
clojure
Tests for run-length-encoding exercise
(ns run-length-encoding-test (:require [clojure.test :refer :all] [run-length-encoding :as rle])) (deftest encode-empty-string (testing "encode an empty string" (is (= (rle/run-length-encode "") "")))) (deftest encode-single-characters-without-count (testing "encode single characters without count" (is (= (rle/run-length-encode "XYZ") "XYZ")))) (deftest encode-string-with-no-single-characters (testing "encode string with no single characters" (is (= (rle/run-length-encode "AABBBCCCC") "2A3B4C")))) (deftest encode-string-with-single-and-mixed-characters (testing "encode string with single and mixed characters" (is (= (rle/run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB") "12WB12W3B24WB")))) (deftest encode-multiple-whitespace (testing "encode string with whitespace characters mixed in it" (is (= (rle/run-length-encode " hsqq qww ") "2 hs2q q2w2 ")))) (deftest encode-lowercase (testing "encode string with lowercase characters" (is (= (rle/run-length-encode "aabbbcccc") "2a3b4c")))) (deftest decode-empty-string (testing "decode empty string" (is (= (rle/run-length-decode "") "")))) (deftest decode-single-characters (testing "decode string with single characters only" (is (= (rle/run-length-decode "XYZ") "XYZ")))) (deftest decode-no-single-characters (testing "decode string with no single characters" (is (= (rle/run-length-decode "2A3B4C") "AABBBCCCC")))) (deftest decode-single-and-repeated-characters (testing "decode string with single and repeated characters" (is (= (rle/run-length-decode "12WB12W3B24WB") "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")))) (deftest decode-lowercase (testing "decode string with lowercase characters" (is (= (rle/run-length-decode "2a3b4c") "aabbbcccc")))) (deftest decode-mixed-whitespace (testing "decode string with mixed whitespace characters in it" (is (= (rle/run-length-decode "2 hs2q q2w2 ") " hsqq qww ")))) (deftest consistency (testing "Encode a string and then decode it. Should return the same one." (is (= (rle/run-length-decode (rle/run-length-encode "zzz ZZ zZ")) "zzz ZZ zZ"))))
5e3361a76cb0113e9b8c00669c91df806945a039fe94a36e2b67bc3dbf5987e8
0install/0install
basedir.mli
Copyright ( C ) 2013 , the README file for details , or visit . * See the README file for details, or visit . *) (** XDG Base Directory support, for locating caches, configuration, etc *) open Common type basedirs = { data: filepath list; cache: filepath list; config: filepath list; } (** Get configuration using [ZEROINSTALL_PORTABLE_BASE] (if set), or the platform default, * modified by any [XDG_*] variables which are set. *) val get_default_config : #system -> basedirs * [ load_first system relpath search_path ] returns the first configuration path ( base + / relpath ) that exists * from the base paths in [ search_path ] . * from the base paths in [search_path]. *) val load_first : #filesystem -> filepath -> filepath list -> filepath option (** [save_path system relpath search_path] creates the directory [List.hd search_path +/ relpath] (and * any missing parents) and returns its path. *) val save_path : #filesystem -> filepath -> filepath list -> filepath (** Get the home directory (normally [$HOME]). If we're running as root and $HOME isn't owned by root * (e.g. under sudo) then return root's real home directory instead. *) val get_unix_home : system -> filepath
null
https://raw.githubusercontent.com/0install/0install/22eebdbe51a9f46cda29eed3e9e02e37e36b2d18/src/support/basedir.mli
ocaml
* XDG Base Directory support, for locating caches, configuration, etc * Get configuration using [ZEROINSTALL_PORTABLE_BASE] (if set), or the platform default, * modified by any [XDG_*] variables which are set. * [save_path system relpath search_path] creates the directory [List.hd search_path +/ relpath] (and * any missing parents) and returns its path. * Get the home directory (normally [$HOME]). If we're running as root and $HOME isn't owned by root * (e.g. under sudo) then return root's real home directory instead.
Copyright ( C ) 2013 , the README file for details , or visit . * See the README file for details, or visit . *) open Common type basedirs = { data: filepath list; cache: filepath list; config: filepath list; } val get_default_config : #system -> basedirs * [ load_first system relpath search_path ] returns the first configuration path ( base + / relpath ) that exists * from the base paths in [ search_path ] . * from the base paths in [search_path]. *) val load_first : #filesystem -> filepath -> filepath list -> filepath option val save_path : #filesystem -> filepath -> filepath list -> filepath val get_unix_home : system -> filepath
62628de006548203f128eec564cfd16c011aca23e1fbdc752ab85abb84713a3f
seckcoder/iu_c311
lang.rkt
#lang racket (require "../../base/utils.rkt") (provide parse parse-exp parse-decl parse-ty Program (all-from-out 'Type) (all-from-out 'Decl) (all-from-out 'Exp) ) ; parser for kyo (module Type racket (provide (prefix-out t: (all-defined-out))) (struct Int () #:transparent) (struct Str () #:transparent) (struct Bool () #:transparent) (struct Record (fs) #:transparent) (struct Vec (t) #:transparent) ; no type (struct Unit () #:transparent) ; any type (struct Any () #:transparent) ; a placeholder; used for recursive types (struct Name (n t) #:transparent) ; rand and return (struct Ft (rnd rt) #:transparent) ) (require 'Type) (define (parse-ty t) (match t ['int (t:Int)] ['str (t:Str)] ['bool (t:Bool)] ['unit (t:Unit)] [(? symbol? t) ; t is a type-id, it refers to some unknown type (t:Name t (ref (None)))] [`(vec ,type-id) (t:Vec type-id)] [`(,t1 -> ,t2) (t:Ft (parse-ty t1) (parse-ty t2))] [`(,t1 -> ,t2 ...) (t:Ft (parse-ty t1) (parse-ty t2))] [`((,id* ,type-id*) ...) (t:Record (map list id* type-id*))] )) (module Decl racket (provide (prefix-out d: (all-defined-out))) (struct tydec (id t) #:transparent) (struct vardec (id t v) #:transparent) ; f is e:fun (struct fundec (id f) #:transparent) ) (require 'Decl) (define (fn? f) (and (pair? f) (eq? (car f) 'fn))) ; return (list type value) (define (parse-decl decl) (match decl [`(type ,type-id ,ty) (d:tydec type-id (parse-ty ty))] [`(def ,v : ,type-id ,val) (d:vardec v (parse-ty type-id) (parse-exp val))] [`(def ,v ,(? fn? f)) (d:fundec v (parse-exp f))] )) (define (parse-binding binding) (match binding [`(,v : ,type-id ,val) (parse-decl `(def ,v : ,type-id ,val))] [`(,v ,(? fn? f)) (parse-decl `(def ,v ,f))])) (define (parse-decls decls) (map parse-decl decls)) (module Exp racket (provide (prefix-out e: (all-defined-out))) (struct const (v) #:transparent) (struct var (v) #:transparent) (struct biop (op a b) #:transparent) (struct unop (op v) #:transparent) (struct vec (t vs) #:transparent) (struct vecref (v i) #:transparent) ;(struct fun (v body) #:transparent) (struct fun (t v) #:transparent) ; function value (struct fv (v body) #:transparent) (struct seq (exps) #:transparent) (struct set (v val) #:transparent) (struct vecset (v i val) #:transparent) (struct ife (test then else) #:transparent) (struct lete (decls body) #:transparent) (struct app (rator rand) #:transparent) ) (require 'Exp) (define const? (anyf number? string? boolean?)) (define (parse-body body) (match body [(list) (error 'body "empty body")] [(list exp) (parse-exp exp)] [(list exp0 exp* ...) (parse-exp `(seq ,exp0 ,@exp*))])) (define (bi-op? op) (memq op '(+ - * and or = < > <= >= ))) (define (un-op? op) (memq op '(not))) (define (parse-exp exp) (match exp [(? const? v) (e:const v)] [(? symbol? v) (e:var v)] [(list (? bi-op? op) a b) (e:biop op (parse-exp a) (parse-exp b))] [(list (? un-op? op) v) (e:unop op (parse-exp v))] [`(fn () : ,ret-type-id ,body ...) (e:fun (t:Ft (t:Unit) (parse-ty ret-type-id)) (e:fv (None) (parse-body body)))] [`(fn ((,v : ,type-id)) : ,ret-type-id ,body ...) (e:fun (t:Ft (parse-ty type-id) (parse-ty ret-type-id)) (e:fv (Some v) (parse-body body)))] [`(fn ([,v0 : ,type-id0] [,v* : ,type-id*] ...) : ,ret-type-id ,body ...) (match (parse-exp `(fn ,(map (lambda (v type-id) `(,v : ,type-id)) v* type-id*) : ,ret-type-id ,@body)) [(e:fun ft fv) (e:fun (t:Ft (parse-ty type-id0) ft) (e:fun (Some v0) fv))] )] [`(vec ,type-id ,v* ...) (e:vec (parse-ty type-id) (map parse-exp v*))] [`(vec-ref ,v ,i) (e:vecref (parse-exp v) (parse-exp i))] [`(seq ,exp0 ,exp* ...) (e:seq (map parse-exp (cons exp0 exp*)))] [`(set! ,v ,val) (e:set v (parse-exp val))] [`(vec-set! ,vec ,i ,val) (e:vecset (parse-exp vec) (parse-exp i) (parse-exp val))] [`(if ,test ,then ,else) (e:ife (parse-exp test) (parse-exp then) (parse-exp else))] [`(let (,bindings ...) ,body ...) (e:lete (map parse-binding bindings) (parse-body body))] [`(,rator ,rand) (e:app (parse-exp rator) (parse-exp rand))] )) (struct Program (decls exp) #:transparent) (define (parse decls exp) (Program (parse-decls decls) (parse-exp exp))) (module+ test (parse (list '(def f (fn ([v : int]) : (vec int) (vec int v)))) '(f v)) (parse '() '(vec int v)) )
null
https://raw.githubusercontent.com/seckcoder/iu_c311/a1215983b6ab08df32058ef1e089cb294419e567/racket/compiler/kyo/lang.rkt
racket
parser for kyo no type any type a placeholder; used for recursive types rand and return t is a type-id, it refers to some unknown type f is e:fun return (list type value) (struct fun (v body) #:transparent) function value
#lang racket (require "../../base/utils.rkt") (provide parse parse-exp parse-decl parse-ty Program (all-from-out 'Type) (all-from-out 'Decl) (all-from-out 'Exp) ) (module Type racket (provide (prefix-out t: (all-defined-out))) (struct Int () #:transparent) (struct Str () #:transparent) (struct Bool () #:transparent) (struct Record (fs) #:transparent) (struct Vec (t) #:transparent) (struct Unit () #:transparent) (struct Any () #:transparent) (struct Name (n t) #:transparent) (struct Ft (rnd rt) #:transparent) ) (require 'Type) (define (parse-ty t) (match t ['int (t:Int)] ['str (t:Str)] ['bool (t:Bool)] ['unit (t:Unit)] [(? symbol? t) (t:Name t (ref (None)))] [`(vec ,type-id) (t:Vec type-id)] [`(,t1 -> ,t2) (t:Ft (parse-ty t1) (parse-ty t2))] [`(,t1 -> ,t2 ...) (t:Ft (parse-ty t1) (parse-ty t2))] [`((,id* ,type-id*) ...) (t:Record (map list id* type-id*))] )) (module Decl racket (provide (prefix-out d: (all-defined-out))) (struct tydec (id t) #:transparent) (struct vardec (id t v) #:transparent) (struct fundec (id f) #:transparent) ) (require 'Decl) (define (fn? f) (and (pair? f) (eq? (car f) 'fn))) (define (parse-decl decl) (match decl [`(type ,type-id ,ty) (d:tydec type-id (parse-ty ty))] [`(def ,v : ,type-id ,val) (d:vardec v (parse-ty type-id) (parse-exp val))] [`(def ,v ,(? fn? f)) (d:fundec v (parse-exp f))] )) (define (parse-binding binding) (match binding [`(,v : ,type-id ,val) (parse-decl `(def ,v : ,type-id ,val))] [`(,v ,(? fn? f)) (parse-decl `(def ,v ,f))])) (define (parse-decls decls) (map parse-decl decls)) (module Exp racket (provide (prefix-out e: (all-defined-out))) (struct const (v) #:transparent) (struct var (v) #:transparent) (struct biop (op a b) #:transparent) (struct unop (op v) #:transparent) (struct vec (t vs) #:transparent) (struct vecref (v i) #:transparent) (struct fun (t v) #:transparent) (struct fv (v body) #:transparent) (struct seq (exps) #:transparent) (struct set (v val) #:transparent) (struct vecset (v i val) #:transparent) (struct ife (test then else) #:transparent) (struct lete (decls body) #:transparent) (struct app (rator rand) #:transparent) ) (require 'Exp) (define const? (anyf number? string? boolean?)) (define (parse-body body) (match body [(list) (error 'body "empty body")] [(list exp) (parse-exp exp)] [(list exp0 exp* ...) (parse-exp `(seq ,exp0 ,@exp*))])) (define (bi-op? op) (memq op '(+ - * and or = < > <= >= ))) (define (un-op? op) (memq op '(not))) (define (parse-exp exp) (match exp [(? const? v) (e:const v)] [(? symbol? v) (e:var v)] [(list (? bi-op? op) a b) (e:biop op (parse-exp a) (parse-exp b))] [(list (? un-op? op) v) (e:unop op (parse-exp v))] [`(fn () : ,ret-type-id ,body ...) (e:fun (t:Ft (t:Unit) (parse-ty ret-type-id)) (e:fv (None) (parse-body body)))] [`(fn ((,v : ,type-id)) : ,ret-type-id ,body ...) (e:fun (t:Ft (parse-ty type-id) (parse-ty ret-type-id)) (e:fv (Some v) (parse-body body)))] [`(fn ([,v0 : ,type-id0] [,v* : ,type-id*] ...) : ,ret-type-id ,body ...) (match (parse-exp `(fn ,(map (lambda (v type-id) `(,v : ,type-id)) v* type-id*) : ,ret-type-id ,@body)) [(e:fun ft fv) (e:fun (t:Ft (parse-ty type-id0) ft) (e:fun (Some v0) fv))] )] [`(vec ,type-id ,v* ...) (e:vec (parse-ty type-id) (map parse-exp v*))] [`(vec-ref ,v ,i) (e:vecref (parse-exp v) (parse-exp i))] [`(seq ,exp0 ,exp* ...) (e:seq (map parse-exp (cons exp0 exp*)))] [`(set! ,v ,val) (e:set v (parse-exp val))] [`(vec-set! ,vec ,i ,val) (e:vecset (parse-exp vec) (parse-exp i) (parse-exp val))] [`(if ,test ,then ,else) (e:ife (parse-exp test) (parse-exp then) (parse-exp else))] [`(let (,bindings ...) ,body ...) (e:lete (map parse-binding bindings) (parse-body body))] [`(,rator ,rand) (e:app (parse-exp rator) (parse-exp rand))] )) (struct Program (decls exp) #:transparent) (define (parse decls exp) (Program (parse-decls decls) (parse-exp exp))) (module+ test (parse (list '(def f (fn ([v : int]) : (vec int) (vec int v)))) '(f v)) (parse '() '(vec int v)) )
8f46cc66a8100d8832a20dc1fc6eb95d788a5c3b8e9ba49af81bdb1a4bbacdba
Decentralized-Pictures/T4L3NT
test_gas_costs.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2020 Nomadic Labs , < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) (** Testing ------- Component: Protocol (gas costs) Invocation: dune exec src/proto_112_Pt4FJEL6/lib_protocol/test/main.exe -- test "^gas cost functions$" Subject: Gas costs Current limitations: for maps, sets & compare, we only test integer comparable keys. *) open Protocol module S = Saturation_repr let dummy_list = Script_list.(cons 42 empty) let forty_two = Alpha_context.Script_int.of_int 42 let forty_two_n = Alpha_context.Script_int.abs forty_two let dummy_set = let open Script_set in update forty_two true (empty Script_typed_ir.(int_key ~annot:None)) let dummy_map = let open Script_map in update forty_two (Some forty_two) (empty Script_typed_ir.(int_key ~annot:None)) let dummy_timestamp = Alpha_context.Script_timestamp.of_zint (Z.of_int 42) let dummy_pk = Signature.Public_key.of_b58check_exn "edpkuFrRoDSEbJYgxRtLx2ps82UdaYc1WwfS9sE11yhauZt5DgCHbU" let dummy_bytes = Bytes.of_string "dummy" let dummy_string = match Alpha_context.Script_string.of_string "dummy" with | Ok s -> s | Error _ -> assert false let free = ["balance"; "bool"; "parsing_unit"; "unparsing_unit"] (* /!\ The compiler will only complain if costs are _removed_ /!\*) let all_interpreter_costs = let open Michelson_v1_gas.Cost_of.Interpreter in [ ("drop", drop); ("dup", dup); ("swap", swap); ("cons_some", cons_some); ("cons_none", cons_none); ("if_none", if_none); ("cons_pair", cons_pair); ("car", car); ("cdr", cdr); ("cons_left", cons_left); ("cons_right", cons_right); ("if_left", if_left); ("cons_list", cons_list); ("nil", nil); ("if_cons", if_cons); ("list_map", list_map dummy_list); ("list_size", list_size); ("list_iter", list_iter dummy_list); ("empty_set", empty_set); ("set_iter", set_iter dummy_set); ("set_mem", set_mem forty_two dummy_set); ("set_update", set_update forty_two dummy_set); ("set_size", set_size); ("empty_map", empty_map); ("map_map", map_map dummy_map); ("map_iter", map_iter dummy_map); ("map_mem", map_mem forty_two dummy_map); ("map_get", map_get forty_two dummy_map); ("map_update", map_update forty_two dummy_map); ("map_size", map_size); ("add_seconds_timestamp", add_seconds_timestamp forty_two dummy_timestamp); ("sub_timestamp_seconds", sub_timestamp_seconds dummy_timestamp forty_two); ("diff_timestamps", diff_timestamps dummy_timestamp dummy_timestamp); ("concat_string_pair", concat_string_pair dummy_string dummy_string); ("slice_string", slice_string dummy_string); ("string_size", string_size); ("concat_bytes_pair", concat_bytes_pair dummy_bytes dummy_bytes); ("slice_bytes", slice_bytes dummy_bytes); ("bytes_size", bytes_size); ("add_tez", add_tez); ("sub_tez", sub_tez); ("mul_teznat", mul_teznat); ("bool_or", bool_or); ("bool_and", bool_and); ("bool_xor", bool_xor); ("bool_not", bool_not); ("is_nat", is_nat); ("abs_int", abs_int forty_two); ("int_nat", int_nat); ("neg_int", neg_int forty_two); ("neg_nat", neg_nat forty_two_n); ("add_intint", add_intint forty_two forty_two); ("sub_int", sub_int forty_two forty_two); ("mul_intint", mul_intint forty_two forty_two); ("ediv_teznat", ediv_teznat Alpha_context.Tez.fifty_cents forty_two); ("ediv_tez", ediv_tez); ("ediv_intint", ediv_intint forty_two (Alpha_context.Script_int.of_int 1)); ("eq", eq); ("lsl_nat", lsl_nat forty_two); ("lsr_nat", lsr_nat forty_two); ("or_nat", or_nat forty_two forty_two); ("and_nat", and_nat forty_two forty_two); ("xor_nat", xor_nat forty_two forty_two); ("not_int", not_int forty_two); ("not_nat", not_nat forty_two); ("if_", if_); ("loop", loop); ("loop_left", loop_left); ("dip", dip); ("check_signature", check_signature dummy_pk dummy_bytes); ("blake2b", blake2b dummy_bytes); ("sha256", sha256 dummy_bytes); ("sha512", sha512 dummy_bytes); ("dign", dign 42); ("dugn", dugn 42); ("dipn", dipn 42); ("dropn", dropn 42); ("neq", neq); ( "compare", compare Script_typed_ir.(int_key ~annot:None) forty_two forty_two ); ( "concat_string_precheck", concat_string_precheck Script_list.(cons "42" empty) ); ("concat_string", concat_string (S.safe_int 42)); ("concat_bytes", concat_bytes (S.safe_int 42)); ("exec", exec); ("apply", apply); ("lambda", lambda); ("address", address); ("contract", contract); ("transfer_tokens", transfer_tokens); ("implicit_account", implicit_account); ("create_contract", create_contract); ("set_delegate", set_delegate); (* balance is free *) ("balance", balance); ("level", level); ("now", now); ("hash_key", hash_key dummy_pk); ("source", source); ("sender", sender); ("self", self); ("self_address", self_address); ("amount", amount); ("chain_id", chain_id); ("unpack_failed", unpack_failed (Bytes.of_string "dummy")); ] (* /!\ The compiler will only complain if costs are _removed_ /!\*) let all_parsing_costs = let open Michelson_v1_gas.Cost_of.Typechecking in [ ("public_key_optimized", public_key_optimized); ("public_key_readable", public_key_readable); ("key_hash_optimized", key_hash_optimized); ("key_hash_readable", key_hash_readable); ("signature_optimized", signature_optimized); ("signature_readable", signature_readable); ("chain_id_optimized", chain_id_optimized); ("chain_id_readable", chain_id_readable); ("address_optimized", address_optimized); ("contract_optimized", contract_optimized); ("contract_readable", contract_readable); ("check_printable", check_printable "dummy"); ("merge_cycle", merge_cycle); ("parse_type_cycle", parse_type_cycle); ("parse_instr_cycle", parse_instr_cycle); ("parse_data_cycle", parse_data_cycle); ("bool", bool); ("parsing_unit", unit); ("timestamp_readable", timestamp_readable); ("contract", contract); ("contract_exists", contract_exists); ("proof_argument", proof_argument 42); ] (* /!\ The compiler will only complain if costs are _removed_ /!\*) let all_unparsing_costs = let open Michelson_v1_gas.Cost_of.Unparsing in [ ("public_key_optimized", public_key_optimized); ("public_key_readable", public_key_readable); ("key_hash_optimized", key_hash_optimized); ("key_hash_readable", key_hash_readable); ("signature_optimized", signature_optimized); ("signature_readable", signature_readable); ("chain_id_optimized", chain_id_optimized); ("chain_id_readable", chain_id_readable); ("timestamp_readable", timestamp_readable); ("address_optimized", address_optimized); ("contract_optimized", contract_optimized); ("contract_readable", contract_readable); ("unparse_type_cycle", unparse_type_cycle); ("unparse_instr_cycle", unparse_instr_cycle); ("unparse_data_cycle", unparse_data_cycle); ("unparsing_unit", unit); ("contract", contract); ("operation", operation dummy_bytes); ] (* /!\ The compiler will only complain if costs are _removed_ /!\*) let all_io_costs = let open Storage_costs in [ ("read_access 0 0", read_access ~path_length:0 ~read_bytes:0); ("read_access 1 0", read_access ~path_length:1 ~read_bytes:0); ("read_access 0 1", read_access ~path_length:0 ~read_bytes:1); ("read_access 1 1", read_access ~path_length:1 ~read_bytes:1); ("write_access 0", write_access ~written_bytes:0); ("write_access 1", write_access ~written_bytes:1); ] (* Here we're using knowledge of the internal representation of costs to cast them to S ... *) let cast_cost_to_s (c : Alpha_context.Gas.cost) : _ S.t = Data_encoding.Binary.to_bytes_exn Alpha_context.Gas.cost_encoding c |> Data_encoding.Binary.of_bytes_exn S.n_encoding (** Checks that all costs are positive values. *) let test_cost_reprs_are_all_positive list () = List.iter_es (fun (cost_name, cost) -> if S.(cost > S.zero) then return_unit else if S.equal cost S.zero && List.mem ~equal:String.equal cost_name free then return_unit else fail (Exn (Failure (Format.asprintf "Gas cost test \"%s\" failed" cost_name)))) list (** Checks that all costs are positive values. *) let test_costs_are_all_positive list () = let list = List.map (fun (cost_name, cost) -> (cost_name, cast_cost_to_s cost)) list in test_cost_reprs_are_all_positive list () let tests = [ Tztest.tztest "Positivity of interpreter costs" `Quick (test_costs_are_all_positive all_interpreter_costs); Tztest.tztest "Positivity of typechecking costs" `Quick (test_costs_are_all_positive all_parsing_costs); Tztest.tztest "Positivity of unparsing costs" `Quick (test_costs_are_all_positive all_unparsing_costs); Tztest.tztest "Positivity of io costs" `Quick (test_cost_reprs_are_all_positive all_io_costs); ]
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/proto_112_Pt4FJEL6/lib_protocol/test/test_gas_costs.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Testing ------- Component: Protocol (gas costs) Invocation: dune exec src/proto_112_Pt4FJEL6/lib_protocol/test/main.exe -- test "^gas cost functions$" Subject: Gas costs Current limitations: for maps, sets & compare, we only test integer comparable keys. /!\ The compiler will only complain if costs are _removed_ /!\ balance is free /!\ The compiler will only complain if costs are _removed_ /!\ /!\ The compiler will only complain if costs are _removed_ /!\ /!\ The compiler will only complain if costs are _removed_ /!\ Here we're using knowledge of the internal representation of costs to cast them to S ... * Checks that all costs are positive values. * Checks that all costs are positive values.
Copyright ( c ) 2020 Nomadic Labs , < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Protocol module S = Saturation_repr let dummy_list = Script_list.(cons 42 empty) let forty_two = Alpha_context.Script_int.of_int 42 let forty_two_n = Alpha_context.Script_int.abs forty_two let dummy_set = let open Script_set in update forty_two true (empty Script_typed_ir.(int_key ~annot:None)) let dummy_map = let open Script_map in update forty_two (Some forty_two) (empty Script_typed_ir.(int_key ~annot:None)) let dummy_timestamp = Alpha_context.Script_timestamp.of_zint (Z.of_int 42) let dummy_pk = Signature.Public_key.of_b58check_exn "edpkuFrRoDSEbJYgxRtLx2ps82UdaYc1WwfS9sE11yhauZt5DgCHbU" let dummy_bytes = Bytes.of_string "dummy" let dummy_string = match Alpha_context.Script_string.of_string "dummy" with | Ok s -> s | Error _ -> assert false let free = ["balance"; "bool"; "parsing_unit"; "unparsing_unit"] let all_interpreter_costs = let open Michelson_v1_gas.Cost_of.Interpreter in [ ("drop", drop); ("dup", dup); ("swap", swap); ("cons_some", cons_some); ("cons_none", cons_none); ("if_none", if_none); ("cons_pair", cons_pair); ("car", car); ("cdr", cdr); ("cons_left", cons_left); ("cons_right", cons_right); ("if_left", if_left); ("cons_list", cons_list); ("nil", nil); ("if_cons", if_cons); ("list_map", list_map dummy_list); ("list_size", list_size); ("list_iter", list_iter dummy_list); ("empty_set", empty_set); ("set_iter", set_iter dummy_set); ("set_mem", set_mem forty_two dummy_set); ("set_update", set_update forty_two dummy_set); ("set_size", set_size); ("empty_map", empty_map); ("map_map", map_map dummy_map); ("map_iter", map_iter dummy_map); ("map_mem", map_mem forty_two dummy_map); ("map_get", map_get forty_two dummy_map); ("map_update", map_update forty_two dummy_map); ("map_size", map_size); ("add_seconds_timestamp", add_seconds_timestamp forty_two dummy_timestamp); ("sub_timestamp_seconds", sub_timestamp_seconds dummy_timestamp forty_two); ("diff_timestamps", diff_timestamps dummy_timestamp dummy_timestamp); ("concat_string_pair", concat_string_pair dummy_string dummy_string); ("slice_string", slice_string dummy_string); ("string_size", string_size); ("concat_bytes_pair", concat_bytes_pair dummy_bytes dummy_bytes); ("slice_bytes", slice_bytes dummy_bytes); ("bytes_size", bytes_size); ("add_tez", add_tez); ("sub_tez", sub_tez); ("mul_teznat", mul_teznat); ("bool_or", bool_or); ("bool_and", bool_and); ("bool_xor", bool_xor); ("bool_not", bool_not); ("is_nat", is_nat); ("abs_int", abs_int forty_two); ("int_nat", int_nat); ("neg_int", neg_int forty_two); ("neg_nat", neg_nat forty_two_n); ("add_intint", add_intint forty_two forty_two); ("sub_int", sub_int forty_two forty_two); ("mul_intint", mul_intint forty_two forty_two); ("ediv_teznat", ediv_teznat Alpha_context.Tez.fifty_cents forty_two); ("ediv_tez", ediv_tez); ("ediv_intint", ediv_intint forty_two (Alpha_context.Script_int.of_int 1)); ("eq", eq); ("lsl_nat", lsl_nat forty_two); ("lsr_nat", lsr_nat forty_two); ("or_nat", or_nat forty_two forty_two); ("and_nat", and_nat forty_two forty_two); ("xor_nat", xor_nat forty_two forty_two); ("not_int", not_int forty_two); ("not_nat", not_nat forty_two); ("if_", if_); ("loop", loop); ("loop_left", loop_left); ("dip", dip); ("check_signature", check_signature dummy_pk dummy_bytes); ("blake2b", blake2b dummy_bytes); ("sha256", sha256 dummy_bytes); ("sha512", sha512 dummy_bytes); ("dign", dign 42); ("dugn", dugn 42); ("dipn", dipn 42); ("dropn", dropn 42); ("neq", neq); ( "compare", compare Script_typed_ir.(int_key ~annot:None) forty_two forty_two ); ( "concat_string_precheck", concat_string_precheck Script_list.(cons "42" empty) ); ("concat_string", concat_string (S.safe_int 42)); ("concat_bytes", concat_bytes (S.safe_int 42)); ("exec", exec); ("apply", apply); ("lambda", lambda); ("address", address); ("contract", contract); ("transfer_tokens", transfer_tokens); ("implicit_account", implicit_account); ("create_contract", create_contract); ("set_delegate", set_delegate); ("balance", balance); ("level", level); ("now", now); ("hash_key", hash_key dummy_pk); ("source", source); ("sender", sender); ("self", self); ("self_address", self_address); ("amount", amount); ("chain_id", chain_id); ("unpack_failed", unpack_failed (Bytes.of_string "dummy")); ] let all_parsing_costs = let open Michelson_v1_gas.Cost_of.Typechecking in [ ("public_key_optimized", public_key_optimized); ("public_key_readable", public_key_readable); ("key_hash_optimized", key_hash_optimized); ("key_hash_readable", key_hash_readable); ("signature_optimized", signature_optimized); ("signature_readable", signature_readable); ("chain_id_optimized", chain_id_optimized); ("chain_id_readable", chain_id_readable); ("address_optimized", address_optimized); ("contract_optimized", contract_optimized); ("contract_readable", contract_readable); ("check_printable", check_printable "dummy"); ("merge_cycle", merge_cycle); ("parse_type_cycle", parse_type_cycle); ("parse_instr_cycle", parse_instr_cycle); ("parse_data_cycle", parse_data_cycle); ("bool", bool); ("parsing_unit", unit); ("timestamp_readable", timestamp_readable); ("contract", contract); ("contract_exists", contract_exists); ("proof_argument", proof_argument 42); ] let all_unparsing_costs = let open Michelson_v1_gas.Cost_of.Unparsing in [ ("public_key_optimized", public_key_optimized); ("public_key_readable", public_key_readable); ("key_hash_optimized", key_hash_optimized); ("key_hash_readable", key_hash_readable); ("signature_optimized", signature_optimized); ("signature_readable", signature_readable); ("chain_id_optimized", chain_id_optimized); ("chain_id_readable", chain_id_readable); ("timestamp_readable", timestamp_readable); ("address_optimized", address_optimized); ("contract_optimized", contract_optimized); ("contract_readable", contract_readable); ("unparse_type_cycle", unparse_type_cycle); ("unparse_instr_cycle", unparse_instr_cycle); ("unparse_data_cycle", unparse_data_cycle); ("unparsing_unit", unit); ("contract", contract); ("operation", operation dummy_bytes); ] let all_io_costs = let open Storage_costs in [ ("read_access 0 0", read_access ~path_length:0 ~read_bytes:0); ("read_access 1 0", read_access ~path_length:1 ~read_bytes:0); ("read_access 0 1", read_access ~path_length:0 ~read_bytes:1); ("read_access 1 1", read_access ~path_length:1 ~read_bytes:1); ("write_access 0", write_access ~written_bytes:0); ("write_access 1", write_access ~written_bytes:1); ] let cast_cost_to_s (c : Alpha_context.Gas.cost) : _ S.t = Data_encoding.Binary.to_bytes_exn Alpha_context.Gas.cost_encoding c |> Data_encoding.Binary.of_bytes_exn S.n_encoding let test_cost_reprs_are_all_positive list () = List.iter_es (fun (cost_name, cost) -> if S.(cost > S.zero) then return_unit else if S.equal cost S.zero && List.mem ~equal:String.equal cost_name free then return_unit else fail (Exn (Failure (Format.asprintf "Gas cost test \"%s\" failed" cost_name)))) list let test_costs_are_all_positive list () = let list = List.map (fun (cost_name, cost) -> (cost_name, cast_cost_to_s cost)) list in test_cost_reprs_are_all_positive list () let tests = [ Tztest.tztest "Positivity of interpreter costs" `Quick (test_costs_are_all_positive all_interpreter_costs); Tztest.tztest "Positivity of typechecking costs" `Quick (test_costs_are_all_positive all_parsing_costs); Tztest.tztest "Positivity of unparsing costs" `Quick (test_costs_are_all_positive all_unparsing_costs); Tztest.tztest "Positivity of io costs" `Quick (test_cost_reprs_are_all_positive all_io_costs); ]
6b83a3830159c727bd8dedc498efb657c1a9911491132e4338154263b8b84220
district0x/district-registry
ds_auth.cljs
(ns district-registry.server.contract.ds-auth (:require [district.server.smart-contracts :as smart-contracts])) (defn owner [contract-key] (smart-contracts/contract-call contract-key :owner)) (defn authority [contract-key] (smart-contracts/contract-call contract-key :authority))
null
https://raw.githubusercontent.com/district0x/district-registry/c2dcf7978d2243a773165b18e7a76632d8ad724e/src/district_registry/server/contract/ds_auth.cljs
clojure
(ns district-registry.server.contract.ds-auth (:require [district.server.smart-contracts :as smart-contracts])) (defn owner [contract-key] (smart-contracts/contract-call contract-key :owner)) (defn authority [contract-key] (smart-contracts/contract-call contract-key :authority))
ee26f64c524fee572079bb8b2e7a4e2dcb8daf4c8ccb6487ac837b81bb316d05
input-output-hk/project-icarus-importer
ServerBench.hs
module Bench.Pos.BlockchainImporter.ServerBench ( runTimeBenchmark , runSpaceBenchmark ) where import Universum import Criterion.Main (bench, defaultConfig, defaultMainWith, nfIO) import Criterion.Types (Config (..)) import Weigh (io, mainWith) import Test.QuickCheck (arbitrary, generate) import Pos.Arbitrary.Txp.Unsafe () import Test.Pos.Configuration (withDefConfigurations) import Pos.BlockchainImporter.BlockchainImporterMode (BlockchainImporterTestParams, runBlockchainImporterTestMode) import Pos.BlockchainImporter.Configuration (withPostGresDB) import Pos.BlockchainImporter.ExtraContext (ExtraContext (..), makeMockExtraCtx) import Pos.BlockchainImporter.TestUtil (BlockNumber, SlotsPerEpoch, generateValidBlockchainImporterMockableMode) import Pos.BlockchainImporter.Web.Server (getBlocksTotal) ---------------------------------------------------------------- -- Mocked functions ---------------------------------------------------------------- type BenchmarkTestParams = (BlockchainImporterTestParams, ExtraContext) -- | @getBlocksTotal@ function for benchmarks. getBlocksTotalBench :: BenchmarkTestParams -> IO Integer getBlocksTotalBench (testParams, extraContext) = withDefConfigurations $ \_ -> -- Postgres db is not mocked as it's never used withPostGresDB (error "No postgres db configured") $ runBlockchainImporterTestMode testParams extraContext getBlocksTotal -- | This is used to generate the test environment. We don't do this while benchmarking -- the functions since that would include the time/memory required for the generation of the -- mock blockchain (test environment), and we don't want to include that in our benchmarks. generateTestParams :: BlockNumber -> SlotsPerEpoch -> IO BenchmarkTestParams generateTestParams totalBlocksNumber slotsPerEpoch = do testParams <- testParamsGen -- We replace the "real" blockchain with our custom generated one. mode <- generateValidBlockchainImporterMockableMode totalBlocksNumber slotsPerEpoch -- The extra context so we can mock the functions. -- Postgres db is not mocked as it's never used let extraContext :: ExtraContext extraContext = withPostGresDB (error "No postgres db configured") $ withDefConfigurations $ const $ makeMockExtraCtx mode pure (testParams, extraContext) where -- | Generated test parameters. testParamsGen :: IO BlockchainImporterTestParams testParamsGen = generate arbitrary -- | Extracted common code. This needs to be run before the benchmarks since we don't -- want to include time/memory of the test data generation in the benchmarks. usingGeneratedBlocks :: IO (BenchmarkTestParams, BenchmarkTestParams, BenchmarkTestParams) usingGeneratedBlocks = do blocks100 <- generateTestParams 100 10 blocks1000 <- generateTestParams 1000 10 blocks10000 <- generateTestParams 10000 10 pure (blocks100, blocks1000, blocks10000) ---------------------------------------------------------------- Time benchmark ---------------------------------------------------------------- -- | Time @getBlocksPage@. runTimeBenchmark :: IO () runTimeBenchmark = do -- Generate the test environment before the benchmarks. (blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks defaultMainWith getBlocksPageConfig [ bench "getBlocksTotal 100 blocks" $ nfIO $ getBlocksTotalBench blocks100 , bench "getBlocksTotal 1000 blocks" $ nfIO $ getBlocksTotalBench blocks1000 , bench "getBlocksTotal 10000 blocks" $ nfIO $ getBlocksTotalBench blocks10000 ] where -- | Configuration. getBlocksPageConfig :: Config getBlocksPageConfig = defaultConfig { reportFile = Just "bench/results/ServerBackend.html" } ---------------------------------------------------------------- -- Space benchmark ---------------------------------------------------------------- -- | Space @getBlocksPage@. runSpaceBenchmark :: IO () runSpaceBenchmark = do -- Generate the test environment before the benchmarks. (blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks mainWith $ do io "getBlocksTotal 100 blocks" getBlocksTotalBench blocks100 io "getBlocksTotal 1000 blocks" getBlocksTotalBench blocks1000 io "getBlocksTotal 10000 blocks" getBlocksTotalBench blocks10000
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/blockchain-importer/bench/Bench/Pos/BlockchainImporter/ServerBench.hs
haskell
-------------------------------------------------------------- Mocked functions -------------------------------------------------------------- | @getBlocksTotal@ function for benchmarks. Postgres db is not mocked as it's never used | This is used to generate the test environment. We don't do this while benchmarking the functions since that would include the time/memory required for the generation of the mock blockchain (test environment), and we don't want to include that in our benchmarks. We replace the "real" blockchain with our custom generated one. The extra context so we can mock the functions. Postgres db is not mocked as it's never used | Generated test parameters. | Extracted common code. This needs to be run before the benchmarks since we don't want to include time/memory of the test data generation in the benchmarks. -------------------------------------------------------------- -------------------------------------------------------------- | Time @getBlocksPage@. Generate the test environment before the benchmarks. | Configuration. -------------------------------------------------------------- Space benchmark -------------------------------------------------------------- | Space @getBlocksPage@. Generate the test environment before the benchmarks.
module Bench.Pos.BlockchainImporter.ServerBench ( runTimeBenchmark , runSpaceBenchmark ) where import Universum import Criterion.Main (bench, defaultConfig, defaultMainWith, nfIO) import Criterion.Types (Config (..)) import Weigh (io, mainWith) import Test.QuickCheck (arbitrary, generate) import Pos.Arbitrary.Txp.Unsafe () import Test.Pos.Configuration (withDefConfigurations) import Pos.BlockchainImporter.BlockchainImporterMode (BlockchainImporterTestParams, runBlockchainImporterTestMode) import Pos.BlockchainImporter.Configuration (withPostGresDB) import Pos.BlockchainImporter.ExtraContext (ExtraContext (..), makeMockExtraCtx) import Pos.BlockchainImporter.TestUtil (BlockNumber, SlotsPerEpoch, generateValidBlockchainImporterMockableMode) import Pos.BlockchainImporter.Web.Server (getBlocksTotal) type BenchmarkTestParams = (BlockchainImporterTestParams, ExtraContext) getBlocksTotalBench :: BenchmarkTestParams -> IO Integer getBlocksTotalBench (testParams, extraContext) = withDefConfigurations $ \_ -> withPostGresDB (error "No postgres db configured") $ runBlockchainImporterTestMode testParams extraContext getBlocksTotal generateTestParams :: BlockNumber -> SlotsPerEpoch -> IO BenchmarkTestParams generateTestParams totalBlocksNumber slotsPerEpoch = do testParams <- testParamsGen mode <- generateValidBlockchainImporterMockableMode totalBlocksNumber slotsPerEpoch let extraContext :: ExtraContext extraContext = withPostGresDB (error "No postgres db configured") $ withDefConfigurations $ const $ makeMockExtraCtx mode pure (testParams, extraContext) where testParamsGen :: IO BlockchainImporterTestParams testParamsGen = generate arbitrary usingGeneratedBlocks :: IO (BenchmarkTestParams, BenchmarkTestParams, BenchmarkTestParams) usingGeneratedBlocks = do blocks100 <- generateTestParams 100 10 blocks1000 <- generateTestParams 1000 10 blocks10000 <- generateTestParams 10000 10 pure (blocks100, blocks1000, blocks10000) Time benchmark runTimeBenchmark :: IO () runTimeBenchmark = do (blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks defaultMainWith getBlocksPageConfig [ bench "getBlocksTotal 100 blocks" $ nfIO $ getBlocksTotalBench blocks100 , bench "getBlocksTotal 1000 blocks" $ nfIO $ getBlocksTotalBench blocks1000 , bench "getBlocksTotal 10000 blocks" $ nfIO $ getBlocksTotalBench blocks10000 ] where getBlocksPageConfig :: Config getBlocksPageConfig = defaultConfig { reportFile = Just "bench/results/ServerBackend.html" } runSpaceBenchmark :: IO () runSpaceBenchmark = do (blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks mainWith $ do io "getBlocksTotal 100 blocks" getBlocksTotalBench blocks100 io "getBlocksTotal 1000 blocks" getBlocksTotalBench blocks1000 io "getBlocksTotal 10000 blocks" getBlocksTotalBench blocks10000
f456daa0b7a1ed9e3b7c969c220a31ef3b80fd73845f0c3fcbc9ad6f42d0419f
adaliu-gh/htdp
5-graphical editor.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname |5-graphical editor|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (require 2htdp/universe) (define-struct editor [pre post]) ; An Editor is a structure: ( make - editor ) ; interpretation (make-editor s t) describes an editor ; whose visible text is (string-appedn s t) with ; the cursor displayed between s and t (define BACK (empty-scene 200 20)) (define CURSOR (rectangle 1 20 "solid" "red")) ;;--------------------- ;; Auxiliary functions: ;;--------------------- ; editor -> Image ; renders the text and the cursor without background image (define (render-text e) (beside (text (editor-pre e) 11 "black") CURSOR (text (editor-post e) 11 "black"))) ; String -> String gets the first character of String str (define (string-first str) (if (> (string-length str) 0) (substring str 0 1) "")) ; String -> String get the last character of String str (define (string-last str) (if (> (string-length str) 0) (substring str (- (string-length str) 1) (string-length str)) "")) ; String -> String ; gets the new string after removing the last character of the original string str (define (string-last-remove str) (if (> (string-length str) 0) (substring str 0 (- (string-length str) 1)) "")) ; String -> String gets the new string after chopping the first character off (define (string-rest str) (if (> (string-length str) 0) (substring str 1 (string-length str)) "")) ;;--------------------- ;; Auxiliary functions. ;;--------------------- ; editor -> Image ; renders the editor and places the cursor between editor-pre and editor-post (define (render e) (overlay/xy (render-text e) 0 0 BACK)) editor KeyEvent - > editor ; obtains new editor after pressing a key " \b " deletes the last character of the editor - pre ; "left" and "right" move the cursor to the right place (if any) ; other letter keys, such as "a" "b", adds a new character to the end of the editor-pre ; all other keys are ignored (define (edit edi ke) (cond [(key=? ke "\b") (make-editor (string-last-remove (editor-pre edi)) (editor-post edi))] [(key=? ke "left") (make-editor (string-last-remove (editor-pre edi)) (string-append (string-last (editor-pre edi)) (editor-post edi)))] [(key=? ke "right") (make-editor (string-append (editor-pre edi) (string-first (editor-post edi))) (string-rest (editor-post edi)))] [(and (= 1 (string-length ke)) (not (key=? ke "\t")) (not (key=? ke "\r")) (> 33 (+ (string-length (editor-pre edi)) (string-length (editor-post edi))))) (make-editor (string-append (editor-pre edi) ke) (editor-post edi))] [else edi])) ; String -> editor (define (run str) (big-bang (make-editor str "") [on-key edit] [to-draw render]))
null
https://raw.githubusercontent.com/adaliu-gh/htdp/a0fca8af2ae8bdcef40d56f6f45021dd92df2995/1-7%20Fixed-Size%20Data/5-graphical%20editor.rkt
racket
about the language level of this file in a form that our tools can easily process. An Editor is a structure: interpretation (make-editor s t) describes an editor whose visible text is (string-appedn s t) with the cursor displayed between s and t --------------------- Auxiliary functions: --------------------- editor -> Image renders the text and the cursor without background image String -> String String -> String String -> String gets the new string after removing the last character of the original string str String -> String --------------------- Auxiliary functions. --------------------- editor -> Image renders the editor and places the cursor between editor-pre and editor-post obtains new editor after pressing a key "left" and "right" move the cursor to the right place (if any) other letter keys, such as "a" "b", adds a new character to the end of the editor-pre all other keys are ignored String -> editor
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname |5-graphical editor|) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (require 2htdp/universe) (define-struct editor [pre post]) ( make - editor ) (define BACK (empty-scene 200 20)) (define CURSOR (rectangle 1 20 "solid" "red")) (define (render-text e) (beside (text (editor-pre e) 11 "black") CURSOR (text (editor-post e) 11 "black"))) gets the first character of String str (define (string-first str) (if (> (string-length str) 0) (substring str 0 1) "")) get the last character of String str (define (string-last str) (if (> (string-length str) 0) (substring str (- (string-length str) 1) (string-length str)) "")) (define (string-last-remove str) (if (> (string-length str) 0) (substring str 0 (- (string-length str) 1)) "")) gets the new string after chopping the first character off (define (string-rest str) (if (> (string-length str) 0) (substring str 1 (string-length str)) "")) (define (render e) (overlay/xy (render-text e) 0 0 BACK)) editor KeyEvent - > editor " \b " deletes the last character of the editor - pre (define (edit edi ke) (cond [(key=? ke "\b") (make-editor (string-last-remove (editor-pre edi)) (editor-post edi))] [(key=? ke "left") (make-editor (string-last-remove (editor-pre edi)) (string-append (string-last (editor-pre edi)) (editor-post edi)))] [(key=? ke "right") (make-editor (string-append (editor-pre edi) (string-first (editor-post edi))) (string-rest (editor-post edi)))] [(and (= 1 (string-length ke)) (not (key=? ke "\t")) (not (key=? ke "\r")) (> 33 (+ (string-length (editor-pre edi)) (string-length (editor-post edi))))) (make-editor (string-append (editor-pre edi) ke) (editor-post edi))] [else edi])) (define (run str) (big-bang (make-editor str "") [on-key edit] [to-draw render]))
0fca3155bd12607f0c15b99d6d8c790e56b8ed83ca875df9ba8c4d39db9e7820
dom96/SimpleIRC
CoreSpec.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - missing - signatures # module CoreSpec (main, spec) where import Control.Concurrent import Test.HUnit import Test.Hspec.Monadic import Test.Hspec.HUnit() import qualified Data.Knob as K import qualified Data.Map as Map import System.IO import qualified Data.ByteString.Char8 as B import Data.Unique import Data.Time.Clock import Network.SimpleIRC.Core appendMVar mList x = do modifyMVar_ mList (\l -> return (x:l)) mockMirc = do k <- K.newKnob "" h <- K.newFileHandle k "test connection" ReadWriteMode u1 <- newUnique u2 <- newUnique u3 <- newUnique resultList <- newMVar [] now <- getCurrentTime mIrc <- newMVar $ IrcServer { sAddr = B.pack "" , sPort = 0 , sNickname = B.pack "" , sPassword = Nothing , sUsername = B.pack "" , sRealname = B.pack "" , sChannels = [] , sEvents = Map.fromList [ (u1, Disconnect $ \_ -> appendMVar resultList True) , (u2, Privmsg $ \_ _ -> appendMVar resultList False) , (u3, Disconnect $ \_ -> appendMVar resultList True) ] , sSock = Just h , sListenThread = Nothing , sCmdThread = Nothing , sCmdChan = undefined , sDebug = False -- Other info , sCTCPVersion = "" , sCTCPTime = return "" , sPingTimeoutInterval = 10 , sFloodControlTimestamp = now } return (resultList, mIrc) executes a list of IO actions and returns the number of seconds -- it took to do so measureM :: [IO ()] -> IO Rational measureM actions = do start <- getCurrentTime sequence_ actions end <- getCurrentTime return $ toRational $ diffUTCTime end start main = hspecX spec spec :: Specs spec = do describe "listenLoop" $ do it "calls the function of all disconnect events on disconnect" $ do (mResultList, mIrc) <- mockMirc listenLoop mIrc resultList <- takeMVar mResultList assertEqual "exactly both disconnect events have added their value to the result list" [True, True] resultList describe "sendMsg flood control" $ do it "takes less than one second to send five messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 5 $ sendMsg mIrc "a" "a" assertBool "it took less than one second to send 5 messages" $ duration < 1 it "takes 4 seconds to send 7 messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 7 $ sendMsg mIrc "a" "a" assertBool "it took roughly 4 seconds to send 7 messages" $ abs (4 - duration) < 0.5 it "takes 30 seconds to send 20 messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 20 $ sendMsg mIrc "a" "a" assertBool "it took roughly 30 seconds to send 20 messages" $ abs (30 - duration) < 0.5
null
https://raw.githubusercontent.com/dom96/SimpleIRC/ee5ab54fcff9ae974458a9394a2484709724e9dc/tests/CoreSpec.hs
haskell
# LANGUAGE OverloadedStrings # Other info it took to do so
# OPTIONS_GHC -fno - warn - missing - signatures # module CoreSpec (main, spec) where import Control.Concurrent import Test.HUnit import Test.Hspec.Monadic import Test.Hspec.HUnit() import qualified Data.Knob as K import qualified Data.Map as Map import System.IO import qualified Data.ByteString.Char8 as B import Data.Unique import Data.Time.Clock import Network.SimpleIRC.Core appendMVar mList x = do modifyMVar_ mList (\l -> return (x:l)) mockMirc = do k <- K.newKnob "" h <- K.newFileHandle k "test connection" ReadWriteMode u1 <- newUnique u2 <- newUnique u3 <- newUnique resultList <- newMVar [] now <- getCurrentTime mIrc <- newMVar $ IrcServer { sAddr = B.pack "" , sPort = 0 , sNickname = B.pack "" , sPassword = Nothing , sUsername = B.pack "" , sRealname = B.pack "" , sChannels = [] , sEvents = Map.fromList [ (u1, Disconnect $ \_ -> appendMVar resultList True) , (u2, Privmsg $ \_ _ -> appendMVar resultList False) , (u3, Disconnect $ \_ -> appendMVar resultList True) ] , sSock = Just h , sListenThread = Nothing , sCmdThread = Nothing , sCmdChan = undefined , sDebug = False , sCTCPVersion = "" , sCTCPTime = return "" , sPingTimeoutInterval = 10 , sFloodControlTimestamp = now } return (resultList, mIrc) executes a list of IO actions and returns the number of seconds measureM :: [IO ()] -> IO Rational measureM actions = do start <- getCurrentTime sequence_ actions end <- getCurrentTime return $ toRational $ diffUTCTime end start main = hspecX spec spec :: Specs spec = do describe "listenLoop" $ do it "calls the function of all disconnect events on disconnect" $ do (mResultList, mIrc) <- mockMirc listenLoop mIrc resultList <- takeMVar mResultList assertEqual "exactly both disconnect events have added their value to the result list" [True, True] resultList describe "sendMsg flood control" $ do it "takes less than one second to send five messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 5 $ sendMsg mIrc "a" "a" assertBool "it took less than one second to send 5 messages" $ duration < 1 it "takes 4 seconds to send 7 messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 7 $ sendMsg mIrc "a" "a" assertBool "it took roughly 4 seconds to send 7 messages" $ abs (4 - duration) < 0.5 it "takes 30 seconds to send 20 messages" $ do (_, mIrc) <- mockMirc duration <- measureM $ replicate 20 $ sendMsg mIrc "a" "a" assertBool "it took roughly 30 seconds to send 20 messages" $ abs (30 - duration) < 0.5
bf4038f147df7b5f4bed88408c33f844aee85e2022704397d0cce3a2a3c7403c
juspay/atlas
Handler.hs
| Copyright 2022 Juspay Technologies Pvt Ltd 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 . Module : API.Parking . Quotes . Handler Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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. Module : API.Parking.Quotes.Handler Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module API.Parking.Quotes.Handler where import API.Parking.Quotes.QuoteId.Handler as QuoteId import API.Parking.Quotes.Types import App.Types handler :: FlowServer API handler = QuoteId.handler
null
https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/parking-bap/src/API/Parking/Quotes/Handler.hs
haskell
| Copyright 2022 Juspay Technologies Pvt Ltd 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 . Module : API.Parking . Quotes . Handler Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022 License : Apache 2.0 ( see the file LICENSE ) Maintainer : Stability : experimental Portability : non - portable Copyright 2022 Juspay Technologies Pvt Ltd 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. Module : API.Parking.Quotes.Handler Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022 License : Apache 2.0 (see the file LICENSE) Maintainer : Stability : experimental Portability : non-portable -} module API.Parking.Quotes.Handler where import API.Parking.Quotes.QuoteId.Handler as QuoteId import API.Parking.Quotes.Types import App.Types handler :: FlowServer API handler = QuoteId.handler
88d1cb5eb70d1167bb7261f6b70ab72aa47e4f6490c0d19d2a70e2e939b154f1
xvw/preface
bind.mli
* A [ Bind ] allow to sequences operations that are dependent from one to another , in contrast to { ! module : Applicative } , which executes a series of independent actions . It is a Monad without [ return ] operation . another, in contrast to {!module:Applicative}, which executes a series of independent actions. It is a Monad without [return] operation. *) * { 2 Laws } To have a predictable behaviour , the instance of [ Bind ] must obey some laws . + [ ( m > > = f ) > > = g = m > > = ( fun x + > f x > > = g ) ] + [ join % join = join % ( map join ) ] + [ map i d = i d ] + [ map ( g % f ) = map g % map f ] + [ map f % join = join % map ( map f ) ] + [ map f % pure = pure % f ] + [ ( f > = > g ) > = > h = f > = > ( g > = > h ) ] To have a predictable behaviour, the instance of [Bind] must obey some laws. + [(m >>= f) >>= g = m >>= (fun x +> f x >>= g)] + [join % join = join % (map join)] + [map id = id] + [map (g % f) = map g % map f] + [map f % join = join % map (map f)] + [map f % pure = pure % f] + [(f >=> g) >=> h = f >=> (g >=> h)] *) * { 1 Minimal definition } (** Minimal definition using [bind]. *) module type WITH_BIND = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.WITH_BIND with type ('a, _) t := 'a t * @inline end (** Minimal definition using [map] and [join]. *) module type WITH_MAP_AND_JOIN = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.WITH_MAP_AND_JOIN with type ('a, _) t := 'a t * @inline end (** Minimal definition using [compose_left_to_right]. *) module type WITH_KLEISLI_COMPOSITION = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.WITH_KLEISLI_COMPOSITION with type ('a, _) t := 'a t * @inline end (** Minimal definition using [map] and [bind]. *) module type WITH_MAP_AND_BIND = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.WITH_MAP_AND_BIND with type ('a, _) t := 'a t * @inline end (** Minimal definition using [map] and [compose_left_to_right]. *) module type WITH_MAP_AND_KLEISLI_COMPOSITION = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.WITH_MAP_AND_KLEISLI_COMPOSITION with type ('a, _) t := 'a t * @inline end (** {1 Structure anatomy} *) (** Basis operations. *) module type CORE = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.CORE with type ('a, _) t := 'a t * @inline end (** Additional operations. *) module type OPERATION = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.OPERATION with type ('a, _) t := 'a t * @inline end (** Syntax extensions. *) module type SYNTAX = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.SYNTAX with type ('a, _) t := 'a t * @inline end (** Infix operators. *) module type INFIX = sig type 'a t (** The type held by the [Bind]. *) include Indexed_bind.INFIX with type ('a, _) t := 'a t * @inline end (** {1 Complete API} *) (** The complete interface of a [Bind]. *) module type API = sig * { 1 Type } type 'a t (** The type held by the [Bind]. *) include Indexed_bind.API with type ('a, _) t := 'a t * @inline end * { 1 Additional references } - { { : -5.3.6/docs/Data-Functor-Bind.html } 's documentation of Bind } - {{:-5.3.6/docs/Data-Functor-Bind.html} Haskell's documentation of Bind} *)
null
https://raw.githubusercontent.com/xvw/preface/51892a7ce2ddfef69de963265da3617968cdb7ad/lib/preface_specs/bind.mli
ocaml
* Minimal definition using [bind]. * The type held by the [Bind]. * Minimal definition using [map] and [join]. * The type held by the [Bind]. * Minimal definition using [compose_left_to_right]. * The type held by the [Bind]. * Minimal definition using [map] and [bind]. * The type held by the [Bind]. * Minimal definition using [map] and [compose_left_to_right]. * The type held by the [Bind]. * {1 Structure anatomy} * Basis operations. * The type held by the [Bind]. * Additional operations. * The type held by the [Bind]. * Syntax extensions. * The type held by the [Bind]. * Infix operators. * The type held by the [Bind]. * {1 Complete API} * The complete interface of a [Bind]. * The type held by the [Bind].
* A [ Bind ] allow to sequences operations that are dependent from one to another , in contrast to { ! module : Applicative } , which executes a series of independent actions . It is a Monad without [ return ] operation . another, in contrast to {!module:Applicative}, which executes a series of independent actions. It is a Monad without [return] operation. *) * { 2 Laws } To have a predictable behaviour , the instance of [ Bind ] must obey some laws . + [ ( m > > = f ) > > = g = m > > = ( fun x + > f x > > = g ) ] + [ join % join = join % ( map join ) ] + [ map i d = i d ] + [ map ( g % f ) = map g % map f ] + [ map f % join = join % map ( map f ) ] + [ map f % pure = pure % f ] + [ ( f > = > g ) > = > h = f > = > ( g > = > h ) ] To have a predictable behaviour, the instance of [Bind] must obey some laws. + [(m >>= f) >>= g = m >>= (fun x +> f x >>= g)] + [join % join = join % (map join)] + [map id = id] + [map (g % f) = map g % map f] + [map f % join = join % map (map f)] + [map f % pure = pure % f] + [(f >=> g) >=> h = f >=> (g >=> h)] *) * { 1 Minimal definition } module type WITH_BIND = sig type 'a t include Indexed_bind.WITH_BIND with type ('a, _) t := 'a t * @inline end module type WITH_MAP_AND_JOIN = sig type 'a t include Indexed_bind.WITH_MAP_AND_JOIN with type ('a, _) t := 'a t * @inline end module type WITH_KLEISLI_COMPOSITION = sig type 'a t include Indexed_bind.WITH_KLEISLI_COMPOSITION with type ('a, _) t := 'a t * @inline end module type WITH_MAP_AND_BIND = sig type 'a t include Indexed_bind.WITH_MAP_AND_BIND with type ('a, _) t := 'a t * @inline end module type WITH_MAP_AND_KLEISLI_COMPOSITION = sig type 'a t include Indexed_bind.WITH_MAP_AND_KLEISLI_COMPOSITION with type ('a, _) t := 'a t * @inline end module type CORE = sig type 'a t include Indexed_bind.CORE with type ('a, _) t := 'a t * @inline end module type OPERATION = sig type 'a t include Indexed_bind.OPERATION with type ('a, _) t := 'a t * @inline end module type SYNTAX = sig type 'a t include Indexed_bind.SYNTAX with type ('a, _) t := 'a t * @inline end module type INFIX = sig type 'a t include Indexed_bind.INFIX with type ('a, _) t := 'a t * @inline end module type API = sig * { 1 Type } type 'a t include Indexed_bind.API with type ('a, _) t := 'a t * @inline end * { 1 Additional references } - { { : -5.3.6/docs/Data-Functor-Bind.html } 's documentation of Bind } - {{:-5.3.6/docs/Data-Functor-Bind.html} Haskell's documentation of Bind} *)
cf1adebb5abba8695742caa84dbcc8ff66256647b5ed14c0021bc5b08e05e033
kind2-mc/kind2
fileId.ml
This file is part of the Kind 2 model checker . Copyright ( c ) 2018 by the Board of Trustees of the University of Iowa 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 . Copyright (c) 2018 by the Board of Trustees of the University of Iowa 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. *) module FileId = struct type t = int * int (* Total order on identifiers *) let compare (ino1, dev1) (ino2, dev2) = match compare ino1 ino2 with | 0 -> compare dev1 dev2 | c -> c let equal id1 id2 = compare id1 id2 = 0 end include FileId let get_id filename = let { Unix.st_dev; Unix.st_ino } = Unix.stat filename in (st_ino, st_dev) module FileIdSet = Set.Make (FileId)
null
https://raw.githubusercontent.com/kind2-mc/kind2/c601470eb68af9bd3b88828b04dbcdbd6bd6bbf5/src/utils/fileId.ml
ocaml
Total order on identifiers
This file is part of the Kind 2 model checker . Copyright ( c ) 2018 by the Board of Trustees of the University of Iowa 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 . Copyright (c) 2018 by the Board of Trustees of the University of Iowa 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. *) module FileId = struct type t = int * int let compare (ino1, dev1) (ino2, dev2) = match compare ino1 ino2 with | 0 -> compare dev1 dev2 | c -> c let equal id1 id2 = compare id1 id2 = 0 end include FileId let get_id filename = let { Unix.st_dev; Unix.st_ino } = Unix.stat filename in (st_ino, st_dev) module FileIdSet = Set.Make (FileId)
9eda9a38003f4f17591ecec3fc46986211a4b6f2b9a68007430cef5a4f869b20
zotonic/zotonic
controller_admin_mailing_status.erl
@author < > 2011 %% @doc Mailing status/control page Copyright 2011 %% 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. -module(controller_admin_mailing_status). -author("Arjan Scherpenisse <>"). -export([ service_available/1, resource_exists/1, is_authorized/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). service_available(Context) -> Context1 = z_context:set_noindex_header(Context), Context2 = z_context:set_nocache_headers(Context1), {true, Context2}. is_authorized(Context) -> {Context2, Id} = controller_admin_edit:ensure_id(Context), z_controller_helper:is_authorized([ {use, mod_mailinglist}, {view, Id} ], Context2). resource_exists(Context) -> {Context2, Id} = controller_admin_edit:ensure_id(Context), case Id of undefined -> {false, Context2}; _N -> {m_rsc:exists(Id, Context2), Context2} end. process(_Method, _AcceptedCT, _ProvidedCT, Context) -> Vars = [ {id, z_context:get(id, Context)} ], Html = z_template:render({cat, <<"admin_mailing_status.tpl">>}, Vars, Context), z_context:output(Html, Context).
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_mailinglist/src/controllers/controller_admin_mailing_status.erl
erlang
@doc Mailing status/control page 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.
@author < > 2011 Copyright 2011 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(controller_admin_mailing_status). -author("Arjan Scherpenisse <>"). -export([ service_available/1, resource_exists/1, is_authorized/1, process/4 ]). -include_lib("zotonic_core/include/zotonic.hrl"). service_available(Context) -> Context1 = z_context:set_noindex_header(Context), Context2 = z_context:set_nocache_headers(Context1), {true, Context2}. is_authorized(Context) -> {Context2, Id} = controller_admin_edit:ensure_id(Context), z_controller_helper:is_authorized([ {use, mod_mailinglist}, {view, Id} ], Context2). resource_exists(Context) -> {Context2, Id} = controller_admin_edit:ensure_id(Context), case Id of undefined -> {false, Context2}; _N -> {m_rsc:exists(Id, Context2), Context2} end. process(_Method, _AcceptedCT, _ProvidedCT, Context) -> Vars = [ {id, z_context:get(id, Context)} ], Html = z_template:render({cat, <<"admin_mailing_status.tpl">>}, Vars, Context), z_context:output(Html, Context).
6ab5b7f07a806e3a242d7b842aaec8219166adde76c705c1f43e59450914a3bb
logicmoo/wam_common_lisp
cpl.lisp
-*-Mode : LISP ; Package : PCL ; ; Syntax : Common - lisp -*- ;;; ;;; ************************************************************************* Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . ;;; All rights reserved. ;;; ;;; Use and copying of this software and preparation of derivative works ;;; based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United ;;; States export control laws. ;;; This software is made available AS IS , and Xerox Corporation makes no ;;; warranty about the software, its performance or its conformity to any ;;; specification. ;;; ;;; Any person obtaining a copy of this software is requested to send their ;;; name and post office or electronic mail address to: CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) ;;; ;;; Suggestions, comments and requests for improvements are also welcome. ;;; ************************************************************************* ;;; (in-package 'pcl) ;;; ;;; compute-class-precedence-list ;;; ;;; Knuth section 2.2.3 has some interesting notes on this. ;;; ;;; What appears here is basically the algorithm presented there. ;;; The key idea is that we use class - precedence - description ( CPD ) structures to store the precedence information as we proceed . The CPD structure for a class stores two critical pieces of information : ;;; ;;; - a count of the number of "reasons" why the class can't go ;;; into the class precedence list yet. ;;; ;;; - a list of the "reasons" this class prevents others from ;;; going in until after it ;; ;;; A "reason" is essentially a single local precedence constraint. If a constraint between two classes arises more than once it generates more than one reason . This makes things simpler , linear , and is n't a problem ;;; as long as we make sure to keep track of each instance of a "reason". ;;; This code is divided into three phases . ;;; - the first phase simply generates the CPD 's for each of the class and its superclasses . The remainder of the code will manipulate ;;; these CPDs rather than the class objects themselves. At the end of this pass , the CPD - SUPERS field of a CPD is a list of the CPDs of the direct superclasses of the class . ;;; - the second phase folds all the local constraints into the CPD structure . The CPD - COUNT of each CPD is built up , and the CPD - AFTER fields are augmented to include precedence constraints from the CPD - SUPERS field and from the order of classes in other ;;; CPD-SUPERS fields. ;;; After this phase , the CPD - AFTER field of a class includes all the direct superclasses of the class plus any class that immediately follows the class in the direct superclasses of another . There can be duplicates in this list . The CPD - COUNT field is equal to the number of times this class appears in the CPD - AFTER field of ;;; all the other CPDs. ;;; - In the third phase , classes are put into the precedence list one at a time , with only those classes with a CPD - COUNT of 0 being candidates for insertion . When a class is inserted , every CPD in its CPD - AFTER field has its count decremented . ;;; In the usual case , there is only one candidate for insertion at any point . If there is more than one , the specified tiebreaker ;;; rule is used to choose among them. ;;; (defmethod compute-class-precedence-list ((root slot-class)) (compute-std-cpl root (class-direct-superclasses root))) (defstruct (class-precedence-description (:conc-name nil) (:print-function (lambda (obj str depth) (declare (ignore depth)) (format str "#<CPD ~S ~D>" (class-name (cpd-class obj)) (cpd-count obj)))) (:constructor make-cpd ())) (cpd-class nil) (cpd-supers ()) (cpd-after ()) (cpd-count 0 :type fixnum)) (defun compute-std-cpl (class supers) First two branches of COND (list class)) ;are implementing the single ((null (cdr supers)) ;inheritance optimization. (cons class (compute-std-cpl (car supers) (class-direct-superclasses (car supers))))) (t (multiple-value-bind (all-cpds nclasses) (compute-std-cpl-phase-1 class supers) (compute-std-cpl-phase-2 all-cpds) (compute-std-cpl-phase-3 class all-cpds nclasses))))) (defvar *compute-std-cpl-class->entry-table-size* 60) (declaim (ftype (function (T T) (values list index)) compute-std-cpl-phase-1)) (defun compute-std-cpl-phase-1 (class supers) (let ((nclasses 0) (all-cpds ()) (table (make-hash-table :size *compute-std-cpl-class->entry-table-size* :test #'eq))) (declare (type index nclasses)) (labels ((get-cpd (c) (or (gethash c table) (setf (gethash c table) (make-cpd)))) (walk (c supers) (if (forward-referenced-class-p c) (cpl-forward-referenced-class-error class c) (let ((cpd (get-cpd c))) (unless (cpd-class cpd) ;If we have already done this ;class before, we can quit. (setf (cpd-class cpd) c) (incf nclasses) (push cpd all-cpds) (setf (cpd-supers cpd) (mapcar #'get-cpd supers)) (dolist (super supers) (walk super (class-direct-superclasses super)))))))) (walk class supers) (values all-cpds nclasses)))) (defun compute-std-cpl-phase-2 (all-cpds) (dolist (cpd all-cpds) (let ((supers (cpd-supers cpd))) (when supers (setf (cpd-after cpd) (nconc (cpd-after cpd) supers)) (incf (cpd-count (car supers)) 1) (do* ((t1 supers t2) (t2 (cdr t1) (cdr t1))) ((null t2)) (incf (cpd-count (car t2)) 2) (push (car t2) (cpd-after (car t1)))))))) (defun compute-std-cpl-phase-3 (class all-cpds nclasses) (declare (type index nclasses)) (let ((candidates ()) (next-cpd nil) (rcpl ())) ;; We have to bootstrap the collection of those CPD 's that have a zero count . Once we get going , we will maintain ;; this list incrementally. ;; (dolist (cpd all-cpds) (when (zerop (cpd-count cpd)) (push cpd candidates))) (loop (when (null candidates) ;; ;; If there are no candidates, and enough classes have been put ;; into the precedence list, then we are all done. Otherwise ;; it means there is a consistency problem. (if (zerop nclasses) (return (reverse rcpl)) (cpl-inconsistent-error class all-cpds))) ;; ;; Try to find the next class to put in from among the candidates. If there is only one , its easy , otherwise we have to use the ;; famous RPG tiebreaker rule. There is some hair here to avoid ;; having to call DELETE on the list of candidates. I dunno if ;; its worth it but what the hell. ;; (setq next-cpd (if (null (cdr candidates)) (prog1 (car candidates) (setq candidates ())) (block tie-breaker (dolist (c rcpl) (let ((supers (class-direct-superclasses c))) (if (memq (cpd-class (car candidates)) supers) (return-from tie-breaker (pop candidates)) (do ((loc candidates (cdr loc))) ((null (cdr loc))) (let ((cpd (cadr loc))) (when (memq (cpd-class cpd) supers) (setf (cdr loc) (cddr loc)) (return-from tie-breaker cpd)))))))))) (decf nclasses) (push (cpd-class next-cpd) rcpl) (dolist (after (cpd-after next-cpd)) (when (zerop (the fixnum (decf (cpd-count after)))) (push after candidates)))))) ;;; ;;; Support code for signalling nice error messages. ;;; (defun cpl-error (class format-string &rest format-args) (error "While computing the class precedence list of the class ~A.~%~A" (if (class-name class) (format nil "named ~S" (class-name class)) class) (apply #'format nil format-string format-args))) (defun cpl-forward-referenced-class-error (class forward-class) (flet ((class-or-name (class) (if (class-name class) (format nil "named ~S" (class-name class)) class))) (let ((names (mapcar #'class-or-name (cdr (find-superclass-chain class forward-class))))) (cpl-error class "The class ~A is a forward referenced class.~@ The class ~A is ~A." (class-or-name forward-class) (class-or-name forward-class) (if (null (cdr names)) (format nil "a direct superclass of the class ~A" (class-or-name class)) (format nil "reached from the class ~A by following~@ the direct superclass chain through: ~A~ ~% ending at the class ~A" (class-or-name class) (format nil "~{~% the class ~A,~}" (butlast names)) (car (last names)))))))) (defun find-superclass-chain (bottom top) (labels ((walk (c chain) (if (eq c top) (return-from find-superclass-chain (nreverse chain)) (dolist (super (class-direct-superclasses c)) (walk super (cons super chain)))))) (walk bottom (list bottom)))) (defun cpl-inconsistent-error (class all-cpds) (let ((reasons (find-cycle-reasons all-cpds))) (cpl-error class "It is not possible to compute the class precedence list because~@ there ~A in the local precedence relations.~@ ~A because:~{~% ~A~}." (if (cdr reasons) "are circularities" "is a circularity") (if (cdr reasons) "These arise" "This arises") (format-cycle-reasons (apply #'append reasons))))) (defun format-cycle-reasons (reasons) (flet ((class-or-name (cpd) (let ((class (cpd-class cpd))) (if (class-name class) (format nil "named ~S" (class-name class)) class)))) (mapcar #'(lambda (reason) (ecase (caddr reason) (:super (format nil "the class ~A appears in the supers of the class ~A" (class-or-name (cadr reason)) (class-or-name (car reason)))) (:in-supers (format nil "the class ~A follows the class ~A in the supers of the class ~A" (class-or-name (cadr reason)) (class-or-name (car reason)) (class-or-name (cadddr reason)))))) reasons))) (defun find-cycle-reasons (all-cpds) (let ((been-here ()) ;List of classes we have visited. (cycle-reasons ())) (labels ((chase (path) (if (memq (car path) (cdr path)) (record-cycle (memq (car path) (nreverse path))) (unless (memq (car path) been-here) (push (car path) been-here) (dolist (after (cpd-after (car path))) (chase (cons after path)))))) (record-cycle (cycle) (let ((reasons ())) (do* ((t1 cycle t2) (t2 (cdr t1) (cdr t1))) ((null t2)) (let ((c1 (car t1)) (c2 (car t2))) (if (memq c2 (cpd-supers c1)) (push (list c1 c2 :super) reasons) (dolist (cpd all-cpds) (when (memq c2 (memq c1 (cpd-supers cpd))) (return (push (list c1 c2 :in-supers cpd) reasons))))))) (push (nreverse reasons) cycle-reasons)))) (dolist (cpd all-cpds) (unless (zerop (cpd-count cpd)) (chase (list cpd)))) cycle-reasons)))
null
https://raw.githubusercontent.com/logicmoo/wam_common_lisp/4396d9e26b050f68182d65c9a2d5a939557616dd/prolog/wam_cl/src/pcl/cpl.lisp
lisp
Package : PCL ; ; Syntax : Common - lisp -*- ************************************************************************* All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this States export control laws. warranty about the software, its performance or its conformity to any specification. Any person obtaining a copy of this software is requested to send their name and post office or electronic mail address to: Suggestions, comments and requests for improvements are also welcome. ************************************************************************* compute-class-precedence-list Knuth section 2.2.3 has some interesting notes on this. What appears here is basically the algorithm presented there. - a count of the number of "reasons" why the class can't go into the class precedence list yet. - a list of the "reasons" this class prevents others from going in until after it A "reason" is essentially a single local precedence constraint. If a as long as we make sure to keep track of each instance of a "reason". these CPDs rather than the class objects themselves. At the end CPD-SUPERS fields. all the other CPDs. rule is used to choose among them. are implementing the single inheritance optimization. If we have already done this class before, we can quit. this list incrementally. If there are no candidates, and enough classes have been put into the precedence list, then we are all done. Otherwise it means there is a consistency problem. Try to find the next class to put in from among the candidates. famous RPG tiebreaker rule. There is some hair here to avoid having to call DELETE on the list of candidates. I dunno if its worth it but what the hell. Support code for signalling nice error messages. List of classes we have visited.
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . software or derivative works must comply with all applicable United This software is made available AS IS , and Xerox Corporation makes no CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) (in-package 'pcl) The key idea is that we use class - precedence - description ( CPD ) structures to store the precedence information as we proceed . The CPD structure for a class stores two critical pieces of information : constraint between two classes arises more than once it generates more than one reason . This makes things simpler , linear , and is n't a problem This code is divided into three phases . - the first phase simply generates the CPD 's for each of the class and its superclasses . The remainder of the code will manipulate of this pass , the CPD - SUPERS field of a CPD is a list of the CPDs of the direct superclasses of the class . - the second phase folds all the local constraints into the CPD structure . The CPD - COUNT of each CPD is built up , and the CPD - AFTER fields are augmented to include precedence constraints from the CPD - SUPERS field and from the order of classes in other After this phase , the CPD - AFTER field of a class includes all the direct superclasses of the class plus any class that immediately follows the class in the direct superclasses of another . There can be duplicates in this list . The CPD - COUNT field is equal to the number of times this class appears in the CPD - AFTER field of - In the third phase , classes are put into the precedence list one at a time , with only those classes with a CPD - COUNT of 0 being candidates for insertion . When a class is inserted , every CPD in its CPD - AFTER field has its count decremented . In the usual case , there is only one candidate for insertion at any point . If there is more than one , the specified tiebreaker (defmethod compute-class-precedence-list ((root slot-class)) (compute-std-cpl root (class-direct-superclasses root))) (defstruct (class-precedence-description (:conc-name nil) (:print-function (lambda (obj str depth) (declare (ignore depth)) (format str "#<CPD ~S ~D>" (class-name (cpd-class obj)) (cpd-count obj)))) (:constructor make-cpd ())) (cpd-class nil) (cpd-supers ()) (cpd-after ()) (cpd-count 0 :type fixnum)) (defun compute-std-cpl (class supers) First two branches of COND (cons class (compute-std-cpl (car supers) (class-direct-superclasses (car supers))))) (t (multiple-value-bind (all-cpds nclasses) (compute-std-cpl-phase-1 class supers) (compute-std-cpl-phase-2 all-cpds) (compute-std-cpl-phase-3 class all-cpds nclasses))))) (defvar *compute-std-cpl-class->entry-table-size* 60) (declaim (ftype (function (T T) (values list index)) compute-std-cpl-phase-1)) (defun compute-std-cpl-phase-1 (class supers) (let ((nclasses 0) (all-cpds ()) (table (make-hash-table :size *compute-std-cpl-class->entry-table-size* :test #'eq))) (declare (type index nclasses)) (labels ((get-cpd (c) (or (gethash c table) (setf (gethash c table) (make-cpd)))) (walk (c supers) (if (forward-referenced-class-p c) (cpl-forward-referenced-class-error class c) (let ((cpd (get-cpd c))) (setf (cpd-class cpd) c) (incf nclasses) (push cpd all-cpds) (setf (cpd-supers cpd) (mapcar #'get-cpd supers)) (dolist (super supers) (walk super (class-direct-superclasses super)))))))) (walk class supers) (values all-cpds nclasses)))) (defun compute-std-cpl-phase-2 (all-cpds) (dolist (cpd all-cpds) (let ((supers (cpd-supers cpd))) (when supers (setf (cpd-after cpd) (nconc (cpd-after cpd) supers)) (incf (cpd-count (car supers)) 1) (do* ((t1 supers t2) (t2 (cdr t1) (cdr t1))) ((null t2)) (incf (cpd-count (car t2)) 2) (push (car t2) (cpd-after (car t1)))))))) (defun compute-std-cpl-phase-3 (class all-cpds nclasses) (declare (type index nclasses)) (let ((candidates ()) (next-cpd nil) (rcpl ())) We have to bootstrap the collection of those CPD 's that have a zero count . Once we get going , we will maintain (dolist (cpd all-cpds) (when (zerop (cpd-count cpd)) (push cpd candidates))) (loop (when (null candidates) (if (zerop nclasses) (return (reverse rcpl)) (cpl-inconsistent-error class all-cpds))) If there is only one , its easy , otherwise we have to use the (setq next-cpd (if (null (cdr candidates)) (prog1 (car candidates) (setq candidates ())) (block tie-breaker (dolist (c rcpl) (let ((supers (class-direct-superclasses c))) (if (memq (cpd-class (car candidates)) supers) (return-from tie-breaker (pop candidates)) (do ((loc candidates (cdr loc))) ((null (cdr loc))) (let ((cpd (cadr loc))) (when (memq (cpd-class cpd) supers) (setf (cdr loc) (cddr loc)) (return-from tie-breaker cpd)))))))))) (decf nclasses) (push (cpd-class next-cpd) rcpl) (dolist (after (cpd-after next-cpd)) (when (zerop (the fixnum (decf (cpd-count after)))) (push after candidates)))))) (defun cpl-error (class format-string &rest format-args) (error "While computing the class precedence list of the class ~A.~%~A" (if (class-name class) (format nil "named ~S" (class-name class)) class) (apply #'format nil format-string format-args))) (defun cpl-forward-referenced-class-error (class forward-class) (flet ((class-or-name (class) (if (class-name class) (format nil "named ~S" (class-name class)) class))) (let ((names (mapcar #'class-or-name (cdr (find-superclass-chain class forward-class))))) (cpl-error class "The class ~A is a forward referenced class.~@ The class ~A is ~A." (class-or-name forward-class) (class-or-name forward-class) (if (null (cdr names)) (format nil "a direct superclass of the class ~A" (class-or-name class)) (format nil "reached from the class ~A by following~@ the direct superclass chain through: ~A~ ~% ending at the class ~A" (class-or-name class) (format nil "~{~% the class ~A,~}" (butlast names)) (car (last names)))))))) (defun find-superclass-chain (bottom top) (labels ((walk (c chain) (if (eq c top) (return-from find-superclass-chain (nreverse chain)) (dolist (super (class-direct-superclasses c)) (walk super (cons super chain)))))) (walk bottom (list bottom)))) (defun cpl-inconsistent-error (class all-cpds) (let ((reasons (find-cycle-reasons all-cpds))) (cpl-error class "It is not possible to compute the class precedence list because~@ there ~A in the local precedence relations.~@ ~A because:~{~% ~A~}." (if (cdr reasons) "are circularities" "is a circularity") (if (cdr reasons) "These arise" "This arises") (format-cycle-reasons (apply #'append reasons))))) (defun format-cycle-reasons (reasons) (flet ((class-or-name (cpd) (let ((class (cpd-class cpd))) (if (class-name class) (format nil "named ~S" (class-name class)) class)))) (mapcar #'(lambda (reason) (ecase (caddr reason) (:super (format nil "the class ~A appears in the supers of the class ~A" (class-or-name (cadr reason)) (class-or-name (car reason)))) (:in-supers (format nil "the class ~A follows the class ~A in the supers of the class ~A" (class-or-name (cadr reason)) (class-or-name (car reason)) (class-or-name (cadddr reason)))))) reasons))) (defun find-cycle-reasons (all-cpds) (cycle-reasons ())) (labels ((chase (path) (if (memq (car path) (cdr path)) (record-cycle (memq (car path) (nreverse path))) (unless (memq (car path) been-here) (push (car path) been-here) (dolist (after (cpd-after (car path))) (chase (cons after path)))))) (record-cycle (cycle) (let ((reasons ())) (do* ((t1 cycle t2) (t2 (cdr t1) (cdr t1))) ((null t2)) (let ((c1 (car t1)) (c2 (car t2))) (if (memq c2 (cpd-supers c1)) (push (list c1 c2 :super) reasons) (dolist (cpd all-cpds) (when (memq c2 (memq c1 (cpd-supers cpd))) (return (push (list c1 c2 :in-supers cpd) reasons))))))) (push (nreverse reasons) cycle-reasons)))) (dolist (cpd all-cpds) (unless (zerop (cpd-count cpd)) (chase (list cpd)))) cycle-reasons)))
5e8fa408e474f28105a64c4fbed40c405b987f3a2a8ca8db85c116fc64e473e1
dgiot/dgiot
modbus_tcp.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2021 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. %%-------------------------------------------------------------------- -module(modbus_tcp). -author("jonhl"). -define(consumer(ChannelId), <<"modbus_consumer_", ChannelId/binary>>). -include("dgiot_modbus.hrl"). -include_lib("dgiot/include/logger.hrl"). -export([ init/1, parse_frame/1, parse_frame/2, parse_frame/3, to_frame/1, build_req_message/1, get_addr/4, set_addr/3] ). -export([is16/1, set_params/3, decode_data/4]). -define(TYPE, ?MODBUS_TCP). %% 注册协议参数 -params(#{ <<"originaltype">> => #{ order => 1, type => string, required => true, default => #{<<"value">> => <<"bit">>, <<"label">> => <<"位"/utf8>>}, enum => [ #{<<"value">> => <<"bit">>, <<"label">> => <<"位"/utf8>>}, #{<<"value">> => <<"short16_AB">>, <<"label">> => <<"16位 有符号(AB)"/utf8>>}, #{<<"value">> => <<"short16_BA">>, <<"label">> => <<"16位 有符号(BA)"/utf8>>}, #{<<"value">> => <<"ushort16_AB">>, <<"label">> => <<"16位 无符号(AB)"/utf8>>}, #{<<"value">> => <<"ushort16_BA">>, <<"label">> => <<"16位 无符号(BA)"/utf8>>}, #{<<"value">> => <<"long32_ABCD">>, <<"label">> => <<"32位 有符号(ABCD)"/utf8>>}, #{<<"value">> => <<"long32_CDAB">>, <<"label">> => <<"32位 有符号(CDAB)"/utf8>>}, #{<<"value">> => <<"ulong32_ABCD">>, <<"label">> => <<"32位 无符号(ABCD)"/utf8>>}, #{<<"value">> => <<"ulong32_CDAB">>, <<"label">> => <<"32位 无符号(CDAB)"/utf8>>}, #{<<"value">> => <<"float32_ABCD">>, <<"label">> => <<"32位 浮点数(ABCD)"/utf8>>}, #{<<"value">> => <<"float32_CDAB">>, <<"label">> => <<"32位 浮点数(CDAB)"/utf8>>} ], title => #{ zh => <<"数据格式"/utf8>> }, description => #{ zh => <<"数据格式"/utf8>> } }, <<"slaveid">> => #{ order => 2, type => string, required => true, default => <<"0000"/utf8>>, title => #{ zh => <<"从机地址"/utf8>> }, description => #{ zh => <<"从机地址(16进制加0X,例如:0X10,否在是10进制),范围1-247,一个字节"/utf8>> } }, <<"operatetype">> => #{ order => 3, type => string, required => true, default => #{<<"value">> => <<"readCoils">>, <<"label">> => <<"0X01:读线圈寄存器"/utf8>>}, enum => [#{<<"value">> => <<"readCoils">>, <<"label">> => <<"0X01:读线圈寄存器"/utf8>>}, #{<<"value">> => <<"readInputs">>, <<"label">> => <<"0X02:读离散输入寄存器"/utf8>>}, #{<<"value">> => <<"readHregs">>, <<"label">> => <<"0X03:读保持寄存器"/utf8>>}, #{<<"value">> => <<"readIregs">>, <<"label">> => <<"0X04:读输入寄存器"/utf8>>}, #{<<"value">> => <<"writeCoil">>, <<"label">> => <<"0X05:写单个线圈寄存器"/utf8>>}, #{<<"value">> => <<"writeHreg">>, <<"label">> => <<"0X06:写单个保持寄存器"/utf8>>}, #{<<"value">> => <<"writeCoils">>, <<"label">> => <<"0X0f:写多个线圈寄存器"/utf8>>}, #{<<"value">> => <<"writeHregs">>, <<"label">> => <<"0X10:写多个保持寄存器"/utf8>>} ], title => #{ zh => <<"寄存器状态"/utf8>> }, description => #{ zh => <<"寄存器状态"/utf8>> } }, <<"address">> => #{ order => 4, type => string, required => true, default => <<"0X00"/utf8>>, title => #{ zh => <<"寄存器地址"/utf8>> }, description => #{ zh => <<"寄存器地址:原数据地址(16进制加0X,例如:0X10,否在是10进制);8位寄存器,一个字节;16位寄存器,两个字节;32位寄存器,四个字节"/utf8>> } }, <<"registersnumber">> => #{ order => 5, type => string, required => true, default => <<"1">>, title => #{ zh => <<"寄存器个数"/utf8>> }, description => #{ zh => <<"寄存器个数(多个寄存器个数)"/utf8>> } } }). %% 注册协议类型 %%-protocol_type(#{ %% cType => ?TYPE, %% type => <<"energy">>, colum = > 10 , %% title => #{ %% zh => <<"MODBUS TCP协议"/utf8>> %% }, %% description => #{ %% zh => <<"MODBUS TCP协议"/utf8>> %% } %%}). init(State) -> State#{<<"req">> => [], <<"ts">> => dgiot_datetime:now_ms(), <<"interval">> => 300}. %% login(#{<<"devaddr " > > : = DTUAddr , < < " product " > > : = ProductId , < < " ip " > > : , < < " channelId " > > : = ChannelId } = State ) - > Topic = < < ProductId / binary , " / " , ChannelId / binary , " / " , DTUAddr / binary > > , %% dgiot_mqtt:subscribe(Topic), dgiot_device : register(ProductId , DTUAddr , ChannelId , # { < < " ip " > > = > Ip } ) , %% {ok, State}; %% %%login(State) -> %% {ok, State}. to_frame(#{ <<"registersnumber">> := Quality, <<"slaveid">> := SlaveId, <<"operatetype">> := Operatetype, <<"address">> := Address }) -> encode_data(Quality, Address, SlaveId, Operatetype); %%<<"cmd">> => Cmd, %%<<"gateway">> => DtuAddr, %%<<"addr">> => SlaveId, %%<<"di">> => Address to_frame(#{ <<"data">> := Value, <<"gateway">> := DtuAddr, <<"slaveid">> := SlaveId, <<"address">> := Address }) -> case dgiot_device:get_subdevice(DtuAddr, SlaveId) of not_find -> []; [ProductId, _DevAddr] -> encode_data(Value, Address, SlaveId, ProductId) end. Quality encode_data(Quality, Address, SlaveId, OperateType) -> {FunCode, NewQuality} = case OperateType of <<"readCoils">> -> {?FC_READ_COILS, dgiot_utils:to_int(Quality)}; <<"readInputs">> -> {?FC_READ_INPUTS, dgiot_utils:to_int(Quality)}; <<"readHregs">> -> {?FC_READ_HREGS, dgiot_utils:to_int(Quality)}; <<"readIregs">> -> {?FC_READ_IREGS, dgiot_utils:to_int(Quality)}; <<"writeCoil">> -> {?FC_WRITE_COIL, dgiot_utils:to_int(Quality)}; <<"writeHreg">> -> {?FC_WRITE_HREG, dgiot_utils:to_int(Quality)}; %%需要校验,写多个线圈是什么状态 <<"writeCoils">> -> {?FC_WRITE_COILS, dgiot_utils:to_int(Quality)}; <<"writeHregs">> -> {?FC_WRITE_HREGS, dgiot_utils:to_int(Quality)}; %%需要校验,写多个保持寄存器是什么状态 _ -> {?FC_READ_HREGS, dgiot_utils:to_int(dgiot_utils:to_int(Quality))} end, <<H:8, L:8>> = dgiot_utils:hex_to_binary(modbus_tcp:is16(Address)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(modbus_tcp:is16(SlaveId)), RtuReq = #rtu_req{ slaveId = Sh * 256 + Sl, funcode = dgiot_utils:to_int(FunCode), address = H * 256 + L, quality = NewQuality }, build_req_message(RtuReq). is16(<<"0X", Data/binary>>) when size(Data) == 4 -> Data; is16(<<"0X", Data/binary>>) when size(Data) > 4 -> Data; is16(<<"0X", Data/binary>>) -> <<"00", Data/binary>>; is16(<<"00", Data/binary>>) -> is16(Data); is16(Data) -> IntData = dgiot_utils:to_int(Data), dgiot_utils:binary_to_hex(<<IntData:16>>). set_params(Payload, _ProductId, _DevAddr) -> Length = length(maps:keys(Payload)), Payloads = lists:foldl(fun(Index, Acc) -> case maps:find(dgiot_utils:to_binary(Index), Payload) of {ok, #{ <<"dataForm">> := #{ <<"protocol">> := <<"MODBUSTCP">>, <<"control">> := Setting}, <<"dataSource">> := #{ <<"slaveid">> := SlaveId, <<"address">> := Address, <<"bytes">> := Bytes, <<"operatetype">> := OperateType} = DataSource } = Data} -> case maps:find(<<"value">>, Data) of error -> Acc; {ok, Value} when erlang:byte_size(Value) == 0 -> Acc; {ok, Value} -> FunCode = case OperateType of <<"readCoils">> -> ?FC_READ_COILS; <<"readInputs">> -> ?FC_READ_INPUTS; <<"readHregs">> -> ?FC_READ_HREGS; <<"readIregs">> -> ?FC_READ_IREGS; <<"writeCoil">> -> ?FC_WRITE_COIL; <<"writeHreg">> -> ?FC_WRITE_HREG; <<"writeCoils">> -> ?FC_WRITE_COILS; %%需要校验,写多个线圈是什么状态 <<"writeHregs">> -> ?FC_WRITE_HREGS; %%需要校验,写多个保持寄存器是什么状态 _ -> ?FC_READ_HREGS end, <<H:8, L:8>> = dgiot_utils:hex_to_binary(is16(Address)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(is16(SlaveId)), Str1 = re:replace(Setting, "%d", "(" ++ dgiot_utils:to_list(Value) ++ ")", [global, {return, list}]), Value1 = dgiot_utils:to_int(dgiot_task:string2value(Str1, <<"type">>)), NewBt = Bytes * 8 , Registersnumber = maps:get(<<"registersnumber">>, DataSource, <<"1">>), RtuReq = #rtu_req{ slaveId = Sh * 256 + Sl, funcode = dgiot_utils:to_int(FunCode), address = H * 256 + L, registersnumber = dgiot_utils:to_int(Registersnumber), dataByteSize = dgiot_utils:to_int(Bytes), quality = Value1 }, Acc ++ [build_req_message(RtuReq)]; _ -> Acc end; _ -> Acc end end, [], lists:seq(1, Length)), Payloads. parse_frame(<<_TransactionId:16, _ProtocolId:16, _Size1:16, _Slaveid:8, _FunCode:8, DataLen:8, Data:DataLen/bytes, _/bytes>>) -> Data. %% 00 03 64 5c parse_frame(FileName, Data) -> AtomName = dgiot_utils:to_atom(FileName), Things = ets:match(AtomName, {'$1', ['_', '_', '_', '_', '$2', '_', '_', '_', '$3', '_', '_', '_', '_', '_', '_', '$4' | '_']}), AllData = lists:foldl(fun([Number, Devaddr, Address, Originaltype | _], Acc) -> ProductId = dgiot_data:get(AtomName, {addr, Address}), IntOffset = dgiot_utils:to_int(Number) - 1, Thing = #{ <<"identifier">> => Address, <<"dataSource">> => #{ <<"registersnumber">> => 1, <<"originaltype">> => Originaltype }}, IntLen = get_len(1, Originaltype), Value = case IntOffset of 0 -> <<V:IntLen/binary, _/binary>> = Data, case format_value(V, Thing, #{}) of {Value1, _Rest} -> Value1; _ -> V end; _ -> NewIntOffset = get_len(IntOffset, Originaltype), <<_:NewIntOffset/binary, V:IntLen/binary, _/binary>> = Data, case format_value(V, Thing, #{}) of {Value1, _Rest} -> Value1; _ -> V end end, NewData = change_data(ProductId, #{Address => Value}), dgiot_task:save_td(ProductId, Devaddr, NewData, #{<<"interval">> => 30}), Acc ++ [NewData] end, [], Things), AllData. change_data(ProductId, Data) -> case dgiot_product:lookup_prod(ProductId) of {ok, #{<<"thing">> := #{<<"properties">> := Props}}} -> lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataSource">> := DataSource} -> Dis = maps:get(<<"dis">>, DataSource, []), NewDis = lists:foldl(fun(X1, Acc1) -> case X1 of #{<<"key">> := Key} -> Acc1 ++ [Key]; _ -> Acc1 end end, [], Dis), maps:fold(fun(PK, PV, Acc2) -> case lists:member(PK, NewDis) of true -> Acc2#{Identifier => PV}; _ -> Acc2 end end, Acc, Data); _ -> Acc end end, #{}, Props); _Error -> Data end. rtu modbus parse_frame(<<>>, Acc, _State) -> {<<>>, Acc}; parse_frame(<<MbAddr:8, BadCode:8, ErrorCode:8, Crc:2/binary>> = Buff, Acc, #{<<"addr">> := DtuAddr} = State) -> CheckCrc = dgiot_utils:crc16(<<MbAddr:8, BadCode:8, ErrorCode:8>>), case CheckCrc =:= Crc of true -> Error = case ErrorCode of ?ILLEGAL_FUNCTION -> {error, illegal_function}; ?ILLEGAL_DATA_ADDRESS -> {error, illegal_data_address}; ?ILLEGAL_DATA_VALUE -> {error, illegal_data_value}; ?SLAVE_DEVICE_FAILURE -> {error, slave_device_failure}; ?ACKNOWLEDGE -> {error, acknowledge}; ?SLAVE_DEVICE_BUSY -> {error, slave_device_busy}; ?NEGATIVE_ACKNOWLEDGE -> {error, negative_acknowledge}; ?MEMORY_PARITY_ERROR -> {error, memory_parity_error}; ?GATEWAY_PATH_UNAVAILABLE -> {error, gateway_path_unavailable}; ?GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND -> {error, gateway_target_device_failed_to_respond}; _ -> {error, unknown_response_code} end, ?LOG(info, "DtuAddr ~p Modbus ~p, BadCode ~p, Error ~p", [DtuAddr, MbAddr, BadCode, Error]), {<<>>, #{}}; false -> parse_frame(Buff, Acc, State) end; modbustcp Buff = < < " 000100000006011000000001 " > > , parse_frame(<<_TransactionId:16, _ProtocolId:16, Size:16, _ResponseData:Size/bytes>> = Buff, Acc, #{<<"dtuproduct">> := ProductId, <<"address">> := Address} = State) -> io:format("~s ~p Buff = ~p.~n", [?FILE, ?LINE, Buff]), case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> [Buff, Acc] end; %% 传感器直接做为dtu物模型的一个指标 parse_frame(<<SlaveId:8, _/binary>> = Buff, Acc, #{<<"dtuproduct">> := ProductId, <<"slaveId">> := SlaveId, <<"dtuaddr">> := _DtuAddr, <<"address">> := Address} = State) -> case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> [Buff, Acc] end; %% 传感器独立建产品,做为子设备挂载到dtu上面 parse_frame(<<SlaveId:8, _/binary>> = Buff, Acc, #{<<"dtuaddr">> := DtuAddr, <<"slaveId">> := SlaveId, <<"address">> := Address} = State) -> case dgiot_device:get_subdevice(DtuAddr, dgiot_utils:to_binary(SlaveId)) of not_find -> [<<>>, Acc]; [ProductId, _DevAddr] -> case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> {Buff, Acc} end end; rtu modbus parse_frame(_Other, Acc, _State) -> io:format("~s ~p _Other = ~p.~n", [?FILE, ?LINE, _Other]), {error, Acc}. decode_data(<<_TransactionId:16, _ProtocolId:16, _Size1:16, Slaveid:8, _FunCode:8, DataLen:8, Data:DataLen/bytes>>, ProductId, Address, Acc) -> {<<>>, modbus_tcp_decoder(ProductId, Slaveid, Address, Data, Acc)}; decode_data(Buff, _ProductId, _Address, Acc) -> io:format("~s ~p errorBuff = ~p.~n", [?FILE, ?LINE, Buff]), {<<>>, Acc}. build_req_message(Req) when is_record(Req, rtu_req) -> % validate if (Req#rtu_req.slaveId < 0) or (Req#rtu_req.slaveId > 247) -> throw({argumentError, Req#rtu_req.slaveId}); true -> ok end, if (Req#rtu_req.funcode < 0) or (Req#rtu_req.funcode > 255) -> throw({argumentError, Req#rtu_req.funcode}); true -> ok end, if (Req#rtu_req.address < 0) or (Req#rtu_req.address > 65535) -> throw({argumentError, Req#rtu_req.address}); true -> ok end, if (Req#rtu_req.quality < 0) or (Req#rtu_req.quality > 2000) -> throw({argumentError, Req#rtu_req.quality}); true -> ok end, Message = case Req#rtu_req.funcode of ?FC_READ_COILS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; ?FC_READ_INPUTS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; ?FC_READ_HREGS -> %% 读保持寄存器 事务处理标识 随机值 <<R:1/binary, _/binary>> = dgiot_utils:random(), Transaction = dgiot_utils:to_int(dgiot_utils:binary_to_hex(R)), %% 协议标识符 00 00表示ModbusTCP协议。 Protocol = 0, Data = <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>, <<Transaction:16, Protocol:16, (size(Data)):16, Data/binary>>; ?FC_READ_IREGS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; ?FC_WRITE_COIL -> ValuesBin = case Req#rtu_req.quality of 1 -> <<16#ff, 16#00>>; _ -> <<16#00, 16#00>> end, <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, ValuesBin/binary>>; ?FC_WRITE_COILS -> Quantity = length(Req#rtu_req.quality), ValuesBin = list_bit_to_binary(Req#rtu_req.quality), ByteCount = length(binary_to_list(ValuesBin)), <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, Quantity:16, ByteCount:8, ValuesBin/binary>>; ?FC_WRITE_HREG -> ValueBin = list_word16_to_binary([Req#rtu_req.quality]), <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, ValueBin/binary>>; ?FC_WRITE_HREGS -> = list_word16_to_binary(Req#rtu_req.quality ) , Count = 1 , 写入字节数 ByteCount = 2 , %% 01 10 01 00 00 01 02 <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.registersnumber):16, (Req#rtu_req.dataByteSize):8, (Req#rtu_req.quality):16>>; _ -> erlang:error(function_not_implemented) end, %% Checksum = dgiot_utils:crc16(Message), Message. list_bit_to_binary(Values) when is_list(Values) -> L = length(Values), AlignedValues = case L rem 8 of 0 -> Values; Remainder -> Values ++ [0 || _ <- lists:seq(1, 8 - Remainder)] end, list_to_binary( bit_as_bytes(AlignedValues) ). bit_as_bytes(L) when is_list(L) -> bit_as_bytes(L, []). bit_as_bytes([], Res) -> lists:reverse(Res); bit_as_bytes([B0, B1, B2, B3, B4, B5, B6, B7 | Rest], Res) -> bit_as_bytes(Rest, [<<B7:1, B6:1, B5:1, B4:1, B3:1, B2:1, B1:1, B0:1>> | Res]). list_word16_to_binary(Values) when is_list(Values) -> list_to_binary( lists:map( fun(X) -> RoundedValue = round(X), <<RoundedValue:16>> end, Values ) ). modbus_tcp_decoder(ProductId, Slaveid, Address, Data, Acc1) -> case dgiot_product:lookup_prod(ProductId) of {ok, #{<<"thing">> := #{<<"properties">> := Props}}} -> lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataForm">> := #{ <<"strategy">> := Strategy, <<"protocol">> := <<"MODBUSTCP">>}, <<"dataSource">> := #{ <<"slaveid">> := OldSlaveid, <<"address">> := OldAddress} } when Strategy =/= <<"计算值"/utf8>> -> <<H:8, L:8>> = dgiot_utils:hex_to_binary(modbus_rtu:is16(OldSlaveid)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(modbus_rtu:is16(OldAddress)), NewSlaveid = H * 256 + L, NewAddress = Sh * 256 + Sl, case {Slaveid, Address} of {NewSlaveid, NewAddress} -> case format_value(Data, X, Props) of {map, Value} -> maps:merge(Acc, Value); {Value, _Rest} -> Acc#{Identifier => Value}; _ -> Acc end; _ -> Acc end; _ -> Acc end end, Acc1, Props); _ -> #{} end. %% 1)大端模式:Big-Endian就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。 %% (其实大端模式才是我们直观上认为的模式,和字符串存储的模式差类似) 低地址 -------------------- > 高地址 0x12 | 0x34 | 0x56 | 0x78 2)小端模式:Little - Endian就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端 。 低地址 -------------------- > 高地址 %% 0x78 | 0x56 | 0x34 | 0x12 format_value(Buff, #{ <<"dataType">> := #{<<"type">> := <<"geopoint">>, <<"gpstype">> := <<"NMEA0183">>}}, _Props) -> {Longitude, Latitude} = dgiot_gps:nmea0183_frame(Buff), {<<Longitude/binary, "_", Latitude/binary>>, <<"Rest">>}; format_value(Buff, #{ <<"accessMode">> := <<"rw">>, <<"dataSource">> := DataSource} = X, Props) -> format_value(Buff, X#{<<"accessMode">> => <<"r">>, <<"dataSource">> => DataSource#{<<"data">> => byte_size(Buff)} }, Props); format_value(Buff, #{<<"identifier">> := BitIdentifier, <<"dataSource">> := #{ <<"originaltype">> := <<"bit">> }}, Props) -> Values = lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataForm">> := #{ <<"protocol">> := <<"MODBUSTCP">>, <<"strategy">> := <<"计算值"/utf8>>}, <<"dataSource">> := #{ <<"slaveid">> := BitIdentifier, <<"address">> := Offset, <<"registersnumber">> := Num, <<"originaltype">> := Originaltype} } -> IntOffset = dgiot_utils:to_int(Offset), IntNum = dgiot_utils:to_int(Num), IntLen = get_len(IntNum, Originaltype), Value = case IntOffset of 0 -> <<V:IntLen/binary, _/binary>> = Buff, case format_value(V, X, Props) of {Value1, _Rest} -> Value1; _ -> V end; _ -> <<_:IntOffset/binary, V:IntLen/binary, _/binary>> = Buff, case format_value(V, X, Props) of {Value1, _Rest} -> Value1; _ -> V end end, Acc#{Identifier => Value}; _ -> Acc end end, #{}, Props), {map, Values}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"short16_AB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/signed-big-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"short16_BA">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/signed-little-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ushort16_AB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/unsigned-big-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ushort16_BA">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/unsigned-little-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"long32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"long32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<L/binary, H/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ulong32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ulong32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<L/binary, H/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"float32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/float>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"float32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/float>> = <<L/binary, H/binary>>, {Value, Rest}; %% @todo 其它类型处理 format_value(Buff, #{<<"identifier">> := Field, <<"originaltype">> := Originaltype}, _Props) -> ?LOG(error, "Field ~p originaltype ~p", [Field, Originaltype]), throw({field_error , < < Field / binary , " _ " , / binary , " is not validate " > > } ) , {<<"">>, Buff}. %% 获取寄存器字节长度 get_len(IntNum, <<"short16_AB">>) -> IntNum * 2; get_len(IntNum, <<"short16_BA">>) -> IntNum * 2; get_len(IntNum, <<"ushort16_AB">>) -> IntNum * 2; get_len(IntNum, <<"ushort16_BA">>) -> IntNum * 2; get_len(IntNum, <<"long32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"long32_CDAB">>) -> IntNum * 4; get_len(IntNum, <<"ulong32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"ulong32_CDAB">>) -> IntNum * 4; get_len(IntNum, <<"float32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"float32_CDAB">>) -> IntNum * 4; get_len(IntNum, _Originaltype) -> IntNum * 2. get_addr(ChannelId, Min, Max, Step) -> case dgiot_data:get_consumer(?consumer(ChannelId), Step) of Step -> Min; Value when (Value + Step) >= Max -> dgiot_data:set_consumer(?consumer(ChannelId), Min, Max), Value - Step; Value -> Value - Step end. set_addr(ChannelId, Min, Max) -> dgiot_data:set_consumer(?consumer(ChannelId), Min, Max).
null
https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_modbus/src/modbus/modbus_tcp.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. -------------------------------------------------------------------- 注册协议参数 注册协议类型 -protocol_type(#{ cType => ?TYPE, type => <<"energy">>, title => #{ zh => <<"MODBUS TCP协议"/utf8>> }, description => #{ zh => <<"MODBUS TCP协议"/utf8>> } }). dgiot_mqtt:subscribe(Topic), {ok, State}; login(State) -> {ok, State}. <<"cmd">> => Cmd, <<"gateway">> => DtuAddr, <<"addr">> => SlaveId, <<"di">> => Address 需要校验,写多个线圈是什么状态 需要校验,写多个保持寄存器是什么状态 需要校验,写多个线圈是什么状态 需要校验,写多个保持寄存器是什么状态 00 03 64 5c 传感器直接做为dtu物模型的一个指标 传感器独立建产品,做为子设备挂载到dtu上面 validate 读保持寄存器 协议标识符 00 00表示ModbusTCP协议。 01 10 01 00 00 01 02 Checksum = dgiot_utils:crc16(Message), 1)大端模式:Big-Endian就是高位字节排放在内存的低地址端,低位字节排放在内存的高地址端。 (其实大端模式才是我们直观上认为的模式,和字符串存储的模式差类似) 0x78 | 0x56 | 0x34 | 0x12 @todo 其它类型处理 获取寄存器字节长度
Copyright ( c ) 2020 - 2021 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(modbus_tcp). -author("jonhl"). -define(consumer(ChannelId), <<"modbus_consumer_", ChannelId/binary>>). -include("dgiot_modbus.hrl"). -include_lib("dgiot/include/logger.hrl"). -export([ init/1, parse_frame/1, parse_frame/2, parse_frame/3, to_frame/1, build_req_message/1, get_addr/4, set_addr/3] ). -export([is16/1, set_params/3, decode_data/4]). -define(TYPE, ?MODBUS_TCP). -params(#{ <<"originaltype">> => #{ order => 1, type => string, required => true, default => #{<<"value">> => <<"bit">>, <<"label">> => <<"位"/utf8>>}, enum => [ #{<<"value">> => <<"bit">>, <<"label">> => <<"位"/utf8>>}, #{<<"value">> => <<"short16_AB">>, <<"label">> => <<"16位 有符号(AB)"/utf8>>}, #{<<"value">> => <<"short16_BA">>, <<"label">> => <<"16位 有符号(BA)"/utf8>>}, #{<<"value">> => <<"ushort16_AB">>, <<"label">> => <<"16位 无符号(AB)"/utf8>>}, #{<<"value">> => <<"ushort16_BA">>, <<"label">> => <<"16位 无符号(BA)"/utf8>>}, #{<<"value">> => <<"long32_ABCD">>, <<"label">> => <<"32位 有符号(ABCD)"/utf8>>}, #{<<"value">> => <<"long32_CDAB">>, <<"label">> => <<"32位 有符号(CDAB)"/utf8>>}, #{<<"value">> => <<"ulong32_ABCD">>, <<"label">> => <<"32位 无符号(ABCD)"/utf8>>}, #{<<"value">> => <<"ulong32_CDAB">>, <<"label">> => <<"32位 无符号(CDAB)"/utf8>>}, #{<<"value">> => <<"float32_ABCD">>, <<"label">> => <<"32位 浮点数(ABCD)"/utf8>>}, #{<<"value">> => <<"float32_CDAB">>, <<"label">> => <<"32位 浮点数(CDAB)"/utf8>>} ], title => #{ zh => <<"数据格式"/utf8>> }, description => #{ zh => <<"数据格式"/utf8>> } }, <<"slaveid">> => #{ order => 2, type => string, required => true, default => <<"0000"/utf8>>, title => #{ zh => <<"从机地址"/utf8>> }, description => #{ zh => <<"从机地址(16进制加0X,例如:0X10,否在是10进制),范围1-247,一个字节"/utf8>> } }, <<"operatetype">> => #{ order => 3, type => string, required => true, default => #{<<"value">> => <<"readCoils">>, <<"label">> => <<"0X01:读线圈寄存器"/utf8>>}, enum => [#{<<"value">> => <<"readCoils">>, <<"label">> => <<"0X01:读线圈寄存器"/utf8>>}, #{<<"value">> => <<"readInputs">>, <<"label">> => <<"0X02:读离散输入寄存器"/utf8>>}, #{<<"value">> => <<"readHregs">>, <<"label">> => <<"0X03:读保持寄存器"/utf8>>}, #{<<"value">> => <<"readIregs">>, <<"label">> => <<"0X04:读输入寄存器"/utf8>>}, #{<<"value">> => <<"writeCoil">>, <<"label">> => <<"0X05:写单个线圈寄存器"/utf8>>}, #{<<"value">> => <<"writeHreg">>, <<"label">> => <<"0X06:写单个保持寄存器"/utf8>>}, #{<<"value">> => <<"writeCoils">>, <<"label">> => <<"0X0f:写多个线圈寄存器"/utf8>>}, #{<<"value">> => <<"writeHregs">>, <<"label">> => <<"0X10:写多个保持寄存器"/utf8>>} ], title => #{ zh => <<"寄存器状态"/utf8>> }, description => #{ zh => <<"寄存器状态"/utf8>> } }, <<"address">> => #{ order => 4, type => string, required => true, default => <<"0X00"/utf8>>, title => #{ zh => <<"寄存器地址"/utf8>> }, description => #{ zh => <<"寄存器地址:原数据地址(16进制加0X,例如:0X10,否在是10进制);8位寄存器,一个字节;16位寄存器,两个字节;32位寄存器,四个字节"/utf8>> } }, <<"registersnumber">> => #{ order => 5, type => string, required => true, default => <<"1">>, title => #{ zh => <<"寄存器个数"/utf8>> }, description => #{ zh => <<"寄存器个数(多个寄存器个数)"/utf8>> } } }). colum = > 10 , init(State) -> State#{<<"req">> => [], <<"ts">> => dgiot_datetime:now_ms(), <<"interval">> => 300}. login(#{<<"devaddr " > > : = DTUAddr , < < " product " > > : = ProductId , < < " ip " > > : , < < " channelId " > > : = ChannelId } = State ) - > Topic = < < ProductId / binary , " / " , ChannelId / binary , " / " , DTUAddr / binary > > , dgiot_device : register(ProductId , DTUAddr , ChannelId , # { < < " ip " > > = > Ip } ) , to_frame(#{ <<"registersnumber">> := Quality, <<"slaveid">> := SlaveId, <<"operatetype">> := Operatetype, <<"address">> := Address }) -> encode_data(Quality, Address, SlaveId, Operatetype); to_frame(#{ <<"data">> := Value, <<"gateway">> := DtuAddr, <<"slaveid">> := SlaveId, <<"address">> := Address }) -> case dgiot_device:get_subdevice(DtuAddr, SlaveId) of not_find -> []; [ProductId, _DevAddr] -> encode_data(Value, Address, SlaveId, ProductId) end. Quality encode_data(Quality, Address, SlaveId, OperateType) -> {FunCode, NewQuality} = case OperateType of <<"readCoils">> -> {?FC_READ_COILS, dgiot_utils:to_int(Quality)}; <<"readInputs">> -> {?FC_READ_INPUTS, dgiot_utils:to_int(Quality)}; <<"readHregs">> -> {?FC_READ_HREGS, dgiot_utils:to_int(Quality)}; <<"readIregs">> -> {?FC_READ_IREGS, dgiot_utils:to_int(Quality)}; <<"writeCoil">> -> {?FC_WRITE_COIL, dgiot_utils:to_int(Quality)}; <<"writeCoils">> -> {?FC_WRITE_COILS, dgiot_utils:to_int(Quality)}; _ -> {?FC_READ_HREGS, dgiot_utils:to_int(dgiot_utils:to_int(Quality))} end, <<H:8, L:8>> = dgiot_utils:hex_to_binary(modbus_tcp:is16(Address)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(modbus_tcp:is16(SlaveId)), RtuReq = #rtu_req{ slaveId = Sh * 256 + Sl, funcode = dgiot_utils:to_int(FunCode), address = H * 256 + L, quality = NewQuality }, build_req_message(RtuReq). is16(<<"0X", Data/binary>>) when size(Data) == 4 -> Data; is16(<<"0X", Data/binary>>) when size(Data) > 4 -> Data; is16(<<"0X", Data/binary>>) -> <<"00", Data/binary>>; is16(<<"00", Data/binary>>) -> is16(Data); is16(Data) -> IntData = dgiot_utils:to_int(Data), dgiot_utils:binary_to_hex(<<IntData:16>>). set_params(Payload, _ProductId, _DevAddr) -> Length = length(maps:keys(Payload)), Payloads = lists:foldl(fun(Index, Acc) -> case maps:find(dgiot_utils:to_binary(Index), Payload) of {ok, #{ <<"dataForm">> := #{ <<"protocol">> := <<"MODBUSTCP">>, <<"control">> := Setting}, <<"dataSource">> := #{ <<"slaveid">> := SlaveId, <<"address">> := Address, <<"bytes">> := Bytes, <<"operatetype">> := OperateType} = DataSource } = Data} -> case maps:find(<<"value">>, Data) of error -> Acc; {ok, Value} when erlang:byte_size(Value) == 0 -> Acc; {ok, Value} -> FunCode = case OperateType of <<"readCoils">> -> ?FC_READ_COILS; <<"readInputs">> -> ?FC_READ_INPUTS; <<"readHregs">> -> ?FC_READ_HREGS; <<"readIregs">> -> ?FC_READ_IREGS; <<"writeCoil">> -> ?FC_WRITE_COIL; <<"writeHreg">> -> ?FC_WRITE_HREG; _ -> ?FC_READ_HREGS end, <<H:8, L:8>> = dgiot_utils:hex_to_binary(is16(Address)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(is16(SlaveId)), Str1 = re:replace(Setting, "%d", "(" ++ dgiot_utils:to_list(Value) ++ ")", [global, {return, list}]), Value1 = dgiot_utils:to_int(dgiot_task:string2value(Str1, <<"type">>)), NewBt = Bytes * 8 , Registersnumber = maps:get(<<"registersnumber">>, DataSource, <<"1">>), RtuReq = #rtu_req{ slaveId = Sh * 256 + Sl, funcode = dgiot_utils:to_int(FunCode), address = H * 256 + L, registersnumber = dgiot_utils:to_int(Registersnumber), dataByteSize = dgiot_utils:to_int(Bytes), quality = Value1 }, Acc ++ [build_req_message(RtuReq)]; _ -> Acc end; _ -> Acc end end, [], lists:seq(1, Length)), Payloads. parse_frame(<<_TransactionId:16, _ProtocolId:16, _Size1:16, _Slaveid:8, _FunCode:8, DataLen:8, Data:DataLen/bytes, _/bytes>>) -> Data. parse_frame(FileName, Data) -> AtomName = dgiot_utils:to_atom(FileName), Things = ets:match(AtomName, {'$1', ['_', '_', '_', '_', '$2', '_', '_', '_', '$3', '_', '_', '_', '_', '_', '_', '$4' | '_']}), AllData = lists:foldl(fun([Number, Devaddr, Address, Originaltype | _], Acc) -> ProductId = dgiot_data:get(AtomName, {addr, Address}), IntOffset = dgiot_utils:to_int(Number) - 1, Thing = #{ <<"identifier">> => Address, <<"dataSource">> => #{ <<"registersnumber">> => 1, <<"originaltype">> => Originaltype }}, IntLen = get_len(1, Originaltype), Value = case IntOffset of 0 -> <<V:IntLen/binary, _/binary>> = Data, case format_value(V, Thing, #{}) of {Value1, _Rest} -> Value1; _ -> V end; _ -> NewIntOffset = get_len(IntOffset, Originaltype), <<_:NewIntOffset/binary, V:IntLen/binary, _/binary>> = Data, case format_value(V, Thing, #{}) of {Value1, _Rest} -> Value1; _ -> V end end, NewData = change_data(ProductId, #{Address => Value}), dgiot_task:save_td(ProductId, Devaddr, NewData, #{<<"interval">> => 30}), Acc ++ [NewData] end, [], Things), AllData. change_data(ProductId, Data) -> case dgiot_product:lookup_prod(ProductId) of {ok, #{<<"thing">> := #{<<"properties">> := Props}}} -> lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataSource">> := DataSource} -> Dis = maps:get(<<"dis">>, DataSource, []), NewDis = lists:foldl(fun(X1, Acc1) -> case X1 of #{<<"key">> := Key} -> Acc1 ++ [Key]; _ -> Acc1 end end, [], Dis), maps:fold(fun(PK, PV, Acc2) -> case lists:member(PK, NewDis) of true -> Acc2#{Identifier => PV}; _ -> Acc2 end end, Acc, Data); _ -> Acc end end, #{}, Props); _Error -> Data end. rtu modbus parse_frame(<<>>, Acc, _State) -> {<<>>, Acc}; parse_frame(<<MbAddr:8, BadCode:8, ErrorCode:8, Crc:2/binary>> = Buff, Acc, #{<<"addr">> := DtuAddr} = State) -> CheckCrc = dgiot_utils:crc16(<<MbAddr:8, BadCode:8, ErrorCode:8>>), case CheckCrc =:= Crc of true -> Error = case ErrorCode of ?ILLEGAL_FUNCTION -> {error, illegal_function}; ?ILLEGAL_DATA_ADDRESS -> {error, illegal_data_address}; ?ILLEGAL_DATA_VALUE -> {error, illegal_data_value}; ?SLAVE_DEVICE_FAILURE -> {error, slave_device_failure}; ?ACKNOWLEDGE -> {error, acknowledge}; ?SLAVE_DEVICE_BUSY -> {error, slave_device_busy}; ?NEGATIVE_ACKNOWLEDGE -> {error, negative_acknowledge}; ?MEMORY_PARITY_ERROR -> {error, memory_parity_error}; ?GATEWAY_PATH_UNAVAILABLE -> {error, gateway_path_unavailable}; ?GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND -> {error, gateway_target_device_failed_to_respond}; _ -> {error, unknown_response_code} end, ?LOG(info, "DtuAddr ~p Modbus ~p, BadCode ~p, Error ~p", [DtuAddr, MbAddr, BadCode, Error]), {<<>>, #{}}; false -> parse_frame(Buff, Acc, State) end; modbustcp Buff = < < " 000100000006011000000001 " > > , parse_frame(<<_TransactionId:16, _ProtocolId:16, Size:16, _ResponseData:Size/bytes>> = Buff, Acc, #{<<"dtuproduct">> := ProductId, <<"address">> := Address} = State) -> io:format("~s ~p Buff = ~p.~n", [?FILE, ?LINE, Buff]), case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> [Buff, Acc] end; parse_frame(<<SlaveId:8, _/binary>> = Buff, Acc, #{<<"dtuproduct">> := ProductId, <<"slaveId">> := SlaveId, <<"dtuaddr">> := _DtuAddr, <<"address">> := Address} = State) -> case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> [Buff, Acc] end; parse_frame(<<SlaveId:8, _/binary>> = Buff, Acc, #{<<"dtuaddr">> := DtuAddr, <<"slaveId">> := SlaveId, <<"address">> := Address} = State) -> case dgiot_device:get_subdevice(DtuAddr, dgiot_utils:to_binary(SlaveId)) of not_find -> [<<>>, Acc]; [ProductId, _DevAddr] -> case decode_data(Buff, ProductId, Address, Acc) of {Rest1, Acc1} -> parse_frame(Rest1, Acc1, State); [Buff, Acc] -> {Buff, Acc} end end; rtu modbus parse_frame(_Other, Acc, _State) -> io:format("~s ~p _Other = ~p.~n", [?FILE, ?LINE, _Other]), {error, Acc}. decode_data(<<_TransactionId:16, _ProtocolId:16, _Size1:16, Slaveid:8, _FunCode:8, DataLen:8, Data:DataLen/bytes>>, ProductId, Address, Acc) -> {<<>>, modbus_tcp_decoder(ProductId, Slaveid, Address, Data, Acc)}; decode_data(Buff, _ProductId, _Address, Acc) -> io:format("~s ~p errorBuff = ~p.~n", [?FILE, ?LINE, Buff]), {<<>>, Acc}. build_req_message(Req) when is_record(Req, rtu_req) -> if (Req#rtu_req.slaveId < 0) or (Req#rtu_req.slaveId > 247) -> throw({argumentError, Req#rtu_req.slaveId}); true -> ok end, if (Req#rtu_req.funcode < 0) or (Req#rtu_req.funcode > 255) -> throw({argumentError, Req#rtu_req.funcode}); true -> ok end, if (Req#rtu_req.address < 0) or (Req#rtu_req.address > 65535) -> throw({argumentError, Req#rtu_req.address}); true -> ok end, if (Req#rtu_req.quality < 0) or (Req#rtu_req.quality > 2000) -> throw({argumentError, Req#rtu_req.quality}); true -> ok end, Message = case Req#rtu_req.funcode of ?FC_READ_COILS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; ?FC_READ_INPUTS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; 事务处理标识 随机值 <<R:1/binary, _/binary>> = dgiot_utils:random(), Transaction = dgiot_utils:to_int(dgiot_utils:binary_to_hex(R)), Protocol = 0, Data = <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>, <<Transaction:16, Protocol:16, (size(Data)):16, Data/binary>>; ?FC_READ_IREGS -> <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.quality):16>>; ?FC_WRITE_COIL -> ValuesBin = case Req#rtu_req.quality of 1 -> <<16#ff, 16#00>>; _ -> <<16#00, 16#00>> end, <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, ValuesBin/binary>>; ?FC_WRITE_COILS -> Quantity = length(Req#rtu_req.quality), ValuesBin = list_bit_to_binary(Req#rtu_req.quality), ByteCount = length(binary_to_list(ValuesBin)), <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, Quantity:16, ByteCount:8, ValuesBin/binary>>; ?FC_WRITE_HREG -> ValueBin = list_word16_to_binary([Req#rtu_req.quality]), <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, ValueBin/binary>>; ?FC_WRITE_HREGS -> = list_word16_to_binary(Req#rtu_req.quality ) , Count = 1 , 写入字节数 ByteCount = 2 , <<(Req#rtu_req.slaveId):8, (Req#rtu_req.funcode):8, (Req#rtu_req.address):16, (Req#rtu_req.registersnumber):16, (Req#rtu_req.dataByteSize):8, (Req#rtu_req.quality):16>>; _ -> erlang:error(function_not_implemented) end, Message. list_bit_to_binary(Values) when is_list(Values) -> L = length(Values), AlignedValues = case L rem 8 of 0 -> Values; Remainder -> Values ++ [0 || _ <- lists:seq(1, 8 - Remainder)] end, list_to_binary( bit_as_bytes(AlignedValues) ). bit_as_bytes(L) when is_list(L) -> bit_as_bytes(L, []). bit_as_bytes([], Res) -> lists:reverse(Res); bit_as_bytes([B0, B1, B2, B3, B4, B5, B6, B7 | Rest], Res) -> bit_as_bytes(Rest, [<<B7:1, B6:1, B5:1, B4:1, B3:1, B2:1, B1:1, B0:1>> | Res]). list_word16_to_binary(Values) when is_list(Values) -> list_to_binary( lists:map( fun(X) -> RoundedValue = round(X), <<RoundedValue:16>> end, Values ) ). modbus_tcp_decoder(ProductId, Slaveid, Address, Data, Acc1) -> case dgiot_product:lookup_prod(ProductId) of {ok, #{<<"thing">> := #{<<"properties">> := Props}}} -> lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataForm">> := #{ <<"strategy">> := Strategy, <<"protocol">> := <<"MODBUSTCP">>}, <<"dataSource">> := #{ <<"slaveid">> := OldSlaveid, <<"address">> := OldAddress} } when Strategy =/= <<"计算值"/utf8>> -> <<H:8, L:8>> = dgiot_utils:hex_to_binary(modbus_rtu:is16(OldSlaveid)), <<Sh:8, Sl:8>> = dgiot_utils:hex_to_binary(modbus_rtu:is16(OldAddress)), NewSlaveid = H * 256 + L, NewAddress = Sh * 256 + Sl, case {Slaveid, Address} of {NewSlaveid, NewAddress} -> case format_value(Data, X, Props) of {map, Value} -> maps:merge(Acc, Value); {Value, _Rest} -> Acc#{Identifier => Value}; _ -> Acc end; _ -> Acc end; _ -> Acc end end, Acc1, Props); _ -> #{} end. 低地址 -------------------- > 高地址 0x12 | 0x34 | 0x56 | 0x78 2)小端模式:Little - Endian就是低位字节排放在内存的低地址端,高位字节排放在内存的高地址端 。 低地址 -------------------- > 高地址 format_value(Buff, #{ <<"dataType">> := #{<<"type">> := <<"geopoint">>, <<"gpstype">> := <<"NMEA0183">>}}, _Props) -> {Longitude, Latitude} = dgiot_gps:nmea0183_frame(Buff), {<<Longitude/binary, "_", Latitude/binary>>, <<"Rest">>}; format_value(Buff, #{ <<"accessMode">> := <<"rw">>, <<"dataSource">> := DataSource} = X, Props) -> format_value(Buff, X#{<<"accessMode">> => <<"r">>, <<"dataSource">> => DataSource#{<<"data">> => byte_size(Buff)} }, Props); format_value(Buff, #{<<"identifier">> := BitIdentifier, <<"dataSource">> := #{ <<"originaltype">> := <<"bit">> }}, Props) -> Values = lists:foldl(fun(X, Acc) -> case X of #{<<"identifier">> := Identifier, <<"dataForm">> := #{ <<"protocol">> := <<"MODBUSTCP">>, <<"strategy">> := <<"计算值"/utf8>>}, <<"dataSource">> := #{ <<"slaveid">> := BitIdentifier, <<"address">> := Offset, <<"registersnumber">> := Num, <<"originaltype">> := Originaltype} } -> IntOffset = dgiot_utils:to_int(Offset), IntNum = dgiot_utils:to_int(Num), IntLen = get_len(IntNum, Originaltype), Value = case IntOffset of 0 -> <<V:IntLen/binary, _/binary>> = Buff, case format_value(V, X, Props) of {Value1, _Rest} -> Value1; _ -> V end; _ -> <<_:IntOffset/binary, V:IntLen/binary, _/binary>> = Buff, case format_value(V, X, Props) of {Value1, _Rest} -> Value1; _ -> V end end, Acc#{Identifier => Value}; _ -> Acc end end, #{}, Props), {map, Values}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"short16_AB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/signed-big-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"short16_BA">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/signed-little-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ushort16_AB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/unsigned-big-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ushort16_BA">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 2 * 8, <<Value:Size/unsigned-little-integer, Rest/binary>> = Buff, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"long32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"long32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<L/binary, H/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ulong32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"ulong32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/integer>> = <<L/binary, H/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"float32_ABCD">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/float>> = <<H/binary, L/binary>>, {Value, Rest}; format_value(Buff, #{<<"dataSource">> := #{ <<"registersnumber">> := Num, <<"originaltype">> := <<"float32_CDAB">> }}, _Props) -> IntNum = dgiot_utils:to_int(Num), Size = IntNum * 4 * 8, <<H:2/binary, L:2/binary, Rest/binary>> = Buff, <<Value:Size/float>> = <<L/binary, H/binary>>, {Value, Rest}; format_value(Buff, #{<<"identifier">> := Field, <<"originaltype">> := Originaltype}, _Props) -> ?LOG(error, "Field ~p originaltype ~p", [Field, Originaltype]), throw({field_error , < < Field / binary , " _ " , / binary , " is not validate " > > } ) , {<<"">>, Buff}. get_len(IntNum, <<"short16_AB">>) -> IntNum * 2; get_len(IntNum, <<"short16_BA">>) -> IntNum * 2; get_len(IntNum, <<"ushort16_AB">>) -> IntNum * 2; get_len(IntNum, <<"ushort16_BA">>) -> IntNum * 2; get_len(IntNum, <<"long32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"long32_CDAB">>) -> IntNum * 4; get_len(IntNum, <<"ulong32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"ulong32_CDAB">>) -> IntNum * 4; get_len(IntNum, <<"float32_ABCD">>) -> IntNum * 4; get_len(IntNum, <<"float32_CDAB">>) -> IntNum * 4; get_len(IntNum, _Originaltype) -> IntNum * 2. get_addr(ChannelId, Min, Max, Step) -> case dgiot_data:get_consumer(?consumer(ChannelId), Step) of Step -> Min; Value when (Value + Step) >= Max -> dgiot_data:set_consumer(?consumer(ChannelId), Min, Max), Value - Step; Value -> Value - Step end. set_addr(ChannelId, Min, Max) -> dgiot_data:set_consumer(?consumer(ChannelId), Min, Max).
062bce04384aa6fe3a30195baaf65265122797117dd074a9ec7fcff66fbd80bd
tisnik/clojure-examples
details.clj
{:aliases {"downgrade" "upgrade"}, :checkout-deps-shares [:source-paths :test-paths :resource-paths :compile-path "#'leiningen.core.classpath/checkout-deps-paths"], :clean-targets [:target-path], :compile-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default/classes", :dependencies ([org.clojure/clojure "1.10.1"] [fundingcircle/jackdaw "0.7.6"] [nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])] [clojure-complete/clojure-complete "0.2.5" :exclusions ([org.clojure/clojure])] [venantius/ultra "0.6.0"]), :deploy-repositories [["clojars" {:url "/", :password :gpg, :username :gpg}]], :description "FIXME: write description", :eval-in :subprocess, :global-vars {}, :group "describe-cluster", :jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""], :jvm-opts ["-XX:-OmitStackTraceInFastThrow" "-XX:+TieredCompilation" "-XX:TieredStopAtLevel=1"], :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0", :url "-2.0/"}, :main describe-cluster.core, :monkeypatch-clojure-test false, :name "describe-cluster", :native-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default/native", :offline? false, :pedantic? ranges, :plugin-repositories [["central" {:url "/", :snapshots false}] ["clojars" {:url "/"}]], :plugins ([lein-codox/lein-codox "0.10.7"] [test2junit/test2junit "1.1.0"] [lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit/lein-kibit "0.1.8"] [lein-clean-m2/lein-clean-m2 "0.1.2"] [lein-project-edn/lein-project-edn "0.3.0"] [lein-marginalia/lein-marginalia "0.9.1"] [venantius/ultra "0.6.0"]), :prep-tasks ["javac" "compile"], :profiles {:uberjar {:aot [:all], :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}, :whidbey/repl {:dependencies [[mvxcvi/whidbey "RELEASE"]], :repl-options {:init (do nil (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil)), :custom-init (do nil (whidbey.repl/update-print-fn!)), :nrepl-context {:interactive-eval {:printer whidbey.repl/render-str}}}}}, :project-edn {:output-file "doc/details.clj"}, :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]], :repl-options {:init (do (do (clojure.core/require 'ultra.hardcore) (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil) (ultra.hardcore/configure! {:repl {:print-meta false, :map-delimiter "", :print-fallback :print, :sort-keys true}})))}, :repositories [["central" {:url "/", :snapshots false}] ["clojars" {:url "/"}]], :resource-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/dev-resources" "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/resources"), :root "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster", :source-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/src"), :target-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default", :test-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/test"), :test-selectors {:default (constantly true)}, :uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""], :url "", :version "0.1.0-SNAPSHOT"}
null
https://raw.githubusercontent.com/tisnik/clojure-examples/ad495c2443e542269cf4784fd5cfa62787cdff98/kafka-describe-cluster/doc/details.clj
clojure
{:aliases {"downgrade" "upgrade"}, :checkout-deps-shares [:source-paths :test-paths :resource-paths :compile-path "#'leiningen.core.classpath/checkout-deps-paths"], :clean-targets [:target-path], :compile-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default/classes", :dependencies ([org.clojure/clojure "1.10.1"] [fundingcircle/jackdaw "0.7.6"] [nrepl/nrepl "0.7.0" :exclusions ([org.clojure/clojure])] [clojure-complete/clojure-complete "0.2.5" :exclusions ([org.clojure/clojure])] [venantius/ultra "0.6.0"]), :deploy-repositories [["clojars" {:url "/", :password :gpg, :username :gpg}]], :description "FIXME: write description", :eval-in :subprocess, :global-vars {}, :group "describe-cluster", :jar-exclusions ["#\"^\\.\"" "#\"\\Q/.\\E\""], :jvm-opts ["-XX:-OmitStackTraceInFastThrow" "-XX:+TieredCompilation" "-XX:TieredStopAtLevel=1"], :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0", :url "-2.0/"}, :main describe-cluster.core, :monkeypatch-clojure-test false, :name "describe-cluster", :native-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default/native", :offline? false, :pedantic? ranges, :plugin-repositories [["central" {:url "/", :snapshots false}] ["clojars" {:url "/"}]], :plugins ([lein-codox/lein-codox "0.10.7"] [test2junit/test2junit "1.1.0"] [lein-cloverage/lein-cloverage "1.0.7-SNAPSHOT"] [lein-kibit/lein-kibit "0.1.8"] [lein-clean-m2/lein-clean-m2 "0.1.2"] [lein-project-edn/lein-project-edn "0.3.0"] [lein-marginalia/lein-marginalia "0.9.1"] [venantius/ultra "0.6.0"]), :prep-tasks ["javac" "compile"], :profiles {:uberjar {:aot [:all], :jvm-opts ["-Dclojure.compiler.direct-linking=true"]}, :whidbey/repl {:dependencies [[mvxcvi/whidbey "RELEASE"]], :repl-options {:init (do nil (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil)), :custom-init (do nil (whidbey.repl/update-print-fn!)), :nrepl-context {:interactive-eval {:printer whidbey.repl/render-str}}}}}, :project-edn {:output-file "doc/details.clj"}, :release-tasks [["vcs" "assert-committed"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]], :repl-options {:init (do (do (clojure.core/require 'ultra.hardcore) (clojure.core/require 'whidbey.repl) (whidbey.repl/init! nil) (ultra.hardcore/configure! {:repl {:print-meta false, :map-delimiter "", :print-fallback :print, :sort-keys true}})))}, :repositories [["central" {:url "/", :snapshots false}] ["clojars" {:url "/"}]], :resource-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/dev-resources" "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/resources"), :root "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster", :source-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/src"), :target-path "/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/target/default", :test-paths ("/home/ptisnovs/src/clojure/clojure-examples/kafka-describe-cluster/test"), :test-selectors {:default (constantly true)}, :uberjar-exclusions ["#\"(?i)^META-INF/[^/]*\\.(SF|RSA|DSA)$\""], :url "", :version "0.1.0-SNAPSHOT"}
a4a7bc1ed099020805cbd414a275b80b45e419c445d390f186680c5bb9408fcc
markostanimirovic/re-action
post_index.cljs
(ns blog.posts.post-index (:require [blog.posts.resource :as resource] [re-action.router :as router] [re-action.core :as re-action] [re-streamer.core :refer [subscribe]])) ;; === Presentational Components === (defn- header [search update-search create] [:div.card-header.page-header [:div.page-title [:h5 "Posts"]] [:div.page-search [:input.form-control {:type :text :placeholder "Search" :value search :on-change #(update-search (.. % -target -value))}]] [:div.page-actions [:span.action-button {:on-click #(create)} [:i.fas.fa-plus]]]]) (defn- body [posts details] [:div.card-body.row (for [post posts] [:div.col-md-3.col-sm-4.buffer-bottom {:key (:id post)} [:a.card {:on-click #(details post)} [:div.card-body [:h5.card-title (:title post)] [:p.card-text.text-truncate (:body post)]]]])]) (defn- footer [page-sizes selected-size update-selected-size] [:div.card-footer.text-center (for [page-size page-sizes] [:button.btn.mr-1 {:class (if (= page-size selected-size) "btn-primary" "btn-light") :key page-size :on-click #(update-selected-size page-size)} page-size])]) ;; === Facade === (defn- facade [] (let [init-state {:posts [] :page-sizes [5 10 15 20] :selected-size 5 :search ""} store (re-action/store init-state) posts (re-action/select store :posts) page-sizes (re-action/select store :page-sizes) selected-size (re-action/select store :selected-size) search (re-action/select store :search) get-posts (re-action/select-distinct store :selected-size :search)] (subscribe get-posts #(re-action/patch-state! store {:posts (resource/get-posts %)})) {:posts (:state posts) :page-sizes (:state page-sizes) :selected-size (:state selected-size) :search (:state search) :update-selected-size #(re-action/patch-state! store {:selected-size %}) :update-search #(re-action/patch-state! store {:search %}) :details #(router/navigate (str "/posts/" (:id %))) :create #(router/navigate "/posts/create")})) ;; === Container Component === (defn container [] (let [facade (facade)] (fn [] [:div.card [header @(:search facade) (:update-search facade) (:create facade)] [body @(:posts facade) (:details facade)] [footer @(:page-sizes facade) @(:selected-size facade) (:update-selected-size facade)]])))
null
https://raw.githubusercontent.com/markostanimirovic/re-action/d6cb33d9ac73bedeac4f09996c2c741d21bda7ba/examples/blog/src/blog/posts/post_index.cljs
clojure
=== Presentational Components === === Facade === === Container Component ===
(ns blog.posts.post-index (:require [blog.posts.resource :as resource] [re-action.router :as router] [re-action.core :as re-action] [re-streamer.core :refer [subscribe]])) (defn- header [search update-search create] [:div.card-header.page-header [:div.page-title [:h5 "Posts"]] [:div.page-search [:input.form-control {:type :text :placeholder "Search" :value search :on-change #(update-search (.. % -target -value))}]] [:div.page-actions [:span.action-button {:on-click #(create)} [:i.fas.fa-plus]]]]) (defn- body [posts details] [:div.card-body.row (for [post posts] [:div.col-md-3.col-sm-4.buffer-bottom {:key (:id post)} [:a.card {:on-click #(details post)} [:div.card-body [:h5.card-title (:title post)] [:p.card-text.text-truncate (:body post)]]]])]) (defn- footer [page-sizes selected-size update-selected-size] [:div.card-footer.text-center (for [page-size page-sizes] [:button.btn.mr-1 {:class (if (= page-size selected-size) "btn-primary" "btn-light") :key page-size :on-click #(update-selected-size page-size)} page-size])]) (defn- facade [] (let [init-state {:posts [] :page-sizes [5 10 15 20] :selected-size 5 :search ""} store (re-action/store init-state) posts (re-action/select store :posts) page-sizes (re-action/select store :page-sizes) selected-size (re-action/select store :selected-size) search (re-action/select store :search) get-posts (re-action/select-distinct store :selected-size :search)] (subscribe get-posts #(re-action/patch-state! store {:posts (resource/get-posts %)})) {:posts (:state posts) :page-sizes (:state page-sizes) :selected-size (:state selected-size) :search (:state search) :update-selected-size #(re-action/patch-state! store {:selected-size %}) :update-search #(re-action/patch-state! store {:search %}) :details #(router/navigate (str "/posts/" (:id %))) :create #(router/navigate "/posts/create")})) (defn container [] (let [facade (facade)] (fn [] [:div.card [header @(:search facade) (:update-search facade) (:create facade)] [body @(:posts facade) (:details facade)] [footer @(:page-sizes facade) @(:selected-size facade) (:update-selected-size facade)]])))
62a85385f7d8446ff451dae989d963c50c525425d2d4992535baafd40fd3e25b
clojure-interop/google-cloud-clients
ConfigServiceV2Stub.clj
(ns com.google.cloud.logging.v2.stub.ConfigServiceV2Stub "Base stub class for Stackdriver Logging API. This class is for advanced usage and reflects the underlying API directly." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.logging.v2.stub ConfigServiceV2Stub])) (defn ->config-service-v-2-stub "Constructor." (^ConfigServiceV2Stub [] (new ConfigServiceV2Stub ))) (defn update-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.UpdateSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.updateSinkCallable)))) (defn list-exclusions-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListExclusionsRequest,com.google.logging.v2.ListExclusionsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listExclusionsCallable)))) (defn delete-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.DeleteExclusionRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.deleteExclusionCallable)))) (defn list-sinks-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListSinksRequest,com.google.cloud.logging.v2.ConfigClient$ListSinksPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listSinksPagedCallable)))) (defn create-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.CreateExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.createExclusionCallable)))) (defn get-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.GetExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.getExclusionCallable)))) (defn close "" ([^ConfigServiceV2Stub this] (-> this (.close)))) (defn create-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.CreateSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.createSinkCallable)))) (defn get-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.GetSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.getSinkCallable)))) (defn list-sinks-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListSinksRequest,com.google.logging.v2.ListSinksResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listSinksCallable)))) (defn update-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.UpdateExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.updateExclusionCallable)))) (defn delete-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.DeleteSinkRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.deleteSinkCallable)))) (defn list-exclusions-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListExclusionsRequest,com.google.cloud.logging.v2.ConfigClient$ListExclusionsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listExclusionsPagedCallable))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.logging/src/com/google/cloud/logging/v2/stub/ConfigServiceV2Stub.clj
clojure
(ns com.google.cloud.logging.v2.stub.ConfigServiceV2Stub "Base stub class for Stackdriver Logging API. This class is for advanced usage and reflects the underlying API directly." (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.logging.v2.stub ConfigServiceV2Stub])) (defn ->config-service-v-2-stub "Constructor." (^ConfigServiceV2Stub [] (new ConfigServiceV2Stub ))) (defn update-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.UpdateSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.updateSinkCallable)))) (defn list-exclusions-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListExclusionsRequest,com.google.logging.v2.ListExclusionsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listExclusionsCallable)))) (defn delete-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.DeleteExclusionRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.deleteExclusionCallable)))) (defn list-sinks-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListSinksRequest,com.google.cloud.logging.v2.ConfigClient$ListSinksPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listSinksPagedCallable)))) (defn create-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.CreateExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.createExclusionCallable)))) (defn get-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.GetExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.getExclusionCallable)))) (defn close "" ([^ConfigServiceV2Stub this] (-> this (.close)))) (defn create-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.CreateSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.createSinkCallable)))) (defn get-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.GetSinkRequest,com.google.logging.v2.LogSink>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.getSinkCallable)))) (defn list-sinks-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListSinksRequest,com.google.logging.v2.ListSinksResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listSinksCallable)))) (defn update-exclusion-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.UpdateExclusionRequest,com.google.logging.v2.LogExclusion>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.updateExclusionCallable)))) (defn delete-sink-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.DeleteSinkRequest,com.google.protobuf.Empty>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.deleteSinkCallable)))) (defn list-exclusions-paged-callable "returns: `com.google.api.gax.rpc.UnaryCallable<com.google.logging.v2.ListExclusionsRequest,com.google.cloud.logging.v2.ConfigClient$ListExclusionsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^ConfigServiceV2Stub this] (-> this (.listExclusionsPagedCallable))))
ca80d571b55173b43938e258f9c5d5824f49ac28d673e887d6d7af8d0b7e67e1
EduardoRFS/youtube-channel
lexer.ml
open Sedlexing.Utf8 open Parser exception Invalid_token let whitespace = [%sedlex.regexp? Plus (' ' | '\n' | '\t')] let lower_alpha = [%sedlex.regexp? 'a' .. 'z'] let number = [%sedlex.regexp? '0' .. '9'] let ident = [%sedlex.regexp? lower_alpha, Star (lower_alpha | number | '_')] let int = [%sedlex.regexp? Plus number] let rec tokenizer buf = match%sedlex buf with | whitespace -> tokenizer buf | ident -> IDENT (lexeme buf) | int -> INT (lexeme buf |> int_of_string) | ':' -> COLON | '.' -> DOT | "->" -> ARROW | '(' -> LPARENS | ')' -> RPARENS | any -> if lexeme buf = "λ" then LAMBDA else raise Invalid_token | eof -> EOF | _ -> assert false let provider buf () = let token = tokenizer buf in let start, stop = Sedlexing.lexing_positions buf in (token, start, stop) let from_string f string = provider (from_string string) |> MenhirLib.Convert.Simplified.traditional2revised f
null
https://raw.githubusercontent.com/EduardoRFS/youtube-channel/941601eabd919edada81660ba6f7eff5ab15cccc/13-parser-for-kids-in-ocaml-with-menhir/code/lexer.ml
ocaml
open Sedlexing.Utf8 open Parser exception Invalid_token let whitespace = [%sedlex.regexp? Plus (' ' | '\n' | '\t')] let lower_alpha = [%sedlex.regexp? 'a' .. 'z'] let number = [%sedlex.regexp? '0' .. '9'] let ident = [%sedlex.regexp? lower_alpha, Star (lower_alpha | number | '_')] let int = [%sedlex.regexp? Plus number] let rec tokenizer buf = match%sedlex buf with | whitespace -> tokenizer buf | ident -> IDENT (lexeme buf) | int -> INT (lexeme buf |> int_of_string) | ':' -> COLON | '.' -> DOT | "->" -> ARROW | '(' -> LPARENS | ')' -> RPARENS | any -> if lexeme buf = "λ" then LAMBDA else raise Invalid_token | eof -> EOF | _ -> assert false let provider buf () = let token = tokenizer buf in let start, stop = Sedlexing.lexing_positions buf in (token, start, stop) let from_string f string = provider (from_string string) |> MenhirLib.Convert.Simplified.traditional2revised f