_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
c16f1e3c6e0717efc714625db4bb48cc50e9b890a327f7e7aa3d287fcd6cd8c5
semmons99/clojure-euler
prob-045.clj
problem 045 ; ; ; ; ; ; ; ; ; ; (use '[clojure.euler.helpers :only (triangles pentagonals hexagonals)]) (defn prob-045 [] (let [ts (apply sorted-set (take 100000 triangles)) ps (apply sorted-set (take 100000 pentagonals))] (second (filter #(and (ts %) (ps %)) (rest hexagonals)))))
null
https://raw.githubusercontent.com/semmons99/clojure-euler/3480bc313b9df7f282dadf6e0b48d96230f1bfc1/prob-045.clj
clojure
; ; ; ; ; ; ; ; ;
(use '[clojure.euler.helpers :only (triangles pentagonals hexagonals)]) (defn prob-045 [] (let [ts (apply sorted-set (take 100000 triangles)) ps (apply sorted-set (take 100000 pentagonals))] (second (filter #(and (ts %) (ps %)) (rest hexagonals)))))
c69d9658c210d70c142c03fc70332b113d0617f5d986793fe59e07b433fc9082
tmaciejewski/see
see_db_storage_ets.erl
-module(see_db_storage_ets). -behaviour(gen_server). -include_lib("see_db_records.hrl"). -export([start/0, stop/0, update_url/3, add_url/1, get_unvisited/0, set_unvisited/1, get_page/1, get_pages_from_index/1, get_words/1, get_page_count/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). start() -> case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of {ok, _} -> ok; {error, Reason} -> {error, Reason} end. stop() -> gen_server:call(?MODULE, stop). update_url(URL, Title, Words) -> gen_server:call(?MODULE, {update_url, URL, Title, Words}). add_url(URL) -> gen_server:call(?MODULE, {add_url, URL}). get_unvisited() -> gen_server:call(?MODULE, get_unvisited). set_unvisited(URL) -> gen_server:call(?MODULE, {set_unvisited, URL}). get_page(Id) -> gen_server:call(?MODULE, {get_page, Id}). get_pages_from_index(Word) -> gen_server:call(?MODULE, {get_pages_from_index, Word}). get_words(Id) -> gen_server:call(?MODULE, {get_words, Id}). get_page_count() -> gen_server:call(?MODULE, get_page_count). %%------------------------------------------------------------- init(_) -> ets:new(see_pages, [named_table, {keypos, #page.id}]), ets:new(see_index, [named_table, {keypos, #index.word}]), {ok, []}. terminate(_, _) -> ets:delete(see_index), ets:delete(see_pages). handle_call(stop, _, State) -> {stop, shutdown, ok, State}; handle_call({update_url, URL, Title, Words}, _, State) -> Id = erlang:phash2(URL), case remove_page(Id) of ok -> ets:insert(see_pages, #page{id = Id, url = URL, title = Title, content = Words}), insert_words_to_index(Words, Id), {reply, ok, State}; not_found -> {reply, not_found, State} end; handle_call({add_url, URL}, _, State) -> Id = erlang:phash2(URL), case ets:lookup(see_pages, Id) of [] -> ets:insert(see_pages, #page{id = Id, url = URL, last_visit = null}), {reply, ok, State}; _ -> {reply, ok, State} end; handle_call(get_unvisited, _, State) -> case ets:match_object(see_pages, #page{last_visit = null, _ = '_'}, 1) of {[Page = #page{url = URL}], _} -> ets:insert(see_pages, Page#page{last_visit = pending}), {reply, {ok, URL}, State}; '$end_of_table' -> {reply, nothing, State} end; handle_call({set_unvisited, URL}, _, State) -> Id = erlang:phash2(URL), case ets:lookup(see_pages, Id) of [Page = #page{last_visit = pending}] -> ets:insert(see_pages, Page#page{last_visit = null}), {reply, ok, State}; _ -> {reply, ok, State} end; handle_call({get_page, Id}, _, State) -> [#page{title = Title, url = URL}] = ets:lookup(see_pages, Id), {reply, {URL, Title}, State}; handle_call({get_pages_from_index, Word}, _, State) -> case ets:lookup(see_index, Word) of [] -> {reply, sets:new(), State}; [#index{pages = Pages}] -> {reply, Pages, State} end; handle_call({get_words, Id}, _, State) -> case ets:lookup(see_pages, Id) of [#page{content = Words}] when is_list(Words) -> {reply, Words, State}; _Other -> {reply, [], State} end; handle_call(get_page_count, _, State) -> {reply, ets:info(see_pages, size), State}. handle_cast(_, State) -> {noreply, State}. handle_info(_, State) -> {noreply, State}. code_change(_OldVsn, State, _) -> {ok, State}. remove_page(Id) -> case ets:lookup(see_pages, Id) of [#page{content = Words}] when is_list(Words) -> lists:foreach(fun(Word) -> remove_from_index(Word, Id) end, Words); [#page{last_visit = pending}] -> ok; _Other -> not_found end. remove_from_index(Word, Id) -> case ets:lookup(see_index, Word) of [] -> ok; [#index{pages = Pages}] -> ets:insert(see_index, #index{word = Word, pages = sets:del_element(Id, Pages)}) end. insert_words_to_index(Words, Id) when is_list(Words) -> lists:foreach(fun(Word) -> insert_word_to_index(Word, Id) end, Words); insert_words_to_index(_, _) -> ok. insert_word_to_index(Word, Id) -> case ets:lookup(see_index, Word) of [#index{pages = Pages}] -> ets:insert(see_index, #index{word = Word, pages = sets:add_element(Id, Pages)}); [] -> ets:insert(see_index, #index{word = Word, pages = sets:from_list([Id])}) end.
null
https://raw.githubusercontent.com/tmaciejewski/see/3838d06c291fe486a5b3634f1fedcd82336ed985/apps/db/src/see_db_storage_ets.erl
erlang
-------------------------------------------------------------
-module(see_db_storage_ets). -behaviour(gen_server). -include_lib("see_db_records.hrl"). -export([start/0, stop/0, update_url/3, add_url/1, get_unvisited/0, set_unvisited/1, get_page/1, get_pages_from_index/1, get_words/1, get_page_count/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). start() -> case gen_server:start({local, ?MODULE}, ?MODULE, [], []) of {ok, _} -> ok; {error, Reason} -> {error, Reason} end. stop() -> gen_server:call(?MODULE, stop). update_url(URL, Title, Words) -> gen_server:call(?MODULE, {update_url, URL, Title, Words}). add_url(URL) -> gen_server:call(?MODULE, {add_url, URL}). get_unvisited() -> gen_server:call(?MODULE, get_unvisited). set_unvisited(URL) -> gen_server:call(?MODULE, {set_unvisited, URL}). get_page(Id) -> gen_server:call(?MODULE, {get_page, Id}). get_pages_from_index(Word) -> gen_server:call(?MODULE, {get_pages_from_index, Word}). get_words(Id) -> gen_server:call(?MODULE, {get_words, Id}). get_page_count() -> gen_server:call(?MODULE, get_page_count). init(_) -> ets:new(see_pages, [named_table, {keypos, #page.id}]), ets:new(see_index, [named_table, {keypos, #index.word}]), {ok, []}. terminate(_, _) -> ets:delete(see_index), ets:delete(see_pages). handle_call(stop, _, State) -> {stop, shutdown, ok, State}; handle_call({update_url, URL, Title, Words}, _, State) -> Id = erlang:phash2(URL), case remove_page(Id) of ok -> ets:insert(see_pages, #page{id = Id, url = URL, title = Title, content = Words}), insert_words_to_index(Words, Id), {reply, ok, State}; not_found -> {reply, not_found, State} end; handle_call({add_url, URL}, _, State) -> Id = erlang:phash2(URL), case ets:lookup(see_pages, Id) of [] -> ets:insert(see_pages, #page{id = Id, url = URL, last_visit = null}), {reply, ok, State}; _ -> {reply, ok, State} end; handle_call(get_unvisited, _, State) -> case ets:match_object(see_pages, #page{last_visit = null, _ = '_'}, 1) of {[Page = #page{url = URL}], _} -> ets:insert(see_pages, Page#page{last_visit = pending}), {reply, {ok, URL}, State}; '$end_of_table' -> {reply, nothing, State} end; handle_call({set_unvisited, URL}, _, State) -> Id = erlang:phash2(URL), case ets:lookup(see_pages, Id) of [Page = #page{last_visit = pending}] -> ets:insert(see_pages, Page#page{last_visit = null}), {reply, ok, State}; _ -> {reply, ok, State} end; handle_call({get_page, Id}, _, State) -> [#page{title = Title, url = URL}] = ets:lookup(see_pages, Id), {reply, {URL, Title}, State}; handle_call({get_pages_from_index, Word}, _, State) -> case ets:lookup(see_index, Word) of [] -> {reply, sets:new(), State}; [#index{pages = Pages}] -> {reply, Pages, State} end; handle_call({get_words, Id}, _, State) -> case ets:lookup(see_pages, Id) of [#page{content = Words}] when is_list(Words) -> {reply, Words, State}; _Other -> {reply, [], State} end; handle_call(get_page_count, _, State) -> {reply, ets:info(see_pages, size), State}. handle_cast(_, State) -> {noreply, State}. handle_info(_, State) -> {noreply, State}. code_change(_OldVsn, State, _) -> {ok, State}. remove_page(Id) -> case ets:lookup(see_pages, Id) of [#page{content = Words}] when is_list(Words) -> lists:foreach(fun(Word) -> remove_from_index(Word, Id) end, Words); [#page{last_visit = pending}] -> ok; _Other -> not_found end. remove_from_index(Word, Id) -> case ets:lookup(see_index, Word) of [] -> ok; [#index{pages = Pages}] -> ets:insert(see_index, #index{word = Word, pages = sets:del_element(Id, Pages)}) end. insert_words_to_index(Words, Id) when is_list(Words) -> lists:foreach(fun(Word) -> insert_word_to_index(Word, Id) end, Words); insert_words_to_index(_, _) -> ok. insert_word_to_index(Word, Id) -> case ets:lookup(see_index, Word) of [#index{pages = Pages}] -> ets:insert(see_index, #index{word = Word, pages = sets:add_element(Id, Pages)}); [] -> ets:insert(see_index, #index{word = Word, pages = sets:from_list([Id])}) end.
1ef4bc564b752f6077086f522bbd2b4efa7256dd4cff5580be19b5b85e6615fb
rowangithub/DOrder
spam1.ml
let rec loopb i j len limit bufsize = if (i < len && j < limit) then ( let _ = assert (j >= 0) in if (i + 1 < len) then ( assert(i+1<len);(*//1*) assert(0<=i);(*//2//Interesting assert*) if (Random.bool ()) then (assert(i<len);(*//12*) assert(0<=i);(*//Really really interesting*) assert(j<bufsize);(*//13*) assert(0<=j); (*//14*) (*// buffer[j] = msg[i];*) let j = j+1 in let i = i+1 in loopb i j len limit bufsize) else (assert(i<len);(*//3*) assert(0<=i); (*//4*) //5 //Interesting Assert assert(0<=j); (*// buffer[j] = msg[i];*) let j = j + 1 in let i = i + 1 in let _ = assert(i<len) in(*//6*) let _ = assert(0<=i) in(*//7*) let _ = assert(j<bufsize) in(*//8 //Very intersting*) let _ = assert(0<=j) in (*//9*) (*// buffer[j] = msg[i];*) let j = j + 1 in let i = i + 1 in //10 let _ = assert(0<=j) in (*//11*) (*/* OK */ // buffer[j] = '.';*) let j = j + 1 in loopb i j len limit bufsize) ) else ( assert(i<len);(*//12*) assert(0<=i);(*//Really really interesting*) assert(j<bufsize);(*//13*) assert(0<=j); (*//14*) (*// buffer[j] = msg[i];*) let j = j+1 in let i = i+1 in loopb i j len limit bufsize ) ) else i let rec loopa i len limit bufsize = if (i < len) then let i = loopb i 0 len limit bufsize in loopa i len limit bufsize else () let main len bufsize = (* char buffer[BUFSZ];*) let limit = bufsize - 4 in loopa 0 len limit bufsize let _ = main 7 5 let _ = main 5 7 let _ = main 6 5 let _ = main 5 6 let _ = main (-5) (-5)
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/splitter/spam1.ml
ocaml
//1 //2//Interesting assert //12 //Really really interesting //13 //14 // buffer[j] = msg[i]; //3 //4 // buffer[j] = msg[i]; //6 //7 //8 //Very intersting //9 // buffer[j] = msg[i]; //11 /* OK */ // buffer[j] = '.'; //12 //Really really interesting //13 //14 // buffer[j] = msg[i]; char buffer[BUFSZ];
let rec loopb i j len limit bufsize = if (i < len && j < limit) then ( let _ = assert (j >= 0) in if (i + 1 < len) then ( if (Random.bool ()) then let j = j+1 in let i = i+1 in loopb i j len limit bufsize) else //5 //Interesting Assert assert(0<=j); let j = j + 1 in let i = i + 1 in let j = j + 1 in let i = i + 1 in //10 let j = j + 1 in loopb i j len limit bufsize) ) else ( let j = j+1 in let i = i+1 in loopb i j len limit bufsize ) ) else i let rec loopa i len limit bufsize = if (i < len) then let i = loopb i 0 len limit bufsize in loopa i len limit bufsize else () let main len bufsize = let limit = bufsize - 4 in loopa 0 len limit bufsize let _ = main 7 5 let _ = main 5 7 let _ = main 6 5 let _ = main 5 6 let _ = main (-5) (-5)
943765f545ee75548a9ca7e48157c338925cde12138767101e2f34d37af98825
clojure-interop/google-cloud-clients
SecurityCenterClient.clj
(ns com.google.cloud.securitycenter.v1beta1.SecurityCenterClient "Service Description: V1 Beta APIs for Security Center service. This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); Source source = Source.newBuilder().build(); Source response = securityCenterClient.createSource(parent, source); } Note: close() needs to be called on the securityCenterClient object to clean up resources such as threads. In the example above, try-with-resources is used, which automatically calls close(). The surface of this class includes several types of Java methods for each of the API's methods: A \"flattened\" method. With this type of method, the fields of the request type have been converted into function parameters. It may be the case that not all fields are available as parameters, and not every API method will have a flattened method entry point. A \"request object\" method. This type of method only takes one parameter, a request object, which must be constructed before the call. Not every API method will have a request object method. A \"callable\" method. This type of method takes no parameters and returns an immutable API callable object, which can be used to initiate calls to the service. See the individual methods for example code. Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parse method to extract the individual identifiers contained within names that are returned. This class can be customized by passing in a custom instance of SecurityCenterSettings to create(). For example: To customize credentials: SecurityCenterSettings securityCenterSettings = SecurityCenterSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) .build(); SecurityCenterClient securityCenterClient = SecurityCenterClient.create(securityCenterSettings); To customize the endpoint: SecurityCenterSettings securityCenterSettings = SecurityCenterSettings.newBuilder().setEndpoint(myEndpoint).build(); SecurityCenterClient securityCenterClient = SecurityCenterClient.create(securityCenterSettings);" (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.securitycenter.v1beta1 SecurityCenterClient])) (defn *create "Constructs an instance of SecurityCenterClient, using the given settings. The channels are created based on the settings passed in, or defaults for any settings that are not set. settings - `com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient` throws: java.io.IOException" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient [^com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings settings] (SecurityCenterClient/create settings)) (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient [] (SecurityCenterClient/create ))) (defn list-findings "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) .build(); for (Finding element : securityCenterClient.listFindings(request).iterateAll()) { // doThingsWith(element); } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.ListFindingsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.ListFindingsRequest request] (-> this (.listFindings request)))) (defn list-sources-paged-callable "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); ListSourcesRequest request = ListSourcesRequest.newBuilder() .setParent(parent.toString()) .build(); ApiFuture<ListSourcesPagedResponse> future = securityCenterClient.listSourcesPagedCallable().futureCall(request); // Do something for (Source element : future.get().iterateAll()) { // doThingsWith(element); } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListSourcesRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listSourcesPagedCallable)))) (defn get-iam-policy-callable "Gets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder() .setResource(resource.toString()) .build(); ApiFuture<Policy> future = securityCenterClient.getIamPolicyCallable().futureCall(request); // Do something Policy response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.GetIamPolicyRequest,com.google.iam.v1.Policy>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getIamPolicyCallable)))) (defn set-iam-policy "Sets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); Policy policy = Policy.newBuilder().build(); Policy response = securityCenterClient.setIamPolicy(resource, policy); } resource - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` policy - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. - `com.google.iam.v1.Policy` returns: `com.google.iam.v1.Policy` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource ^com.google.iam.v1.Policy policy] (-> this (.setIamPolicy resource policy))) (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.iam.v1.SetIamPolicyRequest request] (-> this (.setIamPolicy request)))) (defn update-source-callable "Updates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { Source source = Source.newBuilder().build(); UpdateSourceRequest request = UpdateSourceRequest.newBuilder() .setSource(source) .build(); ApiFuture<Source> future = securityCenterClient.updateSourceCallable().futureCall(request); // Do something Source response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateSourceCallable)))) (defn get-settings "returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings`" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings [^SecurityCenterClient this] (-> this (.getSettings)))) (defn update-organization-settings-callable "Updates an organization's settings. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationSettings organizationSettings = OrganizationSettings.newBuilder().build(); UpdateOrganizationSettingsRequest request = UpdateOrganizationSettingsRequest.newBuilder() .setOrganizationSettings(organizationSettings) .build(); ApiFuture<OrganizationSettings> future = securityCenterClient.updateOrganizationSettingsCallable().futureCall(request); // Do something OrganizationSettings response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateOrganizationSettingsRequest,com.google.cloud.securitycenter.v1beta1.OrganizationSettings>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateOrganizationSettingsCallable)))) (defn run-asset-discovery-callable "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); RunAssetDiscoveryRequest request = RunAssetDiscoveryRequest.newBuilder() .setParent(parent.toString()) .build(); ApiFuture<Operation> future = securityCenterClient.runAssetDiscoveryCallable().futureCall(request); // Do something future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest,com.google.longrunning.Operation>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.runAssetDiscoveryCallable)))) (defn list-findings-callable "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) .build(); while (true) { ListFindingsResponse response = securityCenterClient.listFindingsCallable().call(request); for (Finding element : response.getFindingsList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListFindingsRequest,com.google.cloud.securitycenter.v1beta1.ListFindingsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listFindingsCallable)))) (defn update-source "Updates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { Source source = Source.newBuilder().build(); Source response = securityCenterClient.updateSource(source); } source - The source resource to update. - `com.google.cloud.securitycenter.v1beta1.Source` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.Source source] (-> this (.updateSource source)))) (defn group-findings-paged-callable "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); String groupBy = \"\"; GroupFindingsRequest request = GroupFindingsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) .build(); ApiFuture<GroupFindingsPagedResponse> future = securityCenterClient.groupFindingsPagedCallable().futureCall(request); // Do something for (GroupResult element : future.get().iterateAll()) { // doThingsWith(element); } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupFindingsPagedCallable)))) (defn get-stub "returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.securitycenter.v1beta1.stub.SecurityCenterStub`" ([^SecurityCenterClient this] (-> this (.getStub)))) (defn run-asset-discovery-async "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); securityCenterClient.runAssetDiscoveryAsync(parent).get(); } parent - Name of the organization to run asset discovery for. Its format is \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.api.gax.longrunning.OperationFuture<com.google.protobuf.Empty,com.google.protobuf.Empty>` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" ([^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent] (-> this (.runAssetDiscoveryAsync parent)))) (defn update-finding-callable "Creates or updates a finding. The corresponding source must exist for a finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { Finding finding = Finding.newBuilder().build(); UpdateFindingRequest request = UpdateFindingRequest.newBuilder() .setFinding(finding) .build(); ApiFuture<Finding> future = securityCenterClient.updateFindingCallable().futureCall(request); // Do something Finding response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateFindingRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateFindingCallable)))) (defn shutdown? "returns: `boolean`" (^Boolean [^SecurityCenterClient this] (-> this (.isShutdown)))) (defn await-termination "duration - `long` unit - `java.util.concurrent.TimeUnit` returns: `boolean` throws: java.lang.InterruptedException" (^Boolean [^SecurityCenterClient this ^Long duration ^java.util.concurrent.TimeUnit unit] (-> this (.awaitTermination duration unit)))) (defn shutdown "" ([^SecurityCenterClient this] (-> this (.shutdown)))) (defn list-findings-paged-callable "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) .build(); ApiFuture<ListFindingsPagedResponse> future = securityCenterClient.listFindingsPagedCallable().futureCall(request); // Do something for (Finding element : future.get().iterateAll()) { // doThingsWith(element); } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListFindingsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listFindingsPagedCallable)))) (defn group-findings "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); String groupBy = \"\"; for (GroupResult element : securityCenterClient.groupFindings(parent, groupBy).iterateAll()) { // doThingsWith(element); } } parent - Name of the source to groupBy. Its format is \"organizations/[organization_id]/sources/[source_id]\". To groupBy across all sources provide a source_id of `-`. For example: organizations/123/sources/- - `com.google.cloud.securitycenter.v1beta1.SourceName` group-by - Expression that defines what assets fields to use for grouping (including `state`). The string value should follow SQL syntax: comma separated list of fields. For example: \"parent,resource_name\". The following fields are supported: * resource_name * category * state * parent - `java.lang.String` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName parent ^java.lang.String group-by] (-> this (.groupFindings parent group-by))) (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest request] (-> this (.groupFindings request)))) (defn list-assets-callable "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) .build(); while (true) { ListAssetsResponse response = securityCenterClient.listAssetsCallable().call(request); for (ListAssetsResponse.ListAssetsResult element : response.getListAssetsResultsList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListAssetsRequest,com.google.cloud.securitycenter.v1beta1.ListAssetsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listAssetsCallable)))) (defn get-source-callable "Gets a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName name = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); GetSourceRequest request = GetSourceRequest.newBuilder() .setName(name.toString()) .build(); ApiFuture<Source> future = securityCenterClient.getSourceCallable().futureCall(request); // Do something Source response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GetSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getSourceCallable)))) (defn get-source "Gets a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName name = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); Source response = securityCenterClient.getSource(name); } name - Relative resource name of the source. Its format is \"organizations/[organization_id]/source/[source_id]\". - `com.google.cloud.securitycenter.v1beta1.SourceName` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName name] (-> this (.getSource name)))) (defn update-organization-settings "Updates an organization's settings. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationSettings organizationSettings = OrganizationSettings.newBuilder().build(); OrganizationSettings response = securityCenterClient.updateOrganizationSettings(organizationSettings); } organization-settings - The organization settings resource to update. - `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` returns: `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.OrganizationSettings [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationSettings organization-settings] (-> this (.updateOrganizationSettings organization-settings)))) (defn group-assets-paged-callable "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); String groupBy = \"\"; GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) .build(); ApiFuture<GroupAssetsPagedResponse> future = securityCenterClient.groupAssetsPagedCallable().futureCall(request); // Do something for (GroupResult element : future.get().iterateAll()) { // doThingsWith(element); } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupAssetsPagedCallable)))) (defn update-security-marks "Updates security marks. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SecurityMarks securityMarks = SecurityMarks.newBuilder().build(); SecurityMarks response = securityCenterClient.updateSecurityMarks(securityMarks); } security-marks - The security marks resource to update. - `com.google.cloud.securitycenter.v1beta1.SecurityMarks` returns: `com.google.cloud.securitycenter.v1beta1.SecurityMarks` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityMarks [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SecurityMarks security-marks] (-> this (.updateSecurityMarks security-marks)))) (defn list-sources "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); for (Source element : securityCenterClient.listSources(parent).iterateAll()) { // doThingsWith(element); } } parent - Resource name of the parent of sources to list. Its format should be \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent] (-> this (.listSources parent)))) (defn get-operations-client "Returns the OperationsClient that can be used to query the status of a long-running operation returned by another API method call. returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.longrunning.OperationsClient`" ([^SecurityCenterClient this] (-> this (.getOperationsClient)))) (defn run-asset-discovery-operation-callable "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); RunAssetDiscoveryRequest request = RunAssetDiscoveryRequest.newBuilder() .setParent(parent.toString()) .build(); OperationFuture<Empty, Empty> future = securityCenterClient.runAssetDiscoveryOperationCallable().futureCall(request); // Do something future.get(); } returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallable<com.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest,com.google.protobuf.Empty,com.google.protobuf.Empty>`" ([^SecurityCenterClient this] (-> this (.runAssetDiscoveryOperationCallable)))) (defn set-iam-policy-callable "Sets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); Policy policy = Policy.newBuilder().build(); SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setResource(resource.toString()) .setPolicy(policy) .build(); ApiFuture<Policy> future = securityCenterClient.setIamPolicyCallable().futureCall(request); // Do something Policy response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.SetIamPolicyRequest,com.google.iam.v1.Policy>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.setIamPolicyCallable)))) (defn update-finding "Creates or updates a finding. The corresponding source must exist for a finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { Finding finding = Finding.newBuilder().build(); Finding response = securityCenterClient.updateFinding(finding); } finding - The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. In the case of creation, the finding id portion of the name must alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - `com.google.cloud.securitycenter.v1beta1.Finding` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.Finding finding] (-> this (.updateFinding finding)))) (defn close "" ([^SecurityCenterClient this] (-> this (.close)))) (defn test-iam-permissions-callable "Returns the permissions that a caller has on the specified source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); List<String> permissions = new ArrayList<>(); TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource(resource.toString()) .addAllPermissions(permissions) .build(); ApiFuture<TestIamPermissionsResponse> future = securityCenterClient.testIamPermissionsCallable().futureCall(request); // Do something TestIamPermissionsResponse response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.TestIamPermissionsRequest,com.google.iam.v1.TestIamPermissionsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.testIamPermissionsCallable)))) (defn update-security-marks-callable "Updates security marks. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SecurityMarks securityMarks = SecurityMarks.newBuilder().build(); UpdateSecurityMarksRequest request = UpdateSecurityMarksRequest.newBuilder() .setSecurityMarks(securityMarks) .build(); ApiFuture<SecurityMarks> future = securityCenterClient.updateSecurityMarksCallable().futureCall(request); // Do something SecurityMarks response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateSecurityMarksRequest,com.google.cloud.securitycenter.v1beta1.SecurityMarks>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateSecurityMarksCallable)))) (defn get-iam-policy "Gets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); Policy response = securityCenterClient.getIamPolicy(resource); } resource - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` returns: `com.google.iam.v1.Policy` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource] (-> this (.getIamPolicy resource)))) (defn group-assets "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); String groupBy = \"\"; GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) .build(); for (GroupResult element : securityCenterClient.groupAssets(request).iterateAll()) { // doThingsWith(element); } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest request] (-> this (.groupAssets request)))) (defn list-assets "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) .build(); for (ListAssetsResponse.ListAssetsResult element : securityCenterClient.listAssets(request).iterateAll()) { // doThingsWith(element); } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.ListAssetsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.ListAssetsRequest request] (-> this (.listAssets request)))) (defn create-finding "Creates a finding. The corresponding source must exist for finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); String findingId = \"\"; Finding finding = Finding.newBuilder().build(); Finding response = securityCenterClient.createFinding(parent, findingId, finding); } parent - Resource name of the new finding's parent. Its format should be \"organizations/[organization_id]/sources/[source_id]\". - `com.google.cloud.securitycenter.v1beta1.SourceName` finding-id - Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - `java.lang.String` finding - The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. - `com.google.cloud.securitycenter.v1beta1.Finding` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName parent ^java.lang.String finding-id ^com.google.cloud.securitycenter.v1beta1.Finding finding] (-> this (.createFinding parent finding-id finding))) (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.CreateFindingRequest request] (-> this (.createFinding request)))) (defn create-source "Creates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); Source source = Source.newBuilder().build(); Source response = securityCenterClient.createSource(parent, source); } parent - Resource name of the new source's parent. Its format should be \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` source - The Source being created, only the display_name and description will be used. All other fields will be ignored. - `com.google.cloud.securitycenter.v1beta1.Source` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent ^com.google.cloud.securitycenter.v1beta1.Source source] (-> this (.createSource parent source))) (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.CreateSourceRequest request] (-> this (.createSource request)))) (defn terminated? "returns: `boolean`" (^Boolean [^SecurityCenterClient this] (-> this (.isTerminated)))) (defn group-findings-callable "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); String groupBy = \"\"; GroupFindingsRequest request = GroupFindingsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) .build(); while (true) { GroupFindingsResponse response = securityCenterClient.groupFindingsCallable().call(request); for (GroupResult element : response.getGroupByResultsList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest,com.google.cloud.securitycenter.v1beta1.GroupFindingsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupFindingsCallable)))) (defn create-source-callable "Creates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); Source source = Source.newBuilder().build(); CreateSourceRequest request = CreateSourceRequest.newBuilder() .setParent(parent.toString()) .setSource(source) .build(); ApiFuture<Source> future = securityCenterClient.createSourceCallable().futureCall(request); // Do something Source response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.CreateSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.createSourceCallable)))) (defn get-organization-settings "Gets the settings for an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationSettingsName name = OrganizationSettingsName.of(\"[ORGANIZATION]\"); OrganizationSettings response = securityCenterClient.getOrganizationSettings(name); } name - Name of the organization to get organization settings for. Its format is \"organizations/[organization_id]/organizationSettings\". - `com.google.cloud.securitycenter.v1beta1.OrganizationSettingsName` returns: `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.OrganizationSettings [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationSettingsName name] (-> this (.getOrganizationSettings name)))) (defn list-sources-callable "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); ListSourcesRequest request = ListSourcesRequest.newBuilder() .setParent(parent.toString()) .build(); while (true) { ListSourcesResponse response = securityCenterClient.listSourcesCallable().call(request); for (Source element : response.getSourcesList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListSourcesRequest,com.google.cloud.securitycenter.v1beta1.ListSourcesResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listSourcesCallable)))) (defn group-assets-callable "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); String groupBy = \"\"; GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) .build(); while (true) { GroupAssetsResponse response = securityCenterClient.groupAssetsCallable().call(request); for (GroupResult element : response.getGroupByResultsList()) { // doThingsWith(element); } String nextPageToken = response.getNextPageToken(); if (!Strings.isNullOrEmpty(nextPageToken)) { request = request.toBuilder().setPageToken(nextPageToken).build(); } else { break; } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest,com.google.cloud.securitycenter.v1beta1.GroupAssetsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupAssetsCallable)))) (defn set-finding-state-callable "Updates the state of a finding. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { FindingName name = FindingName.of(\"[ORGANIZATION]\", \"[SOURCE]\", \"[FINDING]\"); Finding.State state = Finding.State.STATE_UNSPECIFIED; Timestamp startTime = Timestamp.newBuilder().build(); SetFindingStateRequest request = SetFindingStateRequest.newBuilder() .setName(name.toString()) .setState(state) .setStartTime(startTime) .build(); ApiFuture<Finding> future = securityCenterClient.setFindingStateCallable().futureCall(request); // Do something Finding response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.setFindingStateCallable)))) (defn create-finding-callable "Creates a finding. The corresponding source must exist for finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName parent = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); String findingId = \"\"; Finding finding = Finding.newBuilder().build(); CreateFindingRequest request = CreateFindingRequest.newBuilder() .setParent(parent.toString()) .setFindingId(findingId) .setFinding(finding) .build(); ApiFuture<Finding> future = securityCenterClient.createFindingCallable().futureCall(request); // Do something Finding response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.CreateFindingRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.createFindingCallable)))) (defn get-organization-settings-callable "Gets the settings for an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationSettingsName name = OrganizationSettingsName.of(\"[ORGANIZATION]\"); GetOrganizationSettingsRequest request = GetOrganizationSettingsRequest.newBuilder() .setName(name.toString()) .build(); ApiFuture<OrganizationSettings> future = securityCenterClient.getOrganizationSettingsCallable().futureCall(request); // Do something OrganizationSettings response = future.get(); } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GetOrganizationSettingsRequest,com.google.cloud.securitycenter.v1beta1.OrganizationSettings>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getOrganizationSettingsCallable)))) (defn list-assets-paged-callable "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { OrganizationName parent = OrganizationName.of(\"[ORGANIZATION]\"); ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) .build(); ApiFuture<ListAssetsPagedResponse> future = securityCenterClient.listAssetsPagedCallable().futureCall(request); // Do something for (ListAssetsResponse.ListAssetsResult element : future.get().iterateAll()) { // doThingsWith(element); } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListAssetsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listAssetsPagedCallable)))) (defn set-finding-state "Updates the state of a finding. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { FindingName name = FindingName.of(\"[ORGANIZATION]\", \"[SOURCE]\", \"[FINDING]\"); Finding.State state = Finding.State.STATE_UNSPECIFIED; Timestamp startTime = Timestamp.newBuilder().build(); Finding response = securityCenterClient.setFindingState(name, state, startTime); } name - The relative resource name of the finding. See: #relative_resource_name Example: \"organizations/123/sources/456/finding/789\". - `com.google.cloud.securitycenter.v1beta1.FindingName` state - The desired State of the finding. - `com.google.cloud.securitycenter.v1beta1.Finding$State` start-time - The time at which the updated state takes effect. - `com.google.protobuf.Timestamp` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.FindingName name ^com.google.cloud.securitycenter.v1beta1.Finding$State state ^com.google.protobuf.Timestamp start-time] (-> this (.setFindingState name state start-time))) (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest request] (-> this (.setFindingState request)))) (defn shutdown-now "" ([^SecurityCenterClient this] (-> this (.shutdownNow)))) (defn test-iam-permissions "Returns the permissions that a caller has on the specified source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SourceName resource = SourceName.of(\"[ORGANIZATION]\", \"[SOURCE]\"); List<String> permissions = new ArrayList<>(); TestIamPermissionsResponse response = securityCenterClient.testIamPermissions(resource, permissions); } resource - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` permissions - The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see [IAM Overview](#permissions). - `java.util.List` returns: `com.google.iam.v1.TestIamPermissionsResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.TestIamPermissionsResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource ^java.util.List permissions] (-> this (.testIamPermissions resource permissions))) (^com.google.iam.v1.TestIamPermissionsResponse [^SecurityCenterClient this ^com.google.iam.v1.TestIamPermissionsRequest request] (-> this (.testIamPermissions request))))
null
https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.securitycenter/src/com/google/cloud/securitycenter/v1beta1/SecurityCenterClient.clj
clojure
"
(ns com.google.cloud.securitycenter.v1beta1.SecurityCenterClient "Service Description: V1 Beta APIs for Security Center service. This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } Note: close() needs to be called on the securityCenterClient object to clean up resources such as threads. In the example above, try-with-resources is used, which automatically calls close(). The surface of this class includes several types of Java methods for each of the API's methods: A \"flattened\" method. With this type of method, the fields of the request type have been converted into function parameters. It may be the case that not all fields are available as parameters, and not every API method will have a flattened method entry point. A \"request object\" method. This type of method only takes one parameter, a request object, which must be constructed before the call. Not every API method will have a request object method. A \"callable\" method. This type of method takes no parameters and returns an immutable API callable object, which can be used to initiate calls to the service. See the individual methods for example code. Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parse method to extract the individual identifiers contained within names that are returned. This class can be customized by passing in a custom instance of SecurityCenterSettings to create(). For example: To customize credentials: SecurityCenterSettings securityCenterSettings = SecurityCenterSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) SecurityCenterClient securityCenterClient = To customize the endpoint: SecurityCenterSettings securityCenterSettings = SecurityCenterClient securityCenterClient = (:refer-clojure :only [require comment defn ->]) (:import [com.google.cloud.securitycenter.v1beta1 SecurityCenterClient])) (defn *create "Constructs an instance of SecurityCenterClient, using the given settings. The channels are created based on the settings passed in, or defaults for any settings that are not set. settings - `com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient` throws: java.io.IOException" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient [^com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings settings] (SecurityCenterClient/create settings)) (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient [] (SecurityCenterClient/create ))) (defn list-findings "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) for (Finding element : securityCenterClient.listFindings(request).iterateAll()) { } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.ListFindingsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.ListFindingsRequest request] (-> this (.listFindings request)))) (defn list-sources-paged-callable "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListSourcesRequest request = ListSourcesRequest.newBuilder() .setParent(parent.toString()) // Do something for (Source element : future.get().iterateAll()) { } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListSourcesRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listSourcesPagedCallable)))) (defn get-iam-policy-callable "Gets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder() .setResource(resource.toString()) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.GetIamPolicyRequest,com.google.iam.v1.Policy>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getIamPolicyCallable)))) (defn set-iam-policy "Sets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } resource - REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` policy - REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. - `com.google.iam.v1.Policy` returns: `com.google.iam.v1.Policy` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource ^com.google.iam.v1.Policy policy] (-> this (.setIamPolicy resource policy))) (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.iam.v1.SetIamPolicyRequest request] (-> this (.setIamPolicy request)))) (defn update-source-callable "Updates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { UpdateSourceRequest request = UpdateSourceRequest.newBuilder() .setSource(source) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateSourceCallable)))) (defn get-settings "returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings`" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterSettings [^SecurityCenterClient this] (-> this (.getSettings)))) (defn update-organization-settings-callable "Updates an organization's settings. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { UpdateOrganizationSettingsRequest request = UpdateOrganizationSettingsRequest.newBuilder() .setOrganizationSettings(organizationSettings) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateOrganizationSettingsRequest,com.google.cloud.securitycenter.v1beta1.OrganizationSettings>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateOrganizationSettingsCallable)))) (defn run-asset-discovery-callable "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { RunAssetDiscoveryRequest request = RunAssetDiscoveryRequest.newBuilder() .setParent(parent.toString()) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest,com.google.longrunning.Operation>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.runAssetDiscoveryCallable)))) (defn list-findings-callable "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) while (true) { for (Finding element : response.getFindingsList()) { } if (!Strings.isNullOrEmpty(nextPageToken)) { } else { } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListFindingsRequest,com.google.cloud.securitycenter.v1beta1.ListFindingsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listFindingsCallable)))) (defn update-source "Updates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } source - The source resource to update. - `com.google.cloud.securitycenter.v1beta1.Source` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.Source source] (-> this (.updateSource source)))) (defn group-findings-paged-callable "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GroupFindingsRequest request = GroupFindingsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) // Do something for (GroupResult element : future.get().iterateAll()) { } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupFindingsPagedCallable)))) (defn get-stub "returns: `(value="A restructuring of stub classes is planned, so this may break in the future") com.google.cloud.securitycenter.v1beta1.stub.SecurityCenterStub`" ([^SecurityCenterClient this] (-> this (.getStub)))) (defn run-asset-discovery-async "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } parent - Name of the organization to run asset discovery for. Its format is \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.api.gax.longrunning.OperationFuture<com.google.protobuf.Empty,com.google.protobuf.Empty>` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" ([^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent] (-> this (.runAssetDiscoveryAsync parent)))) (defn update-finding-callable "Creates or updates a finding. The corresponding source must exist for a finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { UpdateFindingRequest request = UpdateFindingRequest.newBuilder() .setFinding(finding) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateFindingRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateFindingCallable)))) (defn shutdown? "returns: `boolean`" (^Boolean [^SecurityCenterClient this] (-> this (.isShutdown)))) (defn await-termination "duration - `long` unit - `java.util.concurrent.TimeUnit` returns: `boolean` throws: java.lang.InterruptedException" (^Boolean [^SecurityCenterClient this ^Long duration ^java.util.concurrent.TimeUnit unit] (-> this (.awaitTermination duration unit)))) (defn shutdown "" ([^SecurityCenterClient this] (-> this (.shutdown)))) (defn list-findings-paged-callable "Lists an organization or source's findings. To list across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListFindingsRequest request = ListFindingsRequest.newBuilder() .setParent(parent.toString()) // Do something for (Finding element : future.get().iterateAll()) { } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListFindingsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListFindingsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listFindingsPagedCallable)))) (defn group-findings "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { for (GroupResult element : securityCenterClient.groupFindings(parent, groupBy).iterateAll()) { } } parent - Name of the source to groupBy. Its format is \"organizations/[organization_id]/sources/[source_id]\". To groupBy across all sources provide a source_id of `-`. For example: organizations/123/sources/- - `com.google.cloud.securitycenter.v1beta1.SourceName` group-by - Expression that defines what assets fields to use for grouping (including `state`). The string value should follow SQL syntax: comma separated list of fields. For example: \"parent,resource_name\". The following fields are supported: * resource_name * category * state * parent - `java.lang.String` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName parent ^java.lang.String group-by] (-> this (.groupFindings parent group-by))) (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupFindingsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest request] (-> this (.groupFindings request)))) (defn list-assets-callable "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) while (true) { for (ListAssetsResponse.ListAssetsResult element : response.getListAssetsResultsList()) { } if (!Strings.isNullOrEmpty(nextPageToken)) { } else { } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListAssetsRequest,com.google.cloud.securitycenter.v1beta1.ListAssetsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listAssetsCallable)))) (defn get-source-callable "Gets a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GetSourceRequest request = GetSourceRequest.newBuilder() .setName(name.toString()) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GetSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getSourceCallable)))) (defn get-source "Gets a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } name - Relative resource name of the source. Its format is \"organizations/[organization_id]/source/[source_id]\". - `com.google.cloud.securitycenter.v1beta1.SourceName` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName name] (-> this (.getSource name)))) (defn update-organization-settings "Updates an organization's settings. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } organization-settings - The organization settings resource to update. - `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` returns: `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.OrganizationSettings [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationSettings organization-settings] (-> this (.updateOrganizationSettings organization-settings)))) (defn group-assets-paged-callable "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) // Do something for (GroupResult element : future.get().iterateAll()) { } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupAssetsPagedCallable)))) (defn update-security-marks "Updates security marks. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } security-marks - The security marks resource to update. - `com.google.cloud.securitycenter.v1beta1.SecurityMarks` returns: `com.google.cloud.securitycenter.v1beta1.SecurityMarks` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityMarks [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SecurityMarks security-marks] (-> this (.updateSecurityMarks security-marks)))) (defn list-sources "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { for (Source element : securityCenterClient.listSources(parent).iterateAll()) { } } parent - Resource name of the parent of sources to list. Its format should be \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListSourcesPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent] (-> this (.listSources parent)))) (defn get-operations-client "Returns the OperationsClient that can be used to query the status of a long-running operation returned by another API method call. returns: `(value="The surface for long-running operations is not stable yet and may change in the future.") com.google.longrunning.OperationsClient`" ([^SecurityCenterClient this] (-> this (.getOperationsClient)))) (defn run-asset-discovery-operation-callable "Runs asset discovery. The discovery is tracked with a long-running operation. This API can only be called with limited frequency for an organization. If it is called too frequently the caller will receive a TOO_MANY_REQUESTS error. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { RunAssetDiscoveryRequest request = RunAssetDiscoveryRequest.newBuilder() .setParent(parent.toString()) // Do something } returns: `(value="The surface for use by generated code is not stable yet and may change in the future.") com.google.api.gax.rpc.OperationCallable<com.google.cloud.securitycenter.v1beta1.RunAssetDiscoveryRequest,com.google.protobuf.Empty,com.google.protobuf.Empty>`" ([^SecurityCenterClient this] (-> this (.runAssetDiscoveryOperationCallable)))) (defn set-iam-policy-callable "Sets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setResource(resource.toString()) .setPolicy(policy) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.SetIamPolicyRequest,com.google.iam.v1.Policy>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.setIamPolicyCallable)))) (defn update-finding "Creates or updates a finding. The corresponding source must exist for a finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } finding - The finding resource to update or create if it does not already exist. parent, security_marks, and update_time will be ignored. In the case of creation, the finding id portion of the name must alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - `com.google.cloud.securitycenter.v1beta1.Finding` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.Finding finding] (-> this (.updateFinding finding)))) (defn close "" ([^SecurityCenterClient this] (-> this (.close)))) (defn test-iam-permissions-callable "Returns the permissions that a caller has on the specified source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource(resource.toString()) .addAllPermissions(permissions) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.iam.v1.TestIamPermissionsRequest,com.google.iam.v1.TestIamPermissionsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.testIamPermissionsCallable)))) (defn update-security-marks-callable "Updates security marks. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { UpdateSecurityMarksRequest request = UpdateSecurityMarksRequest.newBuilder() .setSecurityMarks(securityMarks) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.UpdateSecurityMarksRequest,com.google.cloud.securitycenter.v1beta1.SecurityMarks>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.updateSecurityMarksCallable)))) (defn get-iam-policy "Gets the access control policy on the specified Source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } resource - REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` returns: `com.google.iam.v1.Policy` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.Policy [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource] (-> this (.getIamPolicy resource)))) (defn group-assets "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) for (GroupResult element : securityCenterClient.groupAssets(request).iterateAll()) { } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$GroupAssetsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest request] (-> this (.groupAssets request)))) (defn list-assets "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) for (ListAssetsResponse.ListAssetsResult element : securityCenterClient.listAssets(request).iterateAll()) { } } request - The request object containing all of the parameters for the API call. - `com.google.cloud.securitycenter.v1beta1.ListAssetsRequest` returns: `com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.ListAssetsRequest request] (-> this (.listAssets request)))) (defn create-finding "Creates a finding. The corresponding source must exist for finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } parent - Resource name of the new finding's parent. Its format should be \"organizations/[organization_id]/sources/[source_id]\". - `com.google.cloud.securitycenter.v1beta1.SourceName` finding-id - Unique identifier provided by the client within the parent scope. It must be alphanumeric and less than or equal to 32 characters and greater than 0 characters in length. - `java.lang.String` finding - The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. - `com.google.cloud.securitycenter.v1beta1.Finding` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName parent ^java.lang.String finding-id ^com.google.cloud.securitycenter.v1beta1.Finding finding] (-> this (.createFinding parent finding-id finding))) (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.CreateFindingRequest request] (-> this (.createFinding request)))) (defn create-source "Creates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } parent - Resource name of the new source's parent. Its format should be \"organizations/[organization_id]\". - `com.google.cloud.securitycenter.v1beta1.OrganizationName` source - The Source being created, only the display_name and description will be used. All other fields will be ignored. - `com.google.cloud.securitycenter.v1beta1.Source` returns: `com.google.cloud.securitycenter.v1beta1.Source` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationName parent ^com.google.cloud.securitycenter.v1beta1.Source source] (-> this (.createSource parent source))) (^com.google.cloud.securitycenter.v1beta1.Source [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.CreateSourceRequest request] (-> this (.createSource request)))) (defn terminated? "returns: `boolean`" (^Boolean [^SecurityCenterClient this] (-> this (.isTerminated)))) (defn group-findings-callable "Filters an organization or source's findings and groups them by their specified properties. To group across all sources provide a `-` as the source id. Example: /v1beta1/organizations/123/sources/-/findings Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GroupFindingsRequest request = GroupFindingsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) while (true) { for (GroupResult element : response.getGroupByResultsList()) { } if (!Strings.isNullOrEmpty(nextPageToken)) { } else { } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupFindingsRequest,com.google.cloud.securitycenter.v1beta1.GroupFindingsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupFindingsCallable)))) (defn create-source-callable "Creates a source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { CreateSourceRequest request = CreateSourceRequest.newBuilder() .setParent(parent.toString()) .setSource(source) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.CreateSourceRequest,com.google.cloud.securitycenter.v1beta1.Source>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.createSourceCallable)))) (defn get-organization-settings "Gets the settings for an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } name - Name of the organization to get organization settings for. Its format is \"organizations/[organization_id]/organizationSettings\". - `com.google.cloud.securitycenter.v1beta1.OrganizationSettingsName` returns: `com.google.cloud.securitycenter.v1beta1.OrganizationSettings` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.OrganizationSettings [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.OrganizationSettingsName name] (-> this (.getOrganizationSettings name)))) (defn list-sources-callable "Lists all sources belonging to an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListSourcesRequest request = ListSourcesRequest.newBuilder() .setParent(parent.toString()) while (true) { for (Source element : response.getSourcesList()) { } if (!Strings.isNullOrEmpty(nextPageToken)) { } else { } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListSourcesRequest,com.google.cloud.securitycenter.v1beta1.ListSourcesResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listSourcesCallable)))) (defn group-assets-callable "Filters an organization's assets and groups them by their specified properties. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GroupAssetsRequest request = GroupAssetsRequest.newBuilder() .setParent(parent.toString()) .setGroupBy(groupBy) while (true) { for (GroupResult element : response.getGroupByResultsList()) { } if (!Strings.isNullOrEmpty(nextPageToken)) { } else { } } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GroupAssetsRequest,com.google.cloud.securitycenter.v1beta1.GroupAssetsResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.groupAssetsCallable)))) (defn set-finding-state-callable "Updates the state of a finding. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { SetFindingStateRequest request = SetFindingStateRequest.newBuilder() .setName(name.toString()) .setState(state) .setStartTime(startTime) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.setFindingStateCallable)))) (defn create-finding-callable "Creates a finding. The corresponding source must exist for finding creation to succeed. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { CreateFindingRequest request = CreateFindingRequest.newBuilder() .setParent(parent.toString()) .setFindingId(findingId) .setFinding(finding) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.CreateFindingRequest,com.google.cloud.securitycenter.v1beta1.Finding>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.createFindingCallable)))) (defn get-organization-settings-callable "Gets the settings for an organization. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { GetOrganizationSettingsRequest request = GetOrganizationSettingsRequest.newBuilder() .setName(name.toString()) // Do something } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.GetOrganizationSettingsRequest,com.google.cloud.securitycenter.v1beta1.OrganizationSettings>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.getOrganizationSettingsCallable)))) (defn list-assets-paged-callable "Lists an organization's assets. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { ListAssetsRequest request = ListAssetsRequest.newBuilder() .setParent(parent.toString()) // Do something for (ListAssetsResponse.ListAssetsResult element : future.get().iterateAll()) { } } returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.securitycenter.v1beta1.ListAssetsRequest,com.google.cloud.securitycenter.v1beta1.SecurityCenterClient$ListAssetsPagedResponse>`" (^com.google.api.gax.rpc.UnaryCallable [^SecurityCenterClient this] (-> this (.listAssetsPagedCallable)))) (defn set-finding-state "Updates the state of a finding. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } name - The relative resource name of the finding. See: #relative_resource_name Example: \"organizations/123/sources/456/finding/789\". - `com.google.cloud.securitycenter.v1beta1.FindingName` state - The desired State of the finding. - `com.google.cloud.securitycenter.v1beta1.Finding$State` start-time - The time at which the updated state takes effect. - `com.google.protobuf.Timestamp` returns: `com.google.cloud.securitycenter.v1beta1.Finding` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.FindingName name ^com.google.cloud.securitycenter.v1beta1.Finding$State state ^com.google.protobuf.Timestamp start-time] (-> this (.setFindingState name state start-time))) (^com.google.cloud.securitycenter.v1beta1.Finding [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SetFindingStateRequest request] (-> this (.setFindingState request)))) (defn shutdown-now "" ([^SecurityCenterClient this] (-> this (.shutdownNow)))) (defn test-iam-permissions "Returns the permissions that a caller has on the specified source. Sample code: try (SecurityCenterClient securityCenterClient = SecurityCenterClient.create()) { } resource - REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. - `com.google.cloud.securitycenter.v1beta1.SourceName` permissions - The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see [IAM Overview](#permissions). - `java.util.List` returns: `com.google.iam.v1.TestIamPermissionsResponse` throws: com.google.api.gax.rpc.ApiException - if the remote call fails" (^com.google.iam.v1.TestIamPermissionsResponse [^SecurityCenterClient this ^com.google.cloud.securitycenter.v1beta1.SourceName resource ^java.util.List permissions] (-> this (.testIamPermissions resource permissions))) (^com.google.iam.v1.TestIamPermissionsResponse [^SecurityCenterClient this ^com.google.iam.v1.TestIamPermissionsRequest request] (-> this (.testIamPermissions request))))
9b0feb5eb81ad1644f78d2c3228863a129ee321ab1c47f0e153ac6195aef1253
day8/de-dupe
bench.cljs
(ns de-dupe.test.core (:require [de-dupe.core :as dd])) (enable-console-print!) (defn random-map [] (let [constant-list (doall (range 100))] (into [] (take 100 (repeatedly (fn [] {:non-cached (rand-int 100) :long-list constant-list})))))) ; (print (random-map)) (def large (doall (take 10 (repeatedly random-map)))) (print "length of string representation" (count (prn-str large))) (print "******* about to create-cache *******") (time (def cache (dd/de-dupe large))) (print "******* finished create-cache ******") (print "length of de-duped string representation" (count (prn-str cache))) (print "******* about to create-eq-cache *******") (time (def eq-cache (dd/de-dupe-eq large))) (print "******* finished create-eq-cache ******") (print "length of de-duped eq string representation" (count (prn-str eq-cache))) (print "******* about to decompress *******") (time (def round-tripped (expand cache))) (print "******* finished decompress ******")
null
https://raw.githubusercontent.com/day8/de-dupe/932a03e1c12f8690ce753b2fe639719a7fe5072f/bench/de_dupe/bench.cljs
clojure
(print (random-map))
(ns de-dupe.test.core (:require [de-dupe.core :as dd])) (enable-console-print!) (defn random-map [] (let [constant-list (doall (range 100))] (into [] (take 100 (repeatedly (fn [] {:non-cached (rand-int 100) :long-list constant-list})))))) (def large (doall (take 10 (repeatedly random-map)))) (print "length of string representation" (count (prn-str large))) (print "******* about to create-cache *******") (time (def cache (dd/de-dupe large))) (print "******* finished create-cache ******") (print "length of de-duped string representation" (count (prn-str cache))) (print "******* about to create-eq-cache *******") (time (def eq-cache (dd/de-dupe-eq large))) (print "******* finished create-eq-cache ******") (print "length of de-duped eq string representation" (count (prn-str eq-cache))) (print "******* about to decompress *******") (time (def round-tripped (expand cache))) (print "******* finished decompress ******")
81de24f11009f81b02438e89db7838d83666b72cbdc8d4913f987e5bd47eb78d
conwaysgame/guile
gameoflife-test.scm
(use-modules (srfi srfi-64) ((game-of-life) #:renamer (symbol-prefix-proc 'gol:))) (test-begin "game_logic") ;still life: (define loaf (gol:new-instance gol:game-of-life)) (gol:send 'setgrid! loaf (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) (gol:send 'step! loaf) (test-equal "loaf at t = 1" (gol:send 'getgrid loaf) (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) ;oscillator: (define toad (gol:new-instance gol:game-of-life)) (gol:send 'setgrid! toad (list (list 0 0 1 0) (list 1 0 0 1) (list 1 0 0 1) (list 0 1 0 0))) (gol:send 'step! toad) (test-equal "toad at t = 1" (gol:send 'getgrid toad) (list (list 0 0 0 0) (list 0 1 1 1) (list 1 1 1 0) (list 0 0 0 0))) (gol:send 'step! toad) (test-equal "toad at t = 2" (gol:send 'getgrid toad) (list (list 0 0 1 0) (list 1 0 0 1) (list 1 0 0 1) (list 0 1 0 0))) (test-end "game_logic") (test-begin "utility_functions") ;pretty printing (define loaf-grid (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) (test-equal "pretty print works with custom dead/alive chars" (gol:pretty-print-grid loaf-grid #\x #\o) "oxxo\nxoox\noxox\nooxo") ;loading from file (define basic-grid (gol:grid-from-file "datasets/3x3.txt")) (test-equal "loading a grid from file works" basic-grid (list (list 0 0 1) (list 1 1 0) (list 0 1 0))) (test-end "utility_functions")
null
https://raw.githubusercontent.com/conwaysgame/guile/49ceb01ed58248f0ff3155bc3ff40e9a495ed248/gameoflife-test.scm
scheme
still life: oscillator: pretty printing loading from file
(use-modules (srfi srfi-64) ((game-of-life) #:renamer (symbol-prefix-proc 'gol:))) (test-begin "game_logic") (define loaf (gol:new-instance gol:game-of-life)) (gol:send 'setgrid! loaf (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) (gol:send 'step! loaf) (test-equal "loaf at t = 1" (gol:send 'getgrid loaf) (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) (define toad (gol:new-instance gol:game-of-life)) (gol:send 'setgrid! toad (list (list 0 0 1 0) (list 1 0 0 1) (list 1 0 0 1) (list 0 1 0 0))) (gol:send 'step! toad) (test-equal "toad at t = 1" (gol:send 'getgrid toad) (list (list 0 0 0 0) (list 0 1 1 1) (list 1 1 1 0) (list 0 0 0 0))) (gol:send 'step! toad) (test-equal "toad at t = 2" (gol:send 'getgrid toad) (list (list 0 0 1 0) (list 1 0 0 1) (list 1 0 0 1) (list 0 1 0 0))) (test-end "game_logic") (test-begin "utility_functions") (define loaf-grid (list (list 0 1 1 0) (list 1 0 0 1) (list 0 1 0 1) (list 0 0 1 0))) (test-equal "pretty print works with custom dead/alive chars" (gol:pretty-print-grid loaf-grid #\x #\o) "oxxo\nxoox\noxox\nooxo") (define basic-grid (gol:grid-from-file "datasets/3x3.txt")) (test-equal "loading a grid from file works" basic-grid (list (list 0 0 1) (list 1 1 0) (list 0 1 0))) (test-end "utility_functions")
9f6e2e56894fb43bac13fee807482c7f3c8b8e9db2d676d8ac34e6adb3e04d2a
simplex-chat/simplex-chat
M20220224_messages_fks.hs
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20220224_messages_fks where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220224_messages_fks :: Query m20220224_messages_fks = [sql| ALTER TABLE messages ADD COLUMN connection_id INTEGER DEFAULT NULL REFERENCES connections ON DELETE CASCADE; ALTER TABLE messages ADD COLUMN group_id INTEGER DEFAULT NULL REFERENCES groups ON DELETE CASCADE; |]
null
https://raw.githubusercontent.com/simplex-chat/simplex-chat/4b39de6c4fdec8d7795b2e7eb457b5661e77aa9b/src/Simplex/Chat/Migrations/M20220224_messages_fks.hs
haskell
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20220224_messages_fks where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220224_messages_fks :: Query m20220224_messages_fks = [sql| ALTER TABLE messages ADD COLUMN connection_id INTEGER DEFAULT NULL REFERENCES connections ON DELETE CASCADE; ALTER TABLE messages ADD COLUMN group_id INTEGER DEFAULT NULL REFERENCES groups ON DELETE CASCADE; |]
27e392b1ebb8517c0dfc20064ced0557c62e1d6583ccfc7fecf5139986f999f6
siclait/6.824-cljlabs-2020
crash.clj
(ns map-reduce.plugin.crash (:require [clojure.string :as string] [map-reduce.plugin :as plugin])) (defn maybe-crash [] (let [max 1000 rr (rand-int max)] (cond (< rr 330) (System/exit 1) (< rr 660) (let [max-ms (* 10 1000) ms (rand-int max-ms)] (Thread/sleep ms))))) (defn mapf [filename contents] (maybe-crash) [{:key "a" :value filename} {:key "b" :value (count filename)} {:key "c" :value (count contents)} {:key "d" :value "xyzzy"}]) (defn reducef [_ vs] (maybe-crash) (string/join " " (sort vs))) (defmethod plugin/load-plugin :crash [_] {:mapf mapf :reducef reducef})
null
https://raw.githubusercontent.com/siclait/6.824-cljlabs-2020/0c7ad7ae07d7617b1eb7240080c65f1937ca8a2d/map-reduce/src/map_reduce/plugin/crash.clj
clojure
(ns map-reduce.plugin.crash (:require [clojure.string :as string] [map-reduce.plugin :as plugin])) (defn maybe-crash [] (let [max 1000 rr (rand-int max)] (cond (< rr 330) (System/exit 1) (< rr 660) (let [max-ms (* 10 1000) ms (rand-int max-ms)] (Thread/sleep ms))))) (defn mapf [filename contents] (maybe-crash) [{:key "a" :value filename} {:key "b" :value (count filename)} {:key "c" :value (count contents)} {:key "d" :value "xyzzy"}]) (defn reducef [_ vs] (maybe-crash) (string/join " " (sort vs))) (defmethod plugin/load-plugin :crash [_] {:mapf mapf :reducef reducef})
027ffc4db751130b5ac325603310864b10e7d4620cc5ec2626e7abfc0bfa7ebd
racket/typed-racket
sqrt.rkt
#;#; #<<END TR opt: sqrt.rkt 4:2 (sqrt x) -- unary float END "" #lang typed/scheme #:optimize #reader typed-racket-test/optimizer/reset-port (: f (Nonnegative-Float -> Nonnegative-Float)) (define (f x) (sqrt x))
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/optimizer/tests/sqrt.rkt
racket
#;
#<<END TR opt: sqrt.rkt 4:2 (sqrt x) -- unary float END "" #lang typed/scheme #:optimize #reader typed-racket-test/optimizer/reset-port (: f (Nonnegative-Float -> Nonnegative-Float)) (define (f x) (sqrt x))
4d10fdccad2465466f8c3245638f520db48494f2f16bd5dab83e1f3a38821f19
plumatic/grab-bag
messages.clj
(ns domain.messages "Definitions for messages involving docs and shares that are passed between services." (:use plumbing.core) (:require [schema.core :as s] [schema.utils :as schema-utils] [plumbing.logging :as log] [domain.docs :as docs] [domain.docs.core :as docs-core] [domain.docs.actions :as actions] [domain.docs.comments :as comments] domain.docs.external-shares [domain.docs.fitness-stats :as fitness-stats] [domain.docs.tags :as tags] [domain.docs.views-by-client :as views-by-client]) (:import [domain.docs Doc] [domain.docs.actions SimpleAction] [domain.docs.comments Comment] [domain.docs.external_shares ExternalShares])) (set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; helpers for doc-hints (s/defschema DocHints (s/maybe {s/Any s/Any})) (defn write-doc-hints [doc-hints] (update-in-when doc-hints [:fitness-stats] fitness-stats/write-fitness-stats)) (defn read-doc-hints [doc-hints] (update-in-when doc-hints [:fitness-stats] fitness-stats/read-fitness-stats)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; new-shares messages: doc-poller --> doc-poller (internal, plus persisted in URL cache) (s/defschema NewSharesMessage {:action (s/eq :new-shares) :url String ;; possibly resolved. :doc-hints DocHints :external-shares ExternalShares}) (s/defn ^:always-validate new-shares-message :- NewSharesMessage [possibly-resolved-url doc-hints external-shares] {:action :new-shares :url possibly-resolved-url ;; used in both ways in different places. :doc-hints doc-hints :external-shares external-shares}) (s/defn ^:always-validate write-new-shares-message [message :- NewSharesMessage] (-> message (update-in [:doc-hints] write-doc-hints) (dissoc :external-shares) (assoc :shares (docs/downgrade-and-write-shares (safe-get message :external-shares) nil)))) (s/defn read-new-shares-message :- NewSharesMessage [message] (letk [[action url doc-hints shares] message [external-shares activity] (docs/read-and-upgrade-shares shares)] (assert (= action :new-shares)) (assert (empty? activity)) (new-shares-message url (read-doc-hints doc-hints) external-shares))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; fetch-doc-message: doc-poller --> doc-fetcher (s/defschema FetchDocMessage {:action (s/eq :fetch-doc) :id long :url String :doc-hints DocHints}) (s/defn ^:always-validate fetch-doc-message :- FetchDocMessage [doc-id url doc-hints] {:action :fetch-doc :id doc-id :url url :doc-hints doc-hints}) (s/defn ^:always-validate write-fetch-doc-message [message :- FetchDocMessage] (update-in message [:doc-hints] write-doc-hints)) (s/defn read-fetch-doc-message :- FetchDocMessage [message] (update-in message [:doc-hints] read-doc-hints)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; doc-related messages used in index-master and api ;; doc-poller --> index-master --> api (defn add-external-shares-message [doc-id doc-hints external-shares] {:action :add-external-shares :id doc-id :doc-hints doc-hints :external-shares external-shares}) ;; doc-fetcher --> index-master --> api (defn add-doc-message [doc] {:action :add-doc :id (safe-get doc :id) :doc doc}) ;; index-master --> search-index (defn add-full-doc-message "Similar to add-doc-message, but includes fetched-page HTML data (from url-cache bucket)" [doc fetched-page] {:action :add-full-doc :id (safe-get doc :id) :doc doc :fetched-page fetched-page}) ;; index-master --> api only (defn delete-doc-message [doc-id] {:action :delete-doc :id doc-id}) (defn re-cluster-message [doc-id new-cluster-id] {:action :re-cluster :id doc-id :new-cluster-id new-cluster-id}) (s/defschema DocUpdate (->> Doc ^schema.core.Record (schema-utils/class-schema) .schema (map-keys (fn [k] (assert (s/specific-key? k)) (s/optional-key (s/explicit-schema-key k)))))) (s/defn ^:always-validate merge-doc-message "Nuclear option, not meant to be used in normal system operation. Can make arbitrary changes to docs: semantics is to replace entire provided top-level keys with new values, leaving other top-level keys alone." [doc-id :- long doc-update :- DocUpdate] (when-let [id (:id doc-update)] (assert (= id doc-id))) {:action :merge-doc :id doc-id :doc-update doc-update}) ;;; api --> index-master --> api NOTE : in - memory format different than wire , now grabbag only (s/defn add-activity-message [doc-id activity :- [SimpleAction]] {:action :add-activity :id doc-id :activity activity}) (s/defn ^:always-validate update-dwell-message [doc-id :- Long user-id :- Long date :- Long client-type :- docs-core/ActionClientType dwell-ms :- Long] {:action :update-dwell :id doc-id :user-id user-id :date date :client-type client-type :dwell-ms dwell-ms}) (defn delete-activity-message [doc-id activity-ids] {:action :delete-activity :id doc-id :activity-ids activity-ids}) (defn add-post-message [post] {:action :add-post :id (safe-get post :id) :doc post}) (defn add-comment-message [doc-id ^Comment comment] {:action :add-comment :id doc-id :comment comment}) (defn add-comment-action-message [doc-id comment-id ^SimpleAction comment-action] {:action :add-comment-action :id doc-id :comment-id comment-id :comment-action comment-action}) (defn delete-comment-action-message [doc-id comment-id action-id] {:action :delete-comment-action :id doc-id :comment-id comment-id :action-id action-id}) (s/defn ^:always-validate mark-viewed-message [doc-id :- long user-id :- long date :- long client-type :- docs-core/ActionClientType] {:action :mark-viewed :id doc-id :user-id user-id :date date :client-type client-type}) (defn update-stats-message "Old mark-viewed message, can eventually be removed once fitness-stats no longer used for views." [doc-id fitness-stats] {:action :update-stats :id doc-id :fitness-stats fitness-stats}) (s/defn ^:always-validate add-tag-message [doc-id :- long tag :- tags/Tag] {:action :add-tag :id doc-id :tag tag}) (s/defn ^:always-validate untag-message [doc-id :- long tag-type :- (s/enum :admin :auto) tag-value :- String] {:action :untag :id doc-id :tag-type tag-type :tag-value tag-value}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Applying messages to docs (more functionality should probably be pulled out here) (defn update-dwell "Returns updated doc, and warns if a click can't be found to attach" [doc message] (letk [[action id user-id date client-type dwell-ms] message] (assert (= action :update-dwell)) (let [[head [target & tail]] (split-with (fn [^SimpleAction action] (not (and (= (.action action) :click) (= (.user-id action) user-id)))) (safe-get doc :activity))] (if target (assoc doc :activity (vec (concat head [(update-in target [:dwell-ms] #(max (or % 0) dwell-ms))] tail))) (do (log/warnf "Missing click applying update-dwell action %s" message) doc))))) (defn mark-viewed! "Mutates doc and returns it." [doc message] (letk [[action user-id date client-type] message] (assert (= action :mark-viewed)) (views-by-client/add-view! (safe-get doc :views-by-client) client-type user-id)) doc) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Converting messages to and from data/records (def +known-action-types+ #{:add-external-shares :add-activity :add-doc :add-full-doc :delete-doc :merge-doc :re-cluster :delete-activity :add-post :add-comment :add-comment-action :delete-comment-action :update-stats :add-tag :untag :update-dwell :mark-viewed}) (defn write-message [message] (assert (long (:id message))) (assert (+known-action-types+ (:action message)) (format "Unknown action type : %s" (:action message))) (-> message (?> (-> message :doc-hints :fitness-stats) (update-in [:doc-hints :fitness-stats] fitness-stats/write-fitness-stats)) (?> (-> message :fitness-stats) (update-in [:fitness-stats] fitness-stats/write-fitness-stats)) (?> (:doc message) (update-in [:doc] docs/write-doc)) (?> (:comment message) (update-in [:comment] (fn [c] (s/validate domain.docs.comments.Comment c) (comments/write-comment c)))) (?> (:comment-action message) (update-in [:comment-action] (fn [ca] (s/validate domain.docs.actions.SimpleAction ca) (actions/Action->old-grabbag-share ca)))) (?> (= :add-activity (:action message)) (update-in [:activity] (partial map actions/Action->old-grabbag-share))) (?> (= :add-external-shares (:action message)) (update-in [:external-shares] #(docs/downgrade-and-write-shares % []))))) (defn read-message [message] (assert (+known-action-types+ (:action message)) message) (-> message (?> (-> message :doc-hints :fitness-stats) (update-in [:doc-hints :fitness-stats] fitness-stats/read-fitness-stats)) (?> (-> message :fitness-stats) (update-in [:fitness-stats] fitness-stats/read-fitness-stats)) (?> (:doc message) (update-in [:doc] docs/read-doc)) (?> (:comment message) (update-in [:comment] comments/read-comment)) (?> (:comment-action message) (update-in [:comment-action] actions/share-data->Action)) (?> (= :add-external-shares (:action message)) (update-in [:external-shares] #(safe-get (docs/read-and-upgrade-shares %) :external-shares))) (?> (= :add-activity (:action message)) (update-in [:activity] (partial map actions/share-data->Action))))) (set! *warn-on-reflection* false)
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/domain/src/domain/messages.clj
clojure
helpers for doc-hints new-shares messages: doc-poller --> doc-poller (internal, plus persisted in URL cache) possibly resolved. used in both ways in different places. fetch-doc-message: doc-poller --> doc-fetcher doc-related messages used in index-master and api doc-poller --> index-master --> api doc-fetcher --> index-master --> api index-master --> search-index index-master --> api only api --> index-master --> api Applying messages to docs (more functionality should probably be pulled out here) Converting messages to and from data/records
(ns domain.messages "Definitions for messages involving docs and shares that are passed between services." (:use plumbing.core) (:require [schema.core :as s] [schema.utils :as schema-utils] [plumbing.logging :as log] [domain.docs :as docs] [domain.docs.core :as docs-core] [domain.docs.actions :as actions] [domain.docs.comments :as comments] domain.docs.external-shares [domain.docs.fitness-stats :as fitness-stats] [domain.docs.tags :as tags] [domain.docs.views-by-client :as views-by-client]) (:import [domain.docs Doc] [domain.docs.actions SimpleAction] [domain.docs.comments Comment] [domain.docs.external_shares ExternalShares])) (set! *warn-on-reflection* true) (s/defschema DocHints (s/maybe {s/Any s/Any})) (defn write-doc-hints [doc-hints] (update-in-when doc-hints [:fitness-stats] fitness-stats/write-fitness-stats)) (defn read-doc-hints [doc-hints] (update-in-when doc-hints [:fitness-stats] fitness-stats/read-fitness-stats)) (s/defschema NewSharesMessage {:action (s/eq :new-shares) :doc-hints DocHints :external-shares ExternalShares}) (s/defn ^:always-validate new-shares-message :- NewSharesMessage [possibly-resolved-url doc-hints external-shares] {:action :new-shares :doc-hints doc-hints :external-shares external-shares}) (s/defn ^:always-validate write-new-shares-message [message :- NewSharesMessage] (-> message (update-in [:doc-hints] write-doc-hints) (dissoc :external-shares) (assoc :shares (docs/downgrade-and-write-shares (safe-get message :external-shares) nil)))) (s/defn read-new-shares-message :- NewSharesMessage [message] (letk [[action url doc-hints shares] message [external-shares activity] (docs/read-and-upgrade-shares shares)] (assert (= action :new-shares)) (assert (empty? activity)) (new-shares-message url (read-doc-hints doc-hints) external-shares))) (s/defschema FetchDocMessage {:action (s/eq :fetch-doc) :id long :url String :doc-hints DocHints}) (s/defn ^:always-validate fetch-doc-message :- FetchDocMessage [doc-id url doc-hints] {:action :fetch-doc :id doc-id :url url :doc-hints doc-hints}) (s/defn ^:always-validate write-fetch-doc-message [message :- FetchDocMessage] (update-in message [:doc-hints] write-doc-hints)) (s/defn read-fetch-doc-message :- FetchDocMessage [message] (update-in message [:doc-hints] read-doc-hints)) (defn add-external-shares-message [doc-id doc-hints external-shares] {:action :add-external-shares :id doc-id :doc-hints doc-hints :external-shares external-shares}) (defn add-doc-message [doc] {:action :add-doc :id (safe-get doc :id) :doc doc}) (defn add-full-doc-message "Similar to add-doc-message, but includes fetched-page HTML data (from url-cache bucket)" [doc fetched-page] {:action :add-full-doc :id (safe-get doc :id) :doc doc :fetched-page fetched-page}) (defn delete-doc-message [doc-id] {:action :delete-doc :id doc-id}) (defn re-cluster-message [doc-id new-cluster-id] {:action :re-cluster :id doc-id :new-cluster-id new-cluster-id}) (s/defschema DocUpdate (->> Doc ^schema.core.Record (schema-utils/class-schema) .schema (map-keys (fn [k] (assert (s/specific-key? k)) (s/optional-key (s/explicit-schema-key k)))))) (s/defn ^:always-validate merge-doc-message "Nuclear option, not meant to be used in normal system operation. Can make arbitrary changes to docs: semantics is to replace entire provided top-level keys with new values, leaving other top-level keys alone." [doc-id :- long doc-update :- DocUpdate] (when-let [id (:id doc-update)] (assert (= id doc-id))) {:action :merge-doc :id doc-id :doc-update doc-update}) NOTE : in - memory format different than wire , now grabbag only (s/defn add-activity-message [doc-id activity :- [SimpleAction]] {:action :add-activity :id doc-id :activity activity}) (s/defn ^:always-validate update-dwell-message [doc-id :- Long user-id :- Long date :- Long client-type :- docs-core/ActionClientType dwell-ms :- Long] {:action :update-dwell :id doc-id :user-id user-id :date date :client-type client-type :dwell-ms dwell-ms}) (defn delete-activity-message [doc-id activity-ids] {:action :delete-activity :id doc-id :activity-ids activity-ids}) (defn add-post-message [post] {:action :add-post :id (safe-get post :id) :doc post}) (defn add-comment-message [doc-id ^Comment comment] {:action :add-comment :id doc-id :comment comment}) (defn add-comment-action-message [doc-id comment-id ^SimpleAction comment-action] {:action :add-comment-action :id doc-id :comment-id comment-id :comment-action comment-action}) (defn delete-comment-action-message [doc-id comment-id action-id] {:action :delete-comment-action :id doc-id :comment-id comment-id :action-id action-id}) (s/defn ^:always-validate mark-viewed-message [doc-id :- long user-id :- long date :- long client-type :- docs-core/ActionClientType] {:action :mark-viewed :id doc-id :user-id user-id :date date :client-type client-type}) (defn update-stats-message "Old mark-viewed message, can eventually be removed once fitness-stats no longer used for views." [doc-id fitness-stats] {:action :update-stats :id doc-id :fitness-stats fitness-stats}) (s/defn ^:always-validate add-tag-message [doc-id :- long tag :- tags/Tag] {:action :add-tag :id doc-id :tag tag}) (s/defn ^:always-validate untag-message [doc-id :- long tag-type :- (s/enum :admin :auto) tag-value :- String] {:action :untag :id doc-id :tag-type tag-type :tag-value tag-value}) (defn update-dwell "Returns updated doc, and warns if a click can't be found to attach" [doc message] (letk [[action id user-id date client-type dwell-ms] message] (assert (= action :update-dwell)) (let [[head [target & tail]] (split-with (fn [^SimpleAction action] (not (and (= (.action action) :click) (= (.user-id action) user-id)))) (safe-get doc :activity))] (if target (assoc doc :activity (vec (concat head [(update-in target [:dwell-ms] #(max (or % 0) dwell-ms))] tail))) (do (log/warnf "Missing click applying update-dwell action %s" message) doc))))) (defn mark-viewed! "Mutates doc and returns it." [doc message] (letk [[action user-id date client-type] message] (assert (= action :mark-viewed)) (views-by-client/add-view! (safe-get doc :views-by-client) client-type user-id)) doc) (def +known-action-types+ #{:add-external-shares :add-activity :add-doc :add-full-doc :delete-doc :merge-doc :re-cluster :delete-activity :add-post :add-comment :add-comment-action :delete-comment-action :update-stats :add-tag :untag :update-dwell :mark-viewed}) (defn write-message [message] (assert (long (:id message))) (assert (+known-action-types+ (:action message)) (format "Unknown action type : %s" (:action message))) (-> message (?> (-> message :doc-hints :fitness-stats) (update-in [:doc-hints :fitness-stats] fitness-stats/write-fitness-stats)) (?> (-> message :fitness-stats) (update-in [:fitness-stats] fitness-stats/write-fitness-stats)) (?> (:doc message) (update-in [:doc] docs/write-doc)) (?> (:comment message) (update-in [:comment] (fn [c] (s/validate domain.docs.comments.Comment c) (comments/write-comment c)))) (?> (:comment-action message) (update-in [:comment-action] (fn [ca] (s/validate domain.docs.actions.SimpleAction ca) (actions/Action->old-grabbag-share ca)))) (?> (= :add-activity (:action message)) (update-in [:activity] (partial map actions/Action->old-grabbag-share))) (?> (= :add-external-shares (:action message)) (update-in [:external-shares] #(docs/downgrade-and-write-shares % []))))) (defn read-message [message] (assert (+known-action-types+ (:action message)) message) (-> message (?> (-> message :doc-hints :fitness-stats) (update-in [:doc-hints :fitness-stats] fitness-stats/read-fitness-stats)) (?> (-> message :fitness-stats) (update-in [:fitness-stats] fitness-stats/read-fitness-stats)) (?> (:doc message) (update-in [:doc] docs/read-doc)) (?> (:comment message) (update-in [:comment] comments/read-comment)) (?> (:comment-action message) (update-in [:comment-action] actions/share-data->Action)) (?> (= :add-external-shares (:action message)) (update-in [:external-shares] #(safe-get (docs/read-and-upgrade-shares %) :external-shares))) (?> (= :add-activity (:action message)) (update-in [:activity] (partial map actions/share-data->Action))))) (set! *warn-on-reflection* false)
0b22e5424d82cffc2d01973bcc7887e99ff5779e76857bb8c7071174bb9555f1
NalaGinrut/artanis
parser.scm
;;; (json parser) --- Guile JSON implementation. Copyright ( C ) 2013 Flaque < > ;; ;; This file is part of guile-json. ;; ;; guile-json is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;; ;; guile-json is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; You should have received a copy of the GNU Lesser General Public ;; License along with guile-json; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA ;;; Commentary: JSON module for ;;; Code: (define-module (artanis third-party json upstream parser) #:use-module (ice-9 rdelim) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-9) #:export (json->scm json-string->scm json-parser? json-parser-port)) ;; Parser record and read helpers ;; (define-record-type json-parser (make-json-parser port) json-parser? (port json-parser-port)) (define (parser-peek-char parser) (peek-char (json-parser-port parser))) (define (parser-read-char parser) (read-char (json-parser-port parser))) (define (parser-read-delimited parser delim handle-delim) (let ((port (json-parser-port parser))) (read-delimited delim port handle-delim))) ;; ;; Number parsing helpers ;; ;; Read + or -. . If something different is found, return empty string. (define (read-sign parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ((#\+ #\-) (let ((ch (parser-read-char parser))) (string-append s (string ch)))) (else s)))) Read digits [ 0 .. 9 ] . If something different is found , return empty ;; string. (define (read-digits parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (let ((ch (parser-read-char parser))) (loop (parser-peek-char parser) (string-append s (string ch))))) (else s)))) (define (read-exp-part parser) (let ((c (parser-peek-char parser)) (s "")) (case c ;; Stop parsing if whitespace found. ((#\ht #\vt #\lf #\cr #\sp) s) ;; We might be in an array or object, so stop here too. ((#\, #\] #\}) s) ;; We might have the exponential part ((#\e #\E) (let ((ch (parser-read-char parser)) ; current char (sign (read-sign parser)) (digits (read-digits parser))) ;; If we don't have sign or digits, we have an invalid ;; number. (if (not (and (string-null? sign) (string-null? digits))) (string-append s (string ch) sign digits) #f))) ;; If we have a character different than e or E, we have an ;; invalid number. (else #f)))) (define (read-real-part parser) (let ((c (parser-peek-char parser)) (s "")) (case c ;; Stop parsing if whitespace found. ((#\ht #\vt #\lf #\cr #\sp) s) ;; We might be in an array or object, so stop here too. ((#\, #\] #\}) s) ;; If we read . we might have a real number ((#\.) (let ((ch (parser-read-char parser)) (digits (read-digits parser))) ;; If we have digits, try to read the exponential part, ;; otherwise we have an invalid number. (cond ((not (string-null? digits)) (let ((exp (read-exp-part parser))) (cond (exp (string-append s (string ch) digits exp)) (else #f)))) (else #f)))) ;; If we have a character different than . we might continue ;; processing. (else #f)))) (define (read-number parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ;; Stop parsing if whitespace found. ((#\ht #\vt #\lf #\cr #\sp) s) ;; We might be in an array or object, so stop here too. ((#\, #\] #\}) s) ((#\-) (let ((ch (parser-read-char parser))) (loop (parser-peek-char parser) (string-append s (string ch))))) ((#\0) (let ((ch (parser-read-char parser))) (string-append s (string ch) (or (read-real-part parser) (throw 'json-invalid parser))))) ((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (let ((ch (parser-read-char parser))) (string-append s (string ch) (read-digits parser) (or (read-real-part parser) (read-exp-part parser) (throw 'json-invalid parser))))) (else (throw 'json-invalid parser))))) ;; ;; Object parsing helpers ;; (define (read-pair parser) ;; Read string key (let ((key (json-read-string parser))) (let loop ((c (parser-peek-char parser))) (case c ;; Skip whitespaces ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser))) ;; Skip colon and read value ((#\:) (parser-read-char parser) (cons key (json-read parser))) ;; invalid object (else (throw 'json-invalid parser)))))) (define (read-object parser) (let loop ((c (parser-peek-char parser)) (pairs (make-hash-table))) (case c ;; Skip whitespaces ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser) pairs)) ;; end of object ((#\}) (parser-read-char parser) pairs) ;; Read one pair and continue ((#\") (let ((pair (read-pair parser))) (hash-set! pairs (car pair) (cdr pair)) (loop (parser-peek-char parser) pairs))) ;; Skip comma and read more pairs ((#\,) (parser-read-char parser) (loop (parser-peek-char parser) pairs)) ;; invalid object (else (throw 'json-invalid parser))))) ;; ;; Array parsing helpers ;; (define (read-array parser) (let loop ((c (parser-peek-char parser)) (values '())) (case c ;; Skip whitespace and comma ((#\ht #\vt #\lf #\cr #\sp #\,) (parser-read-char parser) (loop (parser-peek-char parser) values)) ;; end of array ((#\]) (parser-read-char parser) values) ;; this can be any json object (else (let ((value (json-read parser))) (loop (parser-peek-char parser) (append values (list value)))))))) ;; ;; String parsing helpers ;; (define (expect parser expected) (let ((ch (parser-read-char parser))) (if (not (char=? ch expected)) (throw 'json-invalid parser) ch))) (define (expect-string parser expected) (list->string (map (lambda (ch) (expect parser ch)) (string->list expected)))) (define (read-hex-digit parser) (let ((c (parser-read-char parser))) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\A #\B #\C #\D #\E #\F #\a #\b #\c #\d #\e #\f) c) (else (throw 'json-invalid parser))))) (define (read-control-char parser) (let ((c (parser-read-char parser))) (case c ((#\" #\\ #\/) (string c)) ((#\b) (string #\bs)) ((#\f) (string #\ff)) ((#\n) (string #\lf)) ((#\r) (string #\cr)) ((#\t) (string #\ht)) ((#\u) (let* ((utf1 (string (read-hex-digit parser) (read-hex-digit parser))) (utf2 (string (read-hex-digit parser) (read-hex-digit parser))) (vu8 (list (string->number utf1 16) (string->number utf2 16))) (utf (u8-list->bytevector vu8))) (utf16->string utf))) (else #f)))) (define (read-string parser) ;; Read characters until \ or " are found. (let loop ((result "") (current (parser-read-delimited parser "\\\"" 'split))) (case (cdr current) ((#\") (string-append result (car current))) ((#\\) (let ((ch (read-control-char parser))) (if ch (loop (string-append result (car current) ch) (parser-read-delimited parser "\\\"" 'split)) (throw 'json-invalid parser )))) (else (throw 'json-invalid parser))))) ;; ;; Main parser functions ;; (define-syntax json-read-delimited (syntax-rules () ((json-read-delimited parser delim read-func) (let loop ((c (parser-read-char parser))) (case c ;; skip whitespace ((#\ht #\vt #\lf #\cr #\sp) (loop (parser-peek-char parser))) ;; read contents ((delim) (read-func parser)) (else (throw 'json-invalid parser))))))) (define (json-read-true parser) (expect-string parser "true") #t) (define (json-read-false parser) (expect-string parser "false") #f) (define (json-read-null parser) (expect-string parser "null") #nil) (define (json-read-object parser) (json-read-delimited parser #\{ read-object)) (define (json-read-array parser) (json-read-delimited parser #\[ read-array)) (define (json-read-string parser) (json-read-delimited parser #\" read-string)) (define (json-read-number parser) (string->number (read-number parser))) (define (json-read parser) (let loop ((c (parser-peek-char parser))) (cond ;;If we reach the end we might have an incomplete document ((eof-object? c) (throw 'json-invalid parser)) (else (case c ;; skip whitespaces ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser))) read ((#\t) (json-read-true parser)) ((#\f) (json-read-false parser)) ((#\n) (json-read-null parser)) ((#\{) (json-read-object parser)) ((#\[) (json-read-array parser)) ((#\") (json-read-string parser)) ;; anything else should be a number (else (json-read-number parser))))))) ;; ;; Public procedures ;; (define* (json->scm #:optional (port (current-input-port))) "Parse a JSON document into native. Takes one optional argument, @var{port}, which defaults to the current input port from where the JSON document is read." (json-read (make-json-parser port))) (define* (json-string->scm str) "Parse a JSON document into native. Takes a string argument, @var{str}, that contains the JSON document." (call-with-input-string str (lambda (p) (json->scm p)))) ;;; (json parser) ends here
null
https://raw.githubusercontent.com/NalaGinrut/artanis/3412d6eb5b46fde71b0965598ba085bacc2a6c12/artanis/third-party/json/upstream/parser.scm
scheme
(json parser) --- Guile JSON implementation. This file is part of guile-json. guile-json is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either guile-json is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with guile-json; if not, write to the Free Software Commentary: Code: Number parsing helpers Read + or -. . If something different is found, return empty string. string. Stop parsing if whitespace found. We might be in an array or object, so stop here too. We might have the exponential part current char If we don't have sign or digits, we have an invalid number. If we have a character different than e or E, we have an invalid number. Stop parsing if whitespace found. We might be in an array or object, so stop here too. If we read . we might have a real number If we have digits, try to read the exponential part, otherwise we have an invalid number. If we have a character different than . we might continue processing. Stop parsing if whitespace found. We might be in an array or object, so stop here too. Object parsing helpers Read string key Skip whitespaces Skip colon and read value invalid object Skip whitespaces end of object Read one pair and continue Skip comma and read more pairs invalid object Array parsing helpers Skip whitespace and comma end of array this can be any json object String parsing helpers Read characters until \ or " are found. Main parser functions skip whitespace read contents If we reach the end we might have an incomplete document skip whitespaces anything else should be a number Public procedures (json parser) ends here
Copyright ( C ) 2013 Flaque < > version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA JSON module for (define-module (artanis third-party json upstream parser) #:use-module (ice-9 rdelim) #:use-module (rnrs bytevectors) #:use-module (srfi srfi-9) #:export (json->scm json-string->scm json-parser? json-parser-port)) Parser record and read helpers (define-record-type json-parser (make-json-parser port) json-parser? (port json-parser-port)) (define (parser-peek-char parser) (peek-char (json-parser-port parser))) (define (parser-read-char parser) (read-char (json-parser-port parser))) (define (parser-read-delimited parser delim handle-delim) (let ((port (json-parser-port parser))) (read-delimited delim port handle-delim))) (define (read-sign parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ((#\+ #\-) (let ((ch (parser-read-char parser))) (string-append s (string ch)))) (else s)))) Read digits [ 0 .. 9 ] . If something different is found , return empty (define (read-digits parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (let ((ch (parser-read-char parser))) (loop (parser-peek-char parser) (string-append s (string ch))))) (else s)))) (define (read-exp-part parser) (let ((c (parser-peek-char parser)) (s "")) (case c ((#\ht #\vt #\lf #\cr #\sp) s) ((#\, #\] #\}) s) ((#\e #\E) (sign (read-sign parser)) (digits (read-digits parser))) (if (not (and (string-null? sign) (string-null? digits))) (string-append s (string ch) sign digits) #f))) (else #f)))) (define (read-real-part parser) (let ((c (parser-peek-char parser)) (s "")) (case c ((#\ht #\vt #\lf #\cr #\sp) s) ((#\, #\] #\}) s) ((#\.) (let ((ch (parser-read-char parser)) (digits (read-digits parser))) (cond ((not (string-null? digits)) (let ((exp (read-exp-part parser))) (cond (exp (string-append s (string ch) digits exp)) (else #f)))) (else #f)))) (else #f)))) (define (read-number parser) (let loop ((c (parser-peek-char parser)) (s "")) (case c ((#\ht #\vt #\lf #\cr #\sp) s) ((#\, #\] #\}) s) ((#\-) (let ((ch (parser-read-char parser))) (loop (parser-peek-char parser) (string-append s (string ch))))) ((#\0) (let ((ch (parser-read-char parser))) (string-append s (string ch) (or (read-real-part parser) (throw 'json-invalid parser))))) ((#\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (let ((ch (parser-read-char parser))) (string-append s (string ch) (read-digits parser) (or (read-real-part parser) (read-exp-part parser) (throw 'json-invalid parser))))) (else (throw 'json-invalid parser))))) (define (read-pair parser) (let ((key (json-read-string parser))) (let loop ((c (parser-peek-char parser))) (case c ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser))) ((#\:) (parser-read-char parser) (cons key (json-read parser))) (else (throw 'json-invalid parser)))))) (define (read-object parser) (let loop ((c (parser-peek-char parser)) (pairs (make-hash-table))) (case c ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser) pairs)) ((#\}) (parser-read-char parser) pairs) ((#\") (let ((pair (read-pair parser))) (hash-set! pairs (car pair) (cdr pair)) (loop (parser-peek-char parser) pairs))) ((#\,) (parser-read-char parser) (loop (parser-peek-char parser) pairs)) (else (throw 'json-invalid parser))))) (define (read-array parser) (let loop ((c (parser-peek-char parser)) (values '())) (case c ((#\ht #\vt #\lf #\cr #\sp #\,) (parser-read-char parser) (loop (parser-peek-char parser) values)) ((#\]) (parser-read-char parser) values) (else (let ((value (json-read parser))) (loop (parser-peek-char parser) (append values (list value)))))))) (define (expect parser expected) (let ((ch (parser-read-char parser))) (if (not (char=? ch expected)) (throw 'json-invalid parser) ch))) (define (expect-string parser expected) (list->string (map (lambda (ch) (expect parser ch)) (string->list expected)))) (define (read-hex-digit parser) (let ((c (parser-read-char parser))) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\A #\B #\C #\D #\E #\F #\a #\b #\c #\d #\e #\f) c) (else (throw 'json-invalid parser))))) (define (read-control-char parser) (let ((c (parser-read-char parser))) (case c ((#\" #\\ #\/) (string c)) ((#\b) (string #\bs)) ((#\f) (string #\ff)) ((#\n) (string #\lf)) ((#\r) (string #\cr)) ((#\t) (string #\ht)) ((#\u) (let* ((utf1 (string (read-hex-digit parser) (read-hex-digit parser))) (utf2 (string (read-hex-digit parser) (read-hex-digit parser))) (vu8 (list (string->number utf1 16) (string->number utf2 16))) (utf (u8-list->bytevector vu8))) (utf16->string utf))) (else #f)))) (define (read-string parser) (let loop ((result "") (current (parser-read-delimited parser "\\\"" 'split))) (case (cdr current) ((#\") (string-append result (car current))) ((#\\) (let ((ch (read-control-char parser))) (if ch (loop (string-append result (car current) ch) (parser-read-delimited parser "\\\"" 'split)) (throw 'json-invalid parser )))) (else (throw 'json-invalid parser))))) (define-syntax json-read-delimited (syntax-rules () ((json-read-delimited parser delim read-func) (let loop ((c (parser-read-char parser))) (case c ((#\ht #\vt #\lf #\cr #\sp) (loop (parser-peek-char parser))) ((delim) (read-func parser)) (else (throw 'json-invalid parser))))))) (define (json-read-true parser) (expect-string parser "true") #t) (define (json-read-false parser) (expect-string parser "false") #f) (define (json-read-null parser) (expect-string parser "null") #nil) (define (json-read-object parser) (json-read-delimited parser #\{ read-object)) (define (json-read-array parser) (json-read-delimited parser #\[ read-array)) (define (json-read-string parser) (json-read-delimited parser #\" read-string)) (define (json-read-number parser) (string->number (read-number parser))) (define (json-read parser) (let loop ((c (parser-peek-char parser))) (cond ((eof-object? c) (throw 'json-invalid parser)) (else (case c ((#\ht #\vt #\lf #\cr #\sp) (parser-read-char parser) (loop (parser-peek-char parser))) read ((#\t) (json-read-true parser)) ((#\f) (json-read-false parser)) ((#\n) (json-read-null parser)) ((#\{) (json-read-object parser)) ((#\[) (json-read-array parser)) ((#\") (json-read-string parser)) (else (json-read-number parser))))))) (define* (json->scm #:optional (port (current-input-port))) "Parse a JSON document into native. Takes one optional argument, @var{port}, which defaults to the current input port from where the JSON document is read." (json-read (make-json-parser port))) (define* (json-string->scm str) "Parse a JSON document into native. Takes a string argument, @var{str}, that contains the JSON document." (call-with-input-string str (lambda (p) (json->scm p))))
d58fa47036e932f7f70a81f7ff17b38eb2f340a932364164f4504f6401c026ab
lloda/guile-newra
print.scm
-*- mode : scheme ; coding : utf-8 -*- ( c ) 2017 - 2018 , 2021 ; This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any ; later version. ;;; Commentary: Printer for ra objects . They start with # % instead of # , otherwise the syntax is the same as for regular arrays . Loading this module installs the ;; printer. This module also provides a pretty-printer (ra-format). ;;; Code: (define-module (newra print) #:export (ra-print-prefix ra-print ra-format *ra-print* *ra-parenthesized-rank-zero*)) (import (rnrs io ports) (rnrs base) (srfi 1) (srfi 4 gnu) (srfi 26) (srfi 71) (ice-9 match) (ice-9 control) (newra base) (newra map) (newra cat) (newra from) (newra lib) (newra reshape)) (define *ra-print* (make-parameter #f (lambda (x) (match x ((or 'box 'box-compact 'default #f (? procedure?)) x) (x (throw 'bad-argument-to-*ra-print* x)))))) (define *ra-parenthesized-rank-zero* (make-parameter #t)) FIXME still need to extend ( truncated - print ) . (define* (ra-print-prefix ra port #:key (dims? #t)) (display #\# port) (display #\% port) (display (ra-rank ra) port) (let ((type (ra-type ra))) (unless (eq? #t type) (display type port))) (vector-for-each (lambda (dim) (let ((lo (dim-lo dim))) (unless (or (not lo) (zero? lo)) (display #\@ port) (display (or lo 'f) port))) (when dims? (display #\: port) (display (match (dim-len dim) ; print len of dead axes with 'd and of infinite axes with 'f. (#f (if (zero? (dim-step dim)) 'd 'f)) (len len)) port))) (ra-dims ra))) (define* (ra-print ra port #:key (dims? #t)) (ra-print-prefix ra port #:dims? dims?) (let ((base (ra-offset (ra-zero ra) (ra-dims ra))) (ref (cute (ra-vref ra) (ra-root ra) <>)) (rank (ra-rank ra))) ; special case (if (zero? rank) (if (*ra-parenthesized-rank-zero*) (begin (display #\( port) (write (ref base) port) (display #\) port)) (begin (display #\space port) (write (ref base) port))) (let loop ((k 0) (b base)) (let* ((dim (vector-ref (ra-dims ra) k)) (i (dim-step dim)) (lo (dim-lo dim)) print dead axes as if of size 1 . Infinite arrays are n't printed ( FIXME ? ) (len (or (dim-len dim) (if (zero? i) 1 #f)))) (when len (let ((hi (+ (or lo 0) len -1))) (display #\( port) (cond ((= (- rank 1) k) (do ((j (or lo 0) (+ 1 j)) (b b (+ b i))) ((> j hi)) (write (ref b) port) (when (< j hi) (display #\space port)))) (else (do ((j (or lo 0) (+ 1 j)) (b b (+ b i))) ((> j hi)) (loop (+ k 1) b) (when (< j hi) (display #\space port))))) (display #\) port)))))))) (define* (sc-print sc #:optional (o #t)) (let ((o (match o (#t (current-output-port)) (#f (throw 'bad-output-spec)) (o o)))) (ra-slice-for-each 1 (lambda (line) (ra-for-each (cut display <> o) line) (newline o)) sc) ; FIXME ra-slice-for-each should do this (values))) (define arts (make-ra-root (vector "┆╌┌┐└┘ " "│─┌┐└┘├┤┬┴┼" "║═╔╗╚╝╠╣╦╩╬" "┃━┏┓┗┛┣┫┳┻╋" "████████████"))) (define (vector-any pred? v) (let/ec exit (vector-for-each (lambda (e) (and=> (pred? e) exit)) v) #f)) (define* (ra-format ra #:optional (port #t) #:key (fmt "~a") (prefix? #t) compact?) (define prefix (and prefix? (call-with-output-string (cut ra-print-prefix ra <>)))) (let ((ra (if (vector-any (lambda (d) (and (not (dim-len d)) (not (zero? (dim-step d))))) (ra-dims ra)) ; for arrays with infinite axes, print just the prefix. (make-ra #f 0) for arrays with dead axes , print them as if the len was 1 , but preserve the prefix . (ra-singletonize ra)))) (define tostring (if (string? fmt) (cut format #f fmt <>) fmt)) ; size the cells (define s (ra-map! (apply make-ra #f (ra-dimensions ra)) (lambda (x) (if (ra? x) (ra-format x #f #:fmt fmt #:prefix? prefix? #:compact? compact?) (ra-tile (make-ra-root (tostring x)) 0 1))) ra)) (define-values (dim0 dim1) (let* ((q r (euclidean/ (ra-rank s) 2)) (a (ra-iota (+ q r) 0 2)) (b (ra-iota q 1 2))) (if (zero? r) (values a b) (values b a)))) (define (lengths dim0 dim1 k compact?) (let* ((sq (apply ra-untranspose s (ra->list (ra-cat #f 0 dim1 dim0)))) (l (apply make-ra 0 (drop (ra-dimensions sq) (ra-len dim1)))) (border (if (or compact? (zero? (ra-rank l))) 0 1))) (ra-slice-for-each-in-order (ra-len dim1) (lambda (w) (ra-map! l (lambda (l w) (max l (+ border (ra-len w k)))) l w)) sq) ; FIXME handle border entirely here (when (and compact? (> (ra-rank l) 0)) FIXME need (let ((ll (ra-from l (dots) (dim-hi (vector-ref (ra-dims l) (- (ra-rank l) 1)))))) (ra-map! ll (cut + <> 1) ll))) l)) (define l0 (lengths dim0 dim1 0 compact?)) (define l1 (lengths dim1 dim0 1 #f)) (define t0 (- (ra-fold + 0 l0) (if (zero? (ra-rank l0)) 1 0))) (define t1 (- (ra-fold + 0 l1) (if (zero? (ra-rank l1)) 1 0))) ; define positions for grid and cells (define (scan! a) (let ((s 0)) (ra-map-in-order! a (lambda (c) (let ((d s)) (set! s (+ s c)) d)) a))) (define (scan-0 a) (scan! (ra-copy a))) (define (scan-1 a) (scan! (ra-cat #f 0 a (make-ra 0)))) (define (marks l k) (and (>= k 0) (let ((m (apply make-ra 0 (take (ra-dimensions l) (+ k 1))))) (ra-slice-for-each (+ k 1) (lambda (l m) (set! (m) (ra-fold + 0 l)) m) l m) (scan-1 (ra-ravel m))))) ; make screen, adding line for prefix if necessary (define scc (make-typed-ra 'a #\space (+ 1 t0 (if (and prefix (< (ra-rank ra) 2)) 1 0)) (max (if prefix (string-length prefix) 0) (+ 1 t1)))) (define sc (if (and prefix (< (ra-rank ra) 2)) (ra-from scc (ra-iota (- (ra-len scc) 1) 1)) scc)) (define (char k n) (string-ref (ra-ref arts (+ (if compact? 0 1) k)) n)) (define (line-0 sc k range at) (ra-amend! sc (char k 0) range at)) (define (line-1 sc k range at) (ra-amend! sc (char k 1) at range)) (cond ((zero? (ra-rank ra)) (let ((s (s))) (ra-copy! (ra-clip sc s) s))) ; align left ((zero? (ra-size ra)) #f) (else ; print grid (let loop ((k 0)) (let* ((m0 (marks l0 (- (ra-rank l0) 1 k))) (m1 (marks l1 (- (ra-rank l1) 1 k))) (>m0< (and m0 (ra-from m0 (ra-iota (- (ra-len m0) 2) 1)))) (>m1< (and m1 (ra-from m1 (ra-iota (- (ra-len m1) 2) 1))))) (cond ((and m0 m1) ; horiz + vert (if (and compact? (zero? k)) (begin (line-1 sc k (ra-iota (+ 1 t1) 0) (ra-ref m0 0)) (line-1 sc k (ra-iota (+ 1 t1) 0) (ra-ref m0 (- (ra-len m0) 1))) (line-0 sc k (ra-iota (+ 1 t0) 0) (ra-ref m1 0)) (line-0 sc k (ra-iota (+ 1 t0) 0) (ra-ref m1 (- (ra-len m1) 1)))) (begin (ra-for-each (lambda (m0) (line-1 sc k (ra-iota (+ 1 t1) 0) m0)) m0) (ra-for-each (lambda (m1) (line-0 sc k (ra-iota (+ 1 t0) 0) m1)) m1))) ; crosses (if compact? (when (> k 0) (ra-for-each (lambda (m0 m1) (ra-set! sc (char k 10) m0 m1)) >m0< (ra-transpose >m1< 1))) (ra-for-each (lambda (m0 m1) (ra-set! sc (char k 10) m0 m1)) >m0< (ra-transpose >m1< 1))) ; crosses horiz + vert (unless (and compact? (zero? k)) (ra-for-each (lambda (m0) (ra-set! sc (char k 6) m0 0) (ra-set! sc (char k 7) m0 t1)) >m0<) (ra-for-each (lambda (m1) (ra-set! sc (char k 8) 0 m1) (ra-set! sc (char k 9) t0 m1)) >m1<)) ; corners (ra-set! sc (char k 2) 0 0) (ra-set! sc (char k 3) 0 t1) (ra-set! sc (char k 4) t0 0) (ra-set! sc (char k 5) t0 t1) (loop (+ k 1))) (m1 (if (and compact? (zero? k)) (begin (line-0 sc k (ra-iota (+ t0 1) 0) 0) (line-0 sc k (ra-iota (+ t0 1) 0) (ra-ref m1 (- (ra-len m1) 1)))) (ra-for-each (lambda (m1) (line-0 sc k (ra-iota (+ t0 1) 0) m1)) m1))) (else #f)))) ; print cells (ra-for-each (lambda (sq o0 l0 o1 l1) (ra-copy! (ra-from sc (ra-iota (ra-len sq 0) (+ o0 (if (> (ra-rank s) 1) 1 0))) (ra-iota (ra-len sq 1) (+ o1 1 (- l1 (ra-len sq 1) 1)))) ; align right sq)) (apply ra-untranspose s (ra->list (ra-cat #f 0 dim0 dim1))) (apply ra-reshape (scan-0 (ra-ravel l0)) 0 (ra-dimensions l0)) l0 (ra-transpose (apply ra-reshape (scan-0 (ra-ravel l1)) 0 (ra-dimensions l1)) (ra-rank l0)) (ra-transpose l1 (ra-rank l0))))) ; print prefix (when prefix (ra-amend! scc (make-ra-root prefix) 0 (ra-iota (string-length prefix)))) (if port (sc-print scc port) scc))) (struct-set! (@ (newra base) <ra-vtable>) vtable-index-printer (lambda (ra o) (match (*ra-print*) ('box (newline o) (ra-format ra o)) ('box-compact (newline o) (ra-format ra o #:compact? #t)) ((or 'default #f) (ra-print ra o)) (f (f ra o)))))
null
https://raw.githubusercontent.com/lloda/guile-newra/80b75ef4e02029958a4e5f699e9cc16220c2f099/mod/newra/print.scm
scheme
coding : utf-8 -*- This library is free software; you can redistribute it and/or modify it under either version 3 of the License , or ( at your option ) any later version. Commentary: printer. This module also provides a pretty-printer (ra-format). Code: print len of dead axes with 'd and of infinite axes with 'f. special case FIXME ra-slice-for-each should do this for arrays with infinite axes, print just the prefix. size the cells FIXME handle border entirely here define positions for grid and cells make screen, adding line for prefix if necessary align left print grid horiz + vert crosses crosses horiz + vert corners print cells align right print prefix
( c ) 2017 - 2018 , 2021 the terms of the GNU General Public License as published by the Free Printer for ra objects . They start with # % instead of # , otherwise the syntax is the same as for regular arrays . Loading this module installs the (define-module (newra print) #:export (ra-print-prefix ra-print ra-format *ra-print* *ra-parenthesized-rank-zero*)) (import (rnrs io ports) (rnrs base) (srfi 1) (srfi 4 gnu) (srfi 26) (srfi 71) (ice-9 match) (ice-9 control) (newra base) (newra map) (newra cat) (newra from) (newra lib) (newra reshape)) (define *ra-print* (make-parameter #f (lambda (x) (match x ((or 'box 'box-compact 'default #f (? procedure?)) x) (x (throw 'bad-argument-to-*ra-print* x)))))) (define *ra-parenthesized-rank-zero* (make-parameter #t)) FIXME still need to extend ( truncated - print ) . (define* (ra-print-prefix ra port #:key (dims? #t)) (display #\# port) (display #\% port) (display (ra-rank ra) port) (let ((type (ra-type ra))) (unless (eq? #t type) (display type port))) (vector-for-each (lambda (dim) (let ((lo (dim-lo dim))) (unless (or (not lo) (zero? lo)) (display #\@ port) (display (or lo 'f) port))) (when dims? (display #\: port) (display (match (dim-len dim) (#f (if (zero? (dim-step dim)) 'd 'f)) (len len)) port))) (ra-dims ra))) (define* (ra-print ra port #:key (dims? #t)) (ra-print-prefix ra port #:dims? dims?) (let ((base (ra-offset (ra-zero ra) (ra-dims ra))) (ref (cute (ra-vref ra) (ra-root ra) <>)) (rank (ra-rank ra))) (if (zero? rank) (if (*ra-parenthesized-rank-zero*) (begin (display #\( port) (write (ref base) port) (display #\) port)) (begin (display #\space port) (write (ref base) port))) (let loop ((k 0) (b base)) (let* ((dim (vector-ref (ra-dims ra) k)) (i (dim-step dim)) (lo (dim-lo dim)) print dead axes as if of size 1 . Infinite arrays are n't printed ( FIXME ? ) (len (or (dim-len dim) (if (zero? i) 1 #f)))) (when len (let ((hi (+ (or lo 0) len -1))) (display #\( port) (cond ((= (- rank 1) k) (do ((j (or lo 0) (+ 1 j)) (b b (+ b i))) ((> j hi)) (write (ref b) port) (when (< j hi) (display #\space port)))) (else (do ((j (or lo 0) (+ 1 j)) (b b (+ b i))) ((> j hi)) (loop (+ k 1) b) (when (< j hi) (display #\space port))))) (display #\) port)))))))) (define* (sc-print sc #:optional (o #t)) (let ((o (match o (#t (current-output-port)) (#f (throw 'bad-output-spec)) (o o)))) (ra-slice-for-each 1 (lambda (line) (ra-for-each (cut display <> o) line) (newline o)) sc) (values))) (define arts (make-ra-root (vector "┆╌┌┐└┘ " "│─┌┐└┘├┤┬┴┼" "║═╔╗╚╝╠╣╦╩╬" "┃━┏┓┗┛┣┫┳┻╋" "████████████"))) (define (vector-any pred? v) (let/ec exit (vector-for-each (lambda (e) (and=> (pred? e) exit)) v) #f)) (define* (ra-format ra #:optional (port #t) #:key (fmt "~a") (prefix? #t) compact?) (define prefix (and prefix? (call-with-output-string (cut ra-print-prefix ra <>)))) (let ((ra (if (vector-any (lambda (d) (and (not (dim-len d)) (not (zero? (dim-step d))))) (ra-dims ra)) (make-ra #f 0) for arrays with dead axes , print them as if the len was 1 , but preserve the prefix . (ra-singletonize ra)))) (define tostring (if (string? fmt) (cut format #f fmt <>) fmt)) (define s (ra-map! (apply make-ra #f (ra-dimensions ra)) (lambda (x) (if (ra? x) (ra-format x #f #:fmt fmt #:prefix? prefix? #:compact? compact?) (ra-tile (make-ra-root (tostring x)) 0 1))) ra)) (define-values (dim0 dim1) (let* ((q r (euclidean/ (ra-rank s) 2)) (a (ra-iota (+ q r) 0 2)) (b (ra-iota q 1 2))) (if (zero? r) (values a b) (values b a)))) (define (lengths dim0 dim1 k compact?) (let* ((sq (apply ra-untranspose s (ra->list (ra-cat #f 0 dim1 dim0)))) (l (apply make-ra 0 (drop (ra-dimensions sq) (ra-len dim1)))) (border (if (or compact? (zero? (ra-rank l))) 0 1))) (ra-slice-for-each-in-order (ra-len dim1) (lambda (w) (ra-map! l (lambda (l w) (max l (+ border (ra-len w k)))) l w)) sq) (when (and compact? (> (ra-rank l) 0)) FIXME need (let ((ll (ra-from l (dots) (dim-hi (vector-ref (ra-dims l) (- (ra-rank l) 1)))))) (ra-map! ll (cut + <> 1) ll))) l)) (define l0 (lengths dim0 dim1 0 compact?)) (define l1 (lengths dim1 dim0 1 #f)) (define t0 (- (ra-fold + 0 l0) (if (zero? (ra-rank l0)) 1 0))) (define t1 (- (ra-fold + 0 l1) (if (zero? (ra-rank l1)) 1 0))) (define (scan! a) (let ((s 0)) (ra-map-in-order! a (lambda (c) (let ((d s)) (set! s (+ s c)) d)) a))) (define (scan-0 a) (scan! (ra-copy a))) (define (scan-1 a) (scan! (ra-cat #f 0 a (make-ra 0)))) (define (marks l k) (and (>= k 0) (let ((m (apply make-ra 0 (take (ra-dimensions l) (+ k 1))))) (ra-slice-for-each (+ k 1) (lambda (l m) (set! (m) (ra-fold + 0 l)) m) l m) (scan-1 (ra-ravel m))))) (define scc (make-typed-ra 'a #\space (+ 1 t0 (if (and prefix (< (ra-rank ra) 2)) 1 0)) (max (if prefix (string-length prefix) 0) (+ 1 t1)))) (define sc (if (and prefix (< (ra-rank ra) 2)) (ra-from scc (ra-iota (- (ra-len scc) 1) 1)) scc)) (define (char k n) (string-ref (ra-ref arts (+ (if compact? 0 1) k)) n)) (define (line-0 sc k range at) (ra-amend! sc (char k 0) range at)) (define (line-1 sc k range at) (ra-amend! sc (char k 1) at range)) (cond ((zero? (ra-rank ra)) ((zero? (ra-size ra)) #f) (else (let loop ((k 0)) (let* ((m0 (marks l0 (- (ra-rank l0) 1 k))) (m1 (marks l1 (- (ra-rank l1) 1 k))) (>m0< (and m0 (ra-from m0 (ra-iota (- (ra-len m0) 2) 1)))) (>m1< (and m1 (ra-from m1 (ra-iota (- (ra-len m1) 2) 1))))) (cond ((and m0 m1) (if (and compact? (zero? k)) (begin (line-1 sc k (ra-iota (+ 1 t1) 0) (ra-ref m0 0)) (line-1 sc k (ra-iota (+ 1 t1) 0) (ra-ref m0 (- (ra-len m0) 1))) (line-0 sc k (ra-iota (+ 1 t0) 0) (ra-ref m1 0)) (line-0 sc k (ra-iota (+ 1 t0) 0) (ra-ref m1 (- (ra-len m1) 1)))) (begin (ra-for-each (lambda (m0) (line-1 sc k (ra-iota (+ 1 t1) 0) m0)) m0) (ra-for-each (lambda (m1) (line-0 sc k (ra-iota (+ 1 t0) 0) m1)) m1))) (if compact? (when (> k 0) (ra-for-each (lambda (m0 m1) (ra-set! sc (char k 10) m0 m1)) >m0< (ra-transpose >m1< 1))) (ra-for-each (lambda (m0 m1) (ra-set! sc (char k 10) m0 m1)) >m0< (ra-transpose >m1< 1))) (unless (and compact? (zero? k)) (ra-for-each (lambda (m0) (ra-set! sc (char k 6) m0 0) (ra-set! sc (char k 7) m0 t1)) >m0<) (ra-for-each (lambda (m1) (ra-set! sc (char k 8) 0 m1) (ra-set! sc (char k 9) t0 m1)) >m1<)) (ra-set! sc (char k 2) 0 0) (ra-set! sc (char k 3) 0 t1) (ra-set! sc (char k 4) t0 0) (ra-set! sc (char k 5) t0 t1) (loop (+ k 1))) (m1 (if (and compact? (zero? k)) (begin (line-0 sc k (ra-iota (+ t0 1) 0) 0) (line-0 sc k (ra-iota (+ t0 1) 0) (ra-ref m1 (- (ra-len m1) 1)))) (ra-for-each (lambda (m1) (line-0 sc k (ra-iota (+ t0 1) 0) m1)) m1))) (else #f)))) (ra-for-each (lambda (sq o0 l0 o1 l1) (ra-copy! (ra-from sc (ra-iota (ra-len sq 0) (+ o0 (if (> (ra-rank s) 1) 1 0))) sq)) (apply ra-untranspose s (ra->list (ra-cat #f 0 dim0 dim1))) (apply ra-reshape (scan-0 (ra-ravel l0)) 0 (ra-dimensions l0)) l0 (ra-transpose (apply ra-reshape (scan-0 (ra-ravel l1)) 0 (ra-dimensions l1)) (ra-rank l0)) (ra-transpose l1 (ra-rank l0))))) (when prefix (ra-amend! scc (make-ra-root prefix) 0 (ra-iota (string-length prefix)))) (if port (sc-print scc port) scc))) (struct-set! (@ (newra base) <ra-vtable>) vtable-index-printer (lambda (ra o) (match (*ra-print*) ('box (newline o) (ra-format ra o)) ('box-compact (newline o) (ra-format ra o #:compact? #t)) ((or 'default #f) (ra-print ra o)) (f (f ra o)))))
73d1b2a3ad9aed6d14ffd7a2569be2db3eb7d676128293b288dbeae8fc148e12
eugeneia/athens
sosemanuk.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- sosemanuk.lisp - implementation of the Sosemanuk stream cipher (in-package :crypto) (defconst +sosemanuk-mul-a+ (make-array 256 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #xE19FCF13 #x6B973726 #x8A08F835 #xD6876E4C #x3718A15F #xBD10596A #x5C8F9679 #x05A7DC98 #xE438138B #x6E30EBBE #x8FAF24AD #xD320B2D4 #x32BF7DC7 #xB8B785F2 #x59284AE1 #x0AE71199 #xEB78DE8A #x617026BF #x80EFE9AC #xDC607FD5 #x3DFFB0C6 #xB7F748F3 #x566887E0 #x0F40CD01 #xEEDF0212 #x64D7FA27 #x85483534 #xD9C7A34D #x38586C5E #xB250946B #x53CF5B78 #x1467229B #xF5F8ED88 #x7FF015BD #x9E6FDAAE #xC2E04CD7 #x237F83C4 #xA9777BF1 #x48E8B4E2 #x11C0FE03 #xF05F3110 #x7A57C925 #x9BC80636 #xC747904F #x26D85F5C #xACD0A769 #x4D4F687A #x1E803302 #xFF1FFC11 #x75170424 #x9488CB37 #xC8075D4E #x2998925D #xA3906A68 #x420FA57B #x1B27EF9A #xFAB82089 #x70B0D8BC #x912F17AF #xCDA081D6 #x2C3F4EC5 #xA637B6F0 #x47A879E3 #x28CE449F #xC9518B8C #x435973B9 #xA2C6BCAA #xFE492AD3 #x1FD6E5C0 #x95DE1DF5 #x7441D2E6 #x2D699807 #xCCF65714 #x46FEAF21 #xA7616032 #xFBEEF64B #x1A713958 #x9079C16D #x71E60E7E #x22295506 #xC3B69A15 #x49BE6220 #xA821AD33 #xF4AE3B4A #x1531F459 #x9F390C6C #x7EA6C37F #x278E899E #xC611468D #x4C19BEB8 #xAD8671AB #xF109E7D2 #x109628C1 #x9A9ED0F4 #x7B011FE7 #x3CA96604 #xDD36A917 #x573E5122 #xB6A19E31 #xEA2E0848 #x0BB1C75B #x81B93F6E #x6026F07D #x390EBA9C #xD891758F #x52998DBA #xB30642A9 #xEF89D4D0 #x0E161BC3 #x841EE3F6 #x65812CE5 #x364E779D #xD7D1B88E #x5DD940BB #xBC468FA8 #xE0C919D1 #x0156D6C2 #x8B5E2EF7 #x6AC1E1E4 #x33E9AB05 #xD2766416 #x587E9C23 #xB9E15330 #xE56EC549 #x04F10A5A #x8EF9F26F #x6F663D7C #x50358897 #xB1AA4784 #x3BA2BFB1 #xDA3D70A2 #x86B2E6DB #x672D29C8 #xED25D1FD #x0CBA1EEE #x5592540F #xB40D9B1C #x3E056329 #xDF9AAC3A #x83153A43 #x628AF550 #xE8820D65 #x091DC276 #x5AD2990E #xBB4D561D #x3145AE28 #xD0DA613B #x8C55F742 #x6DCA3851 #xE7C2C064 #x065D0F77 #x5F754596 #xBEEA8A85 #x34E272B0 #xD57DBDA3 #x89F22BDA #x686DE4C9 #xE2651CFC #x03FAD3EF #x4452AA0C #xA5CD651F #x2FC59D2A #xCE5A5239 #x92D5C440 #x734A0B53 #xF942F366 #x18DD3C75 #x41F57694 #xA06AB987 #x2A6241B2 #xCBFD8EA1 #x977218D8 #x76EDD7CB #xFCE52FFE #x1D7AE0ED #x4EB5BB95 #xAF2A7486 #x25228CB3 #xC4BD43A0 #x9832D5D9 #x79AD1ACA #xF3A5E2FF #x123A2DEC #x4B12670D #xAA8DA81E #x2085502B #xC11A9F38 #x9D950941 #x7C0AC652 #xF6023E67 #x179DF174 #x78FBCC08 #x9964031B #x136CFB2E #xF2F3343D #xAE7CA244 #x4FE36D57 #xC5EB9562 #x24745A71 #x7D5C1090 #x9CC3DF83 #x16CB27B6 #xF754E8A5 #xABDB7EDC #x4A44B1CF #xC04C49FA #x21D386E9 #x721CDD91 #x93831282 #x198BEAB7 #xF81425A4 #xA49BB3DD #x45047CCE #xCF0C84FB #x2E934BE8 #x77BB0109 #x9624CE1A #x1C2C362F #xFDB3F93C #xA13C6F45 #x40A3A056 #xCAAB5863 #x2B349770 #x6C9CEE93 #x8D032180 #x070BD9B5 #xE69416A6 #xBA1B80DF #x5B844FCC #xD18CB7F9 #x301378EA #x693B320B #x88A4FD18 #x02AC052D #xE333CA3E #xBFBC5C47 #x5E239354 #xD42B6B61 #x35B4A472 #x667BFF0A #x87E43019 #x0DECC82C #xEC73073F #xB0FC9146 #x51635E55 #xDB6BA660 #x3AF46973 #x63DC2392 #x8243EC81 #x084B14B4 #xE9D4DBA7 #xB55B4DDE #x54C482CD #xDECC7AF8 #x3F53B5EB))) (defconst +sosemanuk-mul-ia+ (make-array 256 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #x180F40CD #x301E8033 #x2811C0FE #x603CA966 #x7833E9AB #x50222955 #x482D6998 #xC078FBCC #xD877BB01 #xF0667BFF #xE8693B32 #xA04452AA #xB84B1267 #x905AD299 #x88559254 #x29F05F31 #x31FF1FFC #x19EEDF02 #x01E19FCF #x49CCF657 #x51C3B69A #x79D27664 #x61DD36A9 #xE988A4FD #xF187E430 #xD99624CE #xC1996403 #x89B40D9B #x91BB4D56 #xB9AA8DA8 #xA1A5CD65 #x5249BE62 #x4A46FEAF #x62573E51 #x7A587E9C #x32751704 #x2A7A57C9 #x026B9737 #x1A64D7FA #x923145AE #x8A3E0563 #xA22FC59D #xBA208550 #xF20DECC8 #xEA02AC05 #xC2136CFB #xDA1C2C36 #x7BB9E153 #x63B6A19E #x4BA76160 #x53A821AD #x1B854835 #x038A08F8 #x2B9BC806 #x339488CB #xBBC11A9F #xA3CE5A52 #x8BDF9AAC #x93D0DA61 #xDBFDB3F9 #xC3F2F334 #xEBE333CA #xF3EC7307 #xA492D5C4 #xBC9D9509 #x948C55F7 #x8C83153A #xC4AE7CA2 #xDCA13C6F #xF4B0FC91 #xECBFBC5C #x64EA2E08 #x7CE56EC5 #x54F4AE3B #x4CFBEEF6 #x04D6876E #x1CD9C7A3 #x34C8075D #x2CC74790 #x8D628AF5 #x956DCA38 #xBD7C0AC6 #xA5734A0B #xED5E2393 #xF551635E #xDD40A3A0 #xC54FE36D #x4D1A7139 #x551531F4 #x7D04F10A #x650BB1C7 #x2D26D85F #x35299892 #x1D38586C #x053718A1 #xF6DB6BA6 #xEED42B6B #xC6C5EB95 #xDECAAB58 #x96E7C2C0 #x8EE8820D #xA6F942F3 #xBEF6023E #x36A3906A #x2EACD0A7 #x06BD1059 #x1EB25094 #x569F390C #x4E9079C1 #x6681B93F #x7E8EF9F2 #xDF2B3497 #xC724745A #xEF35B4A4 #xF73AF469 #xBF179DF1 #xA718DD3C #x8F091DC2 #x97065D0F #x1F53CF5B #x075C8F96 #x2F4D4F68 #x37420FA5 #x7F6F663D #x676026F0 #x4F71E60E #x577EA6C3 #xE18D0321 #xF98243EC #xD1938312 #xC99CC3DF #x81B1AA47 #x99BEEA8A #xB1AF2A74 #xA9A06AB9 #x21F5F8ED #x39FAB820 #x11EB78DE #x09E43813 #x41C9518B #x59C61146 #x71D7D1B8 #x69D89175 #xC87D5C10 #xD0721CDD #xF863DC23 #xE06C9CEE #xA841F576 #xB04EB5BB #x985F7545 #x80503588 #x0805A7DC #x100AE711 #x381B27EF #x20146722 #x68390EBA #x70364E77 #x58278E89 #x4028CE44 #xB3C4BD43 #xABCBFD8E #x83DA3D70 #x9BD57DBD #xD3F81425 #xCBF754E8 #xE3E69416 #xFBE9D4DB #x73BC468F #x6BB30642 #x43A2C6BC #x5BAD8671 #x1380EFE9 #x0B8FAF24 #x239E6FDA #x3B912F17 #x9A34E272 #x823BA2BF #xAA2A6241 #xB225228C #xFA084B14 #xE2070BD9 #xCA16CB27 #xD2198BEA #x5A4C19BE #x42435973 #x6A52998D #x725DD940 #x3A70B0D8 #x227FF015 #x0A6E30EB #x12617026 #x451FD6E5 #x5D109628 #x750156D6 #x6D0E161B #x25237F83 #x3D2C3F4E #x153DFFB0 #x0D32BF7D #x85672D29 #x9D686DE4 #xB579AD1A #xAD76EDD7 #xE55B844F #xFD54C482 #xD545047C #xCD4A44B1 #x6CEF89D4 #x74E0C919 #x5CF109E7 #x44FE492A #x0CD320B2 #x14DC607F #x3CCDA081 #x24C2E04C #xAC977218 #xB49832D5 #x9C89F22B #x8486B2E6 #xCCABDB7E #xD4A49BB3 #xFCB55B4D #xE4BA1B80 #x17566887 #x0F59284A #x2748E8B4 #x3F47A879 #x776AC1E1 #x6F65812C #x477441D2 #x5F7B011F #xD72E934B #xCF21D386 #xE7301378 #xFF3F53B5 #xB7123A2D #xAF1D7AE0 #x870CBA1E #x9F03FAD3 #x3EA637B6 #x26A9777B #x0EB8B785 #x16B7F748 #x5E9A9ED0 #x4695DE1D #x6E841EE3 #x768B5E2E #xFEDECC7A #xE6D18CB7 #xCEC04C49 #xD6CF0C84 #x9EE2651C #x86ED25D1 #xAEFCE52F #xB6F3A5E2))) (defmacro sosemanuk-s0 (x0 x1 x2 x3 x4) `(setf ,x3 (logxor ,x3 ,x0) ,x4 ,x1 ,x1 (logand ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x4) ,x4 (logxor ,x4 ,x3) ,x3 (logxor ,x3 ,x2) ,x2 (logior ,x2 ,x1) ,x2 (logxor ,x2 ,x4) ,x4 (mod32lognot ,x4) ,x4 (logior ,x4 ,x1) ,x1 (logxor ,x1 ,x3) ,x1 (logxor ,x1 ,x4) ,x3 (logior ,x3 ,x0) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x3))) (defmacro sosemanuk-s1 (x0 x1 x2 x3 x4) `(setf ,x0 (mod32lognot ,x0) ,x2 (mod32lognot ,x2) ,x4 ,x0 ,x0 (logand ,x0 ,x1) ,x2 (logxor ,x2 ,x0) ,x0 (logior ,x0 ,x3) ,x3 (logxor ,x3 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logxor ,x0 ,x4) ,x4 (logior ,x4 ,x1) ,x1 (logxor ,x1 ,x3) ,x2 (logior ,x2 ,x0) ,x2 (logand ,x2 ,x4) ,x0 (logxor ,x0 ,x1) ,x1 (logand ,x1 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logand ,x0 ,x2) ,x0 (logxor ,x0 ,x4))) (defmacro sosemanuk-s2 (x0 x1 x2 x3 x4) `(setf ,x4 ,x0 ,x0 (logand ,x0 ,x2) ,x0 (logxor ,x0 ,x3) ,x2 (logxor ,x2 ,x1) ,x2 (logxor ,x2 ,x0) ,x3 (logior ,x3 ,x4) ,x3 (logxor ,x3 ,x1) ,x4 (logxor ,x4 ,x2) ,x1 ,x3 ,x3 (logior ,x3 ,x4) ,x3 (logxor ,x3 ,x0) ,x0 (logand ,x0 ,x1) ,x4 (logxor ,x4 ,x0) ,x1 (logxor ,x1 ,x3) ,x1 (logxor ,x1 ,x4) ,x4 (mod32lognot ,x4))) (defmacro sosemanuk-s3 (x0 x1 x2 x3 x4) `(setf ,x4 ,x0 ,x0 (logior ,x0 ,x3) ,x3 (logxor ,x3 ,x1) ,x1 (logand ,x1 ,x4) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x3) ,x3 (logand ,x3 ,x0) ,x4 (logior ,x4 ,x1) ,x3 (logxor ,x3 ,x4) ,x0 (logxor ,x0 ,x1) ,x4 (logand ,x4 ,x0) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x1 (logior ,x1 ,x0) ,x1 (logxor ,x1 ,x2) ,x0 (logxor ,x0 ,x3) ,x2 ,x1 ,x1 (logior ,x1 ,x3) ,x1 (logxor ,x1 ,x0))) (defmacro sosemanuk-s4 (x0 x1 x2 x3 x4) `(setf ,x1 (logxor ,x1 ,x3) ,x3 (mod32lognot ,x3) ,x2 (logxor ,x2 ,x3) ,x3 (logxor ,x3 ,x0) ,x4 ,x1 ,x1 (logand ,x1 ,x3) ,x1 (logxor ,x1 ,x2) ,x4 (logxor ,x4 ,x3) ,x0 (logxor ,x0 ,x4) ,x2 (logand ,x2 ,x4) ,x2 (logxor ,x2 ,x0) ,x0 (logand ,x0 ,x1) ,x3 (logxor ,x3 ,x0) ,x4 (logior ,x4 ,x1) ,x4 (logxor ,x4 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x2) ,x2 (logand ,x2 ,x3) ,x0 (mod32lognot ,x0) ,x4 (logxor ,x4 ,x2))) (defmacro sosemanuk-s5 (x0 x1 x2 x3 x4) `(setf ,x0 (logxor ,x0 ,x1) ,x1 (logxor ,x1 ,x3) ,x3 (mod32lognot ,x3) ,x4 ,x1 ,x1 (logand ,x1 ,x0) ,x2 (logxor ,x2 ,x3) ,x1 (logxor ,x1 ,x2) ,x2 (logior ,x2 ,x4) ,x4 (logxor ,x4 ,x3) ,x3 (logand ,x3 ,x1) ,x3 (logxor ,x3 ,x0) ,x4 (logxor ,x4 ,x1) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x0) ,x0 (logand ,x0 ,x3) ,x2 (mod32lognot ,x2) ,x0 (logxor ,x0 ,x4) ,x4 (logior ,x4 ,x3) ,x2 (logxor ,x2 ,x4))) (defmacro sosemanuk-s6 (x0 x1 x2 x3 x4) `(setf ,x2 (mod32lognot ,x2) ,x4 ,x3 ,x3 (logand ,x3 ,x0) ,x0 (logxor ,x0 ,x4) ,x3 (logxor ,x3 ,x2) ,x2 (logior ,x2 ,x4) ,x1 (logxor ,x1 ,x3) ,x2 (logxor ,x2 ,x0) ,x0 (logior ,x0 ,x1) ,x2 (logxor ,x2 ,x1) ,x4 (logxor ,x4 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x2) ,x4 (logxor ,x4 ,x3) ,x4 (logxor ,x4 ,x0) ,x3 (mod32lognot ,x3) ,x2 (logand ,x2 ,x4) ,x2 (logxor ,x2 ,x3))) (defmacro sosemanuk-s7 (x0 x1 x2 x3 x4) `(setf ,x4 ,x1 ,x1 (logior ,x1 ,x2) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x1) ,x3 (logior ,x3 ,x4) ,x3 (logand ,x3 ,x0) ,x4 (logxor ,x4 ,x2) ,x3 (logxor ,x3 ,x1) ,x1 (logior ,x1 ,x4) ,x1 (logxor ,x1 ,x0) ,x0 (logior ,x0 ,x4) ,x0 (logxor ,x0 ,x2) ,x1 (logxor ,x1 ,x4) ,x2 (logxor ,x2 ,x1) ,x1 (logand ,x1 ,x0) ,x1 (logxor ,x1 ,x4) ,x2 (mod32lognot ,x2) ,x2 (logior ,x2 ,x0) ,x4 (logxor ,x4 ,x2))) (defmacro sosemanuk-lt (x0 x1 x2 x3) `(setf ,x0 (rol32 ,x0 13) ,x2 (rol32 ,x2 3) ,x1 (logxor ,x1 ,x0 ,x2) ,x3 (logxor ,x3 ,x2 (mod32ash ,x0 3)) ,x1 (rol32 ,x1 1) ,x3 (rol32 ,x3 7) ,x0 (logxor ,x0 ,x1 ,x3) ,x2 (logxor ,x2 ,x3 (mod32ash ,x1 7)) ,x0 (rol32 ,x0 5) ,x2 (rol32 ,x2 22))) (defmacro sosemanuk-mkname (prefix n) `,(read-from-string (format nil "~a~d" prefix n))) (defclass sosemanuk (stream-cipher) ((state :accessor sosemanuk-state :initform (make-array 10 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (10))) (state-r :accessor sosemanuk-state-r :initform (make-array 2 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (2))) (keystream-buffer :accessor sosemanuk-keystream-buffer :initform (make-array 80 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (80))) (keystream-buffer-remaining :accessor sosemanuk-keystream-buffer-remaining :initform 0 :type (integer 0 80)) (subkeys :accessor sosemanuk-subkeys :type (or (simple-array (unsigned-byte 32) (100)) null)))) (defmethod schedule-key ((cipher sosemanuk) key) (let ((key-length (length key)) (subkeys (make-array 100 :element-type '(unsigned-byte 32))) (buffer (make-array 32 :element-type '(unsigned-byte 8))) (w0 0) (w1 0) (w2 0) (w3 0) (w4 0) (w5 0) (w6 0) (w7 0) (i 0)) (declare (type (simple-array (unsigned-byte 32) (100)) subkeys) (type (simple-array (unsigned-byte 8) (32)) buffer) (type (unsigned-byte 32) w0 w1 w2 w3 w4 w5 w6 w7) (type fixnum key-length i)) (replace buffer key :end2 key-length) (when (< key-length 32) (setf (aref buffer key-length) 1) (when (< key-length 31) (fill buffer 0 :start (1+ key-length)))) (setf w0 (ub32ref/le buffer 0) w1 (ub32ref/le buffer 4) w2 (ub32ref/le buffer 8) w3 (ub32ref/le buffer 12) w4 (ub32ref/le buffer 16) w5 (ub32ref/le buffer 20) w6 (ub32ref/le buffer 24) w7 (ub32ref/le buffer 28)) (macrolet ((sks (s o0 o1 o2 o3 d0 d1 d2 d3) `(let ((r0 (sosemanuk-mkname "w" ,o0)) (r1 (sosemanuk-mkname "w" ,o1)) (r2 (sosemanuk-mkname "w" ,o2)) (r3 (sosemanuk-mkname "w" ,o3)) (r4 0)) (declare (type (unsigned-byte 32) r0 r1 r2 r3)) (,s r0 r1 r2 r3 r4) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d0)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d1)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d2)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d3)) (incf i))) (sks0 () `(sks sosemanuk-s0 4 5 6 7 1 4 2 0)) (sks1 () `(sks sosemanuk-s1 0 1 2 3 2 0 3 1)) (sks2 () `(sks sosemanuk-s2 4 5 6 7 2 3 1 4)) (sks3 () `(sks sosemanuk-s3 0 1 2 3 1 2 3 4)) (sks4 () `(sks sosemanuk-s4 4 5 6 7 1 4 0 3)) (sks5 () `(sks sosemanuk-s5 0 1 2 3 1 3 0 2)) (sks6 () `(sks sosemanuk-s6 4 5 6 7 0 1 4 2)) (sks7 () `(sks sosemanuk-s7 0 1 2 3 4 3 1 0)) (wup (wi wi5 wi3 wi1 cc) `(setf ,wi (rol32 (logxor ,wi ,wi5 ,wi3 ,wi1 ,cc #x9e3779b9) 11))) (wup0 (cc) `(progn (wup w0 w3 w5 w7 ,cc) (wup w1 w4 w6 w0 ,(+ cc 1)) (wup w2 w5 w7 w1 ,(+ cc 2)) (wup w3 w6 w0 w2 ,(+ cc 3)))) (wup1 (cc) `(progn (wup w4 w7 w1 w3 ,cc) (wup w5 w0 w2 w4 ,(+ cc 1)) (wup w6 w1 w3 w5 ,(+ cc 2)) (wup w7 w2 w4 w6 ,(+ cc 3))))) (wup0 0) (sks3) (wup1 4) (sks2) (wup0 8) (sks1) (wup1 12) (sks0) (wup0 16) (sks7) (wup1 20) (sks6) (wup0 24) (sks5) (wup1 28) (sks4) (wup0 32) (sks3) (wup1 36) (sks2) (wup0 40) (sks1) (wup1 44) (sks0) (wup0 48) (sks7) (wup1 52) (sks6) (wup0 56) (sks5) (wup1 60) (sks4) (wup0 64) (sks3) (wup1 68) (sks2) (wup0 72) (sks1) (wup1 76) (sks0) (wup0 80) (sks7) (wup1 84) (sks6) (wup0 88) (sks5) (wup1 92) (sks4) (wup0 96) (sks3) (setf (sosemanuk-subkeys cipher) subkeys))) cipher) (defmethod shared-initialize :after ((cipher sosemanuk) slot-names &rest initargs &key initialization-vector &allow-other-keys) (declare (ignore slot-names initargs)) (let ((state (sosemanuk-state cipher)) (state-r (sosemanuk-state-r cipher)) (subkeys (sosemanuk-subkeys cipher)) (r0 0) (r1 0) (r2 0) (r3 0) (r4 0)) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r subkeys) (type (unsigned-byte 32) r0 r1 r2 r3 r4)) (when initialization-vector (if (= (length initialization-vector) 16) (setf r0 (ub32ref/le initialization-vector 0) r1 (ub32ref/le initialization-vector 4) r2 (ub32ref/le initialization-vector 8) r3 (ub32ref/le initialization-vector 12)) (error 'invalid-initialization-vector :cipher (class-name (class-of cipher)) :block-length 16))) (macrolet ((ka (zc x0 x1 x2 x3) `(setf ,x0 (logxor ,x0 (aref subkeys ,zc)) ,x1 (logxor ,x1 (aref subkeys ,(+ zc 1))) ,x2 (logxor ,x2 (aref subkeys ,(+ zc 2))) ,x3 (logxor ,x3 (aref subkeys ,(+ zc 3))))) (fss (zc s i0 i1 i2 i3 i4 o0 o1 o2 o3) `(progn (ka ,zc (sosemanuk-mkname "r" ,i0) (sosemanuk-mkname "r" ,i1) (sosemanuk-mkname "r" ,i2) (sosemanuk-mkname "r" ,i3)) (,s (sosemanuk-mkname "r" ,i0) (sosemanuk-mkname "r" ,i1) (sosemanuk-mkname "r" ,i2) (sosemanuk-mkname "r" ,i3) (sosemanuk-mkname "r" ,i4)) (sosemanuk-lt (sosemanuk-mkname "r" ,o0) (sosemanuk-mkname "r" ,o1) (sosemanuk-mkname "r" ,o2) (sosemanuk-mkname "r" ,o3)))) (fsf (zc s i0 i1 i2 i3 i4 o0 o1 o2 o3) `(progn (fss ,zc ,s ,i0 ,i1 ,i2 ,i3 ,i4 ,o0 ,o1 ,o2 ,o3) (ka ,(+ zc 4) (sosemanuk-mkname "r" ,o0) (sosemanuk-mkname "r" ,o1) (sosemanuk-mkname "r" ,o2) (sosemanuk-mkname "r" ,o3))))) (fss 0 sosemanuk-s0 0 1 2 3 4 1 4 2 0) (fss 4 sosemanuk-s1 1 4 2 0 3 2 1 0 4) (fss 8 sosemanuk-s2 2 1 0 4 3 0 4 1 3) (fss 12 sosemanuk-s3 0 4 1 3 2 4 1 3 2) (fss 16 sosemanuk-s4 4 1 3 2 0 1 0 4 2) (fss 20 sosemanuk-s5 1 0 4 2 3 0 2 1 4) (fss 24 sosemanuk-s6 0 2 1 4 3 0 2 3 1) (fss 28 sosemanuk-s7 0 2 3 1 4 4 1 2 0) (fss 32 sosemanuk-s0 4 1 2 0 3 1 3 2 4) (fss 36 sosemanuk-s1 1 3 2 4 0 2 1 4 3) (fss 40 sosemanuk-s2 2 1 4 3 0 4 3 1 0) (fss 44 sosemanuk-s3 4 3 1 0 2 3 1 0 2) (setf (aref state 9) r3 (aref state 8) r1 (aref state 7) r0 (aref state 6) r2) (fss 48 sosemanuk-s4 3 1 0 2 4 1 4 3 2) (fss 52 sosemanuk-s5 1 4 3 2 0 4 2 1 3) (fss 56 sosemanuk-s6 4 2 1 3 0 4 2 0 1) (fss 60 sosemanuk-s7 4 2 0 1 3 3 1 2 4) (fss 64 sosemanuk-s0 3 1 2 4 0 1 0 2 3) (fss 68 sosemanuk-s1 1 0 2 3 4 2 1 3 0) (setf (aref state-r 0) r2 (aref state 4) r1 (aref state-r 1) r3 (aref state 5) r0) (fss 72 sosemanuk-s2 2 1 3 0 4 3 0 1 4) (fss 76 sosemanuk-s3 3 0 1 4 2 0 1 4 2) (fss 80 sosemanuk-s4 0 1 4 2 3 1 3 0 2) (fss 84 sosemanuk-s5 1 3 0 2 4 3 2 1 0) (fss 88 sosemanuk-s6 3 2 1 0 4 3 2 4 1) (fsf 92 sosemanuk-s7 3 2 4 1 0 0 1 2 3) (setf (aref state 3) r0 (aref state 2) r1 (aref state 1) r2 (aref state 0) r3)) (fill subkeys 0) (setf (sosemanuk-subkeys cipher) nil (sosemanuk-keystream-buffer-remaining cipher) 0)) cipher) (defun sosemanuk-compute-block (state state-r buffer) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r) (type (simple-array (unsigned-byte 8) (80)) buffer) (optimize (speed 3) (space 0) (safety 0) (debug 0))) (let ((s0 (aref state 0)) (s1 (aref state 1)) (s2 (aref state 2)) (s3 (aref state 3)) (s4 (aref state 4)) (s5 (aref state 5)) (s6 (aref state 6)) (s7 (aref state 7)) (s8 (aref state 8)) (s9 (aref state 9)) (r1 (aref state-r 0)) (r2 (aref state-r 1)) (u0 0) (u1 0) (u2 0) (u3 0) (u4 0) (v0 0) (v1 0) (v2 0) (v3 0)) (declare (type (unsigned-byte 32) s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 r1 r2) (type (unsigned-byte 32) u0 u1 u2 u3 u4 v0 v1 v2 v3)) (macrolet ((mul-a (x) `(logxor (mod32ash ,x 8) (aref +sosemanuk-mul-a+ (mod32ash ,x -24)))) (mul-g (x) `(logxor (mod32ash ,x -8) (aref +sosemanuk-mul-ia+ (logand ,x 255)))) (xmux (c x y) `(if (zerop (logand ,c 1)) ,x (logxor ,x ,y))) (fsm (x1 x8) `(let ((tt 0) (or1 0)) (declare (type (unsigned-byte 32) tt or1)) (setf tt (xmux r1 (sosemanuk-mkname "s" ,x1) (sosemanuk-mkname "s" ,x8)) or1 r1 r1 (mod32+ r2 tt) tt (mod32* or1 #x54655307) r2 (rol32 tt 7)))) (lru (x0 x3 x9 dd) `(setf ,dd (sosemanuk-mkname "s" ,x0) (sosemanuk-mkname "s" ,x0) (logxor (mul-a (sosemanuk-mkname "s" ,x0)) (mul-g (sosemanuk-mkname "s" ,x3)) (sosemanuk-mkname "s" ,x9)))) (cc1 (x9 ee) `(setf ,ee (logxor (mod32+ (sosemanuk-mkname "s" ,x9) r1) r2))) (stp (x0 x1 x3 x8 x9 dd ee) `(progn (fsm ,x1 ,x8) (lru ,x0 ,x3 ,x9 ,dd) (cc1 ,x9 ,ee))) (srd (s x0 x1 x2 x3 ooff) `(progn (,s u0 u1 u2 u3 u4) (setf (ub32ref/le buffer ,ooff) (logxor (sosemanuk-mkname "u" ,x0) v0) (ub32ref/le buffer ,(+ ooff 4)) (logxor (sosemanuk-mkname "u" ,x1) v1) (ub32ref/le buffer ,(+ ooff 8)) (logxor (sosemanuk-mkname "u" ,x2) v2) (ub32ref/le buffer ,(+ ooff 12)) (logxor (sosemanuk-mkname "u" ,x3) v3))))) (stp 0 1 3 8 9 v0 u0) (stp 1 2 4 9 0 v1 u1) (stp 2 3 5 0 1 v2 u2) (stp 3 4 6 1 2 v3 u3) (srd sosemanuk-s2 2 3 1 4 0) (stp 4 5 7 2 3 v0 u0) (stp 5 6 8 3 4 v1 u1) (stp 6 7 9 4 5 v2 u2) (stp 7 8 0 5 6 v3 u3) (srd sosemanuk-s2 2 3 1 4 16) (stp 8 9 1 6 7 v0 u0) (stp 9 0 2 7 8 v1 u1) (stp 0 1 3 8 9 v2 u2) (stp 1 2 4 9 0 v3 u3) (srd sosemanuk-s2 2 3 1 4 32) (stp 2 3 5 0 1 v0 u0) (stp 3 4 6 1 2 v1 u1) (stp 4 5 7 2 3 v2 u2) (stp 5 6 8 3 4 v3 u3) (srd sosemanuk-s2 2 3 1 4 48) (stp 6 7 9 4 5 v0 u0) (stp 7 8 0 5 6 v1 u1) (stp 8 9 1 6 7 v2 u2) (stp 9 0 2 7 8 v3 u3) (srd sosemanuk-s2 2 3 1 4 64) (setf (aref state 0) s0 (aref state 1) s1 (aref state 2) s2 (aref state 3) s3 (aref state 4) s4 (aref state 5) s5 (aref state 6) s6 (aref state 7) s7 (aref state 8) s8 (aref state 9) s9 (aref state-r 0) r1 (aref state-r 1) r2))) (values)) (define-stream-cryptor sosemanuk (let ((state (sosemanuk-state context)) (state-r (sosemanuk-state-r context)) (keystream-buffer (sosemanuk-keystream-buffer context)) (keystream-buffer-remaining (sosemanuk-keystream-buffer-remaining context)) (remaining-keystream (make-array 80 :element-type '(unsigned-byte 8)))) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r) (type (simple-array (unsigned-byte 8) (80)) keystream-buffer remaining-keystream) (type (integer 0 80) keystream-buffer-remaining) (dynamic-extent remaining-keystream)) (unless (zerop length) (unless (zerop keystream-buffer-remaining) (let ((size (min length keystream-buffer-remaining))) (declare (type (integer 0 80) size)) (replace remaining-keystream keystream-buffer :end1 size :start2 (- 80 keystream-buffer-remaining)) (xor-block size remaining-keystream plaintext plaintext-start ciphertext ciphertext-start) (decf keystream-buffer-remaining size) (decf length size) (incf ciphertext-start size) (incf plaintext-start size))) (unless (zerop length) (loop (sosemanuk-compute-block state state-r keystream-buffer) (when (<= length 80) (xor-block length keystream-buffer plaintext plaintext-start ciphertext ciphertext-start) (setf (sosemanuk-keystream-buffer-remaining context) (- 80 length)) (return-from sosemanuk-crypt (values))) (xor-block 80 keystream-buffer plaintext plaintext-start ciphertext ciphertext-start) (decf length 80) (incf ciphertext-start 80) (incf plaintext-start 80))) (setf (sosemanuk-keystream-buffer-remaining context) keystream-buffer-remaining)) (values))) (defcipher sosemanuk (:mode :stream) (:crypt-function sosemanuk-crypt) (:key-length (:variable 16 32 1)))
null
https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/ironclad-v0.40/src/ciphers/sosemanuk.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*-
sosemanuk.lisp - implementation of the Sosemanuk stream cipher (in-package :crypto) (defconst +sosemanuk-mul-a+ (make-array 256 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #xE19FCF13 #x6B973726 #x8A08F835 #xD6876E4C #x3718A15F #xBD10596A #x5C8F9679 #x05A7DC98 #xE438138B #x6E30EBBE #x8FAF24AD #xD320B2D4 #x32BF7DC7 #xB8B785F2 #x59284AE1 #x0AE71199 #xEB78DE8A #x617026BF #x80EFE9AC #xDC607FD5 #x3DFFB0C6 #xB7F748F3 #x566887E0 #x0F40CD01 #xEEDF0212 #x64D7FA27 #x85483534 #xD9C7A34D #x38586C5E #xB250946B #x53CF5B78 #x1467229B #xF5F8ED88 #x7FF015BD #x9E6FDAAE #xC2E04CD7 #x237F83C4 #xA9777BF1 #x48E8B4E2 #x11C0FE03 #xF05F3110 #x7A57C925 #x9BC80636 #xC747904F #x26D85F5C #xACD0A769 #x4D4F687A #x1E803302 #xFF1FFC11 #x75170424 #x9488CB37 #xC8075D4E #x2998925D #xA3906A68 #x420FA57B #x1B27EF9A #xFAB82089 #x70B0D8BC #x912F17AF #xCDA081D6 #x2C3F4EC5 #xA637B6F0 #x47A879E3 #x28CE449F #xC9518B8C #x435973B9 #xA2C6BCAA #xFE492AD3 #x1FD6E5C0 #x95DE1DF5 #x7441D2E6 #x2D699807 #xCCF65714 #x46FEAF21 #xA7616032 #xFBEEF64B #x1A713958 #x9079C16D #x71E60E7E #x22295506 #xC3B69A15 #x49BE6220 #xA821AD33 #xF4AE3B4A #x1531F459 #x9F390C6C #x7EA6C37F #x278E899E #xC611468D #x4C19BEB8 #xAD8671AB #xF109E7D2 #x109628C1 #x9A9ED0F4 #x7B011FE7 #x3CA96604 #xDD36A917 #x573E5122 #xB6A19E31 #xEA2E0848 #x0BB1C75B #x81B93F6E #x6026F07D #x390EBA9C #xD891758F #x52998DBA #xB30642A9 #xEF89D4D0 #x0E161BC3 #x841EE3F6 #x65812CE5 #x364E779D #xD7D1B88E #x5DD940BB #xBC468FA8 #xE0C919D1 #x0156D6C2 #x8B5E2EF7 #x6AC1E1E4 #x33E9AB05 #xD2766416 #x587E9C23 #xB9E15330 #xE56EC549 #x04F10A5A #x8EF9F26F #x6F663D7C #x50358897 #xB1AA4784 #x3BA2BFB1 #xDA3D70A2 #x86B2E6DB #x672D29C8 #xED25D1FD #x0CBA1EEE #x5592540F #xB40D9B1C #x3E056329 #xDF9AAC3A #x83153A43 #x628AF550 #xE8820D65 #x091DC276 #x5AD2990E #xBB4D561D #x3145AE28 #xD0DA613B #x8C55F742 #x6DCA3851 #xE7C2C064 #x065D0F77 #x5F754596 #xBEEA8A85 #x34E272B0 #xD57DBDA3 #x89F22BDA #x686DE4C9 #xE2651CFC #x03FAD3EF #x4452AA0C #xA5CD651F #x2FC59D2A #xCE5A5239 #x92D5C440 #x734A0B53 #xF942F366 #x18DD3C75 #x41F57694 #xA06AB987 #x2A6241B2 #xCBFD8EA1 #x977218D8 #x76EDD7CB #xFCE52FFE #x1D7AE0ED #x4EB5BB95 #xAF2A7486 #x25228CB3 #xC4BD43A0 #x9832D5D9 #x79AD1ACA #xF3A5E2FF #x123A2DEC #x4B12670D #xAA8DA81E #x2085502B #xC11A9F38 #x9D950941 #x7C0AC652 #xF6023E67 #x179DF174 #x78FBCC08 #x9964031B #x136CFB2E #xF2F3343D #xAE7CA244 #x4FE36D57 #xC5EB9562 #x24745A71 #x7D5C1090 #x9CC3DF83 #x16CB27B6 #xF754E8A5 #xABDB7EDC #x4A44B1CF #xC04C49FA #x21D386E9 #x721CDD91 #x93831282 #x198BEAB7 #xF81425A4 #xA49BB3DD #x45047CCE #xCF0C84FB #x2E934BE8 #x77BB0109 #x9624CE1A #x1C2C362F #xFDB3F93C #xA13C6F45 #x40A3A056 #xCAAB5863 #x2B349770 #x6C9CEE93 #x8D032180 #x070BD9B5 #xE69416A6 #xBA1B80DF #x5B844FCC #xD18CB7F9 #x301378EA #x693B320B #x88A4FD18 #x02AC052D #xE333CA3E #xBFBC5C47 #x5E239354 #xD42B6B61 #x35B4A472 #x667BFF0A #x87E43019 #x0DECC82C #xEC73073F #xB0FC9146 #x51635E55 #xDB6BA660 #x3AF46973 #x63DC2392 #x8243EC81 #x084B14B4 #xE9D4DBA7 #xB55B4DDE #x54C482CD #xDECC7AF8 #x3F53B5EB))) (defconst +sosemanuk-mul-ia+ (make-array 256 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #x180F40CD #x301E8033 #x2811C0FE #x603CA966 #x7833E9AB #x50222955 #x482D6998 #xC078FBCC #xD877BB01 #xF0667BFF #xE8693B32 #xA04452AA #xB84B1267 #x905AD299 #x88559254 #x29F05F31 #x31FF1FFC #x19EEDF02 #x01E19FCF #x49CCF657 #x51C3B69A #x79D27664 #x61DD36A9 #xE988A4FD #xF187E430 #xD99624CE #xC1996403 #x89B40D9B #x91BB4D56 #xB9AA8DA8 #xA1A5CD65 #x5249BE62 #x4A46FEAF #x62573E51 #x7A587E9C #x32751704 #x2A7A57C9 #x026B9737 #x1A64D7FA #x923145AE #x8A3E0563 #xA22FC59D #xBA208550 #xF20DECC8 #xEA02AC05 #xC2136CFB #xDA1C2C36 #x7BB9E153 #x63B6A19E #x4BA76160 #x53A821AD #x1B854835 #x038A08F8 #x2B9BC806 #x339488CB #xBBC11A9F #xA3CE5A52 #x8BDF9AAC #x93D0DA61 #xDBFDB3F9 #xC3F2F334 #xEBE333CA #xF3EC7307 #xA492D5C4 #xBC9D9509 #x948C55F7 #x8C83153A #xC4AE7CA2 #xDCA13C6F #xF4B0FC91 #xECBFBC5C #x64EA2E08 #x7CE56EC5 #x54F4AE3B #x4CFBEEF6 #x04D6876E #x1CD9C7A3 #x34C8075D #x2CC74790 #x8D628AF5 #x956DCA38 #xBD7C0AC6 #xA5734A0B #xED5E2393 #xF551635E #xDD40A3A0 #xC54FE36D #x4D1A7139 #x551531F4 #x7D04F10A #x650BB1C7 #x2D26D85F #x35299892 #x1D38586C #x053718A1 #xF6DB6BA6 #xEED42B6B #xC6C5EB95 #xDECAAB58 #x96E7C2C0 #x8EE8820D #xA6F942F3 #xBEF6023E #x36A3906A #x2EACD0A7 #x06BD1059 #x1EB25094 #x569F390C #x4E9079C1 #x6681B93F #x7E8EF9F2 #xDF2B3497 #xC724745A #xEF35B4A4 #xF73AF469 #xBF179DF1 #xA718DD3C #x8F091DC2 #x97065D0F #x1F53CF5B #x075C8F96 #x2F4D4F68 #x37420FA5 #x7F6F663D #x676026F0 #x4F71E60E #x577EA6C3 #xE18D0321 #xF98243EC #xD1938312 #xC99CC3DF #x81B1AA47 #x99BEEA8A #xB1AF2A74 #xA9A06AB9 #x21F5F8ED #x39FAB820 #x11EB78DE #x09E43813 #x41C9518B #x59C61146 #x71D7D1B8 #x69D89175 #xC87D5C10 #xD0721CDD #xF863DC23 #xE06C9CEE #xA841F576 #xB04EB5BB #x985F7545 #x80503588 #x0805A7DC #x100AE711 #x381B27EF #x20146722 #x68390EBA #x70364E77 #x58278E89 #x4028CE44 #xB3C4BD43 #xABCBFD8E #x83DA3D70 #x9BD57DBD #xD3F81425 #xCBF754E8 #xE3E69416 #xFBE9D4DB #x73BC468F #x6BB30642 #x43A2C6BC #x5BAD8671 #x1380EFE9 #x0B8FAF24 #x239E6FDA #x3B912F17 #x9A34E272 #x823BA2BF #xAA2A6241 #xB225228C #xFA084B14 #xE2070BD9 #xCA16CB27 #xD2198BEA #x5A4C19BE #x42435973 #x6A52998D #x725DD940 #x3A70B0D8 #x227FF015 #x0A6E30EB #x12617026 #x451FD6E5 #x5D109628 #x750156D6 #x6D0E161B #x25237F83 #x3D2C3F4E #x153DFFB0 #x0D32BF7D #x85672D29 #x9D686DE4 #xB579AD1A #xAD76EDD7 #xE55B844F #xFD54C482 #xD545047C #xCD4A44B1 #x6CEF89D4 #x74E0C919 #x5CF109E7 #x44FE492A #x0CD320B2 #x14DC607F #x3CCDA081 #x24C2E04C #xAC977218 #xB49832D5 #x9C89F22B #x8486B2E6 #xCCABDB7E #xD4A49BB3 #xFCB55B4D #xE4BA1B80 #x17566887 #x0F59284A #x2748E8B4 #x3F47A879 #x776AC1E1 #x6F65812C #x477441D2 #x5F7B011F #xD72E934B #xCF21D386 #xE7301378 #xFF3F53B5 #xB7123A2D #xAF1D7AE0 #x870CBA1E #x9F03FAD3 #x3EA637B6 #x26A9777B #x0EB8B785 #x16B7F748 #x5E9A9ED0 #x4695DE1D #x6E841EE3 #x768B5E2E #xFEDECC7A #xE6D18CB7 #xCEC04C49 #xD6CF0C84 #x9EE2651C #x86ED25D1 #xAEFCE52F #xB6F3A5E2))) (defmacro sosemanuk-s0 (x0 x1 x2 x3 x4) `(setf ,x3 (logxor ,x3 ,x0) ,x4 ,x1 ,x1 (logand ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x4) ,x4 (logxor ,x4 ,x3) ,x3 (logxor ,x3 ,x2) ,x2 (logior ,x2 ,x1) ,x2 (logxor ,x2 ,x4) ,x4 (mod32lognot ,x4) ,x4 (logior ,x4 ,x1) ,x1 (logxor ,x1 ,x3) ,x1 (logxor ,x1 ,x4) ,x3 (logior ,x3 ,x0) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x3))) (defmacro sosemanuk-s1 (x0 x1 x2 x3 x4) `(setf ,x0 (mod32lognot ,x0) ,x2 (mod32lognot ,x2) ,x4 ,x0 ,x0 (logand ,x0 ,x1) ,x2 (logxor ,x2 ,x0) ,x0 (logior ,x0 ,x3) ,x3 (logxor ,x3 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logxor ,x0 ,x4) ,x4 (logior ,x4 ,x1) ,x1 (logxor ,x1 ,x3) ,x2 (logior ,x2 ,x0) ,x2 (logand ,x2 ,x4) ,x0 (logxor ,x0 ,x1) ,x1 (logand ,x1 ,x2) ,x1 (logxor ,x1 ,x0) ,x0 (logand ,x0 ,x2) ,x0 (logxor ,x0 ,x4))) (defmacro sosemanuk-s2 (x0 x1 x2 x3 x4) `(setf ,x4 ,x0 ,x0 (logand ,x0 ,x2) ,x0 (logxor ,x0 ,x3) ,x2 (logxor ,x2 ,x1) ,x2 (logxor ,x2 ,x0) ,x3 (logior ,x3 ,x4) ,x3 (logxor ,x3 ,x1) ,x4 (logxor ,x4 ,x2) ,x1 ,x3 ,x3 (logior ,x3 ,x4) ,x3 (logxor ,x3 ,x0) ,x0 (logand ,x0 ,x1) ,x4 (logxor ,x4 ,x0) ,x1 (logxor ,x1 ,x3) ,x1 (logxor ,x1 ,x4) ,x4 (mod32lognot ,x4))) (defmacro sosemanuk-s3 (x0 x1 x2 x3 x4) `(setf ,x4 ,x0 ,x0 (logior ,x0 ,x3) ,x3 (logxor ,x3 ,x1) ,x1 (logand ,x1 ,x4) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x3) ,x3 (logand ,x3 ,x0) ,x4 (logior ,x4 ,x1) ,x3 (logxor ,x3 ,x4) ,x0 (logxor ,x0 ,x1) ,x4 (logand ,x4 ,x0) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x1 (logior ,x1 ,x0) ,x1 (logxor ,x1 ,x2) ,x0 (logxor ,x0 ,x3) ,x2 ,x1 ,x1 (logior ,x1 ,x3) ,x1 (logxor ,x1 ,x0))) (defmacro sosemanuk-s4 (x0 x1 x2 x3 x4) `(setf ,x1 (logxor ,x1 ,x3) ,x3 (mod32lognot ,x3) ,x2 (logxor ,x2 ,x3) ,x3 (logxor ,x3 ,x0) ,x4 ,x1 ,x1 (logand ,x1 ,x3) ,x1 (logxor ,x1 ,x2) ,x4 (logxor ,x4 ,x3) ,x0 (logxor ,x0 ,x4) ,x2 (logand ,x2 ,x4) ,x2 (logxor ,x2 ,x0) ,x0 (logand ,x0 ,x1) ,x3 (logxor ,x3 ,x0) ,x4 (logior ,x4 ,x1) ,x4 (logxor ,x4 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x2) ,x2 (logand ,x2 ,x3) ,x0 (mod32lognot ,x0) ,x4 (logxor ,x4 ,x2))) (defmacro sosemanuk-s5 (x0 x1 x2 x3 x4) `(setf ,x0 (logxor ,x0 ,x1) ,x1 (logxor ,x1 ,x3) ,x3 (mod32lognot ,x3) ,x4 ,x1 ,x1 (logand ,x1 ,x0) ,x2 (logxor ,x2 ,x3) ,x1 (logxor ,x1 ,x2) ,x2 (logior ,x2 ,x4) ,x4 (logxor ,x4 ,x3) ,x3 (logand ,x3 ,x1) ,x3 (logxor ,x3 ,x0) ,x4 (logxor ,x4 ,x1) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x0) ,x0 (logand ,x0 ,x3) ,x2 (mod32lognot ,x2) ,x0 (logxor ,x0 ,x4) ,x4 (logior ,x4 ,x3) ,x2 (logxor ,x2 ,x4))) (defmacro sosemanuk-s6 (x0 x1 x2 x3 x4) `(setf ,x2 (mod32lognot ,x2) ,x4 ,x3 ,x3 (logand ,x3 ,x0) ,x0 (logxor ,x0 ,x4) ,x3 (logxor ,x3 ,x2) ,x2 (logior ,x2 ,x4) ,x1 (logxor ,x1 ,x3) ,x2 (logxor ,x2 ,x0) ,x0 (logior ,x0 ,x1) ,x2 (logxor ,x2 ,x1) ,x4 (logxor ,x4 ,x0) ,x0 (logior ,x0 ,x3) ,x0 (logxor ,x0 ,x2) ,x4 (logxor ,x4 ,x3) ,x4 (logxor ,x4 ,x0) ,x3 (mod32lognot ,x3) ,x2 (logand ,x2 ,x4) ,x2 (logxor ,x2 ,x3))) (defmacro sosemanuk-s7 (x0 x1 x2 x3 x4) `(setf ,x4 ,x1 ,x1 (logior ,x1 ,x2) ,x1 (logxor ,x1 ,x3) ,x4 (logxor ,x4 ,x2) ,x2 (logxor ,x2 ,x1) ,x3 (logior ,x3 ,x4) ,x3 (logand ,x3 ,x0) ,x4 (logxor ,x4 ,x2) ,x3 (logxor ,x3 ,x1) ,x1 (logior ,x1 ,x4) ,x1 (logxor ,x1 ,x0) ,x0 (logior ,x0 ,x4) ,x0 (logxor ,x0 ,x2) ,x1 (logxor ,x1 ,x4) ,x2 (logxor ,x2 ,x1) ,x1 (logand ,x1 ,x0) ,x1 (logxor ,x1 ,x4) ,x2 (mod32lognot ,x2) ,x2 (logior ,x2 ,x0) ,x4 (logxor ,x4 ,x2))) (defmacro sosemanuk-lt (x0 x1 x2 x3) `(setf ,x0 (rol32 ,x0 13) ,x2 (rol32 ,x2 3) ,x1 (logxor ,x1 ,x0 ,x2) ,x3 (logxor ,x3 ,x2 (mod32ash ,x0 3)) ,x1 (rol32 ,x1 1) ,x3 (rol32 ,x3 7) ,x0 (logxor ,x0 ,x1 ,x3) ,x2 (logxor ,x2 ,x3 (mod32ash ,x1 7)) ,x0 (rol32 ,x0 5) ,x2 (rol32 ,x2 22))) (defmacro sosemanuk-mkname (prefix n) `,(read-from-string (format nil "~a~d" prefix n))) (defclass sosemanuk (stream-cipher) ((state :accessor sosemanuk-state :initform (make-array 10 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (10))) (state-r :accessor sosemanuk-state-r :initform (make-array 2 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (2))) (keystream-buffer :accessor sosemanuk-keystream-buffer :initform (make-array 80 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (80))) (keystream-buffer-remaining :accessor sosemanuk-keystream-buffer-remaining :initform 0 :type (integer 0 80)) (subkeys :accessor sosemanuk-subkeys :type (or (simple-array (unsigned-byte 32) (100)) null)))) (defmethod schedule-key ((cipher sosemanuk) key) (let ((key-length (length key)) (subkeys (make-array 100 :element-type '(unsigned-byte 32))) (buffer (make-array 32 :element-type '(unsigned-byte 8))) (w0 0) (w1 0) (w2 0) (w3 0) (w4 0) (w5 0) (w6 0) (w7 0) (i 0)) (declare (type (simple-array (unsigned-byte 32) (100)) subkeys) (type (simple-array (unsigned-byte 8) (32)) buffer) (type (unsigned-byte 32) w0 w1 w2 w3 w4 w5 w6 w7) (type fixnum key-length i)) (replace buffer key :end2 key-length) (when (< key-length 32) (setf (aref buffer key-length) 1) (when (< key-length 31) (fill buffer 0 :start (1+ key-length)))) (setf w0 (ub32ref/le buffer 0) w1 (ub32ref/le buffer 4) w2 (ub32ref/le buffer 8) w3 (ub32ref/le buffer 12) w4 (ub32ref/le buffer 16) w5 (ub32ref/le buffer 20) w6 (ub32ref/le buffer 24) w7 (ub32ref/le buffer 28)) (macrolet ((sks (s o0 o1 o2 o3 d0 d1 d2 d3) `(let ((r0 (sosemanuk-mkname "w" ,o0)) (r1 (sosemanuk-mkname "w" ,o1)) (r2 (sosemanuk-mkname "w" ,o2)) (r3 (sosemanuk-mkname "w" ,o3)) (r4 0)) (declare (type (unsigned-byte 32) r0 r1 r2 r3)) (,s r0 r1 r2 r3 r4) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d0)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d1)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d2)) (incf i) (setf (aref subkeys i) (sosemanuk-mkname "r" ,d3)) (incf i))) (sks0 () `(sks sosemanuk-s0 4 5 6 7 1 4 2 0)) (sks1 () `(sks sosemanuk-s1 0 1 2 3 2 0 3 1)) (sks2 () `(sks sosemanuk-s2 4 5 6 7 2 3 1 4)) (sks3 () `(sks sosemanuk-s3 0 1 2 3 1 2 3 4)) (sks4 () `(sks sosemanuk-s4 4 5 6 7 1 4 0 3)) (sks5 () `(sks sosemanuk-s5 0 1 2 3 1 3 0 2)) (sks6 () `(sks sosemanuk-s6 4 5 6 7 0 1 4 2)) (sks7 () `(sks sosemanuk-s7 0 1 2 3 4 3 1 0)) (wup (wi wi5 wi3 wi1 cc) `(setf ,wi (rol32 (logxor ,wi ,wi5 ,wi3 ,wi1 ,cc #x9e3779b9) 11))) (wup0 (cc) `(progn (wup w0 w3 w5 w7 ,cc) (wup w1 w4 w6 w0 ,(+ cc 1)) (wup w2 w5 w7 w1 ,(+ cc 2)) (wup w3 w6 w0 w2 ,(+ cc 3)))) (wup1 (cc) `(progn (wup w4 w7 w1 w3 ,cc) (wup w5 w0 w2 w4 ,(+ cc 1)) (wup w6 w1 w3 w5 ,(+ cc 2)) (wup w7 w2 w4 w6 ,(+ cc 3))))) (wup0 0) (sks3) (wup1 4) (sks2) (wup0 8) (sks1) (wup1 12) (sks0) (wup0 16) (sks7) (wup1 20) (sks6) (wup0 24) (sks5) (wup1 28) (sks4) (wup0 32) (sks3) (wup1 36) (sks2) (wup0 40) (sks1) (wup1 44) (sks0) (wup0 48) (sks7) (wup1 52) (sks6) (wup0 56) (sks5) (wup1 60) (sks4) (wup0 64) (sks3) (wup1 68) (sks2) (wup0 72) (sks1) (wup1 76) (sks0) (wup0 80) (sks7) (wup1 84) (sks6) (wup0 88) (sks5) (wup1 92) (sks4) (wup0 96) (sks3) (setf (sosemanuk-subkeys cipher) subkeys))) cipher) (defmethod shared-initialize :after ((cipher sosemanuk) slot-names &rest initargs &key initialization-vector &allow-other-keys) (declare (ignore slot-names initargs)) (let ((state (sosemanuk-state cipher)) (state-r (sosemanuk-state-r cipher)) (subkeys (sosemanuk-subkeys cipher)) (r0 0) (r1 0) (r2 0) (r3 0) (r4 0)) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r subkeys) (type (unsigned-byte 32) r0 r1 r2 r3 r4)) (when initialization-vector (if (= (length initialization-vector) 16) (setf r0 (ub32ref/le initialization-vector 0) r1 (ub32ref/le initialization-vector 4) r2 (ub32ref/le initialization-vector 8) r3 (ub32ref/le initialization-vector 12)) (error 'invalid-initialization-vector :cipher (class-name (class-of cipher)) :block-length 16))) (macrolet ((ka (zc x0 x1 x2 x3) `(setf ,x0 (logxor ,x0 (aref subkeys ,zc)) ,x1 (logxor ,x1 (aref subkeys ,(+ zc 1))) ,x2 (logxor ,x2 (aref subkeys ,(+ zc 2))) ,x3 (logxor ,x3 (aref subkeys ,(+ zc 3))))) (fss (zc s i0 i1 i2 i3 i4 o0 o1 o2 o3) `(progn (ka ,zc (sosemanuk-mkname "r" ,i0) (sosemanuk-mkname "r" ,i1) (sosemanuk-mkname "r" ,i2) (sosemanuk-mkname "r" ,i3)) (,s (sosemanuk-mkname "r" ,i0) (sosemanuk-mkname "r" ,i1) (sosemanuk-mkname "r" ,i2) (sosemanuk-mkname "r" ,i3) (sosemanuk-mkname "r" ,i4)) (sosemanuk-lt (sosemanuk-mkname "r" ,o0) (sosemanuk-mkname "r" ,o1) (sosemanuk-mkname "r" ,o2) (sosemanuk-mkname "r" ,o3)))) (fsf (zc s i0 i1 i2 i3 i4 o0 o1 o2 o3) `(progn (fss ,zc ,s ,i0 ,i1 ,i2 ,i3 ,i4 ,o0 ,o1 ,o2 ,o3) (ka ,(+ zc 4) (sosemanuk-mkname "r" ,o0) (sosemanuk-mkname "r" ,o1) (sosemanuk-mkname "r" ,o2) (sosemanuk-mkname "r" ,o3))))) (fss 0 sosemanuk-s0 0 1 2 3 4 1 4 2 0) (fss 4 sosemanuk-s1 1 4 2 0 3 2 1 0 4) (fss 8 sosemanuk-s2 2 1 0 4 3 0 4 1 3) (fss 12 sosemanuk-s3 0 4 1 3 2 4 1 3 2) (fss 16 sosemanuk-s4 4 1 3 2 0 1 0 4 2) (fss 20 sosemanuk-s5 1 0 4 2 3 0 2 1 4) (fss 24 sosemanuk-s6 0 2 1 4 3 0 2 3 1) (fss 28 sosemanuk-s7 0 2 3 1 4 4 1 2 0) (fss 32 sosemanuk-s0 4 1 2 0 3 1 3 2 4) (fss 36 sosemanuk-s1 1 3 2 4 0 2 1 4 3) (fss 40 sosemanuk-s2 2 1 4 3 0 4 3 1 0) (fss 44 sosemanuk-s3 4 3 1 0 2 3 1 0 2) (setf (aref state 9) r3 (aref state 8) r1 (aref state 7) r0 (aref state 6) r2) (fss 48 sosemanuk-s4 3 1 0 2 4 1 4 3 2) (fss 52 sosemanuk-s5 1 4 3 2 0 4 2 1 3) (fss 56 sosemanuk-s6 4 2 1 3 0 4 2 0 1) (fss 60 sosemanuk-s7 4 2 0 1 3 3 1 2 4) (fss 64 sosemanuk-s0 3 1 2 4 0 1 0 2 3) (fss 68 sosemanuk-s1 1 0 2 3 4 2 1 3 0) (setf (aref state-r 0) r2 (aref state 4) r1 (aref state-r 1) r3 (aref state 5) r0) (fss 72 sosemanuk-s2 2 1 3 0 4 3 0 1 4) (fss 76 sosemanuk-s3 3 0 1 4 2 0 1 4 2) (fss 80 sosemanuk-s4 0 1 4 2 3 1 3 0 2) (fss 84 sosemanuk-s5 1 3 0 2 4 3 2 1 0) (fss 88 sosemanuk-s6 3 2 1 0 4 3 2 4 1) (fsf 92 sosemanuk-s7 3 2 4 1 0 0 1 2 3) (setf (aref state 3) r0 (aref state 2) r1 (aref state 1) r2 (aref state 0) r3)) (fill subkeys 0) (setf (sosemanuk-subkeys cipher) nil (sosemanuk-keystream-buffer-remaining cipher) 0)) cipher) (defun sosemanuk-compute-block (state state-r buffer) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r) (type (simple-array (unsigned-byte 8) (80)) buffer) (optimize (speed 3) (space 0) (safety 0) (debug 0))) (let ((s0 (aref state 0)) (s1 (aref state 1)) (s2 (aref state 2)) (s3 (aref state 3)) (s4 (aref state 4)) (s5 (aref state 5)) (s6 (aref state 6)) (s7 (aref state 7)) (s8 (aref state 8)) (s9 (aref state 9)) (r1 (aref state-r 0)) (r2 (aref state-r 1)) (u0 0) (u1 0) (u2 0) (u3 0) (u4 0) (v0 0) (v1 0) (v2 0) (v3 0)) (declare (type (unsigned-byte 32) s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 r1 r2) (type (unsigned-byte 32) u0 u1 u2 u3 u4 v0 v1 v2 v3)) (macrolet ((mul-a (x) `(logxor (mod32ash ,x 8) (aref +sosemanuk-mul-a+ (mod32ash ,x -24)))) (mul-g (x) `(logxor (mod32ash ,x -8) (aref +sosemanuk-mul-ia+ (logand ,x 255)))) (xmux (c x y) `(if (zerop (logand ,c 1)) ,x (logxor ,x ,y))) (fsm (x1 x8) `(let ((tt 0) (or1 0)) (declare (type (unsigned-byte 32) tt or1)) (setf tt (xmux r1 (sosemanuk-mkname "s" ,x1) (sosemanuk-mkname "s" ,x8)) or1 r1 r1 (mod32+ r2 tt) tt (mod32* or1 #x54655307) r2 (rol32 tt 7)))) (lru (x0 x3 x9 dd) `(setf ,dd (sosemanuk-mkname "s" ,x0) (sosemanuk-mkname "s" ,x0) (logxor (mul-a (sosemanuk-mkname "s" ,x0)) (mul-g (sosemanuk-mkname "s" ,x3)) (sosemanuk-mkname "s" ,x9)))) (cc1 (x9 ee) `(setf ,ee (logxor (mod32+ (sosemanuk-mkname "s" ,x9) r1) r2))) (stp (x0 x1 x3 x8 x9 dd ee) `(progn (fsm ,x1 ,x8) (lru ,x0 ,x3 ,x9 ,dd) (cc1 ,x9 ,ee))) (srd (s x0 x1 x2 x3 ooff) `(progn (,s u0 u1 u2 u3 u4) (setf (ub32ref/le buffer ,ooff) (logxor (sosemanuk-mkname "u" ,x0) v0) (ub32ref/le buffer ,(+ ooff 4)) (logxor (sosemanuk-mkname "u" ,x1) v1) (ub32ref/le buffer ,(+ ooff 8)) (logxor (sosemanuk-mkname "u" ,x2) v2) (ub32ref/le buffer ,(+ ooff 12)) (logxor (sosemanuk-mkname "u" ,x3) v3))))) (stp 0 1 3 8 9 v0 u0) (stp 1 2 4 9 0 v1 u1) (stp 2 3 5 0 1 v2 u2) (stp 3 4 6 1 2 v3 u3) (srd sosemanuk-s2 2 3 1 4 0) (stp 4 5 7 2 3 v0 u0) (stp 5 6 8 3 4 v1 u1) (stp 6 7 9 4 5 v2 u2) (stp 7 8 0 5 6 v3 u3) (srd sosemanuk-s2 2 3 1 4 16) (stp 8 9 1 6 7 v0 u0) (stp 9 0 2 7 8 v1 u1) (stp 0 1 3 8 9 v2 u2) (stp 1 2 4 9 0 v3 u3) (srd sosemanuk-s2 2 3 1 4 32) (stp 2 3 5 0 1 v0 u0) (stp 3 4 6 1 2 v1 u1) (stp 4 5 7 2 3 v2 u2) (stp 5 6 8 3 4 v3 u3) (srd sosemanuk-s2 2 3 1 4 48) (stp 6 7 9 4 5 v0 u0) (stp 7 8 0 5 6 v1 u1) (stp 8 9 1 6 7 v2 u2) (stp 9 0 2 7 8 v3 u3) (srd sosemanuk-s2 2 3 1 4 64) (setf (aref state 0) s0 (aref state 1) s1 (aref state 2) s2 (aref state 3) s3 (aref state 4) s4 (aref state 5) s5 (aref state 6) s6 (aref state 7) s7 (aref state 8) s8 (aref state 9) s9 (aref state-r 0) r1 (aref state-r 1) r2))) (values)) (define-stream-cryptor sosemanuk (let ((state (sosemanuk-state context)) (state-r (sosemanuk-state-r context)) (keystream-buffer (sosemanuk-keystream-buffer context)) (keystream-buffer-remaining (sosemanuk-keystream-buffer-remaining context)) (remaining-keystream (make-array 80 :element-type '(unsigned-byte 8)))) (declare (type (simple-array (unsigned-byte 32) (*)) state state-r) (type (simple-array (unsigned-byte 8) (80)) keystream-buffer remaining-keystream) (type (integer 0 80) keystream-buffer-remaining) (dynamic-extent remaining-keystream)) (unless (zerop length) (unless (zerop keystream-buffer-remaining) (let ((size (min length keystream-buffer-remaining))) (declare (type (integer 0 80) size)) (replace remaining-keystream keystream-buffer :end1 size :start2 (- 80 keystream-buffer-remaining)) (xor-block size remaining-keystream plaintext plaintext-start ciphertext ciphertext-start) (decf keystream-buffer-remaining size) (decf length size) (incf ciphertext-start size) (incf plaintext-start size))) (unless (zerop length) (loop (sosemanuk-compute-block state state-r keystream-buffer) (when (<= length 80) (xor-block length keystream-buffer plaintext plaintext-start ciphertext ciphertext-start) (setf (sosemanuk-keystream-buffer-remaining context) (- 80 length)) (return-from sosemanuk-crypt (values))) (xor-block 80 keystream-buffer plaintext plaintext-start ciphertext ciphertext-start) (decf length 80) (incf ciphertext-start 80) (incf plaintext-start 80))) (setf (sosemanuk-keystream-buffer-remaining context) keystream-buffer-remaining)) (values))) (defcipher sosemanuk (:mode :stream) (:crypt-function sosemanuk-crypt) (:key-length (:variable 16 32 1)))
a565b8d81346f8535a1666e8bb9759c5265d02ffc2e72d6157cdd4abaa1af5c1
hugoduncan/makejack
jar.clj
(ns makejack.tasks.jar (:require [babashka.fs :as fs] [clojure.tools.build.api :as b] [makejack.defaults.api :as defaults] [makejack.deps.api :as mj-deps] [makejack.project-data.api :as project-data] [makejack.verbose.api :as v])) (defn jar "Build a jar file" [params] (binding [b/*project-root* (:dir params ".")] (let [params (defaults/project-data params) params (project-data/expand-version params) jar-path (fs/path (defaults/target-path params) (defaults/jar-filename params)) basis (mj-deps/lift-local-deps (or (:basis params) (defaults/basis params))) src-dirs (defaults/paths basis) class-dir (str (defaults/classes-path params)) relative? (complement fs/absolute?)] (v/println params "Build jar" (str jar-path)) (binding [b/*project-root* (:dir params ".")] (b/write-pom {:basis (update basis :paths #(filterv relative? %)) :class-dir class-dir :lib (:name params) :version (:version params)}) (b/copy-dir {:src-dirs src-dirs :target-dir class-dir :ignores (defaults/jar-ignores)}) (b/jar {:class-dir class-dir :jar-file (str jar-path)})) (assoc params :jar-file (str jar-path)))))
null
https://raw.githubusercontent.com/hugoduncan/makejack/29bd56233997bd1b9a2140e562f6364251b549a6/bases/tasks/src/makejack/tasks/jar.clj
clojure
(ns makejack.tasks.jar (:require [babashka.fs :as fs] [clojure.tools.build.api :as b] [makejack.defaults.api :as defaults] [makejack.deps.api :as mj-deps] [makejack.project-data.api :as project-data] [makejack.verbose.api :as v])) (defn jar "Build a jar file" [params] (binding [b/*project-root* (:dir params ".")] (let [params (defaults/project-data params) params (project-data/expand-version params) jar-path (fs/path (defaults/target-path params) (defaults/jar-filename params)) basis (mj-deps/lift-local-deps (or (:basis params) (defaults/basis params))) src-dirs (defaults/paths basis) class-dir (str (defaults/classes-path params)) relative? (complement fs/absolute?)] (v/println params "Build jar" (str jar-path)) (binding [b/*project-root* (:dir params ".")] (b/write-pom {:basis (update basis :paths #(filterv relative? %)) :class-dir class-dir :lib (:name params) :version (:version params)}) (b/copy-dir {:src-dirs src-dirs :target-dir class-dir :ignores (defaults/jar-ignores)}) (b/jar {:class-dir class-dir :jar-file (str jar-path)})) (assoc params :jar-file (str jar-path)))))
2e240eec5a44d4d27534067c5e188c1542e8cd93c9727a972d8de21ca92c3003
helium/router
router_decoder_cayenne.erl
%%%------------------------------------------------------------------- %%% @doc %%% == Cayenne Decoder == %%% LPP = Low Power Payload MyDevices Cayenne LPP Docs %%% [/#lora-cayenne-low-power-payload] %%% Test Vectors [] %%% #issuecomment-822964880 %%% %%% `last' key is added to last map in collection for json templating %%% %%% @end %%%------------------------------------------------------------------- -module(router_decoder_cayenne). -export([decode/3]). -define(DIGITAL_IN, 0). -define(DIGITAL_OUT, 1). -define(ANALOG_IN, 2). -define(ANALOG_OUT, 3). -define(GENERIC_SENSOR, 100). -define(LUMINANCE, 101). -define(PRESENCE, 102). -define(TEMPERATURE, 103). -define(HUMIDITY, 104). -define(ACCELEROMETER, 113). -define(BAROMETER, 115). -define(VOLTAGE, 116). -define(CURRENT, 117). -define(FREQUENCY, 118). -define(PERCENTAGE, 120). -define(ALTITUDE, 121). -define(CONCENTRATION, 125). -define(POWER, 128). -define(DISTANCE, 130). -define(ENERGY, 131). -define(DIRECTION, 132). -define(GYROMETER, 134). -define(COLOUR, 135). -define(GPS, 136). -define(SWITCH, 142). -spec decode(router_decoder:decoder(), binary(), integer()) -> {ok, binary()} | {error, any()}. decode(_Decoder, Payload, _Port) -> decode_lpp(Payload, []). decode_lpp(<<>>, [M | Tail]) -> {ok, lists:reverse([maps:put(last, true, M) | Tail])}; decode_lpp(<<Channel:8/unsigned-integer, _/binary>>, _) when Channel > 99 -> {error, lpp_reserved_channel}; decode_lpp( <<Channel:8/unsigned-integer, ?DIGITAL_IN:8/integer, Value:8/unsigned-integer, Rest/binary>>, Acc ) -> TODO this should be 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?DIGITAL_IN, value => Value, name => digital_in} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DIGITAL_OUT:8/integer, Value:8/unsigned-integer, Rest/binary>>, Acc ) -> TODO this should be 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?DIGITAL_OUT, value => Value, name => digital_out} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ANALOG_IN:8/integer, Value:16/signed-integer, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?ANALOG_IN, value => Value / 100, name => analog_in} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ANALOG_OUT:8/integer, Value:16/big-signed-integer, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?ANALOG_OUT, value => Value / 100, name => analog_out} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GENERIC_SENSOR:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{channel => Channel, type => ?GENERIC_SENSOR, value => Value / 100, name => generic_sensor} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?LUMINANCE:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?LUMINANCE, value => Value, unit => lux, name => luminance} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?PRESENCE:8/integer, Value:8/integer, Rest/binary>>, Acc ) -> TODO value is 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?PRESENCE, value => Value, name => presence} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?TEMPERATURE:8/integer, Value:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?TEMPERATURE, value => Value / 10, unit => celcius, name => temperature } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?HUMIDITY:8/integer, Value:8/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?HUMIDITY, value => Value / 2, unit => percent, name => humidity } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ACCELEROMETER:8/integer, X:16/integer-signed-big, Y:16/integer-signed-big, Z:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ACCELEROMETER, value => #{x => X / 1000, y => Y / 1000, z => Z / 1000}, unit => 'G', name => accelerometer } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?BAROMETER:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?BAROMETER, value => Value / 10, unit => 'hPa', name => humidity } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?VOLTAGE:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?VOLTAGE, value => Value / 100, unit => 'V', name => voltage } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?CURRENT:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?CURRENT, value => Value / 1000, unit => 'A', name => current } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?FREQUENCY:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?FREQUENCY, value => Value, unit => 'Hz', name => frequency } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?PERCENTAGE:8/integer, Value:8/integer-unsigned, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?PERCENTAGE, value => Value, unit => '%', name => percentage } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ALTITUDE:8/integer, Value:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ALTITUDE, value => Value, unit => 'm', name => altitude } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?CONCENTRATION:8/integer, Value:16/integer-unsigned, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?CONCENTRATION, value => Value, unit => 'PPM', name => concentration } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?POWER:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?POWER, value => Value, unit => 'W', name => power } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DISTANCE:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?DISTANCE, value => Value / 1000, unit => 'm', name => distance } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ENERGY:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ENERGY, value => Value / 1000, unit => 'kWh', name => energy } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DIRECTION:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?DIRECTION, value => Value, unit => 'º', name => direction } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GYROMETER:8/integer, X:16/integer-signed-big, Y:16/integer-signed-big, Z:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?GYROMETER, value => #{x => X / 100, y => Y / 100, z => Z / 100}, unit => '°/s', name => gyrometer } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?COLOUR:8/integer, R:8/integer, G:8/integer, B:8/integer, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?COLOUR, value => #{r => R, g => G, b => B}, name => colour } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GPS:8/integer, Lat:24/integer-signed-big, Lon:24/integer-signed-big, Alt:24/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?GPS, value => #{latitude => Lat / 10000, longitude => Lon / 10000, altitude => Alt / 100}, name => gps } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?SWITCH:8/integer, Value:8/integer, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?SWITCH, value => Value, name => switch } | Acc ]); decode_lpp(_, _) -> {error, lpp_decoder_failure}. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). decode_test() -> %% test vectors from ?assertEqual( {ok, [ #{ channel => 3, value => 27.2, unit => celcius, name => temperature, type => ?TEMPERATURE }, #{ channel => 5, value => 25.5, unit => celcius, name => temperature, type => ?TEMPERATURE, last => true } ]}, decode_lpp(<<16#03, 16#67, 16#01, 16#10, 16#05, 16#67, 16#00, 16#FF>>, []) ), ?assertEqual( {ok, [ #{ channel => 6, value => #{x => 1.234, y => -1.234, z => 0.0}, name => accelerometer, type => ?ACCELEROMETER, unit => 'G', last => true } ]}, decode_lpp(<<16#06, 16#71, 16#04, 16#D2, 16#FB, 16#2E, 16#00, 16#00>>, []) ). -endif.
null
https://raw.githubusercontent.com/helium/router/d0dc9aadfcb3042e9f8e81f5afa71ff34bd208b8/src/decoders/router_decoder_cayenne.erl
erlang
------------------------------------------------------------------- @doc == Cayenne Decoder == [/#lora-cayenne-low-power-payload] Test Vectors [] #issuecomment-822964880 `last' key is added to last map in collection for json templating @end ------------------------------------------------------------------- ', test vectors from
LPP = Low Power Payload MyDevices Cayenne LPP Docs -module(router_decoder_cayenne). -export([decode/3]). -define(DIGITAL_IN, 0). -define(DIGITAL_OUT, 1). -define(ANALOG_IN, 2). -define(ANALOG_OUT, 3). -define(GENERIC_SENSOR, 100). -define(LUMINANCE, 101). -define(PRESENCE, 102). -define(TEMPERATURE, 103). -define(HUMIDITY, 104). -define(ACCELEROMETER, 113). -define(BAROMETER, 115). -define(VOLTAGE, 116). -define(CURRENT, 117). -define(FREQUENCY, 118). -define(PERCENTAGE, 120). -define(ALTITUDE, 121). -define(CONCENTRATION, 125). -define(POWER, 128). -define(DISTANCE, 130). -define(ENERGY, 131). -define(DIRECTION, 132). -define(GYROMETER, 134). -define(COLOUR, 135). -define(GPS, 136). -define(SWITCH, 142). -spec decode(router_decoder:decoder(), binary(), integer()) -> {ok, binary()} | {error, any()}. decode(_Decoder, Payload, _Port) -> decode_lpp(Payload, []). decode_lpp(<<>>, [M | Tail]) -> {ok, lists:reverse([maps:put(last, true, M) | Tail])}; decode_lpp(<<Channel:8/unsigned-integer, _/binary>>, _) when Channel > 99 -> {error, lpp_reserved_channel}; decode_lpp( <<Channel:8/unsigned-integer, ?DIGITAL_IN:8/integer, Value:8/unsigned-integer, Rest/binary>>, Acc ) -> TODO this should be 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?DIGITAL_IN, value => Value, name => digital_in} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DIGITAL_OUT:8/integer, Value:8/unsigned-integer, Rest/binary>>, Acc ) -> TODO this should be 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?DIGITAL_OUT, value => Value, name => digital_out} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ANALOG_IN:8/integer, Value:16/signed-integer, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?ANALOG_IN, value => Value / 100, name => analog_in} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ANALOG_OUT:8/integer, Value:16/big-signed-integer, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?ANALOG_OUT, value => Value / 100, name => analog_out} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GENERIC_SENSOR:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{channel => Channel, type => ?GENERIC_SENSOR, value => Value / 100, name => generic_sensor} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?LUMINANCE:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> TODO is the value MSB or LSB decode_lpp(Rest, [ #{channel => Channel, type => ?LUMINANCE, value => Value, unit => lux, name => luminance} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?PRESENCE:8/integer, Value:8/integer, Rest/binary>>, Acc ) -> TODO value is 0 or 1 decode_lpp(Rest, [ #{channel => Channel, type => ?PRESENCE, value => Value, name => presence} | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?TEMPERATURE:8/integer, Value:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?TEMPERATURE, value => Value / 10, unit => celcius, name => temperature } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?HUMIDITY:8/integer, Value:8/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?HUMIDITY, value => Value / 2, unit => percent, name => humidity } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ACCELEROMETER:8/integer, X:16/integer-signed-big, Y:16/integer-signed-big, Z:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ACCELEROMETER, value => #{x => X / 1000, y => Y / 1000, z => Z / 1000}, unit => 'G', name => accelerometer } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?BAROMETER:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?BAROMETER, value => Value / 10, unit => 'hPa', name => humidity } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?VOLTAGE:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?VOLTAGE, value => Value / 100, unit => 'V', name => voltage } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?CURRENT:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?CURRENT, value => Value / 1000, unit => 'A', name => current } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?FREQUENCY:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?FREQUENCY, value => Value, unit => 'Hz', name => frequency } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?PERCENTAGE:8/integer, Value:8/integer-unsigned, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?PERCENTAGE, value => Value, name => percentage } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ALTITUDE:8/integer, Value:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ALTITUDE, value => Value, unit => 'm', name => altitude } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?CONCENTRATION:8/integer, Value:16/integer-unsigned, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?CONCENTRATION, value => Value, unit => 'PPM', name => concentration } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?POWER:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?POWER, value => Value, unit => 'W', name => power } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DISTANCE:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?DISTANCE, value => Value / 1000, unit => 'm', name => distance } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?ENERGY:8/integer, Value:32/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?ENERGY, value => Value / 1000, unit => 'kWh', name => energy } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?DIRECTION:8/integer, Value:16/integer-unsigned-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?DIRECTION, value => Value, unit => 'º', name => direction } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GYROMETER:8/integer, X:16/integer-signed-big, Y:16/integer-signed-big, Z:16/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?GYROMETER, value => #{x => X / 100, y => Y / 100, z => Z / 100}, unit => '°/s', name => gyrometer } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?COLOUR:8/integer, R:8/integer, G:8/integer, B:8/integer, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?COLOUR, value => #{r => R, g => G, b => B}, name => colour } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?GPS:8/integer, Lat:24/integer-signed-big, Lon:24/integer-signed-big, Alt:24/integer-signed-big, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?GPS, value => #{latitude => Lat / 10000, longitude => Lon / 10000, altitude => Alt / 100}, name => gps } | Acc ]); decode_lpp( <<Channel:8/unsigned-integer, ?SWITCH:8/integer, Value:8/integer, Rest/binary>>, Acc ) -> decode_lpp(Rest, [ #{ channel => Channel, type => ?SWITCH, value => Value, name => switch } | Acc ]); decode_lpp(_, _) -> {error, lpp_decoder_failure}. -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). decode_test() -> ?assertEqual( {ok, [ #{ channel => 3, value => 27.2, unit => celcius, name => temperature, type => ?TEMPERATURE }, #{ channel => 5, value => 25.5, unit => celcius, name => temperature, type => ?TEMPERATURE, last => true } ]}, decode_lpp(<<16#03, 16#67, 16#01, 16#10, 16#05, 16#67, 16#00, 16#FF>>, []) ), ?assertEqual( {ok, [ #{ channel => 6, value => #{x => 1.234, y => -1.234, z => 0.0}, name => accelerometer, type => ?ACCELEROMETER, unit => 'G', last => true } ]}, decode_lpp(<<16#06, 16#71, 16#04, 16#D2, 16#FB, 16#2E, 16#00, 16#00>>, []) ). -endif.
b6866750d000988d2f1ff2af411972cd4a97aa2179e1b4371d8f9aabdedb799a
zachjs/sv2v
Expr.hs
# LANGUAGE PatternSynonyms # sv2v - Author : < > - Initial Verilog AST Author : < > - - SystemVerilog expressions - Author: Zachary Snow <> - Initial Verilog AST Author: Tom Hawkins <> - - SystemVerilog expressions -} module Language.SystemVerilog.AST.Expr ( Expr (..) , Range , TypeOrExpr , Args (..) , PartSelectMode (..) , DimsFn (..) , DimFn (..) , showAssignment , showRange , showRanges , ParamBinding , showParams , pattern RawNum ) where import Data.List (intercalate) import Text.Printf (printf) import Language.SystemVerilog.AST.Number (Number(..)) import Language.SystemVerilog.AST.Op import Language.SystemVerilog.AST.ShowHelp import {-# SOURCE #-} Language.SystemVerilog.AST.Type type Range = (Expr, Expr) type TypeOrExpr = Either Type Expr pattern RawNum :: Integer -> Expr pattern RawNum n = Number (Decimal (-32) True n) data Expr = String String | Real String | Number Number | Time String | Ident Identifier | PSIdent Identifier Identifier | CSIdent Identifier [ParamBinding] Identifier | Range Expr PartSelectMode Range | Bit Expr Expr | Repeat Expr [Expr] | Concat [Expr] | Stream StreamOp Expr [Expr] | Call Expr Args | UniOp UniOp Expr | BinOp BinOp Expr Expr | Mux Expr Expr Expr | Cast TypeOrExpr Expr | DimsFn DimsFn TypeOrExpr | DimFn DimFn TypeOrExpr Expr | Dot Expr Identifier | Pattern [(TypeOrExpr, Expr)] | Inside Expr [Expr] | MinTypMax Expr Expr Expr | ExprAsgn Expr Expr | Nil deriving Eq instance Show Expr where show (Nil ) = "" show (Time str ) = str show (Ident str ) = str show (Real str ) = str show (Number n ) = show n show (PSIdent x y ) = printf "%s::%s" x y show (CSIdent x p y) = printf "%s#%s::%s" x (showParams p) y show (String str ) = printf "\"%s\"" str show (Bit e b ) = printf "%s[%s]" (show e) (show b) show (Range e m r) = printf "%s[%s%s%s]" (show e) (show $ fst r) (show m) (show $ snd r) show (Repeat e l ) = printf "{%s {%s}}" (show e) (commas $ map show l) show (Concat l ) = printf "{%s}" (commas $ map show l) show (Stream o e l) = printf "{%s %s%s}" (show o) (show e) (show $ Concat l) show (Cast tore e ) = printf "%s'(%s)" toreStr (show e) where toreStr = either show (flip showBinOpPrec []) tore show (DimsFn f v ) = printf "%s(%s)" (show f) (showEither v) show (DimFn f v e) = printf "%s(%s, %s)" (show f) (showEither v) (show e) show (Inside e l ) = printf "(%s inside { %s })" (show e) (intercalate ", " $ map show l) show (Pattern l ) = printf "'{\n%s\n}" (indent $ intercalate ",\n" $ map showPatternItem l) where showPatternItem :: (TypeOrExpr, Expr) -> String showPatternItem (Right Nil, v) = show v showPatternItem (Right e, v) = printf "%s: %s" (show e) (show v) showPatternItem (Left t, v) = printf "%s: %s" tStr (show v) where tStr = if null (show t) then "default" else show t show (MinTypMax a b c) = printf "(%s : %s : %s)" (show a) (show b) (show c) show (ExprAsgn l r) = printf "(%s = %s)" (show l) (show r) show e@UniOp{} = showsPrec 0 e "" show e@BinOp{} = showsPrec 0 e "" show e@Dot {} = showsPrec 0 e "" show e@Mux {} = showsPrec 0 e "" show e@Call {} = showsPrec 0 e "" showsPrec _ (UniOp o e ) = shows o . showUniOpPrec e showsPrec _ (BinOp o a b) = showBinOpPrec a . showChar ' ' . shows o . showChar ' ' . showBinOpPrec b showsPrec _ (Dot e n ) = shows e . showChar '.' . showString n showsPrec _ (Mux c a b) = showChar '(' . shows c . showString " ? " . shows a . showString " : " . shows b . showChar ')' showsPrec _ (Call e l ) = shows e . shows l showsPrec _ e = \s -> show e ++ s data Args = Args [Expr] [(Identifier, Expr)] deriving Eq instance Show Args where show (Args pnArgs kwArgs) = '(' : commas strs ++ ")" where strs = (map show pnArgs) ++ (map showKwArg kwArgs) showKwArg (x, e) = printf ".%s(%s)" x (show e) data PartSelectMode = NonIndexed | IndexedPlus | IndexedMinus deriving Eq instance Show PartSelectMode where show NonIndexed = ":" show IndexedPlus = "+:" show IndexedMinus = "-:" data DimsFn = FnBits | FnDimensions | FnUnpackedDimensions deriving Eq data DimFn = FnLeft | FnRight | FnLow | FnHigh | FnIncrement | FnSize deriving Eq instance Show DimsFn where show FnBits = "$bits" show FnDimensions = "$dimensions" show FnUnpackedDimensions = "$unpacked_dimensions" instance Show DimFn where show FnLeft = "$left" show FnRight = "$right" show FnLow = "$low" show FnHigh = "$high" show FnIncrement = "$increment" show FnSize = "$size" showAssignment :: Expr -> String showAssignment Nil = "" showAssignment val = " = " ++ show val showRanges :: [Range] -> String showRanges [] = "" showRanges l = ' ' : concatMap showRange l showRange :: Range -> String showRange (h, l) = '[' : show h ++ ':' : show l ++ "]" showUniOpPrec :: Expr -> ShowS showUniOpPrec e@UniOp{} = (showParen True . shows) e showUniOpPrec e@BinOp{} = (showParen True . shows) e showUniOpPrec e = shows e showBinOpPrec :: Expr -> ShowS showBinOpPrec e@BinOp{} = (showParen True . shows) e showBinOpPrec e = shows e type ParamBinding = (Identifier, TypeOrExpr) showParams :: [ParamBinding] -> String showParams params = indentedParenList $ map showParam params showParam :: ParamBinding -> String showParam ("", arg) = showEither arg showParam (i, arg) = printf ".%s(%s)" i (showEither arg)
null
https://raw.githubusercontent.com/zachjs/sv2v/ed09fe88cffa38f36372ff29b32e15cd463a7bfe/src/Language/SystemVerilog/AST/Expr.hs
haskell
# SOURCE #
# LANGUAGE PatternSynonyms # sv2v - Author : < > - Initial Verilog AST Author : < > - - SystemVerilog expressions - Author: Zachary Snow <> - Initial Verilog AST Author: Tom Hawkins <> - - SystemVerilog expressions -} module Language.SystemVerilog.AST.Expr ( Expr (..) , Range , TypeOrExpr , Args (..) , PartSelectMode (..) , DimsFn (..) , DimFn (..) , showAssignment , showRange , showRanges , ParamBinding , showParams , pattern RawNum ) where import Data.List (intercalate) import Text.Printf (printf) import Language.SystemVerilog.AST.Number (Number(..)) import Language.SystemVerilog.AST.Op import Language.SystemVerilog.AST.ShowHelp type Range = (Expr, Expr) type TypeOrExpr = Either Type Expr pattern RawNum :: Integer -> Expr pattern RawNum n = Number (Decimal (-32) True n) data Expr = String String | Real String | Number Number | Time String | Ident Identifier | PSIdent Identifier Identifier | CSIdent Identifier [ParamBinding] Identifier | Range Expr PartSelectMode Range | Bit Expr Expr | Repeat Expr [Expr] | Concat [Expr] | Stream StreamOp Expr [Expr] | Call Expr Args | UniOp UniOp Expr | BinOp BinOp Expr Expr | Mux Expr Expr Expr | Cast TypeOrExpr Expr | DimsFn DimsFn TypeOrExpr | DimFn DimFn TypeOrExpr Expr | Dot Expr Identifier | Pattern [(TypeOrExpr, Expr)] | Inside Expr [Expr] | MinTypMax Expr Expr Expr | ExprAsgn Expr Expr | Nil deriving Eq instance Show Expr where show (Nil ) = "" show (Time str ) = str show (Ident str ) = str show (Real str ) = str show (Number n ) = show n show (PSIdent x y ) = printf "%s::%s" x y show (CSIdent x p y) = printf "%s#%s::%s" x (showParams p) y show (String str ) = printf "\"%s\"" str show (Bit e b ) = printf "%s[%s]" (show e) (show b) show (Range e m r) = printf "%s[%s%s%s]" (show e) (show $ fst r) (show m) (show $ snd r) show (Repeat e l ) = printf "{%s {%s}}" (show e) (commas $ map show l) show (Concat l ) = printf "{%s}" (commas $ map show l) show (Stream o e l) = printf "{%s %s%s}" (show o) (show e) (show $ Concat l) show (Cast tore e ) = printf "%s'(%s)" toreStr (show e) where toreStr = either show (flip showBinOpPrec []) tore show (DimsFn f v ) = printf "%s(%s)" (show f) (showEither v) show (DimFn f v e) = printf "%s(%s, %s)" (show f) (showEither v) (show e) show (Inside e l ) = printf "(%s inside { %s })" (show e) (intercalate ", " $ map show l) show (Pattern l ) = printf "'{\n%s\n}" (indent $ intercalate ",\n" $ map showPatternItem l) where showPatternItem :: (TypeOrExpr, Expr) -> String showPatternItem (Right Nil, v) = show v showPatternItem (Right e, v) = printf "%s: %s" (show e) (show v) showPatternItem (Left t, v) = printf "%s: %s" tStr (show v) where tStr = if null (show t) then "default" else show t show (MinTypMax a b c) = printf "(%s : %s : %s)" (show a) (show b) (show c) show (ExprAsgn l r) = printf "(%s = %s)" (show l) (show r) show e@UniOp{} = showsPrec 0 e "" show e@BinOp{} = showsPrec 0 e "" show e@Dot {} = showsPrec 0 e "" show e@Mux {} = showsPrec 0 e "" show e@Call {} = showsPrec 0 e "" showsPrec _ (UniOp o e ) = shows o . showUniOpPrec e showsPrec _ (BinOp o a b) = showBinOpPrec a . showChar ' ' . shows o . showChar ' ' . showBinOpPrec b showsPrec _ (Dot e n ) = shows e . showChar '.' . showString n showsPrec _ (Mux c a b) = showChar '(' . shows c . showString " ? " . shows a . showString " : " . shows b . showChar ')' showsPrec _ (Call e l ) = shows e . shows l showsPrec _ e = \s -> show e ++ s data Args = Args [Expr] [(Identifier, Expr)] deriving Eq instance Show Args where show (Args pnArgs kwArgs) = '(' : commas strs ++ ")" where strs = (map show pnArgs) ++ (map showKwArg kwArgs) showKwArg (x, e) = printf ".%s(%s)" x (show e) data PartSelectMode = NonIndexed | IndexedPlus | IndexedMinus deriving Eq instance Show PartSelectMode where show NonIndexed = ":" show IndexedPlus = "+:" show IndexedMinus = "-:" data DimsFn = FnBits | FnDimensions | FnUnpackedDimensions deriving Eq data DimFn = FnLeft | FnRight | FnLow | FnHigh | FnIncrement | FnSize deriving Eq instance Show DimsFn where show FnBits = "$bits" show FnDimensions = "$dimensions" show FnUnpackedDimensions = "$unpacked_dimensions" instance Show DimFn where show FnLeft = "$left" show FnRight = "$right" show FnLow = "$low" show FnHigh = "$high" show FnIncrement = "$increment" show FnSize = "$size" showAssignment :: Expr -> String showAssignment Nil = "" showAssignment val = " = " ++ show val showRanges :: [Range] -> String showRanges [] = "" showRanges l = ' ' : concatMap showRange l showRange :: Range -> String showRange (h, l) = '[' : show h ++ ':' : show l ++ "]" showUniOpPrec :: Expr -> ShowS showUniOpPrec e@UniOp{} = (showParen True . shows) e showUniOpPrec e@BinOp{} = (showParen True . shows) e showUniOpPrec e = shows e showBinOpPrec :: Expr -> ShowS showBinOpPrec e@BinOp{} = (showParen True . shows) e showBinOpPrec e = shows e type ParamBinding = (Identifier, TypeOrExpr) showParams :: [ParamBinding] -> String showParams params = indentedParenList $ map showParam params showParam :: ParamBinding -> String showParam ("", arg) = showEither arg showParam (i, arg) = printf ".%s(%s)" i (showEither arg)
62439bd976bfdca12bbafcb4c13e5b93b50c2a4c48348ecf07d766847068be1d
moby/vpnkit
cstructs.mli
* A subset of the Cstruct signature with type t = Cstruct.t list This should be replaced with another parser , perhaps ? This should be replaced with another parser, perhaps angstrom? *) type t = Cstruct.t list (** Data stored as a list of fragments *) val to_string: t -> string val shift: t -> int -> t val len: t -> int val sub: t -> int -> int -> t val get_uint8: t -> int -> int val to_cstruct: t -> Cstruct.t (** Returns a contiguous Cstruct.t, which may or may not involve a copy. *) module BE: sig val get_uint16: t -> int -> int val get_uint32: t -> int -> int32 end
null
https://raw.githubusercontent.com/moby/vpnkit/7bfcba6e59c1e5450b667a392bf56371faae58b2/src/cstructs/cstructs.mli
ocaml
* Data stored as a list of fragments * Returns a contiguous Cstruct.t, which may or may not involve a copy.
* A subset of the Cstruct signature with type t = Cstruct.t list This should be replaced with another parser , perhaps ? This should be replaced with another parser, perhaps angstrom? *) type t = Cstruct.t list val to_string: t -> string val shift: t -> int -> t val len: t -> int val sub: t -> int -> int -> t val get_uint8: t -> int -> int val to_cstruct: t -> Cstruct.t module BE: sig val get_uint16: t -> int -> int val get_uint32: t -> int -> int32 end
0ea557557283bb3a11df11a0f9682fc39a8df30140366b45e62d752b59bbcc9f
emqx/emqx
emqx_conf_cli.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ 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(emqx_conf_cli). -export([ load/0, admins/1, unload/0 ]). -define(CMD, cluster_call). load() -> emqx_ctl:register_command(?CMD, {?MODULE, admins}, []). unload() -> emqx_ctl:unregister_command(?CMD). admins(["status"]) -> status(); admins(["skip"]) -> status(), Nodes = mria_mnesia:running_nodes(), lists:foreach(fun emqx_cluster_rpc:skip_failed_commit/1, Nodes), status(); admins(["skip", Node0]) -> status(), Node = list_to_existing_atom(Node0), emqx_cluster_rpc:skip_failed_commit(Node), status(); admins(["tnxid", TnxId0]) -> TnxId = list_to_integer(TnxId0), emqx_ctl:print("~p~n", [emqx_cluster_rpc:query(TnxId)]); admins(["fast_forward"]) -> status(), Nodes = mria_mnesia:running_nodes(), TnxId = emqx_cluster_rpc:latest_tnx_id(), lists:foreach(fun(N) -> emqx_cluster_rpc:fast_forward_to_commit(N, TnxId) end, Nodes), status(); admins(["fast_forward", ToTnxId]) -> status(), Nodes = mria_mnesia:running_nodes(), TnxId = list_to_integer(ToTnxId), lists:foreach(fun(N) -> emqx_cluster_rpc:fast_forward_to_commit(N, TnxId) end, Nodes), status(); admins(["fast_forward", Node0, ToTnxId]) -> status(), TnxId = list_to_integer(ToTnxId), Node = list_to_existing_atom(Node0), emqx_cluster_rpc:fast_forward_to_commit(Node, TnxId), status(); admins(_) -> emqx_ctl:usage( [ {"cluster_call status", "status"}, {"cluster_call skip [node]", "increase one commit on specific node"}, {"cluster_call tnxid <TnxId>", "get detailed about TnxId"}, {"cluster_call fast_forward [node] [tnx_id]", "fast forwards to tnx_id"} ] ). status() -> emqx_ctl:print("-----------------------------------------------\n"), {atomic, Status} = emqx_cluster_rpc:status(), lists:foreach( fun(S) -> #{ node := Node, tnx_id := TnxId, mfa := {M, F, A}, created_at := CreatedAt } = S, emqx_ctl:print( "~p:[~w] CreatedAt:~p ~p:~p/~w\n", [Node, TnxId, CreatedAt, M, F, length(A)] ) end, Status ), emqx_ctl:print("-----------------------------------------------\n").
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_conf/src/emqx_conf_cli.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. --------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ 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(emqx_conf_cli). -export([ load/0, admins/1, unload/0 ]). -define(CMD, cluster_call). load() -> emqx_ctl:register_command(?CMD, {?MODULE, admins}, []). unload() -> emqx_ctl:unregister_command(?CMD). admins(["status"]) -> status(); admins(["skip"]) -> status(), Nodes = mria_mnesia:running_nodes(), lists:foreach(fun emqx_cluster_rpc:skip_failed_commit/1, Nodes), status(); admins(["skip", Node0]) -> status(), Node = list_to_existing_atom(Node0), emqx_cluster_rpc:skip_failed_commit(Node), status(); admins(["tnxid", TnxId0]) -> TnxId = list_to_integer(TnxId0), emqx_ctl:print("~p~n", [emqx_cluster_rpc:query(TnxId)]); admins(["fast_forward"]) -> status(), Nodes = mria_mnesia:running_nodes(), TnxId = emqx_cluster_rpc:latest_tnx_id(), lists:foreach(fun(N) -> emqx_cluster_rpc:fast_forward_to_commit(N, TnxId) end, Nodes), status(); admins(["fast_forward", ToTnxId]) -> status(), Nodes = mria_mnesia:running_nodes(), TnxId = list_to_integer(ToTnxId), lists:foreach(fun(N) -> emqx_cluster_rpc:fast_forward_to_commit(N, TnxId) end, Nodes), status(); admins(["fast_forward", Node0, ToTnxId]) -> status(), TnxId = list_to_integer(ToTnxId), Node = list_to_existing_atom(Node0), emqx_cluster_rpc:fast_forward_to_commit(Node, TnxId), status(); admins(_) -> emqx_ctl:usage( [ {"cluster_call status", "status"}, {"cluster_call skip [node]", "increase one commit on specific node"}, {"cluster_call tnxid <TnxId>", "get detailed about TnxId"}, {"cluster_call fast_forward [node] [tnx_id]", "fast forwards to tnx_id"} ] ). status() -> emqx_ctl:print("-----------------------------------------------\n"), {atomic, Status} = emqx_cluster_rpc:status(), lists:foreach( fun(S) -> #{ node := Node, tnx_id := TnxId, mfa := {M, F, A}, created_at := CreatedAt } = S, emqx_ctl:print( "~p:[~w] CreatedAt:~p ~p:~p/~w\n", [Node, TnxId, CreatedAt, M, F, length(A)] ) end, Status ), emqx_ctl:print("-----------------------------------------------\n").
9e4de07a65f6570350a4faa9eb5870ebee05f5fcf10e4ce0c2420faaa1fe3b00
blindglobe/clocc
menu.lisp
-*- Mode : Lisp ; Package : USER ; ; Lowercase : T ; Syntax : Common - Lisp -*- ;;;----------------------------------------------------------------------------------+ ;;; | ;;; TEXAS INSTRUMENTS INCORPORATED | P.O. BOX 149149 | , TEXAS 78714 - 9149 | ;;; | ;;; Copyright (C) 1989,1990 Texas Instruments Incorporated | ;;; | ;;; Permission is granted to any individual or institution to use, copy, modify, and | ;;; distribute this software, provided that this complete copyright and permission | ;;; notice is maintained, intact, in all copies and supporting documentation. | ;;; | Texas Instruments Incorporated provides this software " as is " without express or | ;;; implied warranty. | ;;; | ;;;----------------------------------------------------------------------------------+ ;;;----------------------------------------------------------------------------+ ;;; | Source code for CLUE examples described in Explorer X Window System | ;;; Programmer's Reference Manual. | ;;; | ;;;----------------------------------------------------------------------------+ (in-package "CLUE-EXAMPLES" :use '(common-lisp xlib clue)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Menu | ;;; | ;;;----------------------------------------------------------------------------+ (defcontact menu (override-shell) () (:resources (font :type font) (foreground :type pixel) (title :type string) (state :initform :withdrawn)) (:documentation "Presents a column of menu items.")) ;; Initialization (defmethod initialize-instance :after ((menu menu) &key title font foreground background &allow-other-keys) ;; Create title-frame containing choices child to manage menu items (let* ((title (make-contact 'title-frame :parent menu :name :title :text title :font font :foreground foreground :background (or background :white))) (manager (make-contact 'choices :parent title :name :manager :border-width 0))) ;; Define callback to handle effect of selection (add-callback manager :select 'popup-menu-select menu) ;; Moving pointer off menu causes nil selection (add-event manager '(:leave-notify :ancestor :nonlinear) '(choice-select nil)))) ;; :Leave-Notify Event Specifications (defun leave-check (event-key &rest kinds) (dolist (kind kinds) (unless (member kind '(:ancestor :virtual :inferior :nonlinear :nonlinear-virtual)) (error "~s isn't a valid kind of ~s event" kind event-key))) (list 'leave-match kinds)) (defun leave-match (event kinds) (member (slot-value event 'kind) kinds :test #'eq)) (setf (check-function :leave-notify) 'leave-check) ;; Menu operations (defun menu-manager (menu) (title-content (first (composite-children menu)))) (defmethod popup-menu-select ((menu menu)) ;; Pop down immediately (setf (contact-state menu) :withdrawn) (display-force-output (contact-display menu)) ;; Invoke menu callback (apply-callback menu :select)) (defun menu-present (menu x y) "Present the MENU with the first item centered on the given position." Complete initial geometry management before positioning menu (unless (realized-p menu) (initialize-geometry menu)) (let ((parent (contact-parent menu)) (item (first (composite-children (menu-manager menu))))) Compute the y position of the center of the first item ;; with respect to the menu (multiple-value-bind (item-x item-y) (contact-translate item 0 (round (contact-height item) 2) menu) (declare (ignore item-x)) Try to center first item at the given location , but ;; make sure menu is completely visible in its parent (change-geometry menu :x (max 0 (min (- (contact-width parent) (contact-width menu)) (- x (round (contact-width menu) 2)))) :y (max 0 (min (- (contact-height parent) (contact-height menu)) (- y item-y))) :accept-p t))) ;; Make menu visible (setf (contact-state menu) :mapped)) (defun menu-choose (menu x y) "Present the MENU at the given location and return the label of the item chosen. If no item is chosen, then nil is returned." ;; Set menu callback to return chosen item label (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y. (menu-present menu x y) ;; Event processing loop (catch :menu-selection (loop (process-next-event (contact-display menu))))) (defun throw-menu-selection (menu) "Throw to :menu-selection tag, returning the label of the selected menu button (if any)." (let ((selection (choice-selection (menu-manager menu)))) (throw :menu-selection (when selection (button-label selection))))) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Title Frame | ;;; | ;;;----------------------------------------------------------------------------+ (defcontact title-frame (composite) ((font :accessor title-font :initarg :font :initform "fixed" :type font) (foreground :accessor title-foreground :initarg :foreground :initform :black :type pixel) (text :accessor title-text :initarg :text :type string) (compress-exposures :allocation :class :initform :on :reader contact-compress-exposures :type (member :off :on))) (:resources font foreground text (event-mask :initform #.(make-event-mask :exposure))) (:documentation "A composite consisting of a text title and another contact.")) ;; Accessors (defmethod (setf title-font) (new-value (title-frame title-frame)) (title-update title-frame :font (convert title-frame new-value 'font))) (defmethod (setf title-text) (new-value (title-frame title-frame)) (title-update title-frame :text new-value)) (defmethod title-update ((title-frame title-frame) &key text font) (with-slots ((current-text text) (current-font font)) title-frame ;; Update slots (setf current-text (or text current-text) current-font (or font current-font)) ;; Update geometry (when (realized-p title-frame) (change-layout title-frame)))) (defmethod title-content ((title-frame title-frame)) (with-slots (children) title-frame (first children))) ;; Geometry management (defmethod add-child :before ((title-frame title-frame) child &key) (declare (ignore child)) ;; A title-frame can only have a single content child (assert (not (title-content title-frame)) nil "~s already has a content." title-frame)) (defmethod manage-geometry ((title-frame title-frame) child x y width height border-width &key) (with-slots ((frame-width width) (frame-height height)) title-frame (let* ((x (or x (contact-x child))) (y (or y (contact-y child))) (width (or width (contact-width child))) (height (or height (contact-height child))) (border-width (or border-width (contact-border-width child))) (total-width (+ width border-width border-width)) (total-height (+ height border-width border-width))) ;; Get preferred frame size for requested content geometry (multiple-value-bind (min-width min-height) (title-preferred-size-if title-frame total-width total-height frame-width frame-height) ;; Try to ensure at least preferred frame size (when (or (setf min-width (when (< frame-width min-width) min-width)) (setf min-height (when (< frame-height min-height) min-height))) (change-geometry title-frame :width min-width :height min-height :accept-p t))) ;; Approve request based on current frame size and title size (multiple-value-bind (title-width title-height) (title-size title-frame) (declare (ignore title-width)) (let ((approved-x 0) (approved-y title-height) (approved-width (- frame-width border-width border-width)) (approved-height (- frame-height title-height border-width border-width))) (values (and (= x approved-x) (= y approved-y) (= width approved-width) (= height approved-height)) approved-x approved-y approved-width approved-height border-width)))))) (defmethod change-layout ((title-frame title-frame) &optional newly-managed) (declare (ignore newly-managed)) (with-slots (width height) title-frame ;; Try to ensure at least preferred size (multiple-value-bind (min-width min-height) (preferred-size title-frame) (when (or (setf min-width (when (< width min-width) min-width)) (setf min-height (when (< height min-height) min-height))) (change-geometry title-frame :width min-width :height min-height :accept-p t))) ;; Adjust title, content geometry to current size (title-adjust title-frame))) (defmethod preferred-size ((title-frame title-frame) &key width height border-width) (let ((content (title-content title-frame)) (width (or width (contact-width title-frame))) (height (or height (contact-height title-frame)))) ;; Determine total size of content, including border width (multiple-value-bind (current-content-width current-content-height) (if content (with-slots ((content-width width) (content-height height) (content-border-width border-width)) content (values (+ content-width content-border-width content-border-width) (+ content-height content-border-width content-border-width))) (values 0 0)) ;; Determine preferred frame size for this content (multiple-value-bind (preferred-width preferred-height) (title-preferred-size-if title-frame current-content-width current-content-height width height) (values preferred-width preferred-height (or border-width (contact-border-width title-frame))))))) (defun title-preferred-size-if (title-frame content-width content-height width height) "Return preferred TITLE-FRAME width and height, assuming given content size and the suggested WIDTH and HEIGHT for the TITLE-FRAME." (multiple-value-bind (title-width title-height) (title-size title-frame) (values ;; width (max title-width content-width width) ;; height (max (+ title-height content-height) height)))) (defun title-adjust (title-frame) "Rearrange title and content according to current size of TITLE-FRAME." (with-slots (width height) title-frame (let* ((content (title-content title-frame)) (border-width (contact-border-width content))) ;; Determine dimensions of title string (multiple-value-bind (title-width title-height) (title-size title-frame) (declare (ignore title-width)) (let ((approved-x 0) (approved-y title-height) (approved-width (- width border-width border-width)) (approved-height (- height title-height border-width border-width))) ;; Reposition content (with-state (content) (when (not (and (= (contact-x content) approved-x) (= (contact-y content) approved-y))) (move content approved-x approved-y)) (when (not (and (= (contact-width content) approved-width) (= (contact-height content) approved-height))) (resize content approved-width approved-height border-width))) ;; Redisplay title (when (realized-p title-frame) (clear-area title-frame :exposures-p t))))))) (defun title-size (title-frame) "Return the width and height of the title string of the TITLE-FRAME." (with-slots (font text) title-frame (values (text-width font text) (+ (font-ascent font) (font-descent font))))) (defun title-position (title-frame) "Return the position of the title string of the TITLE-FRAME." (with-slots (font text width) title-frame (values (round (- width (text-width font text)) 2) (font-ascent font)))) (defmethod resize :after ((title-frame title-frame) width height border-width) (declare (ignore width height border-width)) (title-adjust title-frame)) ;; Display (defmethod display ((title-frame title-frame) &optional x y width height &key) (declare (ignore x y width height)) (with-slots (font text foreground background) title-frame (multiple-value-bind (title-x title-y) (title-position title-frame) ;; Draw title string in "reverse-video" (using-gcontext (gc :drawable title-frame :font font :foreground background :background foreground) (draw-image-glyphs title-frame gc title-x title-y text))))) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Column | ;;; | ;;;----------------------------------------------------------------------------+ (defcontact column (composite) () (:documentation "Arranges its children in a vertical column.")) (defmethod manage-geometry ((column column) child x y width height border-width &key) (with-slots ((child-width width) (child-height height) (child-border-width border-width) (child-x x) (child-y y)) child (let* ;; No position change can be approved. ((position-approved-p (not (or (unless (null x) (/= x child-x)) (unless (null y) (/= y child-y))))) ;; Check if requested size change can be approved. (total-width (+ child-width child-border-width child-border-width)) (total-height (+ child-height child-border-width child-border-width)) (requested-width (or width child-width)) (requested-height (or height child-height)) (requested-border-width (or border-width child-border-width)) (new-total-width (+ requested-width requested-border-width requested-border-width)) (new-total-height (+ requested-height requested-border-width requested-border-width))) ;; Refuse size change immediately if it reduces item size (when (or (< new-total-width total-width) (< new-total-height total-height)) (return-from manage-geometry (values nil child-x child-y (- child-width requested-border-width requested-border-width) (- child-height requested-border-width requested-border-width) requested-border-width))) ;; Approve size change immediately if it does not affect item size (when (and (= new-total-width total-width) (= new-total-height total-height)) (return-from manage-geometry (values position-approved-p child-x child-y requested-width requested-height requested-border-width))) ;; Otherwise, a larger item size has been requested. ;; Check if column size can be enlarged sufficiently. (multiple-value-bind (column-width column-height) (column-preferred-size column new-total-width new-total-height) ;; Request change to preferred column size (multiple-value-bind (approved-p approved-x approved-y approved-width approved-height) (change-geometry column :width column-width :height column-height) (declare (ignore approved-x approved-y)) (if approved-p ;; Larger column size approved. (return-from manage-geometry (values ;; When requested child geometry approved (both size and position), ;; then return a function to implement the after-effect of approved ;; child geometry changes. Column layout will then reflect the new ;; item size. (when position-approved-p 'change-layout) child-x child-y requested-width requested-height requested-border-width)) ;; Larger column size NOT approved. Return best item size that could fit ;; approved column size (return-from manage-geometry (values nil child-x child-y (- approved-width requested-border-width requested-border-width) (- (floor approved-height (length (composite-children column))) requested-border-width requested-border-width) requested-border-width)))))))) (defmethod change-layout ((column column) &optional newly-managed) (declare (ignore newly-managed)) (with-slots (width height) column ;; Compute the maximum preferred size of all children. (multiple-value-bind (item-width item-height) (column-item-size column) Compute preferred column size , assuming this item size (multiple-value-bind (preferred-width preferred-height) (column-preferred-size column item-width item-height) ;; Try to ensure at least preferred size (if (or (setf preferred-width (when (< width preferred-width) preferred-width)) (setf preferred-height (when (< height preferred-height) preferred-height))) ;; Ask parent for larger size (change-geometry column :width preferred-width :height preferred-height :accept-p t) ;; Else current size is big enough (column-adjust column item-width item-height)))))) (defmethod preferred-size ((column column) &key width height border-width) (multiple-value-bind (item-width item-height) (column-item-size column) (multiple-value-bind (preferred-width preferred-height) (column-preferred-size column item-width item-height) (values (if width (max width preferred-width) preferred-width) (if height (max height preferred-height) preferred-height) (or border-width (slot-value column 'border-width)))))) (defun column-preferred-size (column item-width item-height) "Return the preferred width and height for COLUMN, assuming the given ITEM-WIDTH and ITEM-HEIGHT." (with-slots (children) column (let ((preferred-margin 8)) (values (+ item-width preferred-margin preferred-margin) (+ (* (length children) (+ item-height preferred-margin)) preferred-margin))))) (defun column-item-size (column) "Return the maximum preferred width and height of all COLUMN children." (with-slots (children) column (let ((item-width 0) (item-height 0)) (dolist (child children) (multiple-value-bind (child-width child-height child-bw) (preferred-size child) (setf item-width (max item-width (+ child-width child-bw child-bw)) item-height (max item-height (+ child-height child-bw child-bw))))) (values item-width item-height)))) (defun column-adjust (column &optional item-width item-height) "Rearrange COLUMN items according to current COLUMN size. If given, ITEM-WIDTH and ITEM-HEIGHT define the new size for all items." (with-slots (children width height) column (when children Compute preferred item size , if necessary (unless item-height (multiple-value-setq (item-width item-height) (column-item-size column))) ;; Compute item spacing (let* ((number-items (length children)) (margin (max (round (- width item-width) 2) 0)) (space (max (round (- height (* number-items item-height)) (1+ number-items)) 0))) ;; Set size and position of each child (let ((y 0)) (dolist (child children) (let ((bw (contact-border-width child))) (with-state (child) (resize child (- item-width bw bw) (- item-height bw bw) bw) (move child margin (incf y space)))) (incf y item-height))))))) (defmethod resize :after ((column column) width height border-width) (declare (ignore width height border-width)) (column-adjust column)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Choices | ;;; | ;;;----------------------------------------------------------------------------+ (defcontact choices (column) ((selection :reader choice-selection :initform nil :type (or null contact))) (:documentation "A column of items to choose from.")) (defmethod add-child :after ((choices choices) child &key) Initialize child 's : select callback (add-callback child :select 'choice-select choices child)) (defmethod choice-select ((choices choices) child) ;; Record current selection (with-slots (selection) choices (setf selection child)) Invoke selection callback (apply-callback choices :select)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Button | ;;; | ;;;----------------------------------------------------------------------------+ (defcontact button (contact) ((label :accessor button-label :initarg :label :initform "" :type string) (font :accessor button-font :initarg :font :initform "fixed" :type font) (foreground :accessor button-foreground :initarg :foreground :initform :black :type pixel) (compress-exposures :allocation :class :initform :on :reader contact-compress-exposures :type (member :off :on))) (:resources (background :initform :white) (border :initform :white) font foreground label) (:documentation "Triggers an action.")) ;; Display (defmethod display ((button button) &optional x y width height &key) (declare (ignore x y width height)) (with-slots (font label foreground (button-width width) (button-height height)) button ;; Get metrics for label string (multiple-value-bind (label-width ascent descent left right font-ascent font-descent) (text-extents font label) (declare (ignore ascent descent left right)) ;; Center label in button (let ((label-x (round (- button-width label-width) 2)) (label-y (+ (round (- button-height font-ascent font-descent) 2) font-ascent))) ;; Use an appropriate graphics context from the cache (using-gcontext (gc :drawable button :font font :foreground foreground) (draw-glyphs button gc label-x label-y label)))))) (defmethod preferred-size ((button button) &key width height border-width) (with-slots (font label (bw border-width)) button ;; Get metrics for label string (multiple-value-bind (label-width ascent descent left right font-ascent font-descent) (text-extents font label) (declare (ignore ascent descent left right)) (let* ((margin 2) (best-width (+ label-width margin margin)) (best-height (+ font-ascent font-descent margin margin))) ;; Return best geometry for this label (values (if width (max width best-width) best-width) (if height (max height best-height) best-height) (or border-width bw)))))) ;; Actions (defmethod button-select ((button button)) (apply-callback button :select)) (defmethod button-set-highlight ((button button) on-p) (with-slots (foreground background) button (setf (window-border button) (if on-p foreground background)))) ;; Event translations (defevent button :button-press button-select) (defevent button :enter-notify (button-set-highlight t)) (defevent button :leave-notify (button-set-highlight nil)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Demonstrations | ;;; | ;;;----------------------------------------------------------------------------+ (defun just-say-lisp (host &optional (font-name "fixed")) (let* ((display (open-contact-display 'just-say-lisp :host host)) (screen (contact-screen (display-root display))) (fg-color (screen-black-pixel screen)) (bg-color (screen-white-pixel screen)) ;; Create menu (menu (make-contact 'menu :parent display :font font-name :title "Please pick your favorite language:" :foreground fg-color :background bg-color)) (menu-mgr (menu-manager menu))) ;; Create menu items (dolist (label '("Fortran" "APL" "Forth" "Lisp")) (make-contact 'button :parent menu-mgr :label label :font font-name :foreground fg-color)) ;; Bedevil the user until he picks a nice programming language (unwind-protect (loop ;; Pop up menu at current pointer position (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (let ((choice (menu-choose menu x y))) (when (string-equal "Lisp" choice) (return))))) (close-display display)))) (defun pick-one (host &rest strings) (let* ((display (open-contact-display 'pick-one :host host)) (menu (make-contact 'menu :parent display :title "Pick one:"))) ;; Create menu items (dolist (string strings) (make-contact 'button :parent (menu-manager menu) :label string)) ;; Set menu callback to return chosen item label (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y (initialize-geometry menu) (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (menu-present menu x y)) ;; Event processing loop (let ((selected (catch :menu-selection (loop (process-next-event display))))) ;; Close server connection (close-display display) ;; Return selected string selected))) (defun resource-menu (host menu-name item-defaults &rest buttons) (let* ((display (open-contact-display 'resource-menu :host host)) (menu (make-contact 'menu :parent display :name menu-name))) (unwind-protect (progn ;; Create menu items (dolist (label buttons) (make-contact 'button :parent (menu-manager menu) :name (intern (string label)) :label (format nil "~:(~a~)" label) :defaults item-defaults)) ;; Set menu callback to return chosen item label (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y (initialize-geometry menu) (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (menu-present menu x y)) ;; Event processing loop --- return selected string. (catch :menu-selection (loop (process-next-event display)))) (close-display display)))) (defun beatlemenuia (host &optional defaults) (loop ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 1 | ;;; | ;;;----------------------------------------------------------------------------+ (define-resources (* beatles title) "Who is your favorite Beatle?") ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 2 | ;;; | ;;;----------------------------------------------------------------------------+ (format t "~%Buttons are white-on-black ...") (define-resources (* button foreground) :white (* button background) :black (* button border) :white) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* button foreground) :white (* button background) :black (* button border) :white) (unless (y-or-n-p "~%Continue?") (return)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 3 | ;;; | ;;;----------------------------------------------------------------------------+ (format t "~%Use large Courier font everywhere ...") (define-resources (resource-menu * font) "*courier-bold-r-normal--24*") (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (resource-menu * font) "*courier-bold-r-normal--24*") (unless (y-or-n-p "~%Continue?") (return)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 4 | ;;; | ;;;----------------------------------------------------------------------------+ (format t "~%Use gray background in menu ...") (define-resources (* beatles * background) .8) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* beatles * background) .8) (unless (y-or-n-p "~%Continue?") (return)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 5 | ;;; | ;;;----------------------------------------------------------------------------+ (format t "~%Only John uses large Courier, Ringo uses gray background ...") (define-resources (* John font) "*courier-bold-r-normal--24*" (* Ringo background) "50%gray") (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* John font) "*courier-bold-r-normal--24*" (* Ringo background) "50%gray") (unless (y-or-n-p "~%Continue?") (return)) ;;;----------------------------------------------------------------------------+ ;;; | ;;; Example 6 | ;;; | ;;;----------------------------------------------------------------------------+ (format t "~%Select only with :button-3 ...") (define-resources (* button event-translations) '(((:button-press :button-3) button-select) ((:button-press :button-1) ignore-action) ((:button-press :button-2) ignore-action))) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* button event-translations) '(((:button-press :button-3) button-select) ((:button-press :button-1) ignore-action) ((:button-press :button-2) ignore-action))) (unless (y-or-n-p "~%Continue?") (return))))
null
https://raw.githubusercontent.com/blindglobe/clocc/a50bb75edb01039b282cf320e4505122a59c59a7/src/gui/clue/clue/examples/menu.lisp
lisp
Package : USER ; ; Lowercase : T ; Syntax : Common - Lisp -*- ----------------------------------------------------------------------------------+ | TEXAS INSTRUMENTS INCORPORATED | | Copyright (C) 1989,1990 Texas Instruments Incorporated | | Permission is granted to any individual or institution to use, copy, modify, and | distribute this software, provided that this complete copyright and permission | notice is maintained, intact, in all copies and supporting documentation. | | implied warranty. | | ----------------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Programmer's Reference Manual. | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Menu | | ----------------------------------------------------------------------------+ Initialization Create title-frame containing choices child to manage menu items Define callback to handle effect of selection Moving pointer off menu causes nil selection :Leave-Notify Event Specifications Menu operations Pop down immediately Invoke menu callback with respect to the menu make sure menu is completely visible in its parent Make menu visible Set menu callback to return chosen item label Event processing loop ----------------------------------------------------------------------------+ | Title Frame | | ----------------------------------------------------------------------------+ Accessors Update slots Update geometry Geometry management A title-frame can only have a single content child Get preferred frame size for requested content geometry Try to ensure at least preferred frame size Approve request based on current frame size and title size Try to ensure at least preferred size Adjust title, content geometry to current size Determine total size of content, including border width Determine preferred frame size for this content width height Determine dimensions of title string Reposition content Redisplay title Display Draw title string in "reverse-video" ----------------------------------------------------------------------------+ | Column | | ----------------------------------------------------------------------------+ No position change can be approved. Check if requested size change can be approved. Refuse size change immediately if it reduces item size Approve size change immediately if it does not affect item size Otherwise, a larger item size has been requested. Check if column size can be enlarged sufficiently. Request change to preferred column size Larger column size approved. When requested child geometry approved (both size and position), then return a function to implement the after-effect of approved child geometry changes. Column layout will then reflect the new item size. Larger column size NOT approved. Return best item size that could fit approved column size Compute the maximum preferred size of all children. Try to ensure at least preferred size Ask parent for larger size Else current size is big enough Compute item spacing Set size and position of each child ----------------------------------------------------------------------------+ | Choices | | ----------------------------------------------------------------------------+ Record current selection ----------------------------------------------------------------------------+ | Button | | ----------------------------------------------------------------------------+ Display Get metrics for label string Center label in button Use an appropriate graphics context from the cache Get metrics for label string Return best geometry for this label Actions Event translations ----------------------------------------------------------------------------+ | Demonstrations | | ----------------------------------------------------------------------------+ Create menu Create menu items Bedevil the user until he picks a nice programming language Pop up menu at current pointer position Create menu items Set menu callback to return chosen item label Event processing loop Close server connection Return selected string Create menu items Set menu callback to return chosen item label Event processing loop --- return selected string. ----------------------------------------------------------------------------+ | Example 1 | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Example 2 | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Example 3 | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Example 4 | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Example 5 | | ----------------------------------------------------------------------------+ ----------------------------------------------------------------------------+ | Example 6 | | ----------------------------------------------------------------------------+
P.O. BOX 149149 | , TEXAS 78714 - 9149 | Texas Instruments Incorporated provides this software " as is " without express or | Source code for CLUE examples described in Explorer X Window System | (in-package "CLUE-EXAMPLES" :use '(common-lisp xlib clue)) (defcontact menu (override-shell) () (:resources (font :type font) (foreground :type pixel) (title :type string) (state :initform :withdrawn)) (:documentation "Presents a column of menu items.")) (defmethod initialize-instance :after ((menu menu) &key title font foreground background &allow-other-keys) (let* ((title (make-contact 'title-frame :parent menu :name :title :text title :font font :foreground foreground :background (or background :white))) (manager (make-contact 'choices :parent title :name :manager :border-width 0))) (add-callback manager :select 'popup-menu-select menu) (add-event manager '(:leave-notify :ancestor :nonlinear) '(choice-select nil)))) (defun leave-check (event-key &rest kinds) (dolist (kind kinds) (unless (member kind '(:ancestor :virtual :inferior :nonlinear :nonlinear-virtual)) (error "~s isn't a valid kind of ~s event" kind event-key))) (list 'leave-match kinds)) (defun leave-match (event kinds) (member (slot-value event 'kind) kinds :test #'eq)) (setf (check-function :leave-notify) 'leave-check) (defun menu-manager (menu) (title-content (first (composite-children menu)))) (defmethod popup-menu-select ((menu menu)) (setf (contact-state menu) :withdrawn) (display-force-output (contact-display menu)) (apply-callback menu :select)) (defun menu-present (menu x y) "Present the MENU with the first item centered on the given position." Complete initial geometry management before positioning menu (unless (realized-p menu) (initialize-geometry menu)) (let ((parent (contact-parent menu)) (item (first (composite-children (menu-manager menu))))) Compute the y position of the center of the first item (multiple-value-bind (item-x item-y) (contact-translate item 0 (round (contact-height item) 2) menu) (declare (ignore item-x)) Try to center first item at the given location , but (change-geometry menu :x (max 0 (min (- (contact-width parent) (contact-width menu)) (- x (round (contact-width menu) 2)))) :y (max 0 (min (- (contact-height parent) (contact-height menu)) (- y item-y))) :accept-p t))) (setf (contact-state menu) :mapped)) (defun menu-choose (menu x y) "Present the MENU at the given location and return the label of the item chosen. If no item is chosen, then nil is returned." (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y. (menu-present menu x y) (catch :menu-selection (loop (process-next-event (contact-display menu))))) (defun throw-menu-selection (menu) "Throw to :menu-selection tag, returning the label of the selected menu button (if any)." (let ((selection (choice-selection (menu-manager menu)))) (throw :menu-selection (when selection (button-label selection))))) (defcontact title-frame (composite) ((font :accessor title-font :initarg :font :initform "fixed" :type font) (foreground :accessor title-foreground :initarg :foreground :initform :black :type pixel) (text :accessor title-text :initarg :text :type string) (compress-exposures :allocation :class :initform :on :reader contact-compress-exposures :type (member :off :on))) (:resources font foreground text (event-mask :initform #.(make-event-mask :exposure))) (:documentation "A composite consisting of a text title and another contact.")) (defmethod (setf title-font) (new-value (title-frame title-frame)) (title-update title-frame :font (convert title-frame new-value 'font))) (defmethod (setf title-text) (new-value (title-frame title-frame)) (title-update title-frame :text new-value)) (defmethod title-update ((title-frame title-frame) &key text font) (with-slots ((current-text text) (current-font font)) title-frame (setf current-text (or text current-text) current-font (or font current-font)) (when (realized-p title-frame) (change-layout title-frame)))) (defmethod title-content ((title-frame title-frame)) (with-slots (children) title-frame (first children))) (defmethod add-child :before ((title-frame title-frame) child &key) (declare (ignore child)) (assert (not (title-content title-frame)) nil "~s already has a content." title-frame)) (defmethod manage-geometry ((title-frame title-frame) child x y width height border-width &key) (with-slots ((frame-width width) (frame-height height)) title-frame (let* ((x (or x (contact-x child))) (y (or y (contact-y child))) (width (or width (contact-width child))) (height (or height (contact-height child))) (border-width (or border-width (contact-border-width child))) (total-width (+ width border-width border-width)) (total-height (+ height border-width border-width))) (multiple-value-bind (min-width min-height) (title-preferred-size-if title-frame total-width total-height frame-width frame-height) (when (or (setf min-width (when (< frame-width min-width) min-width)) (setf min-height (when (< frame-height min-height) min-height))) (change-geometry title-frame :width min-width :height min-height :accept-p t))) (multiple-value-bind (title-width title-height) (title-size title-frame) (declare (ignore title-width)) (let ((approved-x 0) (approved-y title-height) (approved-width (- frame-width border-width border-width)) (approved-height (- frame-height title-height border-width border-width))) (values (and (= x approved-x) (= y approved-y) (= width approved-width) (= height approved-height)) approved-x approved-y approved-width approved-height border-width)))))) (defmethod change-layout ((title-frame title-frame) &optional newly-managed) (declare (ignore newly-managed)) (with-slots (width height) title-frame (multiple-value-bind (min-width min-height) (preferred-size title-frame) (when (or (setf min-width (when (< width min-width) min-width)) (setf min-height (when (< height min-height) min-height))) (change-geometry title-frame :width min-width :height min-height :accept-p t))) (title-adjust title-frame))) (defmethod preferred-size ((title-frame title-frame) &key width height border-width) (let ((content (title-content title-frame)) (width (or width (contact-width title-frame))) (height (or height (contact-height title-frame)))) (multiple-value-bind (current-content-width current-content-height) (if content (with-slots ((content-width width) (content-height height) (content-border-width border-width)) content (values (+ content-width content-border-width content-border-width) (+ content-height content-border-width content-border-width))) (values 0 0)) (multiple-value-bind (preferred-width preferred-height) (title-preferred-size-if title-frame current-content-width current-content-height width height) (values preferred-width preferred-height (or border-width (contact-border-width title-frame))))))) (defun title-preferred-size-if (title-frame content-width content-height width height) "Return preferred TITLE-FRAME width and height, assuming given content size and the suggested WIDTH and HEIGHT for the TITLE-FRAME." (multiple-value-bind (title-width title-height) (title-size title-frame) (values (max title-width content-width width) (max (+ title-height content-height) height)))) (defun title-adjust (title-frame) "Rearrange title and content according to current size of TITLE-FRAME." (with-slots (width height) title-frame (let* ((content (title-content title-frame)) (border-width (contact-border-width content))) (multiple-value-bind (title-width title-height) (title-size title-frame) (declare (ignore title-width)) (let ((approved-x 0) (approved-y title-height) (approved-width (- width border-width border-width)) (approved-height (- height title-height border-width border-width))) (with-state (content) (when (not (and (= (contact-x content) approved-x) (= (contact-y content) approved-y))) (move content approved-x approved-y)) (when (not (and (= (contact-width content) approved-width) (= (contact-height content) approved-height))) (resize content approved-width approved-height border-width))) (when (realized-p title-frame) (clear-area title-frame :exposures-p t))))))) (defun title-size (title-frame) "Return the width and height of the title string of the TITLE-FRAME." (with-slots (font text) title-frame (values (text-width font text) (+ (font-ascent font) (font-descent font))))) (defun title-position (title-frame) "Return the position of the title string of the TITLE-FRAME." (with-slots (font text width) title-frame (values (round (- width (text-width font text)) 2) (font-ascent font)))) (defmethod resize :after ((title-frame title-frame) width height border-width) (declare (ignore width height border-width)) (title-adjust title-frame)) (defmethod display ((title-frame title-frame) &optional x y width height &key) (declare (ignore x y width height)) (with-slots (font text foreground background) title-frame (multiple-value-bind (title-x title-y) (title-position title-frame) (using-gcontext (gc :drawable title-frame :font font :foreground background :background foreground) (draw-image-glyphs title-frame gc title-x title-y text))))) (defcontact column (composite) () (:documentation "Arranges its children in a vertical column.")) (defmethod manage-geometry ((column column) child x y width height border-width &key) (with-slots ((child-width width) (child-height height) (child-border-width border-width) (child-x x) (child-y y)) child (let* ((position-approved-p (not (or (unless (null x) (/= x child-x)) (unless (null y) (/= y child-y))))) (total-width (+ child-width child-border-width child-border-width)) (total-height (+ child-height child-border-width child-border-width)) (requested-width (or width child-width)) (requested-height (or height child-height)) (requested-border-width (or border-width child-border-width)) (new-total-width (+ requested-width requested-border-width requested-border-width)) (new-total-height (+ requested-height requested-border-width requested-border-width))) (when (or (< new-total-width total-width) (< new-total-height total-height)) (return-from manage-geometry (values nil child-x child-y (- child-width requested-border-width requested-border-width) (- child-height requested-border-width requested-border-width) requested-border-width))) (when (and (= new-total-width total-width) (= new-total-height total-height)) (return-from manage-geometry (values position-approved-p child-x child-y requested-width requested-height requested-border-width))) (multiple-value-bind (column-width column-height) (column-preferred-size column new-total-width new-total-height) (multiple-value-bind (approved-p approved-x approved-y approved-width approved-height) (change-geometry column :width column-width :height column-height) (declare (ignore approved-x approved-y)) (if approved-p (return-from manage-geometry (values (when position-approved-p 'change-layout) child-x child-y requested-width requested-height requested-border-width)) (return-from manage-geometry (values nil child-x child-y (- approved-width requested-border-width requested-border-width) (- (floor approved-height (length (composite-children column))) requested-border-width requested-border-width) requested-border-width)))))))) (defmethod change-layout ((column column) &optional newly-managed) (declare (ignore newly-managed)) (with-slots (width height) column (multiple-value-bind (item-width item-height) (column-item-size column) Compute preferred column size , assuming this item size (multiple-value-bind (preferred-width preferred-height) (column-preferred-size column item-width item-height) (if (or (setf preferred-width (when (< width preferred-width) preferred-width)) (setf preferred-height (when (< height preferred-height) preferred-height))) (change-geometry column :width preferred-width :height preferred-height :accept-p t) (column-adjust column item-width item-height)))))) (defmethod preferred-size ((column column) &key width height border-width) (multiple-value-bind (item-width item-height) (column-item-size column) (multiple-value-bind (preferred-width preferred-height) (column-preferred-size column item-width item-height) (values (if width (max width preferred-width) preferred-width) (if height (max height preferred-height) preferred-height) (or border-width (slot-value column 'border-width)))))) (defun column-preferred-size (column item-width item-height) "Return the preferred width and height for COLUMN, assuming the given ITEM-WIDTH and ITEM-HEIGHT." (with-slots (children) column (let ((preferred-margin 8)) (values (+ item-width preferred-margin preferred-margin) (+ (* (length children) (+ item-height preferred-margin)) preferred-margin))))) (defun column-item-size (column) "Return the maximum preferred width and height of all COLUMN children." (with-slots (children) column (let ((item-width 0) (item-height 0)) (dolist (child children) (multiple-value-bind (child-width child-height child-bw) (preferred-size child) (setf item-width (max item-width (+ child-width child-bw child-bw)) item-height (max item-height (+ child-height child-bw child-bw))))) (values item-width item-height)))) (defun column-adjust (column &optional item-width item-height) "Rearrange COLUMN items according to current COLUMN size. If given, ITEM-WIDTH and ITEM-HEIGHT define the new size for all items." (with-slots (children width height) column (when children Compute preferred item size , if necessary (unless item-height (multiple-value-setq (item-width item-height) (column-item-size column))) (let* ((number-items (length children)) (margin (max (round (- width item-width) 2) 0)) (space (max (round (- height (* number-items item-height)) (1+ number-items)) 0))) (let ((y 0)) (dolist (child children) (let ((bw (contact-border-width child))) (with-state (child) (resize child (- item-width bw bw) (- item-height bw bw) bw) (move child margin (incf y space)))) (incf y item-height))))))) (defmethod resize :after ((column column) width height border-width) (declare (ignore width height border-width)) (column-adjust column)) (defcontact choices (column) ((selection :reader choice-selection :initform nil :type (or null contact))) (:documentation "A column of items to choose from.")) (defmethod add-child :after ((choices choices) child &key) Initialize child 's : select callback (add-callback child :select 'choice-select choices child)) (defmethod choice-select ((choices choices) child) (with-slots (selection) choices (setf selection child)) Invoke selection callback (apply-callback choices :select)) (defcontact button (contact) ((label :accessor button-label :initarg :label :initform "" :type string) (font :accessor button-font :initarg :font :initform "fixed" :type font) (foreground :accessor button-foreground :initarg :foreground :initform :black :type pixel) (compress-exposures :allocation :class :initform :on :reader contact-compress-exposures :type (member :off :on))) (:resources (background :initform :white) (border :initform :white) font foreground label) (:documentation "Triggers an action.")) (defmethod display ((button button) &optional x y width height &key) (declare (ignore x y width height)) (with-slots (font label foreground (button-width width) (button-height height)) button (multiple-value-bind (label-width ascent descent left right font-ascent font-descent) (text-extents font label) (declare (ignore ascent descent left right)) (let ((label-x (round (- button-width label-width) 2)) (label-y (+ (round (- button-height font-ascent font-descent) 2) font-ascent))) (using-gcontext (gc :drawable button :font font :foreground foreground) (draw-glyphs button gc label-x label-y label)))))) (defmethod preferred-size ((button button) &key width height border-width) (with-slots (font label (bw border-width)) button (multiple-value-bind (label-width ascent descent left right font-ascent font-descent) (text-extents font label) (declare (ignore ascent descent left right)) (let* ((margin 2) (best-width (+ label-width margin margin)) (best-height (+ font-ascent font-descent margin margin))) (values (if width (max width best-width) best-width) (if height (max height best-height) best-height) (or border-width bw)))))) (defmethod button-select ((button button)) (apply-callback button :select)) (defmethod button-set-highlight ((button button) on-p) (with-slots (foreground background) button (setf (window-border button) (if on-p foreground background)))) (defevent button :button-press button-select) (defevent button :enter-notify (button-set-highlight t)) (defevent button :leave-notify (button-set-highlight nil)) (defun just-say-lisp (host &optional (font-name "fixed")) (let* ((display (open-contact-display 'just-say-lisp :host host)) (screen (contact-screen (display-root display))) (fg-color (screen-black-pixel screen)) (bg-color (screen-white-pixel screen)) (menu (make-contact 'menu :parent display :font font-name :title "Please pick your favorite language:" :foreground fg-color :background bg-color)) (menu-mgr (menu-manager menu))) (dolist (label '("Fortran" "APL" "Forth" "Lisp")) (make-contact 'button :parent menu-mgr :label label :font font-name :foreground fg-color)) (unwind-protect (loop (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (let ((choice (menu-choose menu x y))) (when (string-equal "Lisp" choice) (return))))) (close-display display)))) (defun pick-one (host &rest strings) (let* ((display (open-contact-display 'pick-one :host host)) (menu (make-contact 'menu :parent display :title "Pick one:"))) (dolist (string strings) (make-contact 'button :parent (menu-manager menu) :label string)) (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y (initialize-geometry menu) (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (menu-present menu x y)) (let ((selected (catch :menu-selection (loop (process-next-event display))))) (close-display display) selected))) (defun resource-menu (host menu-name item-defaults &rest buttons) (let* ((display (open-contact-display 'resource-menu :host host)) (menu (make-contact 'menu :parent display :name menu-name))) (unwind-protect (progn (dolist (label buttons) (make-contact 'button :parent (menu-manager menu) :name (intern (string label)) :label (format nil "~:(~a~)" label) :defaults item-defaults)) (add-callback menu :select 'throw-menu-selection menu) Display the menu so that first item is at x , y (initialize-geometry menu) (multiple-value-bind (x y) (query-pointer (contact-parent menu)) (menu-present menu x y)) (catch :menu-selection (loop (process-next-event display)))) (close-display display)))) (defun beatlemenuia (host &optional defaults) (loop (define-resources (* beatles title) "Who is your favorite Beatle?") (format t "~%Buttons are white-on-black ...") (define-resources (* button foreground) :white (* button background) :black (* button border) :white) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* button foreground) :white (* button background) :black (* button border) :white) (unless (y-or-n-p "~%Continue?") (return)) (format t "~%Use large Courier font everywhere ...") (define-resources (resource-menu * font) "*courier-bold-r-normal--24*") (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (resource-menu * font) "*courier-bold-r-normal--24*") (unless (y-or-n-p "~%Continue?") (return)) (format t "~%Use gray background in menu ...") (define-resources (* beatles * background) .8) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* beatles * background) .8) (unless (y-or-n-p "~%Continue?") (return)) (format t "~%Only John uses large Courier, Ringo uses gray background ...") (define-resources (* John font) "*courier-bold-r-normal--24*" (* Ringo background) "50%gray") (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* John font) "*courier-bold-r-normal--24*" (* Ringo background) "50%gray") (unless (y-or-n-p "~%Continue?") (return)) (format t "~%Select only with :button-3 ...") (define-resources (* button event-translations) '(((:button-press :button-3) button-select) ((:button-press :button-1) ignore-action) ((:button-press :button-2) ignore-action))) (format t " Choice is ~a" (resource-menu host 'Beatles defaults 'John 'Paul 'George 'Ringo)) (undefine-resources (* button event-translations) '(((:button-press :button-3) button-select) ((:button-press :button-1) ignore-action) ((:button-press :button-2) ignore-action))) (unless (y-or-n-p "~%Continue?") (return))))
8e0e105486f5e828b3e357dca1d8d54f4bf4d46e3874f1d5ff95720f5bb29e8a
yrashk/erlang
ssh_connection_manager.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 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% %% %% %%---------------------------------------------------------------------- %% Purpose: Handles multiplexing to ssh channels and global connection requests e.i . the SSH Connection Protocol ( RFC 4254 ) , that provides %% interactive login sessions, remote execution of commands, forwarded %% TCP/IP connections, and forwarded X11 connections. Details of the protocol is implemented in ssh_connection.erl %% ---------------------------------------------------------------------- -module(ssh_connection_manager). -behaviour(gen_server). -include("ssh.hrl"). -include("ssh_connect.hrl"). -export([start_link/1]). -export([info/1, info/2, renegotiate/1, connection_info/2, channel_info/3, peer_addr/1, send_window/3, recv_window/3, adjust_window/3, close/2, stop/1, send/5, send_eof/2]). -export([open_channel/6, request/6, request/7, global_request/4, event/2, cast/2]). %% Internal application API and spawn -export([send_msg/1, ssh_channel_info_handler/3]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(DBG_MESSAGE, true). -record(state, { role, client, starter, connection, % pid() connection_state, % #connection{} latest_channel_id = 0, opts, channel_args, connected }). %%==================================================================== Internal application API %%==================================================================== start_link(Opts) -> gen_server:start_link(?MODULE, Opts, []). open_channel(ConnectionManager, ChannelType, ChannelSpecificData, InitialWindowSize, MaxPacketSize, Timeout) -> case (catch call(ConnectionManager, {open, self(), ChannelType, InitialWindowSize, MaxPacketSize, ChannelSpecificData}, Timeout)) of {open, Channel} -> {ok, Channel}; Error -> %% TODO: Best way? Error end. request(ConnectionManager, ChannelPid, ChannelId, Type, true, Data, Timeout) -> call(ConnectionManager, {request, ChannelPid, ChannelId, Type, Data}, Timeout); request(ConnectionManager, ChannelPid, ChannelId, Type, false, Data, _) -> cast(ConnectionManager, {request, ChannelPid, ChannelId, Type, Data}). request(ConnectionManager, ChannelId, Type, true, Data, Timeout) -> call(ConnectionManager, {request, ChannelId, Type, Data}, Timeout); request(ConnectionManager, ChannelId, Type, false, Data, _) -> cast(ConnectionManager, {request, ChannelId, Type, Data}). global_request(ConnectionManager, Type, true = Reply, Data) -> case call(ConnectionManager, {global_request, self(), Type, Reply, Data}) of {ssh_cm, ConnectionManager, {success, _}} -> ok; {ssh_cm, ConnectionManager, {failure, _}} -> error end; global_request(ConnectionManager, Type, false = Reply, Data) -> cast(ConnectionManager, {global_request, self(), Type, Reply, Data}). event(ConnectionManager, BinMsg) -> call(ConnectionManager, {ssh_msg, self(), BinMsg}). info(ConnectionManager) -> info(ConnectionManager, {info, all}). info(ConnectionManager, ChannelProcess) -> call(ConnectionManager, {info, ChannelProcess}). %% TODO: Do we really want this function? Should not %% renegotiation be triggered by configurable timer %% or amount of data sent counter! renegotiate(ConnectionManager) -> cast(ConnectionManager, renegotiate). connection_info(ConnectionManager, Options) -> call(ConnectionManager, {connection_info, Options}). channel_info(ConnectionManager, ChannelId, Options) -> call(ConnectionManager, {channel_info, ChannelId, Options}). %% Replaced by option peer to connection_info/2 keep for now %% for Backwards compatibility! peer_addr(ConnectionManager) -> call(ConnectionManager, {peer_addr, self()}). %% Backwards compatibility! send_window(ConnectionManager, Channel, TimeOut) -> call(ConnectionManager, {send_window, Channel}, TimeOut). %% Backwards compatibility! recv_window(ConnectionManager, Channel, TimeOut) -> call(ConnectionManager, {recv_window, Channel}, TimeOut). adjust_window(ConnectionManager, Channel, Bytes) -> cast(ConnectionManager, {adjust_window, Channel, Bytes}). close(ConnectionManager, ChannelId) -> try call(ConnectionManager, {close, ChannelId}) of ok -> ok catch exit:{noproc, _} -> ok end. stop(ConnectionManager) -> try call(ConnectionManager, stop) of ok -> ok catch exit:{noproc, _} -> ok end. send(ConnectionManager, ChannelId, Type, Data, Timeout) -> call(ConnectionManager, {data, ChannelId, Type, Data}, Timeout). send_eof(ConnectionManager, ChannelId) -> cast(ConnectionManager, {eof, ChannelId}). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([server, _Socket, Opts]) -> process_flag(trap_exit, true), ssh_bits:install_messages(ssh_connection:messages()), Cache = ssh_channel:cache_create(), {ok, #state{role = server, connection_state = #connection{channel_cache = Cache, channel_id_seed = 0, port_bindings = [], requests = [], channel_pids = []}, opts = Opts, connected = false}}; init([client, Opts]) -> process_flag(trap_exit, true), {links, [Parent]} = process_info(self(), links), ssh_bits:install_messages(ssh_connection:messages()), Cache = ssh_channel:cache_create(), Address = proplists:get_value(address, Opts), Port = proplists:get_value(port, Opts), SocketOpts = proplists:get_value(socket_opts, Opts), Options = proplists:get_value(ssh_opts, Opts), ChannelPid = proplists:get_value(channel_pid, Opts), self() ! {start_connection, client, [Parent, Address, Port, ChannelPid, SocketOpts, Options]}, {ok, #state{role = client, client = ChannelPid, connection_state = #connection{channel_cache = Cache, channel_id_seed = 0, port_bindings = [], requests = [], channel_pids = []}, opts = Opts, connected = false}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({request, ChannelPid, ChannelId, Type, Data}, From, State0) -> {{replies, Replies}, State} = handle_request(ChannelPid, ChannelId, Type, Data, true, From, State0), %% Sends message to the connection handler process, reply to %% channel is sent later when reply arrives from the connection %% handler. lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_call({request, ChannelId, Type, Data}, From, State0) -> {{replies, Replies}, State} = handle_request(ChannelId, Type, Data, true, From, State0), %% Sends message to the connection handler process, reply to %% channel is sent later when reply arrives from the connection %% handler. lists:foreach(fun send_msg/1, Replies), {noreply, State}; %% Message from ssh_connection_handler handle_call({ssh_msg, Pid, Msg}, From, #state{connection_state = Connection0, role = Role, opts = Opts, connected = IsConnected, client = ClientPid} = State) -> %% To avoid that not all data sent by the other side is processes before possible crash in takes down the connection . gen_server:reply(From, ok), ConnectionMsg = decode_ssh_msg(Msg), try ssh_connection:handle_msg(ConnectionMsg, Connection0, Pid, Role) of {{replies, Replies}, Connection} -> lists:foreach(fun send_msg/1, Replies), {noreply, State#state{connection_state = Connection}}; {noreply, Connection} -> {noreply, State#state{connection_state = Connection}}; {disconnect, {_, Reason}, {{replies, Replies}, Connection}} when Role == client andalso (not IsConnected) -> lists:foreach(fun send_msg/1, Replies), ClientPid ! {self(), not_connected, Reason}, {stop, normal, State#state{connection = Connection}}; {disconnect, Reason, {{replies, Replies}, Connection}} -> lists:foreach(fun send_msg/1, Replies), SSHOpts = proplists:get_value(ssh_opts, Opts), disconnect_fun(Reason, SSHOpts), {stop, normal, State#state{connection_state = Connection}} catch exit:{noproc, Reason} -> Report = io_lib:format("Connection probably terminated:~n~p~n~p~n", [ConnectionMsg, Reason]), error_logger:info_report(Report), {noreply, State}; exit:Exit -> Report = io_lib:format("Connection message returned:~n~p~n~p~n", [ConnectionMsg, Exit]), error_logger:info_report(Report), {noreply, State} end; handle_call({global_request, Pid, _, _, _} = Request, From, #state{connection_state = #connection{channel_cache = Cache}} = State0) -> State1 = handle_global_request(Request, State0), Channel = ssh_channel:cache_find(Pid, Cache), State = add_request(true, Channel#channel.local_id, From, State1), {noreply, State}; handle_call({data, ChannelId, Type, Data}, From, #state{connection_state = #connection{channel_cache = _Cache} = Connection0, connection = ConnectionPid} = State) -> channel_data(ChannelId, Type, Data, Connection0, ConnectionPid, From, State); handle_call({connection_info, Options}, From, #state{connection = Connection} = State) -> ssh_connection_handler:connection_info(Connection, From, Options), %% Reply will be sent by the connection handler by calling %% ssh_connection_handler:send_msg/1. {noreply, State}; handle_call({channel_info, ChannelId, Options}, From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{} = Channel -> spawn(?MODULE, ssh_channel_info_handler, [Options, Channel, From]), {noreply, State}; undefined -> {reply, []} end; handle_call({info, ChannelPid}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Result = ssh_channel:cache_foldl( fun(Channel, Acc) when ChannelPid == all; Channel#channel.user == ChannelPid -> [Channel | Acc]; (_, Acc) -> Acc end, [], Cache), {reply, {ok, Result}, State}; handle_call({open, ChannelPid, Type, InitialWindowSize, MaxPacketSize, Data}, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> {ChannelId, State1} = new_channel_id(State0), Msg = ssh_connection:channel_open_msg(Type, ChannelId, InitialWindowSize, MaxPacketSize, Data), send_msg({connection_reply, Pid, Msg}), Channel = #channel{type = Type, sys = "none", user = ChannelPid, local_id = ChannelId, recv_window_size = InitialWindowSize, recv_packet_size = MaxPacketSize}, ssh_channel:cache_update(Cache, Channel), State = add_request(true, ChannelId, From, State1), {noreply, State}; handle_call({send_window, ChannelId}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Reply = case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{send_window_size = WinSize, send_packet_size = Packsize} -> {ok, {WinSize, Packsize}}; undefined -> {error, einval} end, {reply, Reply, State}; handle_call({recv_window, ChannelId}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Reply = case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{recv_window_size = WinSize, recv_packet_size = Packsize} -> {ok, {WinSize, Packsize}}; undefined -> {error, einval} end, {reply, Reply, State}; %% Replaced by option peer to connection_info/2 keep for now %% for Backwards compatibility! handle_call({peer_addr, _ChannelId}, _From, #state{connection = Pid} = State) -> Reply = ssh_connection_handler:peer_address(Pid), {reply, Reply, State}; handle_call(opts, _, #state{opts = Opts} = State) -> {reply, Opts, State}; handle_call({close, ChannelId}, _, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> send_msg({connection_reply, Pid, ssh_connection:channel_close_msg(Id)}), {reply, ok, State}; undefined -> {reply, ok, State} end; handle_call(stop, _, State) -> {stop, normal, ok, State}; %% API violation make it the violaters problem %% by ignoring it. The violating process will get %% a timeout or hang. handle_call(_, _, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast({request, ChannelPid, ChannelId, Type, Data}, State0) -> {{replies, Replies}, State} = handle_request(ChannelPid, ChannelId, Type, Data, false, none, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_cast({request, ChannelId, Type, Data}, State0) -> {{replies, Replies}, State} = handle_request(ChannelId, Type, Data, false, none, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_cast({global_request, _, _, _, _} = Request, State0) -> State = handle_global_request(Request, State0), {noreply, State}; handle_cast(renegotiate, #state{connection = Pid} = State) -> ssh_connection_handler:renegotiate(Pid), {noreply, State}; handle_cast({adjust_window, ChannelId, Bytes}, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{recv_window_size = WinSize, remote_id = Id} = Channel -> ssh_channel:cache_update(Cache, Channel#channel{recv_window_size = WinSize + Bytes}), Msg = ssh_connection:channel_adjust_window_msg(Id, Bytes), send_msg({connection_reply, Pid, Msg}); undefined -> ignore end, {noreply, State}; handle_cast({eof, ChannelId}, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> send_msg({connection_reply, Pid, ssh_connection:channel_eof_msg(Id)}), {noreply, State}; undefined -> {noreply, State} end; handle_cast({success, ChannelId}, #state{connection = Pid} = State) -> Msg = ssh_connection:channel_success_msg(ChannelId), send_msg({connection_reply, Pid, Msg}), {noreply, State}; handle_cast({failure, ChannelId}, #state{connection = Pid} = State) -> Msg = ssh_connection:channel_failure_msg(ChannelId), send_msg({connection_reply, Pid, Msg}), {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info({start_connection, server, [Address, Port, Socket, Options]}, #state{connection_state = CState} = State) -> {ok, Connection} = ssh_transport:accept(Address, Port, Socket, Options), Shell = proplists:get_value(shell, Options), CliSpec = proplists:get_value(ssh_cli, Options, {ssh_cli, [Shell]}), {noreply, State#state{connection = Connection, connection_state = CState#connection{address = Address, port = Port, cli_spec = CliSpec, options = Options}}}; handle_info({start_connection, client, [Parent, Address, Port, ChannelPid, SocketOpts, Options]}, State) -> case (catch ssh_transport:connect(Parent, Address, Port, SocketOpts, Options)) of {ok, Connection} -> erlang:monitor(process, ChannelPid), {noreply, State#state{connection = Connection}}; Reason -> ChannelPid ! {self(), not_connected, Reason}, {stop, normal, State} end; handle_info({ssh_cm, _Sender, Msg}, State0) -> %% Backwards compatibility! State = cm_message(Msg, State0), {noreply, State}; Nop backwards compatibility handle_info({same_user, _}, State) -> {noreply, State}; handle_info(ssh_connected, #state{role = client, client = Pid} = State) -> Pid ! {self(), is_connected}, {noreply, State#state{connected = true}}; handle_info(ssh_connected, #state{role = server} = State) -> {noreply, State#state{connected = true}}; handle_info({'DOWN', _Ref, process, ChannelPid, normal}, State0) -> handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'DOWN', _Ref, process, ChannelPid, shutdown}, State0) -> handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'DOWN', _Ref, process, ChannelPid, Reason}, State0) -> Report = io_lib:format("Pid ~p DOWN ~p\n", [ChannelPid, Reason]), error_logger:error_report(Report), handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'EXIT', _, _}, State) -> %% Handled in 'DOWN' {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(Reason, #state{connection_state = #connection{requests = Requests}, opts = Opts}) -> SSHOpts = proplists:get_value(ssh_opts, Opts), disconnect_fun(Reason, SSHOpts), (catch lists:foreach(fun({_, From}) -> gen_server:reply(From, {error, connection_closed}) end, Requests)), ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- channel_data(Id, Type, Data, Connection0, ConnectionPid, From, State) -> case ssh_connection:channel_data(Id, Type, Data, Connection0, ConnectionPid, From) of {{replies, Replies}, Connection} -> lists:foreach(fun send_msg/1, Replies), {noreply, State#state{connection_state = Connection}}; {noreply, Connection} -> {noreply, State#state{connection_state = Connection}} end. call(Pid, Msg) -> call(Pid, Msg, infinity). call(Pid, Msg, Timeout) -> try gen_server:call(Pid, Msg, Timeout) of Result -> Result catch exit:{timeout, _} -> {error, timeout} end. cast(Pid, Msg) -> gen_server:cast(Pid, Msg). decode_ssh_msg(BinMsg) when is_binary(BinMsg)-> ssh_bits:decode(BinMsg); decode_ssh_msg(Msg) -> Msg. send_msg({channel_data, Pid, Data}) -> Pid ! {ssh_cm, self(), Data}; send_msg({channel_requst_reply, From, Data}) -> gen_server:reply(From, Data); send_msg({connection_reply, Pid, Data}) -> Msg = ssh_bits:encode(Data), ssh_connection_handler:send(Pid, Msg); send_msg({flow_control, Cache, Channel, From, Msg}) -> ssh_channel:cache_update(Cache, Channel#channel{flow_control = undefined}), gen_server:reply(From, Msg). handle_request(ChannelPid, ChannelId, Type, Data, WantReply, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} = Channel -> update_sys(Cache, Channel, Type, ChannelPid), Msg = ssh_connection:channel_request_msg(Id, Type, WantReply, Data), Replies = [{connection_reply, Pid, Msg}], State = add_request(WantReply, ChannelId, From, State0), {{replies, Replies}, State}; undefined -> {noreply, State0} end. handle_request(ChannelId, Type, Data, WantReply, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> Msg = ssh_connection:channel_request_msg(Id, Type, WantReply, Data), Replies = [{connection_reply, Pid, Msg}], State = add_request(WantReply, ChannelId, From, State0), {{replies, Replies}, State}; undefined -> {noreply, State0} end. handle_down({{replies, Replies}, State}) -> lists:foreach(fun send_msg/1, Replies), {noreply, State}. handle_channel_down(ChannelPid, #state{connection_state = #connection{channel_cache = Cache}} = State) -> ssh_channel:cache_foldl( fun(Channel, Acc) when Channel#channel.user == ChannelPid -> ssh_channel:cache_delete(Cache, Channel#channel.local_id), Acc; (_,Acc) -> Acc end, [], Cache), {{replies, []}, State}. update_sys(Cache, Channel, Type, ChannelPid) -> ssh_channel:cache_update(Cache, Channel#channel{sys = Type, user = ChannelPid}). add_request(false, _ChannelId, _From, State) -> State; add_request(true, ChannelId, From, #state{connection_state = #connection{requests = Requests0} = Connection} = State) -> Requests = [{ChannelId, From} | Requests0], State#state{connection_state = Connection#connection{requests = Requests}}. new_channel_id(#state{connection_state = #connection{channel_id_seed = Id} = Connection} = State) -> {Id, State#state{connection_state = Connection#connection{channel_id_seed = Id + 1}}}. handle_global_request({global_request, ChannelPid, "tcpip-forward" = Type, WantReply, <<?UINT32(IPLen), IP:IPLen/binary, ?UINT32(Port)>> = Data}, #state{connection = ConnectionPid, connection_state = #connection{channel_cache = Cache} = Connection0} = State) -> ssh_channel:cache_update(Cache, #channel{user = ChannelPid, type = "forwarded-tcpip", sys = none}), Connection = ssh_connection:bind(IP, Port, ChannelPid, Connection0), Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, ConnectionPid, Msg}), State#state{connection_state = Connection}; handle_global_request({global_request, _Pid, "cancel-tcpip-forward" = Type, WantReply, <<?UINT32(IPLen), IP:IPLen/binary, ?UINT32(Port)>> = Data}, #state{connection = Pid, connection_state = Connection0} = State) -> Connection = ssh_connection:unbind(IP, Port, Connection0), Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, Pid, Msg}), State#state{connection_state = Connection}; handle_global_request({global_request, _Pid, "cancel-tcpip-forward" = Type, WantReply, Data}, #state{connection = Pid} = State) -> Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, Pid, Msg}), State. cm_message(Msg, State) -> {noreply, NewState} = handle_cast(Msg, State), NewState. disconnect_fun(Reason, Opts) -> case proplists:get_value(disconnectfun, Opts) of undefined -> ok; Fun -> catch Fun(Reason) end. ssh_channel_info_handler(Options, Channel, From) -> Info = ssh_channel_info(Options, Channel, []), send_msg({channel_requst_reply, From, Info}). ssh_channel_info([], _, Acc) -> Acc; ssh_channel_info([recv_window | Rest], #channel{recv_window_size = WinSize, recv_packet_size = Packsize } = Channel, Acc) -> ssh_channel_info(Rest, Channel, [{recv_window, {{win_size, WinSize}, {packet_size, Packsize}}} | Acc]); ssh_channel_info([send_window | Rest], #channel{send_window_size = WinSize, send_packet_size = Packsize } = Channel, Acc) -> ssh_channel_info(Rest, Channel, [{send_window, {{win_size, WinSize}, {packet_size, Packsize}}} | Acc]); ssh_channel_info([ _ | Rest], Channel, Acc) -> ssh_channel_info(Rest, Channel, Acc).
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/ssh/src/ssh_connection_manager.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% ---------------------------------------------------------------------- Purpose: Handles multiplexing to ssh channels and global connection interactive login sessions, remote execution of commands, forwarded TCP/IP connections, and forwarded X11 connections. Details of the ---------------------------------------------------------------------- Internal application API and spawn gen_server callbacks pid() #connection{} ==================================================================== ==================================================================== TODO: Best way? TODO: Do we really want this function? Should not renegotiation be triggered by configurable timer or amount of data sent counter! Replaced by option peer to connection_info/2 keep for now for Backwards compatibility! Backwards compatibility! Backwards compatibility! ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- Sends message to the connection handler process, reply to channel is sent later when reply arrives from the connection handler. Sends message to the connection handler process, reply to channel is sent later when reply arrives from the connection handler. Message from ssh_connection_handler To avoid that not all data sent by the other side is processes before Reply will be sent by the connection handler by calling ssh_connection_handler:send_msg/1. Replaced by option peer to connection_info/2 keep for now for Backwards compatibility! API violation make it the violaters problem by ignoring it. The violating process will get a timeout or hang. -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- Backwards compatibility! Handled in 'DOWN' -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright Ericsson AB 2008 - 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 " requests e.i . the SSH Connection Protocol ( RFC 4254 ) , that provides protocol is implemented in ssh_connection.erl -module(ssh_connection_manager). -behaviour(gen_server). -include("ssh.hrl"). -include("ssh_connect.hrl"). -export([start_link/1]). -export([info/1, info/2, renegotiate/1, connection_info/2, channel_info/3, peer_addr/1, send_window/3, recv_window/3, adjust_window/3, close/2, stop/1, send/5, send_eof/2]). -export([open_channel/6, request/6, request/7, global_request/4, event/2, cast/2]). -export([send_msg/1, ssh_channel_info_handler/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(DBG_MESSAGE, true). -record(state, { role, client, starter, latest_channel_id = 0, opts, channel_args, connected }). Internal application API start_link(Opts) -> gen_server:start_link(?MODULE, Opts, []). open_channel(ConnectionManager, ChannelType, ChannelSpecificData, InitialWindowSize, MaxPacketSize, Timeout) -> case (catch call(ConnectionManager, {open, self(), ChannelType, InitialWindowSize, MaxPacketSize, ChannelSpecificData}, Timeout)) of {open, Channel} -> {ok, Channel}; Error -> Error end. request(ConnectionManager, ChannelPid, ChannelId, Type, true, Data, Timeout) -> call(ConnectionManager, {request, ChannelPid, ChannelId, Type, Data}, Timeout); request(ConnectionManager, ChannelPid, ChannelId, Type, false, Data, _) -> cast(ConnectionManager, {request, ChannelPid, ChannelId, Type, Data}). request(ConnectionManager, ChannelId, Type, true, Data, Timeout) -> call(ConnectionManager, {request, ChannelId, Type, Data}, Timeout); request(ConnectionManager, ChannelId, Type, false, Data, _) -> cast(ConnectionManager, {request, ChannelId, Type, Data}). global_request(ConnectionManager, Type, true = Reply, Data) -> case call(ConnectionManager, {global_request, self(), Type, Reply, Data}) of {ssh_cm, ConnectionManager, {success, _}} -> ok; {ssh_cm, ConnectionManager, {failure, _}} -> error end; global_request(ConnectionManager, Type, false = Reply, Data) -> cast(ConnectionManager, {global_request, self(), Type, Reply, Data}). event(ConnectionManager, BinMsg) -> call(ConnectionManager, {ssh_msg, self(), BinMsg}). info(ConnectionManager) -> info(ConnectionManager, {info, all}). info(ConnectionManager, ChannelProcess) -> call(ConnectionManager, {info, ChannelProcess}). renegotiate(ConnectionManager) -> cast(ConnectionManager, renegotiate). connection_info(ConnectionManager, Options) -> call(ConnectionManager, {connection_info, Options}). channel_info(ConnectionManager, ChannelId, Options) -> call(ConnectionManager, {channel_info, ChannelId, Options}). peer_addr(ConnectionManager) -> call(ConnectionManager, {peer_addr, self()}). send_window(ConnectionManager, Channel, TimeOut) -> call(ConnectionManager, {send_window, Channel}, TimeOut). recv_window(ConnectionManager, Channel, TimeOut) -> call(ConnectionManager, {recv_window, Channel}, TimeOut). adjust_window(ConnectionManager, Channel, Bytes) -> cast(ConnectionManager, {adjust_window, Channel, Bytes}). close(ConnectionManager, ChannelId) -> try call(ConnectionManager, {close, ChannelId}) of ok -> ok catch exit:{noproc, _} -> ok end. stop(ConnectionManager) -> try call(ConnectionManager, stop) of ok -> ok catch exit:{noproc, _} -> ok end. send(ConnectionManager, ChannelId, Type, Data, Timeout) -> call(ConnectionManager, {data, ChannelId, Type, Data}, Timeout). send_eof(ConnectionManager, ChannelId) -> cast(ConnectionManager, {eof, ChannelId}). { ok , State , Timeout } | init([server, _Socket, Opts]) -> process_flag(trap_exit, true), ssh_bits:install_messages(ssh_connection:messages()), Cache = ssh_channel:cache_create(), {ok, #state{role = server, connection_state = #connection{channel_cache = Cache, channel_id_seed = 0, port_bindings = [], requests = [], channel_pids = []}, opts = Opts, connected = false}}; init([client, Opts]) -> process_flag(trap_exit, true), {links, [Parent]} = process_info(self(), links), ssh_bits:install_messages(ssh_connection:messages()), Cache = ssh_channel:cache_create(), Address = proplists:get_value(address, Opts), Port = proplists:get_value(port, Opts), SocketOpts = proplists:get_value(socket_opts, Opts), Options = proplists:get_value(ssh_opts, Opts), ChannelPid = proplists:get_value(channel_pid, Opts), self() ! {start_connection, client, [Parent, Address, Port, ChannelPid, SocketOpts, Options]}, {ok, #state{role = client, client = ChannelPid, connection_state = #connection{channel_cache = Cache, channel_id_seed = 0, port_bindings = [], requests = [], channel_pids = []}, opts = Opts, connected = false}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({request, ChannelPid, ChannelId, Type, Data}, From, State0) -> {{replies, Replies}, State} = handle_request(ChannelPid, ChannelId, Type, Data, true, From, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_call({request, ChannelId, Type, Data}, From, State0) -> {{replies, Replies}, State} = handle_request(ChannelId, Type, Data, true, From, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_call({ssh_msg, Pid, Msg}, From, #state{connection_state = Connection0, role = Role, opts = Opts, connected = IsConnected, client = ClientPid} = State) -> possible crash in takes down the connection . gen_server:reply(From, ok), ConnectionMsg = decode_ssh_msg(Msg), try ssh_connection:handle_msg(ConnectionMsg, Connection0, Pid, Role) of {{replies, Replies}, Connection} -> lists:foreach(fun send_msg/1, Replies), {noreply, State#state{connection_state = Connection}}; {noreply, Connection} -> {noreply, State#state{connection_state = Connection}}; {disconnect, {_, Reason}, {{replies, Replies}, Connection}} when Role == client andalso (not IsConnected) -> lists:foreach(fun send_msg/1, Replies), ClientPid ! {self(), not_connected, Reason}, {stop, normal, State#state{connection = Connection}}; {disconnect, Reason, {{replies, Replies}, Connection}} -> lists:foreach(fun send_msg/1, Replies), SSHOpts = proplists:get_value(ssh_opts, Opts), disconnect_fun(Reason, SSHOpts), {stop, normal, State#state{connection_state = Connection}} catch exit:{noproc, Reason} -> Report = io_lib:format("Connection probably terminated:~n~p~n~p~n", [ConnectionMsg, Reason]), error_logger:info_report(Report), {noreply, State}; exit:Exit -> Report = io_lib:format("Connection message returned:~n~p~n~p~n", [ConnectionMsg, Exit]), error_logger:info_report(Report), {noreply, State} end; handle_call({global_request, Pid, _, _, _} = Request, From, #state{connection_state = #connection{channel_cache = Cache}} = State0) -> State1 = handle_global_request(Request, State0), Channel = ssh_channel:cache_find(Pid, Cache), State = add_request(true, Channel#channel.local_id, From, State1), {noreply, State}; handle_call({data, ChannelId, Type, Data}, From, #state{connection_state = #connection{channel_cache = _Cache} = Connection0, connection = ConnectionPid} = State) -> channel_data(ChannelId, Type, Data, Connection0, ConnectionPid, From, State); handle_call({connection_info, Options}, From, #state{connection = Connection} = State) -> ssh_connection_handler:connection_info(Connection, From, Options), {noreply, State}; handle_call({channel_info, ChannelId, Options}, From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{} = Channel -> spawn(?MODULE, ssh_channel_info_handler, [Options, Channel, From]), {noreply, State}; undefined -> {reply, []} end; handle_call({info, ChannelPid}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Result = ssh_channel:cache_foldl( fun(Channel, Acc) when ChannelPid == all; Channel#channel.user == ChannelPid -> [Channel | Acc]; (_, Acc) -> Acc end, [], Cache), {reply, {ok, Result}, State}; handle_call({open, ChannelPid, Type, InitialWindowSize, MaxPacketSize, Data}, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> {ChannelId, State1} = new_channel_id(State0), Msg = ssh_connection:channel_open_msg(Type, ChannelId, InitialWindowSize, MaxPacketSize, Data), send_msg({connection_reply, Pid, Msg}), Channel = #channel{type = Type, sys = "none", user = ChannelPid, local_id = ChannelId, recv_window_size = InitialWindowSize, recv_packet_size = MaxPacketSize}, ssh_channel:cache_update(Cache, Channel), State = add_request(true, ChannelId, From, State1), {noreply, State}; handle_call({send_window, ChannelId}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Reply = case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{send_window_size = WinSize, send_packet_size = Packsize} -> {ok, {WinSize, Packsize}}; undefined -> {error, einval} end, {reply, Reply, State}; handle_call({recv_window, ChannelId}, _From, #state{connection_state = #connection{channel_cache = Cache}} = State) -> Reply = case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{recv_window_size = WinSize, recv_packet_size = Packsize} -> {ok, {WinSize, Packsize}}; undefined -> {error, einval} end, {reply, Reply, State}; handle_call({peer_addr, _ChannelId}, _From, #state{connection = Pid} = State) -> Reply = ssh_connection_handler:peer_address(Pid), {reply, Reply, State}; handle_call(opts, _, #state{opts = Opts} = State) -> {reply, Opts, State}; handle_call({close, ChannelId}, _, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> send_msg({connection_reply, Pid, ssh_connection:channel_close_msg(Id)}), {reply, ok, State}; undefined -> {reply, ok, State} end; handle_call(stop, _, State) -> {stop, normal, ok, State}; handle_call(_, _, State) -> {noreply, State}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast({request, ChannelPid, ChannelId, Type, Data}, State0) -> {{replies, Replies}, State} = handle_request(ChannelPid, ChannelId, Type, Data, false, none, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_cast({request, ChannelId, Type, Data}, State0) -> {{replies, Replies}, State} = handle_request(ChannelId, Type, Data, false, none, State0), lists:foreach(fun send_msg/1, Replies), {noreply, State}; handle_cast({global_request, _, _, _, _} = Request, State0) -> State = handle_global_request(Request, State0), {noreply, State}; handle_cast(renegotiate, #state{connection = Pid} = State) -> ssh_connection_handler:renegotiate(Pid), {noreply, State}; handle_cast({adjust_window, ChannelId, Bytes}, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{recv_window_size = WinSize, remote_id = Id} = Channel -> ssh_channel:cache_update(Cache, Channel#channel{recv_window_size = WinSize + Bytes}), Msg = ssh_connection:channel_adjust_window_msg(Id, Bytes), send_msg({connection_reply, Pid, Msg}); undefined -> ignore end, {noreply, State}; handle_cast({eof, ChannelId}, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> send_msg({connection_reply, Pid, ssh_connection:channel_eof_msg(Id)}), {noreply, State}; undefined -> {noreply, State} end; handle_cast({success, ChannelId}, #state{connection = Pid} = State) -> Msg = ssh_connection:channel_success_msg(ChannelId), send_msg({connection_reply, Pid, Msg}), {noreply, State}; handle_cast({failure, ChannelId}, #state{connection = Pid} = State) -> Msg = ssh_connection:channel_failure_msg(ChannelId), send_msg({connection_reply, Pid, Msg}), {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({start_connection, server, [Address, Port, Socket, Options]}, #state{connection_state = CState} = State) -> {ok, Connection} = ssh_transport:accept(Address, Port, Socket, Options), Shell = proplists:get_value(shell, Options), CliSpec = proplists:get_value(ssh_cli, Options, {ssh_cli, [Shell]}), {noreply, State#state{connection = Connection, connection_state = CState#connection{address = Address, port = Port, cli_spec = CliSpec, options = Options}}}; handle_info({start_connection, client, [Parent, Address, Port, ChannelPid, SocketOpts, Options]}, State) -> case (catch ssh_transport:connect(Parent, Address, Port, SocketOpts, Options)) of {ok, Connection} -> erlang:monitor(process, ChannelPid), {noreply, State#state{connection = Connection}}; Reason -> ChannelPid ! {self(), not_connected, Reason}, {stop, normal, State} end; handle_info({ssh_cm, _Sender, Msg}, State0) -> State = cm_message(Msg, State0), {noreply, State}; Nop backwards compatibility handle_info({same_user, _}, State) -> {noreply, State}; handle_info(ssh_connected, #state{role = client, client = Pid} = State) -> Pid ! {self(), is_connected}, {noreply, State#state{connected = true}}; handle_info(ssh_connected, #state{role = server} = State) -> {noreply, State#state{connected = true}}; handle_info({'DOWN', _Ref, process, ChannelPid, normal}, State0) -> handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'DOWN', _Ref, process, ChannelPid, shutdown}, State0) -> handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'DOWN', _Ref, process, ChannelPid, Reason}, State0) -> Report = io_lib:format("Pid ~p DOWN ~p\n", [ChannelPid, Reason]), error_logger:error_report(Report), handle_down(handle_channel_down(ChannelPid, State0)); handle_info({'EXIT', _, _}, State) -> {noreply, State}. terminate(Reason, #state{connection_state = #connection{requests = Requests}, opts = Opts}) -> SSHOpts = proplists:get_value(ssh_opts, Opts), disconnect_fun(Reason, SSHOpts), (catch lists:foreach(fun({_, From}) -> gen_server:reply(From, {error, connection_closed}) end, Requests)), ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions channel_data(Id, Type, Data, Connection0, ConnectionPid, From, State) -> case ssh_connection:channel_data(Id, Type, Data, Connection0, ConnectionPid, From) of {{replies, Replies}, Connection} -> lists:foreach(fun send_msg/1, Replies), {noreply, State#state{connection_state = Connection}}; {noreply, Connection} -> {noreply, State#state{connection_state = Connection}} end. call(Pid, Msg) -> call(Pid, Msg, infinity). call(Pid, Msg, Timeout) -> try gen_server:call(Pid, Msg, Timeout) of Result -> Result catch exit:{timeout, _} -> {error, timeout} end. cast(Pid, Msg) -> gen_server:cast(Pid, Msg). decode_ssh_msg(BinMsg) when is_binary(BinMsg)-> ssh_bits:decode(BinMsg); decode_ssh_msg(Msg) -> Msg. send_msg({channel_data, Pid, Data}) -> Pid ! {ssh_cm, self(), Data}; send_msg({channel_requst_reply, From, Data}) -> gen_server:reply(From, Data); send_msg({connection_reply, Pid, Data}) -> Msg = ssh_bits:encode(Data), ssh_connection_handler:send(Pid, Msg); send_msg({flow_control, Cache, Channel, From, Msg}) -> ssh_channel:cache_update(Cache, Channel#channel{flow_control = undefined}), gen_server:reply(From, Msg). handle_request(ChannelPid, ChannelId, Type, Data, WantReply, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} = Channel -> update_sys(Cache, Channel, Type, ChannelPid), Msg = ssh_connection:channel_request_msg(Id, Type, WantReply, Data), Replies = [{connection_reply, Pid, Msg}], State = add_request(WantReply, ChannelId, From, State0), {{replies, Replies}, State}; undefined -> {noreply, State0} end. handle_request(ChannelId, Type, Data, WantReply, From, #state{connection = Pid, connection_state = #connection{channel_cache = Cache}} = State0) -> case ssh_channel:cache_lookup(Cache, ChannelId) of #channel{remote_id = Id} -> Msg = ssh_connection:channel_request_msg(Id, Type, WantReply, Data), Replies = [{connection_reply, Pid, Msg}], State = add_request(WantReply, ChannelId, From, State0), {{replies, Replies}, State}; undefined -> {noreply, State0} end. handle_down({{replies, Replies}, State}) -> lists:foreach(fun send_msg/1, Replies), {noreply, State}. handle_channel_down(ChannelPid, #state{connection_state = #connection{channel_cache = Cache}} = State) -> ssh_channel:cache_foldl( fun(Channel, Acc) when Channel#channel.user == ChannelPid -> ssh_channel:cache_delete(Cache, Channel#channel.local_id), Acc; (_,Acc) -> Acc end, [], Cache), {{replies, []}, State}. update_sys(Cache, Channel, Type, ChannelPid) -> ssh_channel:cache_update(Cache, Channel#channel{sys = Type, user = ChannelPid}). add_request(false, _ChannelId, _From, State) -> State; add_request(true, ChannelId, From, #state{connection_state = #connection{requests = Requests0} = Connection} = State) -> Requests = [{ChannelId, From} | Requests0], State#state{connection_state = Connection#connection{requests = Requests}}. new_channel_id(#state{connection_state = #connection{channel_id_seed = Id} = Connection} = State) -> {Id, State#state{connection_state = Connection#connection{channel_id_seed = Id + 1}}}. handle_global_request({global_request, ChannelPid, "tcpip-forward" = Type, WantReply, <<?UINT32(IPLen), IP:IPLen/binary, ?UINT32(Port)>> = Data}, #state{connection = ConnectionPid, connection_state = #connection{channel_cache = Cache} = Connection0} = State) -> ssh_channel:cache_update(Cache, #channel{user = ChannelPid, type = "forwarded-tcpip", sys = none}), Connection = ssh_connection:bind(IP, Port, ChannelPid, Connection0), Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, ConnectionPid, Msg}), State#state{connection_state = Connection}; handle_global_request({global_request, _Pid, "cancel-tcpip-forward" = Type, WantReply, <<?UINT32(IPLen), IP:IPLen/binary, ?UINT32(Port)>> = Data}, #state{connection = Pid, connection_state = Connection0} = State) -> Connection = ssh_connection:unbind(IP, Port, Connection0), Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, Pid, Msg}), State#state{connection_state = Connection}; handle_global_request({global_request, _Pid, "cancel-tcpip-forward" = Type, WantReply, Data}, #state{connection = Pid} = State) -> Msg = ssh_connection:global_request_msg(Type, WantReply, Data), send_msg({connection_reply, Pid, Msg}), State. cm_message(Msg, State) -> {noreply, NewState} = handle_cast(Msg, State), NewState. disconnect_fun(Reason, Opts) -> case proplists:get_value(disconnectfun, Opts) of undefined -> ok; Fun -> catch Fun(Reason) end. ssh_channel_info_handler(Options, Channel, From) -> Info = ssh_channel_info(Options, Channel, []), send_msg({channel_requst_reply, From, Info}). ssh_channel_info([], _, Acc) -> Acc; ssh_channel_info([recv_window | Rest], #channel{recv_window_size = WinSize, recv_packet_size = Packsize } = Channel, Acc) -> ssh_channel_info(Rest, Channel, [{recv_window, {{win_size, WinSize}, {packet_size, Packsize}}} | Acc]); ssh_channel_info([send_window | Rest], #channel{send_window_size = WinSize, send_packet_size = Packsize } = Channel, Acc) -> ssh_channel_info(Rest, Channel, [{send_window, {{win_size, WinSize}, {packet_size, Packsize}}} | Acc]); ssh_channel_info([ _ | Rest], Channel, Acc) -> ssh_channel_info(Rest, Channel, Acc).
1b8e079fe9bdbb6ddef3bbecd8bac125ec23fcd330926501cb0036197d926c4e
den1k/vimsical
transit.cljs
(ns vimsical.common.util.transit (:require [cognitect.transit :as transit])) ;; ;; * Types ;; (def sorted-map-write-handler (transit/write-handler (constantly "sorted-map") (fn [x] (into {} x)))) (def sorted-map-read-handler (transit/read-handler (fn [x] (into (sorted-map) x)))) ;; ;; * Writer ;; (def default-writer-opts {:handlers {cljs.core/PersistentTreeMap sorted-map-write-handler}}) (def writer (transit/writer :json default-writer-opts)) ;; ;; * Reader ;; (def default-reader-opts {:handlers {"sorted-map" sorted-map-read-handler Transit cljs has its own uuid type ? ! ;; /#!topic/clojurescript/_B52tadgUgw "u" uuid}}) (def reader (transit/reader :json default-reader-opts)) ;; ;; * API ;; (defn write-transit [data] (transit/write writer data)) (defn read-transit [string] (transit/read reader string)) (comment (let [val {:foo {:bar (into (sorted-map) {2 2 1 1})}}] (assert (= val (read-transit (write-transit val)))) (write-transit val)))
null
https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/common/vimsical/common/util/transit.cljs
clojure
* Types * Writer * Reader /#!topic/clojurescript/_B52tadgUgw * API
(ns vimsical.common.util.transit (:require [cognitect.transit :as transit])) (def sorted-map-write-handler (transit/write-handler (constantly "sorted-map") (fn [x] (into {} x)))) (def sorted-map-read-handler (transit/read-handler (fn [x] (into (sorted-map) x)))) (def default-writer-opts {:handlers {cljs.core/PersistentTreeMap sorted-map-write-handler}}) (def writer (transit/writer :json default-writer-opts)) (def default-reader-opts {:handlers {"sorted-map" sorted-map-read-handler Transit cljs has its own uuid type ? ! "u" uuid}}) (def reader (transit/reader :json default-reader-opts)) (defn write-transit [data] (transit/write writer data)) (defn read-transit [string] (transit/read reader string)) (comment (let [val {:foo {:bar (into (sorted-map) {2 2 1 1})}}] (assert (= val (read-transit (write-transit val)))) (write-transit val)))
3695e4cbe1bd7662083a661c132e98924857e60f9895c9174b87a655999b23dc
UU-ComputerScience/uhc
Main.hs
- This is a EHC modified version of th 3 ^ 8 benchmark of the nofib / imaginary - Original code by to be compiled by EHC : - This is a EHC modified version of th 3^8 benchmark of the nofib/imaginary - Original code by Lennart Augustsson - Changes to be compiled by EHC: John van Schie -} infix 8 ^^^ data Nat = Z | S Nat -- Num instance plusNum :: Nat -> Nat -> Nat plusNum Z y = y plusNum (S x) y = S (plusNum x y) mulNum :: Nat -> Nat -> Nat mulNum x Z = Z mulNum x (S y) = plusNum (mulNum x y) x fromInteger' :: Int -> Nat fromInteger' x = if x < 1 then Z else S (fromInteger' (x-1)) -- partain:sig int :: Nat -> Int int Z = 0 int (S x) = 1 + int x (^^^) :: Nat -> Nat -> Nat x ^^^ Z = S Z x ^^^ S y = mulNum x (x ^^^ y) arg = <ARG1> main = <PRINT_INT> int ((fromInteger' 3) ^^^ (fromInteger' arg))
null
https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/nofib-jvschie/imaginary/exp3_8/Main.hs
haskell
Num instance partain:sig
- This is a EHC modified version of th 3 ^ 8 benchmark of the nofib / imaginary - Original code by to be compiled by EHC : - This is a EHC modified version of th 3^8 benchmark of the nofib/imaginary - Original code by Lennart Augustsson - Changes to be compiled by EHC: John van Schie -} infix 8 ^^^ data Nat = Z | S Nat plusNum :: Nat -> Nat -> Nat plusNum Z y = y plusNum (S x) y = S (plusNum x y) mulNum :: Nat -> Nat -> Nat mulNum x Z = Z mulNum x (S y) = plusNum (mulNum x y) x fromInteger' :: Int -> Nat fromInteger' x = if x < 1 then Z else S (fromInteger' (x-1)) int :: Nat -> Int int Z = 0 int (S x) = 1 + int x (^^^) :: Nat -> Nat -> Nat x ^^^ Z = S Z x ^^^ S y = mulNum x (x ^^^ y) arg = <ARG1> main = <PRINT_INT> int ((fromInteger' 3) ^^^ (fromInteger' arg))
d794443b2f1d6e31adf460bb1ed45736e7b457341e4c9c6cfdf95fba5f6df2db
Kleidukos/Intrigue
Lexer.hs
module Intrigue.Lexer where import Data.Text ( Text ) import Data.Void import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L type Parser = Parsec Void Text skipLineComment :: Parser () skipLineComment = L.skipLineComment ";" skipBlockComment :: Parser () skipBlockComment = L.skipBlockComment "{-" "-}" consumeSpaces :: Parser () consumeSpaces = L.space space1 skipLineComment skipBlockComment lexeme :: Parser a -> Parser a lexeme = L.lexeme consumeSpaces symbol :: Text -> Parser Text symbol = L.symbol consumeSpaces integer :: Parser Integer integer = lexeme L.decimal signedInteger :: Parser Integer signedInteger = L.signed consumeSpaces integer parens :: Parser a -> Parser a parens = between (symbol "(") (symbol ")")
null
https://raw.githubusercontent.com/Kleidukos/Intrigue/d6cb7a0ee13c04b7ef0c8ca15ac5600da25100ff/src/Intrigue/Lexer.hs
haskell
module Intrigue.Lexer where import Data.Text ( Text ) import Data.Void import Text.Megaparsec import Text.Megaparsec.Char import qualified Text.Megaparsec.Char.Lexer as L type Parser = Parsec Void Text skipLineComment :: Parser () skipLineComment = L.skipLineComment ";" skipBlockComment :: Parser () skipBlockComment = L.skipBlockComment "{-" "-}" consumeSpaces :: Parser () consumeSpaces = L.space space1 skipLineComment skipBlockComment lexeme :: Parser a -> Parser a lexeme = L.lexeme consumeSpaces symbol :: Text -> Parser Text symbol = L.symbol consumeSpaces integer :: Parser Integer integer = lexeme L.decimal signedInteger :: Parser Integer signedInteger = L.signed consumeSpaces integer parens :: Parser a -> Parser a parens = between (symbol "(") (symbol ")")
ccdd985155bfa2dbcf1e1ebd21b3b8b3996247cfa4f6ab47983ebf8f77d7804c
tweag/ormolu
associated-data.hs
# LANGUAGE TypeFamilies # instance Foo Int where data Bar Int = IntBar Int Int instance Foo Double where newtype Bar Double = DoubleBar Double Double instance Foo [a] where data Bar [a] = ListBar [Bar a] data Baz [a] = ListBaz
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/instance/associated-data.hs
haskell
# LANGUAGE TypeFamilies # instance Foo Int where data Bar Int = IntBar Int Int instance Foo Double where newtype Bar Double = DoubleBar Double Double instance Foo [a] where data Bar [a] = ListBar [Bar a] data Baz [a] = ListBaz
4945991653d079fb3e9e692c5ae8b197dbd9955eb874d3ce71736934f9fb2c50
shirok/Gauche
173.scm
;;; ;;; SRFI-173 hooks ;;; (define-module srfi.173 (use gauche.hook) (export make-hook hook? list->hook list->hook! hook-add! hook-delete! hook-reset! hook->list hook-run)) (select-module srfi.173) ;; The following procedures are the same as gauche.hook make - hook hook ? hook->list (define (hook-add! hook proc) (add-hook! hook proc)) (define (hook-delete! hook proc) (delete-hook! hook proc)) (define (hook-reset! hook) (reset-hook! hook)) (define (list->hook arity lst) (rlet1 hook (make-hook arity) (dolist [p lst] (add-hook! hook p)))) (define (list->hook! hook lst) (reset-hook! hook) (dolist [p lst] (add-hook! hook p))) (define (hook-run hook . args) (apply run-hook hook args))
null
https://raw.githubusercontent.com/shirok/Gauche/e606bfe5a94b100d5807bca9c2bb95df94f60aa6/lib/srfi/173.scm
scheme
SRFI-173 hooks The following procedures are the same as gauche.hook
(define-module srfi.173 (use gauche.hook) (export make-hook hook? list->hook list->hook! hook-add! hook-delete! hook-reset! hook->list hook-run)) (select-module srfi.173) make - hook hook ? hook->list (define (hook-add! hook proc) (add-hook! hook proc)) (define (hook-delete! hook proc) (delete-hook! hook proc)) (define (hook-reset! hook) (reset-hook! hook)) (define (list->hook arity lst) (rlet1 hook (make-hook arity) (dolist [p lst] (add-hook! hook p)))) (define (list->hook! hook lst) (reset-hook! hook) (dolist [p lst] (add-hook! hook p))) (define (hook-run hook . args) (apply run-hook hook args))
d6818a130c242e00e8b23489b118836d46f73e255f8da6d483edd01e3028469b
aryx/xix
IO.ml
* Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) (*****************************************************************************) (* Prelude *) (*****************************************************************************) Generalized Input / functions . * * Most of the code below comes from : * -extlib/blob/master/src/IO.ml * * alternatives : * - in_channel / out_channel in pervasives.ml * no function for little / big - endian binary IO . We could add those functions , * but still there is no inchannel_of_string ( ) or outchannel_of_buffer ( ) * so not general enough . * - batIO.ml from batteries - included ( comes from extLib 's ) * complexified * - mstruct / cstruct * good when have .h declarations of struct , * but more complex than IO.ml . Bytes and Buffer with small wrappers * around ( e.g. , ) for little / big endian stuff is good enough . * Still / cstruct allows to compute the length , offset , or * to backtrack ( shift ) . Some of those features can be implemented * with IO.ml thx to IO.pos_in but not all of them . * - scanf / printf ? good for binary IO ? * - bitstring ( was called bitmatch ) * Erlang style binary IO . Very declarative , very powerful , but * requires or ppx . * * Most of the code below comes from: * -extlib/blob/master/src/IO.ml * * alternatives: * - in_channel/out_channel in pervasives.ml * no function for little/big-endian binary IO. We could add those functions, * but still there is no inchannel_of_string() or outchannel_of_buffer() * so not general enough. * - batIO.ml from batteries-included (comes from extLib's IO.ml) * complexified * - mstruct/cstruct * good when have .h declarations of struct, * but more complex than IO.ml. Bytes and Buffer with small wrappers * around (e.g., IO.ml) for little/big endian stuff is good enough. * Still mstruct/cstruct allows to compute the length, offset, or * to backtrack (shift). Some of those features can be implemented * with IO.ml thx to IO.pos_in but not all of them. * - scanf/printf? good for binary IO? * - bitstring (was called bitmatch) * Erlang style binary IO. Very declarative, very powerful, but * requires camlp4 or ppx. *) (*****************************************************************************) (* Types *) (*****************************************************************************) (* start of copy-pasted code from extLib/IO.ml *) type input = { mutable in_read : unit -> char; mutable in_input : bytes -> int (** pos *) -> int (** len *) -> int; mutable in_close : unit -> unit; } type 'a output = { mutable out_write : char -> unit; mutable out_output : bytes -> int -> int -> int; mutable out_close : unit -> 'a; mutable out_flush : unit -> unit; } exception No_more_input exception Input_closed exception Output_closed (* -------------------------------------------------------------- *) (* API *) let default_close = (fun () -> ()) (* pad: could use intermediate struct instead of keyword arguments *) let create_in ~read ~input ~close = { in_read = read; in_input = input; in_close = close; } let create_out ~write ~output ~flush ~close = { out_write = write; out_output = output; out_close = close; out_flush = flush; } let read i = i.in_read() let nread i n = if n < 0 then invalid_arg "IO.nread"; if n = 0 then Bytes.empty else let s = Bytes.create n in let l = ref n in let p = ref 0 in try while !l > 0 do let r = i.in_input s !p !l in if r = 0 then raise No_more_input; p := !p + r; l := !l - r; done; s with No_more_input as e -> if !p = 0 then raise e; Bytes.sub s 0 !p let nread_string i n = [ nread ] transfers ownership of the returned string , so [ unsafe_to_string ] is safe here [unsafe_to_string] is safe here *) Bytes.unsafe_to_string (nread i n) let really_output o s p l' = let sl = Bytes.length s in if p + l' > sl || p < 0 || l' < 0 then invalid_arg "IO.really_output"; let l = ref l' in let p = ref p in while !l > 0 do let w = o.out_output s !p !l in if w = 0 then raise Sys_blocked_io; p := !p + w; l := !l - w; done; l' let input i s p l = let sl = Bytes.length s in if p + l > sl || p < 0 || l < 0 then invalid_arg "IO.input"; if l = 0 then 0 else i.in_input s p l let really_input i s p l' = let sl = Bytes.length s in if p + l' > sl || p < 0 || l' < 0 then invalid_arg "IO.really_input"; let l = ref l' in let p = ref p in while !l > 0 do let r = i.in_input s !p !l in if r = 0 then raise Sys_blocked_io; p := !p + r; l := !l - r; done; l' let really_nread i n = if n < 0 then invalid_arg "IO.really_nread"; if n = 0 then Bytes.empty else let s = Bytes.create n in ignore(really_input i s 0 n); s let really_nread_string i n = (* [really_nread] transfers ownership of the returned string, so [unsafe_to_string] is safe here *) Bytes.unsafe_to_string (really_nread i n) let close_in i = let f _ = raise Input_closed in i.in_close(); i.in_read <- f; i.in_input <- f; i.in_close <- f let write o x = o.out_write x let nwrite o s = let p = ref 0 in let l = ref (Bytes.length s) in while !l > 0 do let w = o.out_output s !p !l in if w = 0 then raise Sys_blocked_io; p := !p + w; l := !l - w; done let nwrite_string o s = (* [nwrite] does not mutate or capture its [bytes] input, so using [Bytes.unsafe_of_string] is safe here *) nwrite o (Bytes.unsafe_of_string s) let output o s p l = let sl = Bytes.length s in if p + l > sl || p < 0 || l < 0 then invalid_arg "IO.output"; o.out_output s p l let scanf i fmt = let ib = Scanf.Scanning.from_function (fun () -> try read i with No_more_input -> raise End_of_file) in Scanf.kscanf ib (fun _ exn -> raise exn) fmt let printf o fmt = Printf.kprintf (fun s -> nwrite_string o s) fmt let flush o = o.out_flush() let close_out o = let f _ = raise Output_closed in let r = o.out_close() in o.out_write <- f; o.out_output <- f; o.out_close <- f; o.out_flush <- f; r let read_all i = let maxlen = 1024 in let str = ref [] in let pos = ref 0 in let rec loop() = let s = nread i maxlen in str := (s,!pos) :: !str; pos := !pos + Bytes.length s; loop() in try loop() with No_more_input -> let buf = Bytes.create !pos in List.iter (fun (s,p) -> Bytes.blit s 0 buf p (Bytes.length s) ) !str; ' buf ' does n't escape , it wo n't be mutated again Bytes.unsafe_to_string buf let pos_in i = let p = ref 0 in { in_read = (fun () -> let c = i.in_read() in incr p; c ); in_input = (fun s sp l -> let n = i.in_input s sp l in p := !p + n; n ); in_close = i.in_close } , (fun () -> !p) let pos_out o = let p = ref 0 in { out_write = (fun c -> o.out_write c; incr p ); out_output = (fun s sp l -> let n = o.out_output s sp l in p := !p + n; n ); out_close = o.out_close; out_flush = o.out_flush; } , (fun () -> !p) (* -------------------------------------------------------------- *) (* Standard IO *) let input_bytes s = let pos = ref 0 in let len = Bytes.length s in { in_read = (fun () -> if !pos >= len then raise No_more_input; let c = Bytes.unsafe_get s !pos in incr pos; c ); in_input = (fun sout p l -> if !pos >= len then raise No_more_input; let n = (if !pos + l > len then len - !pos else l) in Bytes.unsafe_blit s !pos sout p n; pos := !pos + n; n ); in_close = (fun () -> ()); } let input_string s = Bytes.unsafe_of_string is safe here as input_bytes does not mutate the byte sequence mutate the byte sequence *) input_bytes (Bytes.unsafe_of_string s) let output_buffer close = let b = Buffer.create 0 in { out_write = (fun c -> Buffer.add_char b c); out_output = (fun s p l -> Buffer.add_subbytes b s p l; l); out_close = (fun () -> close b); out_flush = (fun () -> ()); } let output_string () = output_buffer Buffer.contents let output_bytes () = output_buffer Buffer.to_bytes let output_strings() = let sl = ref [] in let size = ref 0 in let b = Buffer.create 0 in { out_write = (fun c -> if !size = Sys.max_string_length then begin sl := Buffer.contents b :: !sl; Buffer.clear b; size := 0; end else incr size; Buffer.add_char b c ); out_output = (fun s p l -> if !size + l > Sys.max_string_length then begin sl := Buffer.contents b :: !sl; Buffer.clear b; size := 0; end else size := !size + l; Buffer.add_subbytes b s p l; l ); out_close = (fun () -> sl := Buffer.contents b :: !sl; List.rev (!sl)); out_flush = (fun () -> ()); } let input_channel ch = { in_read = (fun () -> try input_char ch with End_of_file -> raise No_more_input ); in_input = (fun s p l -> let n = Pervasives.input ch s p l in if n = 0 then raise No_more_input; n ); in_close = (fun () -> Pervasives.close_in ch); } let output_channel ch = { out_write = (fun c -> output_char ch c); out_output = (fun s p l -> Pervasives.output ch s p l; l); out_close = (fun () -> Pervasives.close_out ch); out_flush = (fun () -> Pervasives.flush ch); } let pipe() = let input = ref "" in let inpos = ref 0 in let output = Buffer.create 0 in let flush() = input := Buffer.contents output; inpos := 0; Buffer.reset output; if String.length !input = 0 then raise No_more_input in let read() = if !inpos = String.length !input then flush(); let c = String.unsafe_get !input !inpos in incr inpos; c in let input s p l = if !inpos = String.length !input then flush(); let r = (if !inpos + l > String.length !input then String.length !input - !inpos else l) in String.unsafe_blit !input !inpos s p r; inpos := !inpos + r; r in let write c = Buffer.add_char output c in let output s p l = Buffer.add_subbytes output s p l; l in let input = { in_read = read; in_input = input; in_close = (fun () -> ()); } in let output = { out_write = write; out_output = output; out_close = (fun () -> ()); out_flush = (fun () -> ()); } in input , output external cast_output : 'a output -> unit output = "%identity" (* -------------------------------------------------------------- *) (* BINARY APIs *) exception Overflow of string let read_byte i = int_of_char (i.in_read()) let read_signed_byte i = let c = int_of_char (i.in_read()) in if c land 128 <> 0 then c - 256 else c let read_string_into_buffer i = let b = Buffer.create 8 in let rec loop() = let c = i.in_read() in if c <> '\000' then begin Buffer.add_char b c; loop(); end; in loop(); b (* pad: added the c_ prefix *) let read_c_string i = Buffer.contents (read_string_into_buffer i) let read_c_bytes i = Buffer.to_bytes (read_string_into_buffer i) let read_line i = let b = Buffer.create 8 in let cr = ref false in let rec loop() = let c = i.in_read() in match c with | '\n' -> () | '\r' -> cr := true; loop() | _ when !cr -> cr := false; Buffer.add_char b '\r'; Buffer.add_char b c; loop(); | _ -> Buffer.add_char b c; loop(); in try loop(); Buffer.contents b with No_more_input -> if !cr then Buffer.add_char b '\r'; if Buffer.length b > 0 then Buffer.contents b else raise No_more_input let write_byte o n = does n't test bounds of n in order to keep semantics of Pervasives.output_byte write o (Char.unsafe_chr (n land 0xFF)) let write_c_string o s = nwrite_string o s; write o '\000' let write_c_bytes o s = nwrite o s; write o '\000' let write_line o s = nwrite_string o s; write o '\n' module LittleEndian = struct pad : Little Endian ( least significant byte first ) let read_ui16 i = let ch1 = read_byte i in let ch2 = read_byte i in ch1 lor (ch2 lsl 8) let read_i16 i = let ch1 = read_byte i in let ch2 = read_byte i in let n = ch1 lor (ch2 lsl 8) in if ch2 land 128 <> 0 then n - 65536 else n let read_i32 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let ch4 = read_byte ch in if ch4 land 128 <> 0 then begin if ch4 land 64 = 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor ((ch4 land 127) lsl 24) end else begin if ch4 land 64 <> 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor (ch4 lsl 24) end let read_real_i32 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let base = Int32.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let big = Int32.shift_left (Int32.of_int (read_byte ch)) 24 in Int32.logor base big let read_i64 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let ch4 = read_byte ch in let base = Int64.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let small = Int64.logor base (Int64.shift_left (Int64.of_int ch4) 24) in let big = Int64.of_int32 (read_real_i32 ch) in Int64.logor (Int64.shift_left big 32) small let read_float32 ch = Int32.float_of_bits (read_real_i32 ch) let read_double ch = Int64.float_of_bits (read_i64 ch) let write_ui16 ch n = if n < 0 || n > 0xFFFF then raise (Overflow "write_ui16"); write_byte ch n; write_byte ch (n lsr 8) let write_i16 ch n = if n < -0x8000 || n > 0x7FFF then raise (Overflow "write_i16"); if n < 0 then write_ui16 ch (65536 + n) else write_ui16 ch n let write_i32 ch n = write_byte ch n; write_byte ch (n lsr 8); write_byte ch (n lsr 16); write_byte ch (n asr 24) let write_real_i32 ch n = let base = Int32.to_int n in let big = Int32.to_int (Int32.shift_right_logical n 24) in write_byte ch base; write_byte ch (base lsr 8); write_byte ch (base lsr 16); write_byte ch big let write_i64 ch n = write_real_i32 ch (Int64.to_int32 n); write_real_i32 ch (Int64.to_int32 (Int64.shift_right_logical n 32)) let write_float32 ch f = write_real_i32 ch (Int32.bits_of_float f) let write_double ch f = write_i64 ch (Int64.bits_of_float f) end (* -------------------------------------------------------------- *) Big Endians module BigEndian = struct let read_ui16 i = let ch2 = read_byte i in let ch1 = read_byte i in ch1 lor (ch2 lsl 8) let read_i16 i = let ch2 = read_byte i in let ch1 = read_byte i in let n = ch1 lor (ch2 lsl 8) in if ch2 land 128 <> 0 then n - 65536 else n let read_i32 ch = let ch4 = read_byte ch in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in if ch4 land 128 <> 0 then begin if ch4 land 64 = 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor ((ch4 land 127) lsl 24) end else begin if ch4 land 64 <> 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor (ch4 lsl 24) end let read_real_i32 ch = let big = Int32.shift_left (Int32.of_int (read_byte ch)) 24 in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in let base = Int32.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in Int32.logor base big let read_i64 ch = let big = Int64.of_int32 (read_real_i32 ch) in let ch4 = read_byte ch in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in let base = Int64.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let small = Int64.logor base (Int64.shift_left (Int64.of_int ch4) 24) in Int64.logor (Int64.shift_left big 32) small let read_float32 ch = Int32.float_of_bits (read_real_i32 ch) let read_double ch = Int64.float_of_bits (read_i64 ch) let write_ui16 ch n = if n < 0 || n > 0xFFFF then raise (Overflow "write_ui16"); write_byte ch (n lsr 8); write_byte ch n let write_i16 ch n = if n < -0x8000 || n > 0x7FFF then raise (Overflow "write_i16"); if n < 0 then write_ui16 ch (65536 + n) else write_ui16 ch n let write_i32 ch n = write_byte ch (n asr 24); write_byte ch (n lsr 16); write_byte ch (n lsr 8); write_byte ch n let write_real_i32 ch n = let base = Int32.to_int n in let big = Int32.to_int (Int32.shift_right_logical n 24) in write_byte ch big; write_byte ch (base lsr 16); write_byte ch (base lsr 8); write_byte ch base let write_i64 ch n = write_real_i32 ch (Int64.to_int32 (Int64.shift_right_logical n 32)); write_real_i32 ch (Int64.to_int32 n) let write_float32 ch f = write_real_i32 ch (Int32.bits_of_float f) let write_double ch f = write_i64 ch (Int64.bits_of_float f) end (* -------------------------------------------------------------- *) (* Bits API *) type 'a bc = { ch : 'a; mutable nbits : int; mutable bits : int; } type in_bits = input bc type out_bits = unit output bc exception Bits_error let input_bits ch = { ch = ch; nbits = 0; bits = 0; } let output_bits ch = { ch = cast_output ch; nbits = 0; bits = 0; } let rec read_bits b n = if b.nbits >= n then begin let c = b.nbits - n in let k = (b.bits asr c) land ((1 lsl n) - 1) in b.nbits <- c; k end else begin let k = read_byte b.ch in if b.nbits >= 24 then begin if n >= 31 then raise Bits_error; let c = 8 + b.nbits - n in let d = b.bits land ((1 lsl b.nbits) - 1) in let d = (d lsl (8 - c)) lor (k lsr c) in b.bits <- k; b.nbits <- c; d end else begin b.bits <- (b.bits lsl 8) lor k; b.nbits <- b.nbits + 8; read_bits b n; end end let drop_bits b = b.nbits <- 0 let rec write_bits b ~nbits x = let n = nbits in if n + b.nbits >= 32 then begin if n > 31 then raise Bits_error; let n2 = 32 - b.nbits - 1 in let n3 = n - n2 in write_bits b ~nbits:n2 (x asr n3); write_bits b ~nbits:n3 (x land ((1 lsl n3) - 1)); end else begin if n < 0 then raise Bits_error; if (x < 0 || x > (1 lsl n - 1)) && n <> 31 then raise Bits_error; b.bits <- (b.bits lsl n) lor x; b.nbits <- b.nbits + n; while b.nbits >= 8 do b.nbits <- b.nbits - 8; write_byte b.ch (b.bits asr b.nbits) done end let flush_bits b = if b.nbits > 0 then write_bits b (8 - b.nbits) 0
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/lib_core/commons/IO.ml
ocaml
*************************************************************************** Prelude *************************************************************************** *************************************************************************** Types *************************************************************************** start of copy-pasted code from extLib/IO.ml * pos * len -------------------------------------------------------------- API pad: could use intermediate struct instead of keyword arguments [really_nread] transfers ownership of the returned string, so [unsafe_to_string] is safe here [nwrite] does not mutate or capture its [bytes] input, so using [Bytes.unsafe_of_string] is safe here -------------------------------------------------------------- Standard IO -------------------------------------------------------------- BINARY APIs pad: added the c_ prefix -------------------------------------------------------------- -------------------------------------------------------------- Bits API
* Copyright ( C ) 2003 * * This library is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation ; either * version 2.1 of the License , or ( at your option ) any later version , * with the special exception on linking described in file LICENSE . * * This library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this library ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * Copyright (C) 2003 Nicolas Cannasse * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version, * with the special exception on linking described in file LICENSE. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *) Generalized Input / functions . * * Most of the code below comes from : * -extlib/blob/master/src/IO.ml * * alternatives : * - in_channel / out_channel in pervasives.ml * no function for little / big - endian binary IO . We could add those functions , * but still there is no inchannel_of_string ( ) or outchannel_of_buffer ( ) * so not general enough . * - batIO.ml from batteries - included ( comes from extLib 's ) * complexified * - mstruct / cstruct * good when have .h declarations of struct , * but more complex than IO.ml . Bytes and Buffer with small wrappers * around ( e.g. , ) for little / big endian stuff is good enough . * Still / cstruct allows to compute the length , offset , or * to backtrack ( shift ) . Some of those features can be implemented * with IO.ml thx to IO.pos_in but not all of them . * - scanf / printf ? good for binary IO ? * - bitstring ( was called bitmatch ) * Erlang style binary IO . Very declarative , very powerful , but * requires or ppx . * * Most of the code below comes from: * -extlib/blob/master/src/IO.ml * * alternatives: * - in_channel/out_channel in pervasives.ml * no function for little/big-endian binary IO. We could add those functions, * but still there is no inchannel_of_string() or outchannel_of_buffer() * so not general enough. * - batIO.ml from batteries-included (comes from extLib's IO.ml) * complexified * - mstruct/cstruct * good when have .h declarations of struct, * but more complex than IO.ml. Bytes and Buffer with small wrappers * around (e.g., IO.ml) for little/big endian stuff is good enough. * Still mstruct/cstruct allows to compute the length, offset, or * to backtrack (shift). Some of those features can be implemented * with IO.ml thx to IO.pos_in but not all of them. * - scanf/printf? good for binary IO? * - bitstring (was called bitmatch) * Erlang style binary IO. Very declarative, very powerful, but * requires camlp4 or ppx. *) type input = { mutable in_read : unit -> char; mutable in_close : unit -> unit; } type 'a output = { mutable out_write : char -> unit; mutable out_output : bytes -> int -> int -> int; mutable out_close : unit -> 'a; mutable out_flush : unit -> unit; } exception No_more_input exception Input_closed exception Output_closed let default_close = (fun () -> ()) let create_in ~read ~input ~close = { in_read = read; in_input = input; in_close = close; } let create_out ~write ~output ~flush ~close = { out_write = write; out_output = output; out_close = close; out_flush = flush; } let read i = i.in_read() let nread i n = if n < 0 then invalid_arg "IO.nread"; if n = 0 then Bytes.empty else let s = Bytes.create n in let l = ref n in let p = ref 0 in try while !l > 0 do let r = i.in_input s !p !l in if r = 0 then raise No_more_input; p := !p + r; l := !l - r; done; s with No_more_input as e -> if !p = 0 then raise e; Bytes.sub s 0 !p let nread_string i n = [ nread ] transfers ownership of the returned string , so [ unsafe_to_string ] is safe here [unsafe_to_string] is safe here *) Bytes.unsafe_to_string (nread i n) let really_output o s p l' = let sl = Bytes.length s in if p + l' > sl || p < 0 || l' < 0 then invalid_arg "IO.really_output"; let l = ref l' in let p = ref p in while !l > 0 do let w = o.out_output s !p !l in if w = 0 then raise Sys_blocked_io; p := !p + w; l := !l - w; done; l' let input i s p l = let sl = Bytes.length s in if p + l > sl || p < 0 || l < 0 then invalid_arg "IO.input"; if l = 0 then 0 else i.in_input s p l let really_input i s p l' = let sl = Bytes.length s in if p + l' > sl || p < 0 || l' < 0 then invalid_arg "IO.really_input"; let l = ref l' in let p = ref p in while !l > 0 do let r = i.in_input s !p !l in if r = 0 then raise Sys_blocked_io; p := !p + r; l := !l - r; done; l' let really_nread i n = if n < 0 then invalid_arg "IO.really_nread"; if n = 0 then Bytes.empty else let s = Bytes.create n in ignore(really_input i s 0 n); s let really_nread_string i n = Bytes.unsafe_to_string (really_nread i n) let close_in i = let f _ = raise Input_closed in i.in_close(); i.in_read <- f; i.in_input <- f; i.in_close <- f let write o x = o.out_write x let nwrite o s = let p = ref 0 in let l = ref (Bytes.length s) in while !l > 0 do let w = o.out_output s !p !l in if w = 0 then raise Sys_blocked_io; p := !p + w; l := !l - w; done let nwrite_string o s = nwrite o (Bytes.unsafe_of_string s) let output o s p l = let sl = Bytes.length s in if p + l > sl || p < 0 || l < 0 then invalid_arg "IO.output"; o.out_output s p l let scanf i fmt = let ib = Scanf.Scanning.from_function (fun () -> try read i with No_more_input -> raise End_of_file) in Scanf.kscanf ib (fun _ exn -> raise exn) fmt let printf o fmt = Printf.kprintf (fun s -> nwrite_string o s) fmt let flush o = o.out_flush() let close_out o = let f _ = raise Output_closed in let r = o.out_close() in o.out_write <- f; o.out_output <- f; o.out_close <- f; o.out_flush <- f; r let read_all i = let maxlen = 1024 in let str = ref [] in let pos = ref 0 in let rec loop() = let s = nread i maxlen in str := (s,!pos) :: !str; pos := !pos + Bytes.length s; loop() in try loop() with No_more_input -> let buf = Bytes.create !pos in List.iter (fun (s,p) -> Bytes.blit s 0 buf p (Bytes.length s) ) !str; ' buf ' does n't escape , it wo n't be mutated again Bytes.unsafe_to_string buf let pos_in i = let p = ref 0 in { in_read = (fun () -> let c = i.in_read() in incr p; c ); in_input = (fun s sp l -> let n = i.in_input s sp l in p := !p + n; n ); in_close = i.in_close } , (fun () -> !p) let pos_out o = let p = ref 0 in { out_write = (fun c -> o.out_write c; incr p ); out_output = (fun s sp l -> let n = o.out_output s sp l in p := !p + n; n ); out_close = o.out_close; out_flush = o.out_flush; } , (fun () -> !p) let input_bytes s = let pos = ref 0 in let len = Bytes.length s in { in_read = (fun () -> if !pos >= len then raise No_more_input; let c = Bytes.unsafe_get s !pos in incr pos; c ); in_input = (fun sout p l -> if !pos >= len then raise No_more_input; let n = (if !pos + l > len then len - !pos else l) in Bytes.unsafe_blit s !pos sout p n; pos := !pos + n; n ); in_close = (fun () -> ()); } let input_string s = Bytes.unsafe_of_string is safe here as input_bytes does not mutate the byte sequence mutate the byte sequence *) input_bytes (Bytes.unsafe_of_string s) let output_buffer close = let b = Buffer.create 0 in { out_write = (fun c -> Buffer.add_char b c); out_output = (fun s p l -> Buffer.add_subbytes b s p l; l); out_close = (fun () -> close b); out_flush = (fun () -> ()); } let output_string () = output_buffer Buffer.contents let output_bytes () = output_buffer Buffer.to_bytes let output_strings() = let sl = ref [] in let size = ref 0 in let b = Buffer.create 0 in { out_write = (fun c -> if !size = Sys.max_string_length then begin sl := Buffer.contents b :: !sl; Buffer.clear b; size := 0; end else incr size; Buffer.add_char b c ); out_output = (fun s p l -> if !size + l > Sys.max_string_length then begin sl := Buffer.contents b :: !sl; Buffer.clear b; size := 0; end else size := !size + l; Buffer.add_subbytes b s p l; l ); out_close = (fun () -> sl := Buffer.contents b :: !sl; List.rev (!sl)); out_flush = (fun () -> ()); } let input_channel ch = { in_read = (fun () -> try input_char ch with End_of_file -> raise No_more_input ); in_input = (fun s p l -> let n = Pervasives.input ch s p l in if n = 0 then raise No_more_input; n ); in_close = (fun () -> Pervasives.close_in ch); } let output_channel ch = { out_write = (fun c -> output_char ch c); out_output = (fun s p l -> Pervasives.output ch s p l; l); out_close = (fun () -> Pervasives.close_out ch); out_flush = (fun () -> Pervasives.flush ch); } let pipe() = let input = ref "" in let inpos = ref 0 in let output = Buffer.create 0 in let flush() = input := Buffer.contents output; inpos := 0; Buffer.reset output; if String.length !input = 0 then raise No_more_input in let read() = if !inpos = String.length !input then flush(); let c = String.unsafe_get !input !inpos in incr inpos; c in let input s p l = if !inpos = String.length !input then flush(); let r = (if !inpos + l > String.length !input then String.length !input - !inpos else l) in String.unsafe_blit !input !inpos s p r; inpos := !inpos + r; r in let write c = Buffer.add_char output c in let output s p l = Buffer.add_subbytes output s p l; l in let input = { in_read = read; in_input = input; in_close = (fun () -> ()); } in let output = { out_write = write; out_output = output; out_close = (fun () -> ()); out_flush = (fun () -> ()); } in input , output external cast_output : 'a output -> unit output = "%identity" exception Overflow of string let read_byte i = int_of_char (i.in_read()) let read_signed_byte i = let c = int_of_char (i.in_read()) in if c land 128 <> 0 then c - 256 else c let read_string_into_buffer i = let b = Buffer.create 8 in let rec loop() = let c = i.in_read() in if c <> '\000' then begin Buffer.add_char b c; loop(); end; in loop(); b let read_c_string i = Buffer.contents (read_string_into_buffer i) let read_c_bytes i = Buffer.to_bytes (read_string_into_buffer i) let read_line i = let b = Buffer.create 8 in let cr = ref false in let rec loop() = let c = i.in_read() in match c with | '\n' -> () | '\r' -> cr := true; loop() | _ when !cr -> cr := false; Buffer.add_char b '\r'; Buffer.add_char b c; loop(); | _ -> Buffer.add_char b c; loop(); in try loop(); Buffer.contents b with No_more_input -> if !cr then Buffer.add_char b '\r'; if Buffer.length b > 0 then Buffer.contents b else raise No_more_input let write_byte o n = does n't test bounds of n in order to keep semantics of Pervasives.output_byte write o (Char.unsafe_chr (n land 0xFF)) let write_c_string o s = nwrite_string o s; write o '\000' let write_c_bytes o s = nwrite o s; write o '\000' let write_line o s = nwrite_string o s; write o '\n' module LittleEndian = struct pad : Little Endian ( least significant byte first ) let read_ui16 i = let ch1 = read_byte i in let ch2 = read_byte i in ch1 lor (ch2 lsl 8) let read_i16 i = let ch1 = read_byte i in let ch2 = read_byte i in let n = ch1 lor (ch2 lsl 8) in if ch2 land 128 <> 0 then n - 65536 else n let read_i32 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let ch4 = read_byte ch in if ch4 land 128 <> 0 then begin if ch4 land 64 = 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor ((ch4 land 127) lsl 24) end else begin if ch4 land 64 <> 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor (ch4 lsl 24) end let read_real_i32 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let base = Int32.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let big = Int32.shift_left (Int32.of_int (read_byte ch)) 24 in Int32.logor base big let read_i64 ch = let ch1 = read_byte ch in let ch2 = read_byte ch in let ch3 = read_byte ch in let ch4 = read_byte ch in let base = Int64.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let small = Int64.logor base (Int64.shift_left (Int64.of_int ch4) 24) in let big = Int64.of_int32 (read_real_i32 ch) in Int64.logor (Int64.shift_left big 32) small let read_float32 ch = Int32.float_of_bits (read_real_i32 ch) let read_double ch = Int64.float_of_bits (read_i64 ch) let write_ui16 ch n = if n < 0 || n > 0xFFFF then raise (Overflow "write_ui16"); write_byte ch n; write_byte ch (n lsr 8) let write_i16 ch n = if n < -0x8000 || n > 0x7FFF then raise (Overflow "write_i16"); if n < 0 then write_ui16 ch (65536 + n) else write_ui16 ch n let write_i32 ch n = write_byte ch n; write_byte ch (n lsr 8); write_byte ch (n lsr 16); write_byte ch (n asr 24) let write_real_i32 ch n = let base = Int32.to_int n in let big = Int32.to_int (Int32.shift_right_logical n 24) in write_byte ch base; write_byte ch (base lsr 8); write_byte ch (base lsr 16); write_byte ch big let write_i64 ch n = write_real_i32 ch (Int64.to_int32 n); write_real_i32 ch (Int64.to_int32 (Int64.shift_right_logical n 32)) let write_float32 ch f = write_real_i32 ch (Int32.bits_of_float f) let write_double ch f = write_i64 ch (Int64.bits_of_float f) end Big Endians module BigEndian = struct let read_ui16 i = let ch2 = read_byte i in let ch1 = read_byte i in ch1 lor (ch2 lsl 8) let read_i16 i = let ch2 = read_byte i in let ch1 = read_byte i in let n = ch1 lor (ch2 lsl 8) in if ch2 land 128 <> 0 then n - 65536 else n let read_i32 ch = let ch4 = read_byte ch in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in if ch4 land 128 <> 0 then begin if ch4 land 64 = 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor ((ch4 land 127) lsl 24) end else begin if ch4 land 64 <> 0 then raise (Overflow "read_i32"); ch1 lor (ch2 lsl 8) lor (ch3 lsl 16) lor (ch4 lsl 24) end let read_real_i32 ch = let big = Int32.shift_left (Int32.of_int (read_byte ch)) 24 in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in let base = Int32.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in Int32.logor base big let read_i64 ch = let big = Int64.of_int32 (read_real_i32 ch) in let ch4 = read_byte ch in let ch3 = read_byte ch in let ch2 = read_byte ch in let ch1 = read_byte ch in let base = Int64.of_int (ch1 lor (ch2 lsl 8) lor (ch3 lsl 16)) in let small = Int64.logor base (Int64.shift_left (Int64.of_int ch4) 24) in Int64.logor (Int64.shift_left big 32) small let read_float32 ch = Int32.float_of_bits (read_real_i32 ch) let read_double ch = Int64.float_of_bits (read_i64 ch) let write_ui16 ch n = if n < 0 || n > 0xFFFF then raise (Overflow "write_ui16"); write_byte ch (n lsr 8); write_byte ch n let write_i16 ch n = if n < -0x8000 || n > 0x7FFF then raise (Overflow "write_i16"); if n < 0 then write_ui16 ch (65536 + n) else write_ui16 ch n let write_i32 ch n = write_byte ch (n asr 24); write_byte ch (n lsr 16); write_byte ch (n lsr 8); write_byte ch n let write_real_i32 ch n = let base = Int32.to_int n in let big = Int32.to_int (Int32.shift_right_logical n 24) in write_byte ch big; write_byte ch (base lsr 16); write_byte ch (base lsr 8); write_byte ch base let write_i64 ch n = write_real_i32 ch (Int64.to_int32 (Int64.shift_right_logical n 32)); write_real_i32 ch (Int64.to_int32 n) let write_float32 ch f = write_real_i32 ch (Int32.bits_of_float f) let write_double ch f = write_i64 ch (Int64.bits_of_float f) end type 'a bc = { ch : 'a; mutable nbits : int; mutable bits : int; } type in_bits = input bc type out_bits = unit output bc exception Bits_error let input_bits ch = { ch = ch; nbits = 0; bits = 0; } let output_bits ch = { ch = cast_output ch; nbits = 0; bits = 0; } let rec read_bits b n = if b.nbits >= n then begin let c = b.nbits - n in let k = (b.bits asr c) land ((1 lsl n) - 1) in b.nbits <- c; k end else begin let k = read_byte b.ch in if b.nbits >= 24 then begin if n >= 31 then raise Bits_error; let c = 8 + b.nbits - n in let d = b.bits land ((1 lsl b.nbits) - 1) in let d = (d lsl (8 - c)) lor (k lsr c) in b.bits <- k; b.nbits <- c; d end else begin b.bits <- (b.bits lsl 8) lor k; b.nbits <- b.nbits + 8; read_bits b n; end end let drop_bits b = b.nbits <- 0 let rec write_bits b ~nbits x = let n = nbits in if n + b.nbits >= 32 then begin if n > 31 then raise Bits_error; let n2 = 32 - b.nbits - 1 in let n3 = n - n2 in write_bits b ~nbits:n2 (x asr n3); write_bits b ~nbits:n3 (x land ((1 lsl n3) - 1)); end else begin if n < 0 then raise Bits_error; if (x < 0 || x > (1 lsl n - 1)) && n <> 31 then raise Bits_error; b.bits <- (b.bits lsl n) lor x; b.nbits <- b.nbits + n; while b.nbits >= 8 do b.nbits <- b.nbits - 8; write_byte b.ch (b.bits asr b.nbits) done end let flush_bits b = if b.nbits > 0 then write_bits b (8 - b.nbits) 0
3fe2553e593a6482214388795521be3a7c74093ae0dd6ca5fa34fbef4b80ebea
haskell-works/hw-prim
ByteString.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE FlexibleInstances # {-# LANGUAGE MultiWayIf #-} # LANGUAGE ScopedTypeVariables # module HaskellWorks.Data.ByteString ( chunkedBy , ToByteString(..) , ToByteStrings(..) , mmap , padded , rechunk , rechunkPadded , resegment , resegmentPadded , hGetContentsChunkedBy ) where import Control.Monad.ST import Data.Word import Foreign.ForeignPtr import qualified Control.Monad.ST.Unsafe as ST import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.Internal as LBSI import qualified Data.Vector.Storable as DVS import qualified Data.Vector.Storable.Mutable as DVSM import qualified System.IO as IO import qualified System.IO.MMap as IO import qualified System.IO.Unsafe as IO class ToByteString a where toByteString :: a -> BS.ByteString instance ToByteString BS.ByteString where toByteString = id # INLINE toByteString # instance ToByteString (DVS.Vector Word8) where toByteString v = case DVS.unsafeToForeignPtr v of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word16) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word32) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word64) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString [Word64] where toByteString = toByteString . DVS.fromList # INLINE toByteString # class ToByteStrings a where toByteStrings :: a -> [BS.ByteString] instance ToByteStrings [BS.ByteString] where toByteStrings = id # INLINE toByteStrings # instance ToByteStrings LBS.ByteString where toByteStrings = LBS.toChunks # INLINE toByteStrings # instance ToByteStrings BS.ByteString where toByteStrings = (:[]) # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word8) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word16) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word32) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word64) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings [Word64] where toByteStrings ws = toByteString <$> go ws where go :: [Word64] -> [DVS.Vector Word64] go us = DVS.createT (goST us) goST :: [Word64] -> ST s [DVSM.MVector s Word64] goST us = do mv <- DVSM.new defaultChunkSize (i, ts) <- writeWords 0 defaultChunkSize us mv mvs <- ST.unsafeInterleaveST (goST ts) if null ts then return [DVSM.take i mv] else return (DVSM.take i mv:mvs) writeWords :: Int -> Int -> [Word64] -> DVSM.MVector s Word64 -> ST s (Int, [Word64]) writeWords i n us mv = if i < n then case us of t:ts -> do DVSM.write mv i t writeWords (i + 1) n ts mv [] -> return (i, us) else return (i, us) defaultChunkSize = (LBSI.defaultChunkSize `div` 64) * 8 # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word8] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word16] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word32] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word64] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # -- | Chunk a @bs into list of smaller byte strings of no more than @n elements chunkedBy :: Int -> BS.ByteString -> [BS.ByteString] chunkedBy n bs = if BS.length bs == 0 then [] else case BS.splitAt n bs of (as, zs) -> as : chunkedBy n zs # INLINE chunkedBy # rechunk :: Int -> [BS.ByteString] -> [BS.ByteString] rechunk size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs] else if size == bsLen then bs:go bss else BS.take size bs:go (BS.drop size bs:bss) else go bss go [] = [] rechunkPadded :: Int -> [BS.ByteString] -> [BS.ByteString] rechunkPadded size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs <> BS.replicate bsNeed 0] else if size == bsLen then bs:go bss else BS.take size bs:go (BS.drop size bs:bss) else go bss go [] = [] resegment :: Int -> [BS.ByteString] -> [BS.ByteString] resegment size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then case bss of (cs:css) -> let bsNeed = size - bsLen; csLen = BS.length cs in if | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) | csLen == bsNeed -> (bs <> cs ):go css | otherwise -> go ((bs <> cs) :css) [] -> [bs] else let bsCroppedLen = (bsLen `div` size) * size in if bsCroppedLen == bsLen then bs:go bss else BS.take bsCroppedLen bs:go (BS.drop bsCroppedLen bs:bss) else go bss go [] = [] resegmentPadded :: Int -> [BS.ByteString] -> [BS.ByteString] resegmentPadded size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs <> BS.replicate bsNeed 0] else case (bsLen `div` size) * size of bsCroppedLen -> if bsCroppedLen == bsLen then bs:go bss else BS.take bsCroppedLen bs:go (BS.drop bsCroppedLen bs:bss) else go bss go [] = [] hGetContentsChunkedBy :: Int -> IO.Handle -> IO [BS.ByteString] hGetContentsChunkedBy k h = lazyRead where lazyRead = IO.unsafeInterleaveIO loop loop = do c <- BSI.createAndTrim k $ \p -> IO.hGetBuf h p k if BS.null c then IO.hClose h >> return [] else (c:) <$> lazyRead mmap :: FilePath -> IO BS.ByteString mmap filepath = do (fptr :: ForeignPtr Word8, offset, size) <- IO.mmapFileForeignPtr filepath IO.ReadOnly Nothing let !bs = BSI.fromForeignPtr (castForeignPtr fptr) offset size return bs padded :: Int -> BS.ByteString -> BS.ByteString padded n v = v <> BS.replicate ((n - BS.length v) `max` 0) 0 # INLINE padded #
null
https://raw.githubusercontent.com/haskell-works/hw-prim/aff74834cd2d3fb0eb4994b24b2d1cdef1e3e673/src/HaskellWorks/Data/ByteString.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE MultiWayIf # | Chunk a @bs into list of smaller byte strings of no more than @n elements
# LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # module HaskellWorks.Data.ByteString ( chunkedBy , ToByteString(..) , ToByteStrings(..) , mmap , padded , rechunk , rechunkPadded , resegment , resegmentPadded , hGetContentsChunkedBy ) where import Control.Monad.ST import Data.Word import Foreign.ForeignPtr import qualified Control.Monad.ST.Unsafe as ST import qualified Data.ByteString as BS import qualified Data.ByteString.Internal as BSI import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.Internal as LBSI import qualified Data.Vector.Storable as DVS import qualified Data.Vector.Storable.Mutable as DVSM import qualified System.IO as IO import qualified System.IO.MMap as IO import qualified System.IO.Unsafe as IO class ToByteString a where toByteString :: a -> BS.ByteString instance ToByteString BS.ByteString where toByteString = id # INLINE toByteString # instance ToByteString (DVS.Vector Word8) where toByteString v = case DVS.unsafeToForeignPtr v of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word16) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word32) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString (DVS.Vector Word64) where toByteString v = case DVS.unsafeToForeignPtr (DVS.unsafeCast v :: DVS.Vector Word8) of (fptr, start, offset) -> BSI.fromForeignPtr fptr start offset # INLINE toByteString # instance ToByteString [Word64] where toByteString = toByteString . DVS.fromList # INLINE toByteString # class ToByteStrings a where toByteStrings :: a -> [BS.ByteString] instance ToByteStrings [BS.ByteString] where toByteStrings = id # INLINE toByteStrings # instance ToByteStrings LBS.ByteString where toByteStrings = LBS.toChunks # INLINE toByteStrings # instance ToByteStrings BS.ByteString where toByteStrings = (:[]) # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word8) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word16) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word32) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings (DVS.Vector Word64) where toByteStrings = (:[]) . toByteString # INLINE toByteStrings # instance ToByteStrings [Word64] where toByteStrings ws = toByteString <$> go ws where go :: [Word64] -> [DVS.Vector Word64] go us = DVS.createT (goST us) goST :: [Word64] -> ST s [DVSM.MVector s Word64] goST us = do mv <- DVSM.new defaultChunkSize (i, ts) <- writeWords 0 defaultChunkSize us mv mvs <- ST.unsafeInterleaveST (goST ts) if null ts then return [DVSM.take i mv] else return (DVSM.take i mv:mvs) writeWords :: Int -> Int -> [Word64] -> DVSM.MVector s Word64 -> ST s (Int, [Word64]) writeWords i n us mv = if i < n then case us of t:ts -> do DVSM.write mv i t writeWords (i + 1) n ts mv [] -> return (i, us) else return (i, us) defaultChunkSize = (LBSI.defaultChunkSize `div` 64) * 8 # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word8] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word16] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word32] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # instance ToByteStrings [DVS.Vector Word64] where toByteStrings = (toByteString <$>) # INLINE toByteStrings # chunkedBy :: Int -> BS.ByteString -> [BS.ByteString] chunkedBy n bs = if BS.length bs == 0 then [] else case BS.splitAt n bs of (as, zs) -> as : chunkedBy n zs # INLINE chunkedBy # rechunk :: Int -> [BS.ByteString] -> [BS.ByteString] rechunk size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs] else if size == bsLen then bs:go bss else BS.take size bs:go (BS.drop size bs:bss) else go bss go [] = [] rechunkPadded :: Int -> [BS.ByteString] -> [BS.ByteString] rechunkPadded size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs <> BS.replicate bsNeed 0] else if size == bsLen then bs:go bss else BS.take size bs:go (BS.drop size bs:bss) else go bss go [] = [] resegment :: Int -> [BS.ByteString] -> [BS.ByteString] resegment size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then case bss of (cs:css) -> let bsNeed = size - bsLen; csLen = BS.length cs in if | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) | csLen == bsNeed -> (bs <> cs ):go css | otherwise -> go ((bs <> cs) :css) [] -> [bs] else let bsCroppedLen = (bsLen `div` size) * size in if bsCroppedLen == bsLen then bs:go bss else BS.take bsCroppedLen bs:go (BS.drop bsCroppedLen bs:bss) else go bss go [] = [] resegmentPadded :: Int -> [BS.ByteString] -> [BS.ByteString] resegmentPadded size = go where go (bs:bss) = let bsLen = BS.length bs in if bsLen > 0 then if bsLen < size then let bsNeed = size - bsLen in case bss of (cs:css) -> case BS.length cs of csLen | csLen > bsNeed -> (bs <> BS.take bsNeed cs ):go (BS.drop bsNeed cs:css) csLen | csLen == bsNeed -> (bs <> cs ):go css _ -> go ((bs <> cs) :css) [] -> [bs <> BS.replicate bsNeed 0] else case (bsLen `div` size) * size of bsCroppedLen -> if bsCroppedLen == bsLen then bs:go bss else BS.take bsCroppedLen bs:go (BS.drop bsCroppedLen bs:bss) else go bss go [] = [] hGetContentsChunkedBy :: Int -> IO.Handle -> IO [BS.ByteString] hGetContentsChunkedBy k h = lazyRead where lazyRead = IO.unsafeInterleaveIO loop loop = do c <- BSI.createAndTrim k $ \p -> IO.hGetBuf h p k if BS.null c then IO.hClose h >> return [] else (c:) <$> lazyRead mmap :: FilePath -> IO BS.ByteString mmap filepath = do (fptr :: ForeignPtr Word8, offset, size) <- IO.mmapFileForeignPtr filepath IO.ReadOnly Nothing let !bs = BSI.fromForeignPtr (castForeignPtr fptr) offset size return bs padded :: Int -> BS.ByteString -> BS.ByteString padded n v = v <> BS.replicate ((n - BS.length v) `max` 0) 0 # INLINE padded #
055bbebbad4c6c2a43f6a8745098d1fa7ff774544a3f12d5dca6255b75b91ee9
yoriyuki/Camomile
absCe.mli
(** Collaiton Element, abstracted *) Copyright ( C ) 2003 (* This library is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public License *) as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . As a special exception to the GNU Library General Public License , you (* may link, statically or dynamically, a "work that uses this library" *) (* with a publicly distributed version of this library to produce an *) (* executable file containing portions of this library, and distribute *) (* that executable file under terms of your choice, without any of the *) additional requirements listed in clause 6 of the GNU Library General (* Public License. By "a publicly distributed version of this library", *) we mean either the unmodified Library as distributed by the authors , (* or a modified version of this library that is distributed under the *) conditions defined in clause 3 of the GNU Library General Public (* License. This exception does not however invalidate any other reasons *) why the executable file might be covered by the GNU Library General (* Public License . *) (* This library is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* Lesser General Public License for more details. *) You should have received a copy of the GNU Lesser General Public (* License along with this library; if not, write to the Free Software *) Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA (* You can contact the authour by sending email to *) (* *) open CamomileLibrary type elt = [ `Seq of UChar.t list | `ImplicitWeight of int list | `CompleteIgnorable | `UCA_Weight of int | `LastVariable | `HiraganaQ | `FirstImplicit | `FirstTrailing ] type ce type ceset module EltMap : Map.S with type key = elt val ces_of : ceset -> UChar.t list -> ceset * ce list val complete_ignorable : ceset -> ce val last_variable : ceset -> ce val first_implicit : ceset -> ce val first_trailing : ceset -> ce val top : ceset -> ce val next : UCol.precision -> ce -> ceset -> ce val prev : UCol.precision -> ce -> ceset -> ce val add_after : UCol.precision -> ce -> ceset -> ce * ceset val add_before : UCol.precision -> ce -> ceset -> ce * ceset val put : elt -> ce list -> ceset -> ceset val import : int list EltMap.t * int list EltMap.t * int list EltMap.t -> ceset type ace_info = {ceset : ceset; variable_option : UCol.variable_option; french : bool; hiraganaQ : bool} val create_ace_info : ?variable_option:UCol.variable_option -> ?french:bool -> ?hiraganaQ:bool -> ceset -> ace_info val cetbl_of : ace_info -> Toolslib.Unidata.col_info type aceset_info = {lowercase_first_tbl : ceset; uppercase_first_tbl : ceset}
null
https://raw.githubusercontent.com/yoriyuki/Camomile/d7d8843c88fae774f513610f8e09a613778e64b3/Camomile/toolslib/absCe.mli
ocaml
* Collaiton Element, abstracted This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License may link, statically or dynamically, a "work that uses this library" with a publicly distributed version of this library to produce an executable file containing portions of this library, and distribute that executable file under terms of your choice, without any of the Public License. By "a publicly distributed version of this library", or a modified version of this library that is distributed under the License. This exception does not however invalidate any other reasons Public License . This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software You can contact the authour by sending email to
Copyright ( C ) 2003 as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . As a special exception to the GNU Library General Public License , you additional requirements listed in clause 6 of the GNU Library General we mean either the unmodified Library as distributed by the authors , conditions defined in clause 3 of the GNU Library General Public why the executable file might be covered by the GNU Library General You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA open CamomileLibrary type elt = [ `Seq of UChar.t list | `ImplicitWeight of int list | `CompleteIgnorable | `UCA_Weight of int | `LastVariable | `HiraganaQ | `FirstImplicit | `FirstTrailing ] type ce type ceset module EltMap : Map.S with type key = elt val ces_of : ceset -> UChar.t list -> ceset * ce list val complete_ignorable : ceset -> ce val last_variable : ceset -> ce val first_implicit : ceset -> ce val first_trailing : ceset -> ce val top : ceset -> ce val next : UCol.precision -> ce -> ceset -> ce val prev : UCol.precision -> ce -> ceset -> ce val add_after : UCol.precision -> ce -> ceset -> ce * ceset val add_before : UCol.precision -> ce -> ceset -> ce * ceset val put : elt -> ce list -> ceset -> ceset val import : int list EltMap.t * int list EltMap.t * int list EltMap.t -> ceset type ace_info = {ceset : ceset; variable_option : UCol.variable_option; french : bool; hiraganaQ : bool} val create_ace_info : ?variable_option:UCol.variable_option -> ?french:bool -> ?hiraganaQ:bool -> ceset -> ace_info val cetbl_of : ace_info -> Toolslib.Unidata.col_info type aceset_info = {lowercase_first_tbl : ceset; uppercase_first_tbl : ceset}
28774ce4f0dff32b407886fef48922603616b2c3995b80481e5bc0f5f09f6169
aeternity/aesophia
aeso_vm_decode.erl
%%%------------------------------------------------------------------- ( C ) 2017 , Aeternity Anstalt %%% @doc Decoding fate data to AST %%% @end %%%------------------------------------------------------------------- -module(aeso_vm_decode). -export([ from_fate/2 ]). -include_lib("aebytecode/include/aeb_fate_data.hrl"). -spec from_fate(aeso_syntax:type(), aeb_fate_data:fate_type()) -> aeso_syntax:expr(). from_fate({id, _, "address"}, ?FATE_ADDRESS(Bin)) -> {account_pubkey, [], Bin}; from_fate({app_t, _, {id, _, "oracle"}, _}, ?FATE_ORACLE(Bin)) -> {oracle_pubkey, [], Bin}; from_fate({app_t, _, {id, _, "oracle_query"}, _}, ?FATE_ORACLE_Q(Bin)) -> {oracle_query_id, [], Bin}; from_fate({con, _, _Name}, ?FATE_CONTRACT(Bin)) -> {contract_pubkey, [], Bin}; from_fate({bytes_t, _, N}, ?FATE_BYTES(Bin)) when byte_size(Bin) == N -> {bytes, [], Bin}; from_fate({id, _, "bits"}, ?FATE_BITS(N)) -> make_bits(N); from_fate({id, _, "int"}, N) when is_integer(N) -> if N < 0 -> {app, [{format, prefix}], {'-', []}, [{int, [], -N}]}; true -> {int, [], N} end; from_fate({id, _, "bool"}, B) when is_boolean(B) -> {bool, [], B}; from_fate({id, _, "string"}, S) when is_binary(S) -> {string, [], S}; from_fate({app_t, _, {id, _, "list"}, [Type]}, List) when is_list(List) -> {list, [], [from_fate(Type, X) || X <- List]}; from_fate({app_t, _, {id, _, "option"}, [Type]}, Val) -> case Val of {variant, [0, 1], 0, {}} -> {con, [], "None"}; {variant, [0, 1], 1, {X}} -> {app, [], {con, [], "Some"}, [from_fate(Type, X)]} end; from_fate({tuple_t, _, []}, ?FATE_UNIT) -> {tuple, [], []}; from_fate({tuple_t, _, Types}, ?FATE_TUPLE(Val)) when length(Types) == tuple_size(Val) -> {tuple, [], [from_fate(Type, X) || {Type, X} <- lists:zip(Types, tuple_to_list(Val))]}; from_fate({record_t, [{field_t, _, FName, FType}]}, Val) -> {record, [], [{field, [], [{proj, [], FName}], from_fate(FType, Val)}]}; from_fate({record_t, Fields}, ?FATE_TUPLE(Val)) when length(Fields) == tuple_size(Val) -> {record, [], [ {field, [], [{proj, [], FName}], from_fate(FType, X)} || {{field_t, _, FName, FType}, X} <- lists:zip(Fields, tuple_to_list(Val)) ]}; from_fate({app_t, _, {id, _, "map"}, [KeyType, ValType]}, Map) when is_map(Map) -> {map, [], [ {from_fate(KeyType, Key), from_fate(ValType, Val)} || {Key, Val} <- maps:to_list(Map) ]}; from_fate({variant_t, Cons}, {variant, Ar, Tag, Args}) when length(Cons) > Tag -> ConType = lists:nth(Tag + 1, Cons), Arity = lists:nth(Tag + 1, Ar), case tuple_to_list(Args) of ArgList when length(ArgList) == Arity -> from_fate(ConType, ArgList); _ -> throw(cannot_translate_to_sophia) end; from_fate({constr_t, _, Con, []}, []) -> Con; from_fate({constr_t, _, Con, Types}, Args) when length(Types) == length(Args) -> {app, [], Con, [ from_fate(Type, Arg) || {Type, Arg} <- lists:zip(Types, Args) ]}; from_fate({qid, _, QType}, Val) -> from_fate_builtin(QType, Val); from_fate(_Type, _Data) -> throw(cannot_translate_to_sophia). from_fate_builtin(QType, Val) -> Con = fun([Name | _] = Names) when is_list(Name) -> {qcon, [], Names}; (Name) -> {con, [], Name} end, App = fun(Name, []) -> Con(Name); (Name, Value) -> {app, [], Con(Name), Value} end, Chk = fun(Type, Value) -> from_fate(Type, Value) end, Int = {id, [], "int"}, Str = {id, [], "string"}, Adr = {id, [], "address"}, Hsh = {bytes_t, [], 32}, I32 = {bytes_t, [], 32}, I48 = {bytes_t, [], 48}, Qid = fun(Name) -> {qid, [], Name} end, Map = fun(KT, VT) -> {app_t, [], {id, [], "map"}, [KT, VT]} end, ChainTxArities = [3, 0, 0, 0, 0, 0, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 0], case {QType, Val} of {["Chain", "ttl"], {variant, [1, 1], 0, {X}}} -> App("RelativeTTL", [Chk(Int, X)]); {["Chain", "ttl"], {variant, [1, 1], 1, {X}}} -> App("FixedTTL", [Chk(Int, X)]); {["AENS", "name"], {variant, [3], 0, {Addr, TTL, Ptrs}}} -> App(["AENS","Name"], [Chk(Adr, Addr), Chk(Qid(["Chain", "ttl"]), TTL), Chk(Map(Str, Qid(["AENS", "pointee"])), Ptrs)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 0, {Addr}}} -> App(["AENS","AccountPt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 1, {Addr}}} -> App(["AENS","OraclePt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 2, {Addr}}} -> App(["AENS","ContractPt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 3, {Addr}}} -> App(["AENS","ChannelPt"], [Chk(Adr, Addr)]); {["Chain", "ga_meta_tx"], {variant, [2], 0, {Addr, X}}} -> App(["Chain","GAMetaTx"], [Chk(Adr, Addr), Chk(Int, X)]); {["Chain", "paying_for_tx"], {variant, [2], 0, {Addr, X}}} -> App(["Chain","PayingForTx"], [Chk(Adr, Addr), Chk(Int, X)]); {["Chain", "base_tx"], {variant, ChainTxArities, 0, {Addr, Fee, Payload}}} -> App(["Chain","SpendTx"], [Chk(Adr, Addr), Chk(Int, Fee), Chk(Str, Payload)]); {["Chain", "base_tx"], {variant, ChainTxArities, 1, {}}} -> App(["Chain","OracleRegisterTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 2, {}}} -> App(["Chain","OracleQueryTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 3, {}}} -> App(["Chain","OracleResponseTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 4, {}}} -> App(["Chain","OracleExtendTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 5, {}}} -> App(["Chain","NamePreclaimTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 6, {Name}}} -> App(["Chain","NameClaimTx"], [Chk(Str, Name)]); {["Chain", "base_tx"], {variant, ChainTxArities, 7, {NameHash}}} -> App(["Chain","NameUpdateTx"], [Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 8, {NameHash}}} -> App(["Chain","NameRevokeTx"], [Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 9, {NewOwner, NameHash}}} -> App(["Chain","NameTransferTx"], [Chk(Adr, NewOwner), Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 10, {Addr}}} -> App(["Chain","ChannelCreateTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 11, {Addr, Amount}}} -> App(["Chain","ChannelDepositTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 12, {Addr, Amount}}} -> App(["Chain","ChannelWithdrawTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 13, {Addr}}} -> App(["Chain","ChannelForceProgressTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 14, {Addr}}} -> App(["Chain","ChannelCloseMutualTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 15, {Addr}}} -> App(["Chain","ChannelCloseSoloTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 16, {Addr}}} -> App(["Chain","ChannelSlashTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 17, {Addr}}} -> App(["Chain","ChannelSettleTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 18, {Addr}}} -> App(["Chain","ChannelSnapshotSoloTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 19, {Amount}}} -> App(["Chain","ContractCreateTx"], [Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 20, {Addr, Amount}}} -> App(["Chain","ContractCallTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 21, {}}} -> App(["Chain","GAAttachTx"], []); {["MCL_BLS12_381", "fp"], X} -> App(["MCL_BLS12_381", "fp"], [Chk(I32, X)]); {["MCL_BLS12_381", "fr"], X} -> App(["MCL_BLS12_381", "fr"], [Chk(I48, X)]); _ -> throw(cannot_translate_to_sophia) end. make_bits(N) -> Id = fun(F) -> {qid, [], ["Bits", F]} end, if N < 0 -> make_bits(Id("clear"), Id("all"), 0, bnot N); true -> make_bits(Id("set"), Id("none"), 0, N) end. make_bits(_Set, Zero, _I, 0) -> Zero; make_bits(Set, Zero, I, N) when 0 == N rem 2 -> make_bits(Set, Zero, I + 1, N div 2); make_bits(Set, Zero, I, N) -> {app, [], Set, [make_bits(Set, Zero, I + 1, N div 2), {int, [], I}]}.
null
https://raw.githubusercontent.com/aeternity/aesophia/a894876f56a818f6237259a7c48cbe6f4a4c01f8/src/aeso_vm_decode.erl
erlang
------------------------------------------------------------------- @doc Decoding fate data to AST @end -------------------------------------------------------------------
( C ) 2017 , Aeternity Anstalt -module(aeso_vm_decode). -export([ from_fate/2 ]). -include_lib("aebytecode/include/aeb_fate_data.hrl"). -spec from_fate(aeso_syntax:type(), aeb_fate_data:fate_type()) -> aeso_syntax:expr(). from_fate({id, _, "address"}, ?FATE_ADDRESS(Bin)) -> {account_pubkey, [], Bin}; from_fate({app_t, _, {id, _, "oracle"}, _}, ?FATE_ORACLE(Bin)) -> {oracle_pubkey, [], Bin}; from_fate({app_t, _, {id, _, "oracle_query"}, _}, ?FATE_ORACLE_Q(Bin)) -> {oracle_query_id, [], Bin}; from_fate({con, _, _Name}, ?FATE_CONTRACT(Bin)) -> {contract_pubkey, [], Bin}; from_fate({bytes_t, _, N}, ?FATE_BYTES(Bin)) when byte_size(Bin) == N -> {bytes, [], Bin}; from_fate({id, _, "bits"}, ?FATE_BITS(N)) -> make_bits(N); from_fate({id, _, "int"}, N) when is_integer(N) -> if N < 0 -> {app, [{format, prefix}], {'-', []}, [{int, [], -N}]}; true -> {int, [], N} end; from_fate({id, _, "bool"}, B) when is_boolean(B) -> {bool, [], B}; from_fate({id, _, "string"}, S) when is_binary(S) -> {string, [], S}; from_fate({app_t, _, {id, _, "list"}, [Type]}, List) when is_list(List) -> {list, [], [from_fate(Type, X) || X <- List]}; from_fate({app_t, _, {id, _, "option"}, [Type]}, Val) -> case Val of {variant, [0, 1], 0, {}} -> {con, [], "None"}; {variant, [0, 1], 1, {X}} -> {app, [], {con, [], "Some"}, [from_fate(Type, X)]} end; from_fate({tuple_t, _, []}, ?FATE_UNIT) -> {tuple, [], []}; from_fate({tuple_t, _, Types}, ?FATE_TUPLE(Val)) when length(Types) == tuple_size(Val) -> {tuple, [], [from_fate(Type, X) || {Type, X} <- lists:zip(Types, tuple_to_list(Val))]}; from_fate({record_t, [{field_t, _, FName, FType}]}, Val) -> {record, [], [{field, [], [{proj, [], FName}], from_fate(FType, Val)}]}; from_fate({record_t, Fields}, ?FATE_TUPLE(Val)) when length(Fields) == tuple_size(Val) -> {record, [], [ {field, [], [{proj, [], FName}], from_fate(FType, X)} || {{field_t, _, FName, FType}, X} <- lists:zip(Fields, tuple_to_list(Val)) ]}; from_fate({app_t, _, {id, _, "map"}, [KeyType, ValType]}, Map) when is_map(Map) -> {map, [], [ {from_fate(KeyType, Key), from_fate(ValType, Val)} || {Key, Val} <- maps:to_list(Map) ]}; from_fate({variant_t, Cons}, {variant, Ar, Tag, Args}) when length(Cons) > Tag -> ConType = lists:nth(Tag + 1, Cons), Arity = lists:nth(Tag + 1, Ar), case tuple_to_list(Args) of ArgList when length(ArgList) == Arity -> from_fate(ConType, ArgList); _ -> throw(cannot_translate_to_sophia) end; from_fate({constr_t, _, Con, []}, []) -> Con; from_fate({constr_t, _, Con, Types}, Args) when length(Types) == length(Args) -> {app, [], Con, [ from_fate(Type, Arg) || {Type, Arg} <- lists:zip(Types, Args) ]}; from_fate({qid, _, QType}, Val) -> from_fate_builtin(QType, Val); from_fate(_Type, _Data) -> throw(cannot_translate_to_sophia). from_fate_builtin(QType, Val) -> Con = fun([Name | _] = Names) when is_list(Name) -> {qcon, [], Names}; (Name) -> {con, [], Name} end, App = fun(Name, []) -> Con(Name); (Name, Value) -> {app, [], Con(Name), Value} end, Chk = fun(Type, Value) -> from_fate(Type, Value) end, Int = {id, [], "int"}, Str = {id, [], "string"}, Adr = {id, [], "address"}, Hsh = {bytes_t, [], 32}, I32 = {bytes_t, [], 32}, I48 = {bytes_t, [], 48}, Qid = fun(Name) -> {qid, [], Name} end, Map = fun(KT, VT) -> {app_t, [], {id, [], "map"}, [KT, VT]} end, ChainTxArities = [3, 0, 0, 0, 0, 0, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 0], case {QType, Val} of {["Chain", "ttl"], {variant, [1, 1], 0, {X}}} -> App("RelativeTTL", [Chk(Int, X)]); {["Chain", "ttl"], {variant, [1, 1], 1, {X}}} -> App("FixedTTL", [Chk(Int, X)]); {["AENS", "name"], {variant, [3], 0, {Addr, TTL, Ptrs}}} -> App(["AENS","Name"], [Chk(Adr, Addr), Chk(Qid(["Chain", "ttl"]), TTL), Chk(Map(Str, Qid(["AENS", "pointee"])), Ptrs)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 0, {Addr}}} -> App(["AENS","AccountPt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 1, {Addr}}} -> App(["AENS","OraclePt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 2, {Addr}}} -> App(["AENS","ContractPt"], [Chk(Adr, Addr)]); {["AENS", "pointee"], {variant, [1, 1, 1, 1], 3, {Addr}}} -> App(["AENS","ChannelPt"], [Chk(Adr, Addr)]); {["Chain", "ga_meta_tx"], {variant, [2], 0, {Addr, X}}} -> App(["Chain","GAMetaTx"], [Chk(Adr, Addr), Chk(Int, X)]); {["Chain", "paying_for_tx"], {variant, [2], 0, {Addr, X}}} -> App(["Chain","PayingForTx"], [Chk(Adr, Addr), Chk(Int, X)]); {["Chain", "base_tx"], {variant, ChainTxArities, 0, {Addr, Fee, Payload}}} -> App(["Chain","SpendTx"], [Chk(Adr, Addr), Chk(Int, Fee), Chk(Str, Payload)]); {["Chain", "base_tx"], {variant, ChainTxArities, 1, {}}} -> App(["Chain","OracleRegisterTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 2, {}}} -> App(["Chain","OracleQueryTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 3, {}}} -> App(["Chain","OracleResponseTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 4, {}}} -> App(["Chain","OracleExtendTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 5, {}}} -> App(["Chain","NamePreclaimTx"], []); {["Chain", "base_tx"], {variant, ChainTxArities, 6, {Name}}} -> App(["Chain","NameClaimTx"], [Chk(Str, Name)]); {["Chain", "base_tx"], {variant, ChainTxArities, 7, {NameHash}}} -> App(["Chain","NameUpdateTx"], [Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 8, {NameHash}}} -> App(["Chain","NameRevokeTx"], [Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 9, {NewOwner, NameHash}}} -> App(["Chain","NameTransferTx"], [Chk(Adr, NewOwner), Chk(Hsh, NameHash)]); {["Chain", "base_tx"], {variant, ChainTxArities, 10, {Addr}}} -> App(["Chain","ChannelCreateTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 11, {Addr, Amount}}} -> App(["Chain","ChannelDepositTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 12, {Addr, Amount}}} -> App(["Chain","ChannelWithdrawTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 13, {Addr}}} -> App(["Chain","ChannelForceProgressTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 14, {Addr}}} -> App(["Chain","ChannelCloseMutualTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 15, {Addr}}} -> App(["Chain","ChannelCloseSoloTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 16, {Addr}}} -> App(["Chain","ChannelSlashTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 17, {Addr}}} -> App(["Chain","ChannelSettleTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 18, {Addr}}} -> App(["Chain","ChannelSnapshotSoloTx"], [Chk(Adr, Addr)]); {["Chain", "base_tx"], {variant, ChainTxArities, 19, {Amount}}} -> App(["Chain","ContractCreateTx"], [Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 20, {Addr, Amount}}} -> App(["Chain","ContractCallTx"], [Chk(Adr, Addr), Chk(Int, Amount)]); {["Chain", "base_tx"], {variant, ChainTxArities, 21, {}}} -> App(["Chain","GAAttachTx"], []); {["MCL_BLS12_381", "fp"], X} -> App(["MCL_BLS12_381", "fp"], [Chk(I32, X)]); {["MCL_BLS12_381", "fr"], X} -> App(["MCL_BLS12_381", "fr"], [Chk(I48, X)]); _ -> throw(cannot_translate_to_sophia) end. make_bits(N) -> Id = fun(F) -> {qid, [], ["Bits", F]} end, if N < 0 -> make_bits(Id("clear"), Id("all"), 0, bnot N); true -> make_bits(Id("set"), Id("none"), 0, N) end. make_bits(_Set, Zero, _I, 0) -> Zero; make_bits(Set, Zero, I, N) when 0 == N rem 2 -> make_bits(Set, Zero, I + 1, N div 2); make_bits(Set, Zero, I, N) -> {app, [], Set, [make_bits(Set, Zero, I + 1, N div 2), {int, [], I}]}.
ca0774a0f30fe0333629d216bcd1f3690bfc6274cd470adb0fc013de6a0dd028
caradoc-org/caradoc
file.mli
(*****************************************************************************) (* Caradoc: a PDF parser and validator *) Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 (* *) (* This program is free software; you can redistribute it and/or modify *) it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . (* *) (* This program is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU General Public License for more details. *) (* *) You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . (*****************************************************************************) open Key open Directobject open Indirectobject open Stats open Boundedint open Intervals open Xref open Document a PDF file until extraction of xref sections , i.e. version , xref tables / streams , trailers Args : - input channel - file statistics Returns : - length of input - intervals of objects in file - xref table - document Args : - input channel - file statistics Returns : - length of input - intervals of objects in file - xref table - document *) val parse_until_xref : in_channel -> Stats.t -> (BoundedInt.t * Key.t Intervals.t * XRefTable.t * Document.t) (* Extract a given object from a PDF file Args : - input channel - object key Returns : - object *) val extract_object : in_channel -> Key.t -> IndirectObject.t (* Extract the trailer(s) from a PDF file Args : - input channel Returns : - list of trailers *) val extract_trailers : in_channel -> (DirectObject.dict_t list) (* Extract detailed statistics from a PDF document Args : - document - file statistics *) val extract_info : Document.t -> Stats.t -> unit (* Extract statistics from a PDF file Args : - input file name - file statistics *) val statistics : string -> Stats.t -> unit a PDF file and extract various data Args : - input file name Returns : - parsed document Args : - input file name Returns : - parsed document *) val parse_file : string -> Stats.t -> Document.t a PDF file and extract various data Args : - input file name Args : - input file name *) val check_file : string -> unit (* Write a cleaned up version of a file to stdout Args : - input file name - output file name *) val cleanup : string -> string -> unit
null
https://raw.githubusercontent.com/caradoc-org/caradoc/100f53bc55ef682049e10fabf24869bc019dc6ce/src/file.mli
ocaml
*************************************************************************** Caradoc: a PDF parser and validator This program is free software; you can redistribute it and/or modify This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. *************************************************************************** Extract a given object from a PDF file Args : - input channel - object key Returns : - object Extract the trailer(s) from a PDF file Args : - input channel Returns : - list of trailers Extract detailed statistics from a PDF document Args : - document - file statistics Extract statistics from a PDF file Args : - input file name - file statistics Write a cleaned up version of a file to stdout Args : - input file name - output file name
Copyright ( C ) 2015 ANSSI Copyright ( C ) 2015 - 2017 it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . open Key open Directobject open Indirectobject open Stats open Boundedint open Intervals open Xref open Document a PDF file until extraction of xref sections , i.e. version , xref tables / streams , trailers Args : - input channel - file statistics Returns : - length of input - intervals of objects in file - xref table - document Args : - input channel - file statistics Returns : - length of input - intervals of objects in file - xref table - document *) val parse_until_xref : in_channel -> Stats.t -> (BoundedInt.t * Key.t Intervals.t * XRefTable.t * Document.t) val extract_object : in_channel -> Key.t -> IndirectObject.t val extract_trailers : in_channel -> (DirectObject.dict_t list) val extract_info : Document.t -> Stats.t -> unit val statistics : string -> Stats.t -> unit a PDF file and extract various data Args : - input file name Returns : - parsed document Args : - input file name Returns : - parsed document *) val parse_file : string -> Stats.t -> Document.t a PDF file and extract various data Args : - input file name Args : - input file name *) val check_file : string -> unit val cleanup : string -> string -> unit
eb120892ff3efa596fdd1fb6958f0737f2e676445ad64f77070d65af33aee562
debasishg/hask
Id.hs
# OPTIONS_GHC -fno - warn - redundant - constraints # # LANGUAGE AllowAmbiguousTypes # -- | Contains safe 'Id' representation. module Lib.Core.Id ( -- * Id Id (..) , AnyId , castId ) where import Data.Type.Equality (type (==)) -- | Wrapper for textual id. Contains phantom type parameter for increased -- type-safety. newtype Id a = Id { unId :: Text } deriving stock (Show, Generic) deriving newtype (Eq, Ord, Hashable, FromField, ToField, FromJSON, ToJSON) -- | When we don't care about type of 'Id' but don't want to deal with type variables type AnyId = Id () -- | Unsafe cast of 'Id'. Implementation uses smart trick to enforce usage -- always with @TypeApplications@. castId ::forall to from to' . ((to == to') ~ 'True) => Id from -> Id to' castId (Id a) = Id a
null
https://raw.githubusercontent.com/debasishg/hask/1745ed50c8175cd035e8070c9cb988f4f5063653/h3layer/src/Lib/Core/Id.hs
haskell
| Contains safe 'Id' representation. * Id | Wrapper for textual id. Contains phantom type parameter for increased type-safety. | When we don't care about type of 'Id' but don't want to deal with type variables | Unsafe cast of 'Id'. Implementation uses smart trick to enforce usage always with @TypeApplications@.
# OPTIONS_GHC -fno - warn - redundant - constraints # # LANGUAGE AllowAmbiguousTypes # module Lib.Core.Id Id (..) , AnyId , castId ) where import Data.Type.Equality (type (==)) newtype Id a = Id { unId :: Text } deriving stock (Show, Generic) deriving newtype (Eq, Ord, Hashable, FromField, ToField, FromJSON, ToJSON) type AnyId = Id () castId ::forall to from to' . ((to == to') ~ 'True) => Id from -> Id to' castId (Id a) = Id a
9a313e72760cdb1d856d3a4541b77ac002be7140a2f6147d1e16d129383f48ea
haskell-works/eta-kafka-client
Producer.hs
{-# LANGUAGE OverloadedStrings #-} module Kafka.Producer ( module X , KafkaProducer, JFuture, JRecordMetadata , newProducer , send , closeProducer , mkJProducerRecord ) where import Java import Java.Collections as J import Control.Monad.IO.Class import Data.Bifunctor import Data.ByteString as BS import Data.Map (Map) import qualified Data.Map as M import Data.Monoid import Kafka.Producer.Bindings import Kafka.Producer.ProducerProperties as X import Kafka.Producer.Types as X import Kafka.Types as X newtype KafkaProducer = KafkaProducer (JKafkaProducer JByteArray JByteArray) fixedProps :: ProducerProperties fixedProps = extraProducerProps $ M.fromList [ ("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer") , ("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer") ] newProducer :: MonadIO m => ProducerProperties -> m KafkaProducer newProducer props = let bsProps = fixedProps <> props prod = mkRawProducer (mkProducerProps bsProps) in liftIO $ KafkaProducer <$> prod send :: MonadIO m => KafkaProducer -> ProducerRecord -> m (JFuture JRecordMetadata) send (KafkaProducer kp) r = liftIO $ rawSend kp (mkJProducerRecord r) mkJProducerRecord :: ProducerRecord -> JProducerRecord JByteArray JByteArray mkJProducerRecord (ProducerRecord t p k v) = let TopicName t' = t p' = (\(PartitionId x) -> x) <$> p k' = toJava . BS.unpack <$> k v' = toJava . BS.unpack <$> v in newJProducerRecord (toJString t') (toJava <$> p') Nothing k' v' closeProducer :: MonadIO m => KafkaProducer -> m () closeProducer (KafkaProducer kp) = liftIO $ flushProducer kp >> destroyProducer kp mkProducerProps :: ProducerProperties -> J.Map JString JString mkProducerProps (ProducerProperties m) = toJava $ bimap toJString toJString <$> M.toList m
null
https://raw.githubusercontent.com/haskell-works/eta-kafka-client/d6f79e7b06e3ab16117150fac543c79413b16483/src/Kafka/Producer.hs
haskell
# LANGUAGE OverloadedStrings #
module Kafka.Producer ( module X , KafkaProducer, JFuture, JRecordMetadata , newProducer , send , closeProducer , mkJProducerRecord ) where import Java import Java.Collections as J import Control.Monad.IO.Class import Data.Bifunctor import Data.ByteString as BS import Data.Map (Map) import qualified Data.Map as M import Data.Monoid import Kafka.Producer.Bindings import Kafka.Producer.ProducerProperties as X import Kafka.Producer.Types as X import Kafka.Types as X newtype KafkaProducer = KafkaProducer (JKafkaProducer JByteArray JByteArray) fixedProps :: ProducerProperties fixedProps = extraProducerProps $ M.fromList [ ("key.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer") , ("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer") ] newProducer :: MonadIO m => ProducerProperties -> m KafkaProducer newProducer props = let bsProps = fixedProps <> props prod = mkRawProducer (mkProducerProps bsProps) in liftIO $ KafkaProducer <$> prod send :: MonadIO m => KafkaProducer -> ProducerRecord -> m (JFuture JRecordMetadata) send (KafkaProducer kp) r = liftIO $ rawSend kp (mkJProducerRecord r) mkJProducerRecord :: ProducerRecord -> JProducerRecord JByteArray JByteArray mkJProducerRecord (ProducerRecord t p k v) = let TopicName t' = t p' = (\(PartitionId x) -> x) <$> p k' = toJava . BS.unpack <$> k v' = toJava . BS.unpack <$> v in newJProducerRecord (toJString t') (toJava <$> p') Nothing k' v' closeProducer :: MonadIO m => KafkaProducer -> m () closeProducer (KafkaProducer kp) = liftIO $ flushProducer kp >> destroyProducer kp mkProducerProps :: ProducerProperties -> J.Map JString JString mkProducerProps (ProducerProperties m) = toJava $ bimap toJString toJString <$> M.toList m
c34f3d2c12cd89fad0bbbd4b8a4046ee86e9a0b2016e3c76b9cf2e8f02b48469
ndmitchell/profiterole
Type.hs
# LANGUAGE RecordWildCards # module Type( Val(..), mergeVal, valFromProfile ) where import GHC.Prof import Data.Maybe import Data.Scientific import Data.Tree import qualified Data.Text as T data Val = Val {name :: String -- Name of this node Time spent under this node Time spent under this node excluding rerooted Time spent in this code ,entries :: Integer -- Number of times this node was called } deriving Show mergeVal :: Val -> Val -> Val mergeVal x y | name x /= name y = error "mergeRoots, invariant violated" | otherwise = Val {name = name x ,timeTot = timeTot x + timeTot y ,timeInh = timeInh x + timeInh y ,timeInd = timeInd x + timeInd y ,entries = entries x + entries y} valFromProfile :: Profile -> Tree Val valFromProfile prf = case costCentres prf of Nothing -> error "Failed to generate value tree from profile (no idea why - corrupt profile?)" Just x | isNothing $ costCentreTicks $ rootLabel x -> fmap toValTime x | otherwise -> fixTotInh $ fmap (toValTick $ (* 0.01) $ fromInteger $ totalTimeTicks $ profileTotalTime prf) x toValTime :: CostCentre -> Val toValTime CostCentre{..} = Val (T.unpack costCentreModule ++ " " ++ T.unpack costCentreName) inh inh (toRealFloat costCentreIndTime) costCentreEntries where inh = toRealFloat costCentreInhTime toValTick :: Double -> CostCentre -> Val toValTick tot cc = (toValTime cc){timeInd = fromInteger (fromJust $ costCentreTicks cc) / tot} fixTotInh :: Tree Val -> Tree Val fixTotInh (Node x xs) = Node x{timeTot=t, timeInh=t} ys where ys = map fixTotInh xs t = timeInd x + sum (map (timeInh . rootLabel) ys)
null
https://raw.githubusercontent.com/ndmitchell/profiterole/984d915652948cd77d7c87216285c94a85d4304b/src/Type.hs
haskell
Name of this node Number of times this node was called
# LANGUAGE RecordWildCards # module Type( Val(..), mergeVal, valFromProfile ) where import GHC.Prof import Data.Maybe import Data.Scientific import Data.Tree import qualified Data.Text as T data Val = Val Time spent under this node Time spent under this node excluding rerooted Time spent in this code } deriving Show mergeVal :: Val -> Val -> Val mergeVal x y | name x /= name y = error "mergeRoots, invariant violated" | otherwise = Val {name = name x ,timeTot = timeTot x + timeTot y ,timeInh = timeInh x + timeInh y ,timeInd = timeInd x + timeInd y ,entries = entries x + entries y} valFromProfile :: Profile -> Tree Val valFromProfile prf = case costCentres prf of Nothing -> error "Failed to generate value tree from profile (no idea why - corrupt profile?)" Just x | isNothing $ costCentreTicks $ rootLabel x -> fmap toValTime x | otherwise -> fixTotInh $ fmap (toValTick $ (* 0.01) $ fromInteger $ totalTimeTicks $ profileTotalTime prf) x toValTime :: CostCentre -> Val toValTime CostCentre{..} = Val (T.unpack costCentreModule ++ " " ++ T.unpack costCentreName) inh inh (toRealFloat costCentreIndTime) costCentreEntries where inh = toRealFloat costCentreInhTime toValTick :: Double -> CostCentre -> Val toValTick tot cc = (toValTime cc){timeInd = fromInteger (fromJust $ costCentreTicks cc) / tot} fixTotInh :: Tree Val -> Tree Val fixTotInh (Node x xs) = Node x{timeTot=t, timeInh=t} ys where ys = map fixTotInh xs t = timeInd x + sum (map (timeInh . rootLabel) ys)
d336e5435add490b26b898927d6e43a01d65584fc0c86860e41664a0837e3f1d
mauricioszabo/atom-chlorine
state.cljs
(ns chlorine.state (:require [reagent.core :as r])) (def configs {:eval-mode {:description "Should we evaluate Clojure or ClojureScript?" :type [:prefer-clj :prefer-cljs :clj :cljs] :default :prefer-clj} :refresh-mode {:description "Should we use clojure.tools.namespace to refresh, or a simple require?" :type [:full :simple] :default :simple} :refresh-on-save {:description "Should we refresh namespaces when we save a file (Clojure Only)?" :type :boolean :default false} :experimental-features {:description "Enable experimental (and possibly unstable) features?" :type :boolean :default false}}) (defn- seed-configs [] (->> configs (map (fn [[k v]] [k (:default v)])) (into {}))) (defonce state (r/atom {:repls {:clj-eval nil :cljs-eval nil :clj-aux nil} :refresh {:needs-clear? true} :config (seed-configs)}))
null
https://raw.githubusercontent.com/mauricioszabo/atom-chlorine/86628b7b9cae7c1ae352abe0caefc6f960c37a3f/src/chlorine/state.cljs
clojure
(ns chlorine.state (:require [reagent.core :as r])) (def configs {:eval-mode {:description "Should we evaluate Clojure or ClojureScript?" :type [:prefer-clj :prefer-cljs :clj :cljs] :default :prefer-clj} :refresh-mode {:description "Should we use clojure.tools.namespace to refresh, or a simple require?" :type [:full :simple] :default :simple} :refresh-on-save {:description "Should we refresh namespaces when we save a file (Clojure Only)?" :type :boolean :default false} :experimental-features {:description "Enable experimental (and possibly unstable) features?" :type :boolean :default false}}) (defn- seed-configs [] (->> configs (map (fn [[k v]] [k (:default v)])) (into {}))) (defonce state (r/atom {:repls {:clj-eval nil :cljs-eval nil :clj-aux nil} :refresh {:needs-clear? true} :config (seed-configs)}))
76ca4a473f486a55c66c7cdbc9c61ce8f038f7389089590ab5ea1b706580ef85
xsc/claro
resolver.cljc
(ns claro.engine.resolver (:require [claro.runtime.impl :as impl] [claro.data [error :refer [error?]] [protocols :as p] [tree :refer [wrap-tree]]])) ;; ## Helpers (defn- result-as-map [batch result] (if (map? result) result (zipmap batch result))) (defn- map-kv [f m] (persistent! (reduce (fn [m e] (assoc! m (key e) (f (key e) (val e)))) (transient {}) m))) # # Resolution (defn- resolve-them-all! [impl adapter env [head :as batch]] (cond (p/batched-resolvable? head) (adapter impl #(p/resolve-batch! head env batch)) (next batch) (let [deferreds (mapv (fn [item] (adapter impl #(p/resolve! item env))) batch)] (impl/zip impl deferreds)) :else (let [deferred (adapter impl #(p/resolve! head env))] (impl/chain1 impl deferred vector)))) (defn raw-resolve-fn "Generate a resolver function for `claro.runtime/run`, suitable for processing `claro.data.protocols/Resolvable` values." [impl adapter] {:pre [impl (fn? adapter)]} (fn [env batch] (impl/chain1 impl (resolve-them-all! impl adapter env batch) #(result-as-map batch %)))) ;; ## Transformation (defn wrap-transform "Generate a function to be called after resolution, postprocessing the resolved value." [impl resolver] (let [transform-fn (fn [resolvable value] (if (error? value) value (p/transform resolvable value)))] (fn [env batch] (impl/chain1 impl (resolver env batch) #(map-kv transform-fn %))))) # # Finalisation (defn wrap-finalize "Generate a function to be called directly before the resolution result is cached." [impl resolver] (fn [env batch] (impl/chain1 impl (resolver env batch) (fn [resolvable->value] (map-kv #(wrap-tree %2) resolvable->value))))) # # Compound Resolver Function (defn build "Combine the given functions to generate a resolver function suitable for the claro runtime." [raw-resolve-fn wrappers] (reduce #(%2 %1) raw-resolve-fn wrappers))
null
https://raw.githubusercontent.com/xsc/claro/16db75b7a775a14f3b656362e8ee4f65dd8b0d49/src/claro/engine/resolver.cljc
clojure
## Helpers ## Transformation
(ns claro.engine.resolver (:require [claro.runtime.impl :as impl] [claro.data [error :refer [error?]] [protocols :as p] [tree :refer [wrap-tree]]])) (defn- result-as-map [batch result] (if (map? result) result (zipmap batch result))) (defn- map-kv [f m] (persistent! (reduce (fn [m e] (assoc! m (key e) (f (key e) (val e)))) (transient {}) m))) # # Resolution (defn- resolve-them-all! [impl adapter env [head :as batch]] (cond (p/batched-resolvable? head) (adapter impl #(p/resolve-batch! head env batch)) (next batch) (let [deferreds (mapv (fn [item] (adapter impl #(p/resolve! item env))) batch)] (impl/zip impl deferreds)) :else (let [deferred (adapter impl #(p/resolve! head env))] (impl/chain1 impl deferred vector)))) (defn raw-resolve-fn "Generate a resolver function for `claro.runtime/run`, suitable for processing `claro.data.protocols/Resolvable` values." [impl adapter] {:pre [impl (fn? adapter)]} (fn [env batch] (impl/chain1 impl (resolve-them-all! impl adapter env batch) #(result-as-map batch %)))) (defn wrap-transform "Generate a function to be called after resolution, postprocessing the resolved value." [impl resolver] (let [transform-fn (fn [resolvable value] (if (error? value) value (p/transform resolvable value)))] (fn [env batch] (impl/chain1 impl (resolver env batch) #(map-kv transform-fn %))))) # # Finalisation (defn wrap-finalize "Generate a function to be called directly before the resolution result is cached." [impl resolver] (fn [env batch] (impl/chain1 impl (resolver env batch) (fn [resolvable->value] (map-kv #(wrap-tree %2) resolvable->value))))) # # Compound Resolver Function (defn build "Combine the given functions to generate a resolver function suitable for the claro runtime." [raw-resolve-fn wrappers] (reduce #(%2 %1) raw-resolve-fn wrappers))
a58c3bb38c66f06b6f68263ee6dbfcb9ad48ad87b521d8038e212a8d53a2588b
pbevin/cardelli
ParseSpec.hs
module ParseSpec where import Test.Hspec import Test.QuickCheck import Parse import ShowExpr import ASTGen import AST import Debug.Trace spec :: Spec spec = do describe "parseFun" $ do it "parses an identifier" $ do parseFun "x" `shouldBe` Var "x" it "parses a number" $ do parseFun "0" `shouldBe` Num 0 it "parses a cond" $ do parseFun "if happy then 42 else 666" `shouldBe` Cond (Var "happy") (Num 42) (Num 666) it "parses a lambda" $ do parseFun "fun(x) x" `shouldBe` Lambda "x" (Var "x") it "parses a function application" $ do parseFun "f(1)" `shouldBe` FunCall (Var "f") (Num 1) it "parses a double function application" $ do parseFun "f(1)(2)" `shouldBe` FunCall (FunCall (Var "f") (Num 1)) (Num 2) it "parses a comma-ized function application" $ do parseFun "f(1, 2)" `shouldBe` parseFun "f(1)(2)" it "parses a let..in" $ do parseFun "let a = 2 in succ(a)" `shouldBe` Block (Assign "a" (Num 2)) (FunCall (Var "succ") (Var "a")) it "parses a let rec..in" $ do parseFun "let rec f = f(0) in f" `shouldBe` Block (Rec (Assign "f" (FunCall (Var "f") (Num 0)))) (Var "f") it "parses a seq" $ do parseFun "let a=3 then b=4 in a" `shouldBe` Block (Seq (Assign "a" (Num 3)) (Assign "b" (Num 4))) (Var "a") it "parses a parenthesized decl" $ do parseFun "let (a=3 then b=4) in a" `shouldBe` parseFun "let a=3 then b=4 in a" it "parses bracketed expressions" $ do parseFun "(if sad then f else g)(0)" `shouldBe` FunCall (Cond (Var "sad") (Var "f") (Var "g")) (Num 0) it "parses arithmetic and boolean operations" $ do parseFun "a+1" `shouldBe` FunCall (FunCall (Var "plus") (Var "a")) (Num 1) parseFun "a-1" `shouldBe` FunCall (FunCall (Var "minus") (Var "a")) (Num 1) parseFun "a*2" `shouldBe` FunCall (FunCall (Var "times") (Var "a")) (Num 2) parseFun "a/2" `shouldBe` FunCall (FunCall (Var "div") (Var "a")) (Num 2) parseFun "-a" `shouldBe` FunCall (Var "negate") (Var "a") parseFun "!b" `shouldBe` FunCall (Var "not") (Var "b") parseFun "happy & youknowit" `shouldBe` FunCall (FunCall (Var "and") (Var "happy")) (Var "youknowit") parseFun "b | !b" `shouldBe` FunCall (FunCall (Var "or") (Var "b")) (FunCall (Var "not") (Var "b")) parseFun "a+b*c" `shouldBe` FunCall (FunCall (Var "plus") (Var "a")) (FunCall (FunCall (Var "times") (Var "b")) (Var "c")) let ab = (FunCall (FunCall (Var "times") (Var "a")) (Var "b")) parseFun "a*b+c" `shouldBe` FunCall (FunCall (Var "plus") ab) (Var "c") it "is the opposite of showExpr" $ property $ \expr - > length ( showExpr expr ) < 100 \expr -> parseFun (showExpr expr) == expr
null
https://raw.githubusercontent.com/pbevin/cardelli/bf239351289d379796fa68c25bb6c56be0e67925/hs/test/ParseSpec.hs
haskell
module ParseSpec where import Test.Hspec import Test.QuickCheck import Parse import ShowExpr import ASTGen import AST import Debug.Trace spec :: Spec spec = do describe "parseFun" $ do it "parses an identifier" $ do parseFun "x" `shouldBe` Var "x" it "parses a number" $ do parseFun "0" `shouldBe` Num 0 it "parses a cond" $ do parseFun "if happy then 42 else 666" `shouldBe` Cond (Var "happy") (Num 42) (Num 666) it "parses a lambda" $ do parseFun "fun(x) x" `shouldBe` Lambda "x" (Var "x") it "parses a function application" $ do parseFun "f(1)" `shouldBe` FunCall (Var "f") (Num 1) it "parses a double function application" $ do parseFun "f(1)(2)" `shouldBe` FunCall (FunCall (Var "f") (Num 1)) (Num 2) it "parses a comma-ized function application" $ do parseFun "f(1, 2)" `shouldBe` parseFun "f(1)(2)" it "parses a let..in" $ do parseFun "let a = 2 in succ(a)" `shouldBe` Block (Assign "a" (Num 2)) (FunCall (Var "succ") (Var "a")) it "parses a let rec..in" $ do parseFun "let rec f = f(0) in f" `shouldBe` Block (Rec (Assign "f" (FunCall (Var "f") (Num 0)))) (Var "f") it "parses a seq" $ do parseFun "let a=3 then b=4 in a" `shouldBe` Block (Seq (Assign "a" (Num 3)) (Assign "b" (Num 4))) (Var "a") it "parses a parenthesized decl" $ do parseFun "let (a=3 then b=4) in a" `shouldBe` parseFun "let a=3 then b=4 in a" it "parses bracketed expressions" $ do parseFun "(if sad then f else g)(0)" `shouldBe` FunCall (Cond (Var "sad") (Var "f") (Var "g")) (Num 0) it "parses arithmetic and boolean operations" $ do parseFun "a+1" `shouldBe` FunCall (FunCall (Var "plus") (Var "a")) (Num 1) parseFun "a-1" `shouldBe` FunCall (FunCall (Var "minus") (Var "a")) (Num 1) parseFun "a*2" `shouldBe` FunCall (FunCall (Var "times") (Var "a")) (Num 2) parseFun "a/2" `shouldBe` FunCall (FunCall (Var "div") (Var "a")) (Num 2) parseFun "-a" `shouldBe` FunCall (Var "negate") (Var "a") parseFun "!b" `shouldBe` FunCall (Var "not") (Var "b") parseFun "happy & youknowit" `shouldBe` FunCall (FunCall (Var "and") (Var "happy")) (Var "youknowit") parseFun "b | !b" `shouldBe` FunCall (FunCall (Var "or") (Var "b")) (FunCall (Var "not") (Var "b")) parseFun "a+b*c" `shouldBe` FunCall (FunCall (Var "plus") (Var "a")) (FunCall (FunCall (Var "times") (Var "b")) (Var "c")) let ab = (FunCall (FunCall (Var "times") (Var "a")) (Var "b")) parseFun "a*b+c" `shouldBe` FunCall (FunCall (Var "plus") ab) (Var "c") it "is the opposite of showExpr" $ property $ \expr - > length ( showExpr expr ) < 100 \expr -> parseFun (showExpr expr) == expr
e14c2d3537bf2717b96128c84b8d41732691e06e3a862fb2422772cf79648c44
brendanhay/gogol
Get.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . ShoppingContent . Content . Orders . Get Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- Retrieves an order from your Merchant Center account . -- /See:/ < API for Shopping Reference > for @content.orders.get@. module Gogol.ShoppingContent.Content.Orders.Get ( -- * Resource ContentOrdersGetResource, -- ** Constructing a Request ContentOrdersGet (..), newContentOrdersGet, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types -- | A resource alias for @content.orders.get@ method which the ' ContentOrdersGet ' request conforms to . type ContentOrdersGetResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "orders" Core.:> Core.Capture "orderId" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] Order | Retrieves an order from your Merchant Center account . -- /See:/ ' newContentOrdersGet ' smart constructor . data ContentOrdersGet = ContentOrdersGet { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), -- | The ID of the account that manages the order. This cannot be a multi-client account. merchantId :: Core.Word64, -- | The ID of the order. orderId :: Core.Text, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentOrdersGet ' with the minimum fields required to make a request . newContentOrdersGet :: -- | The ID of the account that manages the order. This cannot be a multi-client account. See 'merchantId'. Core.Word64 -> -- | The ID of the order. See 'orderId'. Core.Text -> ContentOrdersGet newContentOrdersGet merchantId orderId = ContentOrdersGet { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, merchantId = merchantId, orderId = orderId, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentOrdersGet where type Rs ContentOrdersGet = Order type Scopes ContentOrdersGet = '[Content'FullControl] requestClient ContentOrdersGet {..} = go merchantId orderId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) shoppingContentService where go = Core.buildClient (Core.Proxy :: Core.Proxy ContentOrdersGetResource) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/fffd4d98a1996d0ffd4cf64545c5e8af9c976cda/lib/services/gogol-shopping-content/gen/Gogol/ShoppingContent/Content/Orders/Get.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated * Resource ** Constructing a Request | A resource alias for @content.orders.get@ method which the | V1 error format. | OAuth access token. | The ID of the account that manages the order. This cannot be a multi-client account. | The ID of the order. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | The ID of the account that manages the order. This cannot be a multi-client account. See 'merchantId'. | The ID of the order. See 'orderId'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . ShoppingContent . Content . Orders . Get Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) Retrieves an order from your Merchant Center account . /See:/ < API for Shopping Reference > for @content.orders.get@. module Gogol.ShoppingContent.Content.Orders.Get ContentOrdersGetResource, ContentOrdersGet (..), newContentOrdersGet, ) where import qualified Gogol.Prelude as Core import Gogol.ShoppingContent.Types ' ContentOrdersGet ' request conforms to . type ContentOrdersGetResource = "content" Core.:> "v2.1" Core.:> Core.Capture "merchantId" Core.Word64 Core.:> "orders" Core.:> Core.Capture "orderId" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.Get '[Core.JSON] Order | Retrieves an order from your Merchant Center account . /See:/ ' newContentOrdersGet ' smart constructor . data ContentOrdersGet = ContentOrdersGet xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), merchantId :: Core.Word64, orderId :: Core.Text, | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of ' ContentOrdersGet ' with the minimum fields required to make a request . newContentOrdersGet :: Core.Word64 -> Core.Text -> ContentOrdersGet newContentOrdersGet merchantId orderId = ContentOrdersGet { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, merchantId = merchantId, orderId = orderId, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest ContentOrdersGet where type Rs ContentOrdersGet = Order type Scopes ContentOrdersGet = '[Content'FullControl] requestClient ContentOrdersGet {..} = go merchantId orderId xgafv accessToken callback uploadType uploadProtocol (Core.Just Core.AltJSON) shoppingContentService where go = Core.buildClient (Core.Proxy :: Core.Proxy ContentOrdersGetResource) Core.mempty
de0382dc42d2deb811306a57404986c7874e5af1e135c8c2dd2bc1938005fe76
sdiehl/paris-fp
Main.hs
module Main where import Protolude import qualified Entry main :: IO () main = Entry.main
null
https://raw.githubusercontent.com/sdiehl/paris-fp/d3ab8e0dde9035e17d755355d275ddc3c5bc57e7/exec/Main.hs
haskell
module Main where import Protolude import qualified Entry main :: IO () main = Entry.main
88f110970c1738af2335a65f2dd27148687e4e27442132d18461bdf3dc93248e
MarcKaufmann/congame
info.rkt
#lang info (define collection "congame-pjb-studies") (define deps '("base" "component-lib" "congame-core" "congame-price-lists" "forms-lib" "gregor-lib" "htdp-lib" "koyo-lib" "marionette-lib" "sentry-lib" "web-server-lib")) (define build-deps '("rackunit-lib")) (define congame-studies '((congame-pjb-studies/pjb-pilot pjb-pilot-study) (congame-pjb-studies/pjb-pilot relax-test-study))) (define congame-bots '((congame-pjb-studies/pjb-pilot-bot make-pjb-pilot-bot #:for pjb-pilot-study #:models (pjb-pilot-bot-model/full)) (congame-pjb-studies/pjb-pilot-bot make-relax-test-bot #:for relax-test-study #:models (relax-test-bot-model))))
null
https://raw.githubusercontent.com/MarcKaufmann/congame/17edf790b5a9af0439d532f3af61dd60d10c8964/congame-pjb-studies/info.rkt
racket
#lang info (define collection "congame-pjb-studies") (define deps '("base" "component-lib" "congame-core" "congame-price-lists" "forms-lib" "gregor-lib" "htdp-lib" "koyo-lib" "marionette-lib" "sentry-lib" "web-server-lib")) (define build-deps '("rackunit-lib")) (define congame-studies '((congame-pjb-studies/pjb-pilot pjb-pilot-study) (congame-pjb-studies/pjb-pilot relax-test-study))) (define congame-bots '((congame-pjb-studies/pjb-pilot-bot make-pjb-pilot-bot #:for pjb-pilot-study #:models (pjb-pilot-bot-model/full)) (congame-pjb-studies/pjb-pilot-bot make-relax-test-bot #:for relax-test-study #:models (relax-test-bot-model))))
399f7e683b8480ce4a37776d7686abd29442c29300c0193202415dffe6cd4988
roman01la/cljs-rum-realworld-example-app
base.cljs
(ns conduit.components.base (:require [rum.core :as rum])) (rum/defc Icon ([icon] (Icon {} icon)) ([{:keys [on-click]} icon] [:i {:on-click on-click :class (str "ion-" (name icon))}])) (defn- btn-class [class type size outline?] (str class " " (case size :L "btn-lg" "btn-sm") " " (case type :secondary (str "btn-" (if outline? "outline-secondary" "secondary")) (str "btn-" (if outline? "outline-primary" "primary"))))) (rum/defc Button ([label] (Button {} label)) ([{:keys [icon class type size outline? disabled? on-click]} label] [:button.btn {:class (btn-class class type size outline?) :disabled disabled? :on-click on-click} (when icon (Icon icon)) (when icon " ") label])) (rum/defc ArticleMeta [{:keys [image username createdAt]} & children] [:header.article-meta [:a {:href "profile.html"} [:img {:src image}]] [:div.info [:a.author {:href ""} username] [:span.date (-> createdAt js/Date. .toDateString)]] children]) (rum/defc Tags [tags] [:ul.tags-list (->> tags (map (fn [tag] [:li.tag-default.tag-pill.tag-outline {:key tag} [:a {:href (str "#/tag/" tag)} tag]])))])
null
https://raw.githubusercontent.com/roman01la/cljs-rum-realworld-example-app/962695bd391806a7066340461c3e02f2215fdc48/src/conduit/components/base.cljs
clojure
(ns conduit.components.base (:require [rum.core :as rum])) (rum/defc Icon ([icon] (Icon {} icon)) ([{:keys [on-click]} icon] [:i {:on-click on-click :class (str "ion-" (name icon))}])) (defn- btn-class [class type size outline?] (str class " " (case size :L "btn-lg" "btn-sm") " " (case type :secondary (str "btn-" (if outline? "outline-secondary" "secondary")) (str "btn-" (if outline? "outline-primary" "primary"))))) (rum/defc Button ([label] (Button {} label)) ([{:keys [icon class type size outline? disabled? on-click]} label] [:button.btn {:class (btn-class class type size outline?) :disabled disabled? :on-click on-click} (when icon (Icon icon)) (when icon " ") label])) (rum/defc ArticleMeta [{:keys [image username createdAt]} & children] [:header.article-meta [:a {:href "profile.html"} [:img {:src image}]] [:div.info [:a.author {:href ""} username] [:span.date (-> createdAt js/Date. .toDateString)]] children]) (rum/defc Tags [tags] [:ul.tags-list (->> tags (map (fn [tag] [:li.tag-default.tag-pill.tag-outline {:key tag} [:a {:href (str "#/tag/" tag)} tag]])))])
6b93d67ee5b1f6bda41bf7bb0c1b5d38915b5bcfc6ce7abd33c676981bd60efe
samply/blaze
spec.clj
(ns blaze.fhir.spec.type.system.spec (:require [blaze.fhir.spec.type.system :as system] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen])) (s/def :system/date (s/with-gen system/date? #(gen/fmap (partial apply system/date) (gen/tuple (s/gen (s/int-in 1 10000)) (s/gen (s/int-in 1 13)) (s/gen (s/int-in 1 29)))))) (s/def :system/date-time system/date-time?) (s/def :system/date-or-date-time (s/or :date :system/date :date-time :system/date-time))
null
https://raw.githubusercontent.com/samply/blaze/693d07d8fbf9ac4e11af6684978e108bbd193780/modules/fhir-structure/src/blaze/fhir/spec/type/system/spec.clj
clojure
(ns blaze.fhir.spec.type.system.spec (:require [blaze.fhir.spec.type.system :as system] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen])) (s/def :system/date (s/with-gen system/date? #(gen/fmap (partial apply system/date) (gen/tuple (s/gen (s/int-in 1 10000)) (s/gen (s/int-in 1 13)) (s/gen (s/int-in 1 29)))))) (s/def :system/date-time system/date-time?) (s/def :system/date-or-date-time (s/or :date :system/date :date-time :system/date-time))
a8d2e11c329db8c710905b9c59c1532200ecc751eddda216b71cd605defee101
jeromesimeon/Galax
code_tj_pathstack.ml
(***********************************************************************) (* *) (* GALAX *) (* XQuery Engine *) (* *) Copyright 2001 - 2007 . (* Distributed only by permission. *) (* *) (***********************************************************************) $ I d : code_tj_pathstack.ml , v 1.6 2007/02/01 22:08:45 simeon Exp $ Module : Code_tj_pathstack Description : This is the code for the PathStack variant of the TwigJoin . Description: This is the code for the PathStack variant of the TwigJoin. *) open Error open Dynamic_stack open Code_util_tj open Code_selection_context open Execution_context open Xquery_algebra_ast open Xquery_algebra_ast_util open Datatypes open Dm_types open Dm_atomic open Dm open Dm_util open Physical_item open Physical_item_util open Physical_sequence open Physical_value_util open Physical_table open Physical_name_index open Code_util open Code_util_xpath open Cs_util open Code_util_materialize (*******************************************************) ALGORITHM : PathStack Holistic Twig Joins , Optimal XML Pattern Matching Bruno , Koudas , SIGMOD ' 02 Madison - USA (*******************************************************) PROCEDURE get_min_source -- PART OF PathStack Get the index or input whose first node has a minimal pre - order (* Returns the index of that source in the source array. *) let get_min_source indices_curs () = let min = ref (-1) in let current = ref None in for i = 0 to (Array.length indices_curs) -1 do begin let next_item = Cursor.cursor_peek indices_curs.(i) in match next_item with | Some node_arr -> begin let node = getNode (Physical_util.get_item (cursor_of_sequence ( node_arr ))) in match !current with | Some node' -> if node_precedes node node' then ignore(current := Some node; min := i) | _ -> ignore(current := Some node; min := i) end | _ -> () end done; if !min < 0 then None else Some !min (******************************************************************************) (* ALGORITHM PathStack *) (******************************************************************************) let pathstack input code_ctxt pattern stacks = let len = Array.length stacks in let retrieve_code = build_retrieve_dom_tuple_code code_ctxt input in let restore_array = build_restore_array pattern code_ctxt in let axes = get_axis_array pattern in fun () eval alg_ctxt curs -> begin let indices = get_name_indices_array code_ctxt pattern in let indices_curs = Array.map (fun index -> pre_cursor_of_name_index_at_pos index 1) indices in let all_sources = Array.append [| common_cursor_of_input_cursor curs retrieve_code |] indices_curs in let source_cursor = Cursor.cursor_of_function (get_min_source all_sources) in let item_fun src = begin let item = Cursor.cursor_next all_sources.(src) in let node = getNode (Physical_util.get_item (cursor_of_sequence item)) in let nextL = pre node in let nextR = post node in (* clean stacks *) for i = 0 to len -1 do while not(empty stacks.(i)) && ((get_top_post_from_stack stacks.(i)) < nextR) do ignore(pop stacks.(i)) done done; (* move stream to stack *) (* Note: possible optimization, short circuit if not all parent stacks non-empty *) let parent_node_index = get_parent_node_index pattern pattern.(src) in if parent_node_index < 0 then push stacks.(src) (item, -1, nextL, nextR) else push stacks.(src) (item, (stacks.(parent_node_index).size), nextL, nextR); (* print_stack_config stacks;*) let output = ref [] in if (is_leaf_node pattern pattern.(src)) then begin output := show_solutions pattern axes stacks src 0; ignore(pop stacks.(src)); end; !output end in let restore_intermed list = Warning , this XPath hack prevents duplicates to occur in the (* output. It only works -for now- if the output corresponds *) (* with the leaf node of a straight-line twig pattern *) replace by duplicat elim over the output fields - Philippe let list' = match list with | hd::tl -> [hd] | _ -> list in Cursor.cursor_map (restore_tuple restore_array) (Cursor.cursor_of_list list') in Cursor.cursor_map_concat restore_intermed (Cursor.cursor_map item_fun source_cursor) end let build_holistic_tuple_tree_pattern_code code_ctxt input pattern = 1 . create field accessor and field restore functions let output_fields = get_restored_outputs_from_twig_pattern pattern in let _ = List.map (add_tuple_reference code_ctxt) output_fields in 2 . create the stack structure let dummy = (sequence_empty(), (-1), (-1), (-1)) in let stacks = Array.init (Array.length pattern) (fun i -> Dynamic_stack.make 16 dummy) in 3 . the algorithm pathstack input code_ctxt pattern stacks
null
https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/code_selection/code/code_tj_pathstack.ml
ocaml
********************************************************************* GALAX XQuery Engine Distributed only by permission. ********************************************************************* ***************************************************** ***************************************************** Returns the index of that source in the source array. **************************************************************************** ALGORITHM PathStack **************************************************************************** clean stacks move stream to stack Note: possible optimization, short circuit if not all parent stacks non-empty print_stack_config stacks; output. It only works -for now- if the output corresponds with the leaf node of a straight-line twig pattern
Copyright 2001 - 2007 . $ I d : code_tj_pathstack.ml , v 1.6 2007/02/01 22:08:45 simeon Exp $ Module : Code_tj_pathstack Description : This is the code for the PathStack variant of the TwigJoin . Description: This is the code for the PathStack variant of the TwigJoin. *) open Error open Dynamic_stack open Code_util_tj open Code_selection_context open Execution_context open Xquery_algebra_ast open Xquery_algebra_ast_util open Datatypes open Dm_types open Dm_atomic open Dm open Dm_util open Physical_item open Physical_item_util open Physical_sequence open Physical_value_util open Physical_table open Physical_name_index open Code_util open Code_util_xpath open Cs_util open Code_util_materialize ALGORITHM : PathStack Holistic Twig Joins , Optimal XML Pattern Matching Bruno , Koudas , SIGMOD ' 02 Madison - USA PROCEDURE get_min_source -- PART OF PathStack Get the index or input whose first node has a minimal pre - order let get_min_source indices_curs () = let min = ref (-1) in let current = ref None in for i = 0 to (Array.length indices_curs) -1 do begin let next_item = Cursor.cursor_peek indices_curs.(i) in match next_item with | Some node_arr -> begin let node = getNode (Physical_util.get_item (cursor_of_sequence ( node_arr ))) in match !current with | Some node' -> if node_precedes node node' then ignore(current := Some node; min := i) | _ -> ignore(current := Some node; min := i) end | _ -> () end done; if !min < 0 then None else Some !min let pathstack input code_ctxt pattern stacks = let len = Array.length stacks in let retrieve_code = build_retrieve_dom_tuple_code code_ctxt input in let restore_array = build_restore_array pattern code_ctxt in let axes = get_axis_array pattern in fun () eval alg_ctxt curs -> begin let indices = get_name_indices_array code_ctxt pattern in let indices_curs = Array.map (fun index -> pre_cursor_of_name_index_at_pos index 1) indices in let all_sources = Array.append [| common_cursor_of_input_cursor curs retrieve_code |] indices_curs in let source_cursor = Cursor.cursor_of_function (get_min_source all_sources) in let item_fun src = begin let item = Cursor.cursor_next all_sources.(src) in let node = getNode (Physical_util.get_item (cursor_of_sequence item)) in let nextL = pre node in let nextR = post node in for i = 0 to len -1 do while not(empty stacks.(i)) && ((get_top_post_from_stack stacks.(i)) < nextR) do ignore(pop stacks.(i)) done done; let parent_node_index = get_parent_node_index pattern pattern.(src) in if parent_node_index < 0 then push stacks.(src) (item, -1, nextL, nextR) else push stacks.(src) (item, (stacks.(parent_node_index).size), nextL, nextR); let output = ref [] in if (is_leaf_node pattern pattern.(src)) then begin output := show_solutions pattern axes stacks src 0; ignore(pop stacks.(src)); end; !output end in let restore_intermed list = Warning , this XPath hack prevents duplicates to occur in the replace by duplicat elim over the output fields - Philippe let list' = match list with | hd::tl -> [hd] | _ -> list in Cursor.cursor_map (restore_tuple restore_array) (Cursor.cursor_of_list list') in Cursor.cursor_map_concat restore_intermed (Cursor.cursor_map item_fun source_cursor) end let build_holistic_tuple_tree_pattern_code code_ctxt input pattern = 1 . create field accessor and field restore functions let output_fields = get_restored_outputs_from_twig_pattern pattern in let _ = List.map (add_tuple_reference code_ctxt) output_fields in 2 . create the stack structure let dummy = (sequence_empty(), (-1), (-1), (-1)) in let stacks = Array.init (Array.length pattern) (fun i -> Dynamic_stack.make 16 dummy) in 3 . the algorithm pathstack input code_ctxt pattern stacks
2a5edc2dd75159f3ad4a970382a5f9e66b223879e4f1c9c60ffc2ff50e215474
froggey/Mezzano
spy.lisp
;;;; Spy ;;;; into the internal state of the compositor . (defpackage :mezzano.gui.spy (:use :cl) (:export #:spy #:spawn) (:local-nicknames (:sync :mezzano.sync) (:gui :mezzano.gui) (:comp :mezzano.gui.compositor) (:font :mezzano.gui.font) (:widgets :mezzano.gui.widgets) (:sup :mezzano.supervisor))) (in-package :mezzano.gui.spy) (defclass spy-window () ((%window :initarg :window :reader window) (%redraw :initarg :redraw :accessor redraw) (%frame :initarg :frame :reader frame) (%text-pane :initarg :text-pane :reader text-pane)) (:default-initargs :redraw t)) (defgeneric dispatch-event (app event) (:method (app event))) (defmethod dispatch-event (app (event comp:window-activation-event)) (let ((frame (frame app))) (setf (widgets:activep frame) (comp:state event)) (widgets:draw-frame frame))) (defmethod dispatch-event (app (event comp:mouse-event)) (handler-case (widgets:frame-mouse-event (frame app) event) (widgets:close-button-clicked () (throw 'quit nil)))) (defmethod dispatch-event (app (event comp:resize-request-event)) (let* ((win (window app)) (old-width (comp:width win)) (old-height (comp:height win)) (new-width (max 100 (comp:width event))) (new-height (max 100 (comp:height event)))) (when (or (not (eql old-width new-width)) (not (eql old-height new-height))) (let ((new-framebuffer (mezzano.gui:make-surface new-width new-height))) (widgets:resize-frame (frame app) new-framebuffer) (comp:resize-window win new-framebuffer :origin (comp:resize-origin event)))))) (defmethod dispatch-event (app (event comp:resize-event)) (let* ((fb (comp:window-buffer (window app))) (new-width (mezzano.gui:surface-width fb)) (new-height (mezzano.gui:surface-height fb))) (multiple-value-bind (left right top bottom) (widgets:frame-size (frame app)) (widgets:resize-widget (text-pane app) fb left top (- new-width left right) (- new-height top bottom)))) (setf (redraw app) t)) (defmethod dispatch-event (app (event comp:window-close-event)) (throw 'quit nil)) (defmethod dispatch-event (app (event comp:quit-event)) (throw 'quit nil)) (defparameter *spy-refresh-interval* 1/5) (defparameter *spy-immediate-mode* nil "Enable instant updates whenever the compositor itself receives an event.") (defparameter *spy-report-mouse-window* t "If true, describe the mouse window, not the active window.") (defun update-spy (spy) (declare (ignore spy)) (let ((*print-pretty* t)) (format t "Mouse: ~Dx~D ~6,'0B ptr: ~S~%" comp::*mouse-x* comp::*mouse-y* comp::*mouse-buttons* comp::*mouse-pointer*) (format t "Mouse win: ~S~%" comp::(window-at-point *mouse-x* *mouse-y*)) (format t "Prev mouse win: ~S~%" comp::*previous-mouse-window*) (format t "Drag ~S~% ~Dx~D origin: ~Dx~D passive: ~S resize: ~S ~Dx~D ~Dx~D~%" comp::*drag-window* comp::*drag-x* comp::*drag-y* comp::*drag-x-origin* comp::*drag-y-origin* comp::*passive-drag* comp::*resize-origin* comp::*prev-resize-rect-x* comp::*prev-resize-rect-y* comp::*prev-resize-rect-w* comp::*prev-resize-rect-h*) (format t "Keymap: ~S~%" comp::*current-keymap*) (format t "Key mods: ~:S~%" comp::*keyboard-modifier-state*) (format t "Windows: ~:S~%" comp::*window-list*) (format t "M-Tab ~S ~:S~%" comp::*m-tab-active* comp::*m-tab-list*) (format t "Postprocess: ~S~%" comp::*postprocess-matrix*) (format t "Active window: ~S~%" comp::*active-window*) (describe (if *spy-report-mouse-window* comp::(window-at-point *mouse-x* *mouse-y*) comp::*active-window*)))) (defun spy () (with-simple-restart (abort "Close spy") (catch 'quit (let ((font (font:open-font font:*default-monospace-font* font:*default-monospace-font-size*)) (mbox (sync:make-mailbox :capacity 50))) (comp:with-window (window mbox 640 700) (let* ((framebuffer (comp:window-buffer window)) (frame (make-instance 'widgets:frame :framebuffer framebuffer :title "Spy" :close-button-p t :resizablep t :damage-function (widgets:default-damage-function window) :set-cursor-function (widgets:default-cursor-function window))) (spy (make-instance 'spy-window :window window :frame frame)) (text-pane (make-instance 'widgets:text-widget :font font :framebuffer framebuffer :x-position (nth-value 0 (widgets:frame-size frame)) :y-position (nth-value 2 (widgets:frame-size frame)) :width (- (comp:width window) (nth-value 0 (widgets:frame-size frame)) (nth-value 1 (widgets:frame-size frame))) :height (- (comp:height window) (nth-value 2 (widgets:frame-size frame)) (nth-value 3 (widgets:frame-size frame))) :damage-function (lambda (&rest args) (declare (ignore args)) (loop (let ((ev (sync:mailbox-receive mbox :wait-p nil))) (when (not ev) (return)) (dispatch-event spy ev))))))) (setf (comp:name window) spy) (setf (slot-value spy '%text-pane) text-pane) (widgets:draw-frame frame) (comp:damage-window window 0 0 (comp:width window) (comp:height window)) (loop (when (redraw spy) (let ((*standard-output* text-pane)) (setf (redraw spy) nil) (widgets:reset *standard-output*) (ignore-errors (update-spy spy)) (comp:damage-window window 0 0 (comp:width window) (comp:height window)))) (when (not (redraw spy)) ;; Spy on the compositor's event queue too, so we refresh ;; immediately when it gets an input or damage event. (if *spy-immediate-mode* (sync:wait-for-objects-with-timeout *spy-refresh-interval* comp::*event-queue* mbox) (sync:wait-for-objects-with-timeout *spy-refresh-interval* mbox)) (let ((evt (sync:mailbox-receive mbox :wait-p nil))) (cond (evt (dispatch-event spy evt)) (t (setf (redraw spy) t)))))))))))) (defun spawn () (mezzano.supervisor:make-thread 'spy :name "Spy" :initial-bindings `((*terminal-io* ,(make-instance 'mezzano.gui.popup-io-stream:popup-io-stream :title "Spy console")) (*standard-input* ,(make-synonym-stream '*terminal-io*)) (*standard-output* ,(make-synonym-stream '*terminal-io*)) (*error-output* ,(make-synonym-stream '*terminal-io*)) (*trace-output* ,(make-synonym-stream '*terminal-io*)) (*debug-io* ,(make-synonym-stream '*terminal-io*)) (*query-io* ,(make-synonym-stream '*terminal-io*)))))
null
https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/applications/spy.lisp
lisp
Spy Spy on the compositor's event queue too, so we refresh immediately when it gets an input or damage event.
into the internal state of the compositor . (defpackage :mezzano.gui.spy (:use :cl) (:export #:spy #:spawn) (:local-nicknames (:sync :mezzano.sync) (:gui :mezzano.gui) (:comp :mezzano.gui.compositor) (:font :mezzano.gui.font) (:widgets :mezzano.gui.widgets) (:sup :mezzano.supervisor))) (in-package :mezzano.gui.spy) (defclass spy-window () ((%window :initarg :window :reader window) (%redraw :initarg :redraw :accessor redraw) (%frame :initarg :frame :reader frame) (%text-pane :initarg :text-pane :reader text-pane)) (:default-initargs :redraw t)) (defgeneric dispatch-event (app event) (:method (app event))) (defmethod dispatch-event (app (event comp:window-activation-event)) (let ((frame (frame app))) (setf (widgets:activep frame) (comp:state event)) (widgets:draw-frame frame))) (defmethod dispatch-event (app (event comp:mouse-event)) (handler-case (widgets:frame-mouse-event (frame app) event) (widgets:close-button-clicked () (throw 'quit nil)))) (defmethod dispatch-event (app (event comp:resize-request-event)) (let* ((win (window app)) (old-width (comp:width win)) (old-height (comp:height win)) (new-width (max 100 (comp:width event))) (new-height (max 100 (comp:height event)))) (when (or (not (eql old-width new-width)) (not (eql old-height new-height))) (let ((new-framebuffer (mezzano.gui:make-surface new-width new-height))) (widgets:resize-frame (frame app) new-framebuffer) (comp:resize-window win new-framebuffer :origin (comp:resize-origin event)))))) (defmethod dispatch-event (app (event comp:resize-event)) (let* ((fb (comp:window-buffer (window app))) (new-width (mezzano.gui:surface-width fb)) (new-height (mezzano.gui:surface-height fb))) (multiple-value-bind (left right top bottom) (widgets:frame-size (frame app)) (widgets:resize-widget (text-pane app) fb left top (- new-width left right) (- new-height top bottom)))) (setf (redraw app) t)) (defmethod dispatch-event (app (event comp:window-close-event)) (throw 'quit nil)) (defmethod dispatch-event (app (event comp:quit-event)) (throw 'quit nil)) (defparameter *spy-refresh-interval* 1/5) (defparameter *spy-immediate-mode* nil "Enable instant updates whenever the compositor itself receives an event.") (defparameter *spy-report-mouse-window* t "If true, describe the mouse window, not the active window.") (defun update-spy (spy) (declare (ignore spy)) (let ((*print-pretty* t)) (format t "Mouse: ~Dx~D ~6,'0B ptr: ~S~%" comp::*mouse-x* comp::*mouse-y* comp::*mouse-buttons* comp::*mouse-pointer*) (format t "Mouse win: ~S~%" comp::(window-at-point *mouse-x* *mouse-y*)) (format t "Prev mouse win: ~S~%" comp::*previous-mouse-window*) (format t "Drag ~S~% ~Dx~D origin: ~Dx~D passive: ~S resize: ~S ~Dx~D ~Dx~D~%" comp::*drag-window* comp::*drag-x* comp::*drag-y* comp::*drag-x-origin* comp::*drag-y-origin* comp::*passive-drag* comp::*resize-origin* comp::*prev-resize-rect-x* comp::*prev-resize-rect-y* comp::*prev-resize-rect-w* comp::*prev-resize-rect-h*) (format t "Keymap: ~S~%" comp::*current-keymap*) (format t "Key mods: ~:S~%" comp::*keyboard-modifier-state*) (format t "Windows: ~:S~%" comp::*window-list*) (format t "M-Tab ~S ~:S~%" comp::*m-tab-active* comp::*m-tab-list*) (format t "Postprocess: ~S~%" comp::*postprocess-matrix*) (format t "Active window: ~S~%" comp::*active-window*) (describe (if *spy-report-mouse-window* comp::(window-at-point *mouse-x* *mouse-y*) comp::*active-window*)))) (defun spy () (with-simple-restart (abort "Close spy") (catch 'quit (let ((font (font:open-font font:*default-monospace-font* font:*default-monospace-font-size*)) (mbox (sync:make-mailbox :capacity 50))) (comp:with-window (window mbox 640 700) (let* ((framebuffer (comp:window-buffer window)) (frame (make-instance 'widgets:frame :framebuffer framebuffer :title "Spy" :close-button-p t :resizablep t :damage-function (widgets:default-damage-function window) :set-cursor-function (widgets:default-cursor-function window))) (spy (make-instance 'spy-window :window window :frame frame)) (text-pane (make-instance 'widgets:text-widget :font font :framebuffer framebuffer :x-position (nth-value 0 (widgets:frame-size frame)) :y-position (nth-value 2 (widgets:frame-size frame)) :width (- (comp:width window) (nth-value 0 (widgets:frame-size frame)) (nth-value 1 (widgets:frame-size frame))) :height (- (comp:height window) (nth-value 2 (widgets:frame-size frame)) (nth-value 3 (widgets:frame-size frame))) :damage-function (lambda (&rest args) (declare (ignore args)) (loop (let ((ev (sync:mailbox-receive mbox :wait-p nil))) (when (not ev) (return)) (dispatch-event spy ev))))))) (setf (comp:name window) spy) (setf (slot-value spy '%text-pane) text-pane) (widgets:draw-frame frame) (comp:damage-window window 0 0 (comp:width window) (comp:height window)) (loop (when (redraw spy) (let ((*standard-output* text-pane)) (setf (redraw spy) nil) (widgets:reset *standard-output*) (ignore-errors (update-spy spy)) (comp:damage-window window 0 0 (comp:width window) (comp:height window)))) (when (not (redraw spy)) (if *spy-immediate-mode* (sync:wait-for-objects-with-timeout *spy-refresh-interval* comp::*event-queue* mbox) (sync:wait-for-objects-with-timeout *spy-refresh-interval* mbox)) (let ((evt (sync:mailbox-receive mbox :wait-p nil))) (cond (evt (dispatch-event spy evt)) (t (setf (redraw spy) t)))))))))))) (defun spawn () (mezzano.supervisor:make-thread 'spy :name "Spy" :initial-bindings `((*terminal-io* ,(make-instance 'mezzano.gui.popup-io-stream:popup-io-stream :title "Spy console")) (*standard-input* ,(make-synonym-stream '*terminal-io*)) (*standard-output* ,(make-synonym-stream '*terminal-io*)) (*error-output* ,(make-synonym-stream '*terminal-io*)) (*trace-output* ,(make-synonym-stream '*terminal-io*)) (*debug-io* ,(make-synonym-stream '*terminal-io*)) (*query-io* ,(make-synonym-stream '*terminal-io*)))))
f3d04718248bef98e9226383e16f91930e0ae4dc74fa9f9dafe1835e82e50db2
ddssff/refact-global-hse
LoadModule.hs
# LANGUAGE FlexibleInstances , PackageImports , ScopedTypeVariables , TemplateHaskell , TypeSynonymInstances # module LoadModule ( loadModule , loadModules , Annot ) where import Control.Lens (view) import CPP (extensionsForHSEParser, GHCOpts, applyHashDefine, enabled, hashDefines) import qualified CPP (defaultCpphsOptions, parseFileWithCommentsAndCPP) import Control.Monad.Trans (MonadIO(liftIO)) import Data.Generics (everywhere, mkT) import Data.List (groupBy, intercalate) import Debug.Trace (trace) import Language.Haskell.Exts.Syntax (Module(..), ModuleHead(ModuleHead), ModuleName(ModuleName)) import Language.Haskell.Exts.Extension (Extension(EnableExtension)) import Language.Haskell.Exts.Parser as Exts (defaultParseMode, fromParseResult, ParseMode(extensions, parseFilename, fixities)) import Language.Haskell.Exts.SrcLoc (SrcSpanInfo(..)) import Language.Haskell.Names (annotate, resolve, Scoped(..)) import Language.Haskell.Names.Imports (importTable) import Language.Haskell.Names.ModuleSymbols (moduleTable) import Language.Preprocessor.Cpphs (BoolOptions(locations), CpphsOptions(..)) import ModuleInfo (ModuleInfo(..)) import ModuleKey (ModuleKey(..)) import SrcLoc (fixEnds, fixSpan, mapTopAnnotations, spanOfText) import System.Directory (canonicalizePath) import System.FilePath (joinPath, makeRelative, splitDirectories, splitExtension, takeDirectory) import Utils (EZPrint(ezPrint)) type Annot = Scoped SrcSpanInfo instance EZPrint Annot where ezPrint (Scoped _ x) = ezPrint x -- | Load a list of modules and compute their global scoping info. loadModules :: GHCOpts -> [FilePath] -> IO [ModuleInfo Annot] loadModules opts paths = do t1 <$> addScoping <$> mapM (loadModule opts) paths where t1 :: [ModuleInfo l] -> [ModuleInfo l] t1 modules = trace ("modules loaded: " ++ show (map ezPrint modules)) modules addScoping :: [ModuleInfo SrcSpanInfo] -> [ModuleInfo (Scoped SrcSpanInfo)] addScoping mods = map (\m -> m {_module = annotate env (_module m), _moduleGlobals = moduleTable (importTable env (_module m)) (_module m)}) mods where env = resolve (map _module mods) mempty loadModule :: GHCOpts -> FilePath -> IO (ModuleInfo SrcSpanInfo) loadModule opts path = do moduleText <- liftIO $ readFile path let cpphsOptions' = foldr applyHashDefine cpphsOptions (view hashDefines opts) (parsed', comments, _processed) <- Exts.fromParseResult <$> CPP.parseFileWithCommentsAndCPP cpphsOptions' mode path let parsed = mapTopAnnotations (fixEnds comments moduleText) $ everywhere (mkT fixSpan) parsed' -- liftIO $ writeFile (path ++ ".cpp") processed -- putStr processed validateParseResults parsed comments processed -- moduleText key <- moduleKey path parsed -- putStrLn ("loaded " ++ prettyShow key) pure $ ModuleInfo { _moduleKey = key , _module = parsed , _moduleComments = comments , _modulePath = makeRelative (case key of ModuleKey {_moduleTop = top} -> top ModuleFullPath p -> takeDirectory p) path , _moduleText = moduleText , _moduleSpan = spanOfText path moduleText , _moduleGlobals = mempty } where mode = Exts.defaultParseMode {Exts.extensions = map EnableExtension (view enabled opts ++ extensionsForHSEParser), Exts.parseFilename = path, Exts.fixities = Nothing } -- | Turn of the locations flag. This means simple #if macros will not -- affect the line numbers of the output text, so we can use the resulting SrcSpan info on the original text . Macro expansions -- could still mess this up. cpphsOptions :: CpphsOptions cpphsOptions = CPP.defaultCpphsOptions { boolopts = ( boolopts CPP.defaultCpphsOptions ) { locations = False } } -- | Compute the module key from a filepath (absolute or relative to -- ".") and the parsed module. moduleKey :: FilePath -> Module SrcSpanInfo -> IO ModuleKey moduleKey _ (XmlPage {}) = error "XmlPage" moduleKey _ (XmlHybrid {}) = error "XmlHybrid" moduleKey path (Module _ Nothing _ _ _) = do ModuleFullPath <$> canonicalizePath path moduleKey path (Module _ (Just (ModuleHead _ (ModuleName _ name) _ _)) _ _ _) = do canonicalizePath path >>= pure . makeKey where makeKey path' = let name' = splitModuleName name (path'', ext) = splitExtension path' dirs = splitDirectories path'' (dirs', name'') = splitAt (length dirs - length name') dirs in case (name'' == name') of False -> ModuleFullPath path' True -> ModuleKey {_moduleTop = joinPath dirs', _moduleName = ModuleName () (intercalate "." name''), _moduleExt = ext} splitModuleName = filter (/= ".") . groupBy (\a b -> (a /= '.') && (b /= '.'))
null
https://raw.githubusercontent.com/ddssff/refact-global-hse/519a017009cae8aa1a3db1b46eb560d76bd9895d/tests/expected/decl2/LoadModule.hs
haskell
| Load a list of modules and compute their global scoping info. liftIO $ writeFile (path ++ ".cpp") processed putStr processed moduleText putStrLn ("loaded " ++ prettyShow key) | Turn of the locations flag. This means simple #if macros will not affect the line numbers of the output text, so we can use the could still mess this up. | Compute the module key from a filepath (absolute or relative to ".") and the parsed module.
# LANGUAGE FlexibleInstances , PackageImports , ScopedTypeVariables , TemplateHaskell , TypeSynonymInstances # module LoadModule ( loadModule , loadModules , Annot ) where import Control.Lens (view) import CPP (extensionsForHSEParser, GHCOpts, applyHashDefine, enabled, hashDefines) import qualified CPP (defaultCpphsOptions, parseFileWithCommentsAndCPP) import Control.Monad.Trans (MonadIO(liftIO)) import Data.Generics (everywhere, mkT) import Data.List (groupBy, intercalate) import Debug.Trace (trace) import Language.Haskell.Exts.Syntax (Module(..), ModuleHead(ModuleHead), ModuleName(ModuleName)) import Language.Haskell.Exts.Extension (Extension(EnableExtension)) import Language.Haskell.Exts.Parser as Exts (defaultParseMode, fromParseResult, ParseMode(extensions, parseFilename, fixities)) import Language.Haskell.Exts.SrcLoc (SrcSpanInfo(..)) import Language.Haskell.Names (annotate, resolve, Scoped(..)) import Language.Haskell.Names.Imports (importTable) import Language.Haskell.Names.ModuleSymbols (moduleTable) import Language.Preprocessor.Cpphs (BoolOptions(locations), CpphsOptions(..)) import ModuleInfo (ModuleInfo(..)) import ModuleKey (ModuleKey(..)) import SrcLoc (fixEnds, fixSpan, mapTopAnnotations, spanOfText) import System.Directory (canonicalizePath) import System.FilePath (joinPath, makeRelative, splitDirectories, splitExtension, takeDirectory) import Utils (EZPrint(ezPrint)) type Annot = Scoped SrcSpanInfo instance EZPrint Annot where ezPrint (Scoped _ x) = ezPrint x loadModules :: GHCOpts -> [FilePath] -> IO [ModuleInfo Annot] loadModules opts paths = do t1 <$> addScoping <$> mapM (loadModule opts) paths where t1 :: [ModuleInfo l] -> [ModuleInfo l] t1 modules = trace ("modules loaded: " ++ show (map ezPrint modules)) modules addScoping :: [ModuleInfo SrcSpanInfo] -> [ModuleInfo (Scoped SrcSpanInfo)] addScoping mods = map (\m -> m {_module = annotate env (_module m), _moduleGlobals = moduleTable (importTable env (_module m)) (_module m)}) mods where env = resolve (map _module mods) mempty loadModule :: GHCOpts -> FilePath -> IO (ModuleInfo SrcSpanInfo) loadModule opts path = do moduleText <- liftIO $ readFile path let cpphsOptions' = foldr applyHashDefine cpphsOptions (view hashDefines opts) (parsed', comments, _processed) <- Exts.fromParseResult <$> CPP.parseFileWithCommentsAndCPP cpphsOptions' mode path let parsed = mapTopAnnotations (fixEnds comments moduleText) $ everywhere (mkT fixSpan) parsed' key <- moduleKey path parsed pure $ ModuleInfo { _moduleKey = key , _module = parsed , _moduleComments = comments , _modulePath = makeRelative (case key of ModuleKey {_moduleTop = top} -> top ModuleFullPath p -> takeDirectory p) path , _moduleText = moduleText , _moduleSpan = spanOfText path moduleText , _moduleGlobals = mempty } where mode = Exts.defaultParseMode {Exts.extensions = map EnableExtension (view enabled opts ++ extensionsForHSEParser), Exts.parseFilename = path, Exts.fixities = Nothing } resulting SrcSpan info on the original text . Macro expansions cpphsOptions :: CpphsOptions cpphsOptions = CPP.defaultCpphsOptions { boolopts = ( boolopts CPP.defaultCpphsOptions ) { locations = False } } moduleKey :: FilePath -> Module SrcSpanInfo -> IO ModuleKey moduleKey _ (XmlPage {}) = error "XmlPage" moduleKey _ (XmlHybrid {}) = error "XmlHybrid" moduleKey path (Module _ Nothing _ _ _) = do ModuleFullPath <$> canonicalizePath path moduleKey path (Module _ (Just (ModuleHead _ (ModuleName _ name) _ _)) _ _ _) = do canonicalizePath path >>= pure . makeKey where makeKey path' = let name' = splitModuleName name (path'', ext) = splitExtension path' dirs = splitDirectories path'' (dirs', name'') = splitAt (length dirs - length name') dirs in case (name'' == name') of False -> ModuleFullPath path' True -> ModuleKey {_moduleTop = joinPath dirs', _moduleName = ModuleName () (intercalate "." name''), _moduleExt = ext} splitModuleName = filter (/= ".") . groupBy (\a b -> (a /= '.') && (b /= '.'))
8abcd86bb1d73556a826db275bcb597ae74537276261957362742bbb24f54f2b
wfnuser/sicp-solutions
e3-1.scm
(define (make-accumulator sum) (lambda (step) (begin (set! sum (+ sum step)) sum)) ) (define A (make-accumulator 5)) (A 10) (A 10)
null
https://raw.githubusercontent.com/wfnuser/sicp-solutions/2c94b28d8ee004dcbfe7311f866e5a346ee01d12/ch3/e3-1.scm
scheme
(define (make-accumulator sum) (lambda (step) (begin (set! sum (+ sum step)) sum)) ) (define A (make-accumulator 5)) (A 10) (A 10)
54cde2d640179472a7d51046bb7b4ac644b80b50bc641ff70ac821542cbc2ead
spurious/sagittarius-scheme-mirror
time-private.scm
-*- mode : scheme ; coding : utf-8 ; -*- ;;; ;;; sagittarius/time-private.scm - private library of time related libraries ;;; Copyright ( c ) 2010 - 2015 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; (library (sagittarius time-private) ;; exports all C procedures + alpha (export make-time time? current-time time-type time-nanosecond time-second set-time-type! set-time-nanosecond! set-time-second! copy-time time-resolution current-time time->seconds seconds->time time<=? time<? time=? time>=? time>? time-difference time-difference! add-duration add-duration! subtract-duration subtract-duration! leap-second-delta +leap-second-table+ get-time-of-day ;; timezone %local-timezone-name ;; time-error &time-error make-time-error time-error? time-error-type ) (import (core) (core conditions) (sagittarius) (sagittarius dynamic-module) (sagittarius time-util)) (load-dynamic-module "sagittarius--time") (define-condition-type &time-error &error make-time-error time-error? (type time-error-type)) (define-constant +leap-second-table+ (include "leap-table.scm")) (define (leap-second-delta utc-seconds) (letrec ( (lsd (lambda (table) (cond ((>= utc-seconds (caar table)) (cdar table)) (else (lsd (cdr table)))))) ) (if (< utc-seconds (* (- 1972 1970) 365 tm:sid)) 0 (lsd +leap-second-table+)))) (define (current-time :optional (type 'time-utc)) (define (make-time-from-times type times) (let ((cpu (+ (vector-ref times 0) (vector-ref times 1))) (tick (vector-ref times 2))) ;; we may loose some of the precesion but since ;; make-time doesn't accept inexact or rational ;; numbers, we don't have any choice. (make-time type (* (div tm:nano tick) (mod cpu tick)) (div cpu tick)))) (let-values (((sec usec) (get-time-of-day))) (case type ((time-utc) (make-time type (* usec 1000) sec)) ((time-tai) (make-time type (* usec 1000) (+ sec (leap-second-delta sec)))) ((time-monotonic) (make-time type (* usec 1000) (+ sec (leap-second-delta sec)))) ((time-process) (make-time-from-times type (get-process-times))) ((time-thread) (make-time-from-times type (get-thread-times))) (else (error 'current-time "TIME-ERROR type current-time: invalid clock type" type))))) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/ext/time/sagittarius/time-private.scm
scheme
coding : utf-8 ; -*- sagittarius/time-private.scm - private library of time related libraries Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. exports all C procedures + alpha timezone time-error we may loose some of the precesion but since make-time doesn't accept inexact or rational numbers, we don't have any choice.
Copyright ( c ) 2010 - 2015 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING (library (sagittarius time-private) (export make-time time? current-time time-type time-nanosecond time-second set-time-type! set-time-nanosecond! set-time-second! copy-time time-resolution current-time time->seconds seconds->time time<=? time<? time=? time>=? time>? time-difference time-difference! add-duration add-duration! subtract-duration subtract-duration! leap-second-delta +leap-second-table+ get-time-of-day %local-timezone-name &time-error make-time-error time-error? time-error-type ) (import (core) (core conditions) (sagittarius) (sagittarius dynamic-module) (sagittarius time-util)) (load-dynamic-module "sagittarius--time") (define-condition-type &time-error &error make-time-error time-error? (type time-error-type)) (define-constant +leap-second-table+ (include "leap-table.scm")) (define (leap-second-delta utc-seconds) (letrec ( (lsd (lambda (table) (cond ((>= utc-seconds (caar table)) (cdar table)) (else (lsd (cdr table)))))) ) (if (< utc-seconds (* (- 1972 1970) 365 tm:sid)) 0 (lsd +leap-second-table+)))) (define (current-time :optional (type 'time-utc)) (define (make-time-from-times type times) (let ((cpu (+ (vector-ref times 0) (vector-ref times 1))) (tick (vector-ref times 2))) (make-time type (* (div tm:nano tick) (mod cpu tick)) (div cpu tick)))) (let-values (((sec usec) (get-time-of-day))) (case type ((time-utc) (make-time type (* usec 1000) sec)) ((time-tai) (make-time type (* usec 1000) (+ sec (leap-second-delta sec)))) ((time-monotonic) (make-time type (* usec 1000) (+ sec (leap-second-delta sec)))) ((time-process) (make-time-from-times type (get-process-times))) ((time-thread) (make-time-from-times type (get-thread-times))) (else (error 'current-time "TIME-ERROR type current-time: invalid clock type" type))))) )
8585ac2e1b02f1a03e2ab03090d8dd089bc09f20e8c026ceb71ae670a6ae949b
NicolasT/landlock-hs
Version.hs
module System.Landlock.Version ( Version (..), version1, version2, version3, ) where -- | Representation of a Landlock ABI version as reported by the kernel. newtype Version = Version { -- | Get the numerical version. getVersion :: Word } deriving (Show, Eq, Ord) All ABI versions supported by this library should be exposed as a value . | ABI version 1 . version1 :: Version version1 = Version 1 | ABI version 2 . version2 :: Version version2 = Version 2 | ABI version 3 . version3 :: Version version3 = Version 3
null
https://raw.githubusercontent.com/NicolasT/landlock-hs/27d2d95478f8c85cfbf4025bb41d57d0e57d670f/landlock/internal/System/Landlock/Version.hs
haskell
| Representation of a Landlock ABI version as reported by the kernel. | Get the numerical version.
module System.Landlock.Version ( Version (..), version1, version2, version3, ) where newtype Version = Version getVersion :: Word } deriving (Show, Eq, Ord) All ABI versions supported by this library should be exposed as a value . | ABI version 1 . version1 :: Version version1 = Version 1 | ABI version 2 . version2 :: Version version2 = Version 2 | ABI version 3 . version3 :: Version version3 = Version 3
5f74d3a9de5c0d4611a85965b8c3a41510eaf7cb696b2f82e35113e130859841
ocaml-omake/omake
lm_map_sig.ml
(************************************************************************ * Maps. *) module type OrderedType = sig type t val compare : t -> t -> int end module type LmMapBase = sig type key type 'a t val empty : 'a t val is_empty : 'a t -> bool val cardinal : 'a t -> int val add : 'a t -> key -> 'a -> 'a t val find : 'a t -> key -> 'a val remove : 'a t -> key -> 'a t val mem : 'a t -> key -> bool val find_key : 'a t -> key -> key option val iter : (key -> 'a -> unit) -> 'a t -> unit val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val fold : ('a -> key -> 'b -> 'a) -> 'a -> 'b t -> 'a val fold_map : ('a -> key -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t val forall2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool val forall : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val find_iter : (key -> 'a -> 'b option) -> 'a t -> 'b option val isect_mem : 'a t -> (key -> bool) -> 'a t val choose : 'a t -> key * 'a val filter_add : 'a t -> key -> ('a option -> 'a) -> 'a t val filter_remove : 'a t -> key -> ('a -> 'a option) -> 'a t val replace : 'a t -> key -> ('a -> 'a) -> 'a t val keys : 'a t -> key list val data : 'a t -> 'a list val add_list : 'a t -> (key * 'a) list -> 'a t val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool end module type LmMap = sig include LmMapBase val union : (key -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t end (* * This is the backwards-compatible version. *) module type S = sig type key type 'a t val empty : 'a t val add : key -> 'a -> 'a t -> 'a t val find : key -> 'a t -> 'a val remove : key -> 'a t -> 'a t val mem : key -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b end module type LmMapList = sig include LmMapBase val filter : 'a t -> key -> ('a list -> 'a list) -> 'a t val find_all : 'a t -> key -> 'a list val find_all_partial : 'a t -> key -> 'a list val iter_all : (key -> 'a list -> unit) -> 'a t -> unit val mapi_all : (key -> 'a list -> 'b list) -> 'a t -> 'b t val fold_all : ('a -> key -> 'b list -> 'a) -> 'a -> 'b t -> 'a val data_all : 'a t -> 'a list list val union : (key -> 'a list -> 'a list -> 'a list) -> 'a t -> 'a t -> 'a t val choose_all : 'a t -> key * 'a list end (************************************************************************ * Tables *) (* * The record of methods. *) type ('elt, 'data, 'table) table_methods = { empty : 'table; make : 'elt -> 'data list -> 'table; is_empty : 'table -> bool; mem : 'table -> 'elt -> bool; add : 'table -> 'elt -> 'data -> 'table; replace : 'table -> 'elt -> 'data list -> 'table; find : 'table -> 'elt -> 'data; find_all : 'table -> 'elt -> 'data list; remove : 'table -> 'elt -> 'table; union : 'table -> 'table -> 'table; elements : 'table -> ('elt * 'data list) list; iter : ('elt -> 'data -> unit) -> 'table -> unit; fold_map : ('elt -> 'data -> 'table -> 'table) -> 'table -> 'table -> 'table; map : ('elt -> 'data -> 'data) -> 'table -> 'table; cardinal : 'table -> int; mem_filt : 'table -> 'elt list -> 'elt list; not_mem_filt : 'table -> 'elt list -> 'elt list; intersectp : 'table -> 'table -> bool; of_list : ('elt * 'data list) list -> 'table; list_of : 'table -> ('elt * 'data list) list; deletemax : 'table -> ('elt * 'data list * 'table); (* Debugging *) print : out_channel -> 'table -> unit } (* * Creation functions. *) type ('elt, 'data, 'table) table_create_type = (out_channel -> 'elt -> 'data list -> unit) -> (* printer *) ('elt -> 'elt -> int) -> (* comparison function *) ('data list -> 'data list -> 'data list) -> (* append during union *) ('elt, 'data, 'table) table_methods (* * Module containing a creation function. *) module type TableCreateSig = sig type ('elt, 'data) t val create : ('elt, 'data, ('elt, 'data) t) table_create_type end (* * Ordering module. *) module type TableBaseSig = sig type elt type data val print : out_channel -> elt -> data list -> unit val compare : elt -> elt -> int val append : data list -> data list -> data list end (* * These are the functions provided by the table. *) module type TableSig = sig type elt type data type t val empty : t val is_empty : t -> bool val length : t -> int val add : t -> elt -> data -> t val replace : t -> elt -> data list -> t val union : t -> t -> t val mem : t -> elt -> bool val find : t -> elt -> data last added first val remove : t -> elt -> t val iter : (elt -> data -> unit) -> t -> unit val fold_map : (elt -> data -> t -> t) -> t -> t -> t val map : (elt -> data -> data) -> t -> t val list_of : t -> (elt * data list) list val deletemax : t -> (elt * data list * t) val print : out_channel -> t -> unit end
null
https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/libmojave/lm_map_sig.ml
ocaml
*********************************************************************** * Maps. * This is the backwards-compatible version. *********************************************************************** * Tables * The record of methods. Debugging * Creation functions. printer comparison function append during union * Module containing a creation function. * Ordering module. * These are the functions provided by the table.
module type OrderedType = sig type t val compare : t -> t -> int end module type LmMapBase = sig type key type 'a t val empty : 'a t val is_empty : 'a t -> bool val cardinal : 'a t -> int val add : 'a t -> key -> 'a -> 'a t val find : 'a t -> key -> 'a val remove : 'a t -> key -> 'a t val mem : 'a t -> key -> bool val find_key : 'a t -> key -> key option val iter : (key -> 'a -> unit) -> 'a t -> unit val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val fold : ('a -> key -> 'b -> 'a) -> 'a -> 'b t -> 'a val fold_map : ('a -> key -> 'b -> 'a * 'c) -> 'a -> 'b t -> 'a * 'c t val forall2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool val forall : (key -> 'a -> bool) -> 'a t -> bool val exists : (key -> 'a -> bool) -> 'a t -> bool val find_iter : (key -> 'a -> 'b option) -> 'a t -> 'b option val isect_mem : 'a t -> (key -> bool) -> 'a t val choose : 'a t -> key * 'a val filter_add : 'a t -> key -> ('a option -> 'a) -> 'a t val filter_remove : 'a t -> key -> ('a -> 'a option) -> 'a t val replace : 'a t -> key -> ('a -> 'a) -> 'a t val keys : 'a t -> key list val data : 'a t -> 'a list val add_list : 'a t -> (key * 'a) list -> 'a t val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool end module type LmMap = sig include LmMapBase val union : (key -> 'a -> 'a -> 'a) -> 'a t -> 'a t -> 'a t end module type S = sig type key type 'a t val empty : 'a t val add : key -> 'a -> 'a t -> 'a t val find : key -> 'a t -> 'a val remove : key -> 'a t -> 'a t val mem : key -> 'a t -> bool val iter : (key -> 'a -> unit) -> 'a t -> unit val map : ('a -> 'b) -> 'a t -> 'b t val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b end module type LmMapList = sig include LmMapBase val filter : 'a t -> key -> ('a list -> 'a list) -> 'a t val find_all : 'a t -> key -> 'a list val find_all_partial : 'a t -> key -> 'a list val iter_all : (key -> 'a list -> unit) -> 'a t -> unit val mapi_all : (key -> 'a list -> 'b list) -> 'a t -> 'b t val fold_all : ('a -> key -> 'b list -> 'a) -> 'a -> 'b t -> 'a val data_all : 'a t -> 'a list list val union : (key -> 'a list -> 'a list -> 'a list) -> 'a t -> 'a t -> 'a t val choose_all : 'a t -> key * 'a list end type ('elt, 'data, 'table) table_methods = { empty : 'table; make : 'elt -> 'data list -> 'table; is_empty : 'table -> bool; mem : 'table -> 'elt -> bool; add : 'table -> 'elt -> 'data -> 'table; replace : 'table -> 'elt -> 'data list -> 'table; find : 'table -> 'elt -> 'data; find_all : 'table -> 'elt -> 'data list; remove : 'table -> 'elt -> 'table; union : 'table -> 'table -> 'table; elements : 'table -> ('elt * 'data list) list; iter : ('elt -> 'data -> unit) -> 'table -> unit; fold_map : ('elt -> 'data -> 'table -> 'table) -> 'table -> 'table -> 'table; map : ('elt -> 'data -> 'data) -> 'table -> 'table; cardinal : 'table -> int; mem_filt : 'table -> 'elt list -> 'elt list; not_mem_filt : 'table -> 'elt list -> 'elt list; intersectp : 'table -> 'table -> bool; of_list : ('elt * 'data list) list -> 'table; list_of : 'table -> ('elt * 'data list) list; deletemax : 'table -> ('elt * 'data list * 'table); print : out_channel -> 'table -> unit } type ('elt, 'data, 'table) table_create_type = ('elt, 'data, 'table) table_methods module type TableCreateSig = sig type ('elt, 'data) t val create : ('elt, 'data, ('elt, 'data) t) table_create_type end module type TableBaseSig = sig type elt type data val print : out_channel -> elt -> data list -> unit val compare : elt -> elt -> int val append : data list -> data list -> data list end module type TableSig = sig type elt type data type t val empty : t val is_empty : t -> bool val length : t -> int val add : t -> elt -> data -> t val replace : t -> elt -> data list -> t val union : t -> t -> t val mem : t -> elt -> bool val find : t -> elt -> data last added first val remove : t -> elt -> t val iter : (elt -> data -> unit) -> t -> unit val fold_map : (elt -> data -> t -> t) -> t -> t -> t val map : (elt -> data -> data) -> t -> t val list_of : t -> (elt * data list) list val deletemax : t -> (elt * data list * t) val print : out_channel -> t -> unit end
c0d69997c70c0471c53ac20c04b1b38dc9cc12050bdbc017c2a9012edcab3065
portkey-cloud/portkey
dev.clj
(ns dev (:require [ring-app.handler :as handler] [portkey.core :as pk] [org.httpkit.server :as http])) (defn start-local-server [] (http/run-server #'handler/app {:port 3000})) (defn deploy-lambda [] (pk/mount-ring! #'handler/app :path "/greetings"))
null
https://raw.githubusercontent.com/portkey-cloud/portkey/30c1e9170c5f6df85fc58d9c644a60cd1464a6d9/examples/ring-app/dev/dev.clj
clojure
(ns dev (:require [ring-app.handler :as handler] [portkey.core :as pk] [org.httpkit.server :as http])) (defn start-local-server [] (http/run-server #'handler/app {:port 3000})) (defn deploy-lambda [] (pk/mount-ring! #'handler/app :path "/greetings"))
ac366ab15aa3e1818f8c424162538ff67bf8ac375f41f58ce3ec97187d40b970
sjl/euler
polydivisible-numbers.lisp
(defpackage :euler/4d/polydivisible-numbers #.euler:*use*) (in-package :euler/4d/polydivisible-numbers) (setf lparallel:*kernel* (lparallel:make-kernel 30)) (deftype radix () '(integer 2 64)) (deftype digit () '(integer 1 63)) (deftype digit-set () '(unsigned-byte 63)) (defun make-digits (radix) (1- (expt 2 (1- radix)))) (defun-inline remove-digit (d digits) (declare (optimize speed) (type digit d) (type digit-set digits)) (dpb 0 (byte 1 (1- d)) digits)) (defun new-candidates (radix candidate remaining) (declare (optimize speed) (type radix radix) (type digit-set remaining) (type (integer 0) candidate)) (iterate (declare (iterate:declare-variables) (type (or (integer 0) digit) d) (type digit-set n more)) (for d :from 1) (for n :first remaining :then more) (for (values more d?) = (truncate n 2)) (unless (zerop d?) (collect (cons (+ (* radix candidate) d) (remove-digit d remaining)))) (until (zerop more)))) (defun find-polydivisible-numbers (radix) (labels ((recur (n candidate remaining) (when (or (zerop n) (dividesp candidate n)) (if (= n (1- radix)) (list candidate) (funcall (if (< n 2) #'lparallel:pmapcan ;; #'mapcan #'mapcan ) (lambda (next) (recur (1+ n) (car next) (cdr next))) (new-candidates radix candidate remaining)))))) (cons radix (recur 0 0 (make-digits radix)))))
null
https://raw.githubusercontent.com/sjl/euler/29cd8242172a2d11128439bb99217a0a859057ed/src/4d/polydivisible-numbers.lisp
lisp
#'mapcan
(defpackage :euler/4d/polydivisible-numbers #.euler:*use*) (in-package :euler/4d/polydivisible-numbers) (setf lparallel:*kernel* (lparallel:make-kernel 30)) (deftype radix () '(integer 2 64)) (deftype digit () '(integer 1 63)) (deftype digit-set () '(unsigned-byte 63)) (defun make-digits (radix) (1- (expt 2 (1- radix)))) (defun-inline remove-digit (d digits) (declare (optimize speed) (type digit d) (type digit-set digits)) (dpb 0 (byte 1 (1- d)) digits)) (defun new-candidates (radix candidate remaining) (declare (optimize speed) (type radix radix) (type digit-set remaining) (type (integer 0) candidate)) (iterate (declare (iterate:declare-variables) (type (or (integer 0) digit) d) (type digit-set n more)) (for d :from 1) (for n :first remaining :then more) (for (values more d?) = (truncate n 2)) (unless (zerop d?) (collect (cons (+ (* radix candidate) d) (remove-digit d remaining)))) (until (zerop more)))) (defun find-polydivisible-numbers (radix) (labels ((recur (n candidate remaining) (when (or (zerop n) (dividesp candidate n)) (if (= n (1- radix)) (list candidate) (funcall (if (< n 2) #'lparallel:pmapcan #'mapcan ) (lambda (next) (recur (1+ n) (car next) (cdr next))) (new-candidates radix candidate remaining)))))) (cons radix (recur 0 0 (make-digits radix)))))
0f511f242c4e0669437c3607163b1b982ad2b16a10d1055678787bf7411d35b0
jwiegley/notes
Bollu.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Bollu where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Control import Control.Monad.Trans.Cont import Data.Maybe import Data.Monoid import Debug.Trace from :: (a -> b) -> a -> Cont r b from f x = return (f x) to :: (forall r. a -> Cont r b) -> a -> b to f x = runCont (f x) id escapeGreater10 :: Int -> Cont Int Int escapeGreater10 num = trace "1..\n" $ do x <- trace "2..\n" $ callCC $ \k -> if num >= 10 then do trace "3..\n" $ k 0 else do trace "4..\n" $ return (num + 1) trace "5..\n" $ return x main = do let nums = fmap (\n -> runCont (escapeGreater10 n) id) [0..12] print nums
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Bollu.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
module Bollu where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Control import Control.Monad.Trans.Cont import Data.Maybe import Data.Monoid import Debug.Trace from :: (a -> b) -> a -> Cont r b from f x = return (f x) to :: (forall r. a -> Cont r b) -> a -> b to f x = runCont (f x) id escapeGreater10 :: Int -> Cont Int Int escapeGreater10 num = trace "1..\n" $ do x <- trace "2..\n" $ callCC $ \k -> if num >= 10 then do trace "3..\n" $ k 0 else do trace "4..\n" $ return (num + 1) trace "5..\n" $ return x main = do let nums = fmap (\n -> runCont (escapeGreater10 n) id) [0..12] print nums
bdaf896f7dac25b41029f7d62c3a364cf54b2298976cfac619b6f1f4c1dc8aa3
e-bigmoon/haskell-blog
Sharing_the_Manager.hs
#!/usr/bin/env stack -- stack script --resolver lts-17.3 {-# LANGUAGE OverloadedStrings #-} import Control.Concurrent.Async (Concurrently (..)) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import Data.Foldable (sequenceA_) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Client import Network.HTTP.Client.TLS import Network.HTTP.Types.Status (statusCode) main :: IO () main = do manager <- newManager tlsManagerSettings runConcurrently $ sequenceA_ $ replicate 16 $ Concurrently $ doSomething manager doSomething :: Manager -> IO () doSomething manager = do let request = "" response <- httpLbs request manager let msg = encodeUtf8 $ T.pack $ concat [ "Got a message with status code " , show $ statusCode $ responseStatus response , " with response body length " , show $ L.length $ responseBody response , "\n" ] -- Using bytestring-based output to avoid interleaving of string-based -- output S8.putStr msg
null
https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/appendix/ap4/Sharing_the_Manager.hs
haskell
stack script --resolver lts-17.3 # LANGUAGE OverloadedStrings # Using bytestring-based output to avoid interleaving of string-based output
#!/usr/bin/env stack import Control.Concurrent.Async (Concurrently (..)) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import Data.Foldable (sequenceA_) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Network.HTTP.Client import Network.HTTP.Client.TLS import Network.HTTP.Types.Status (statusCode) main :: IO () main = do manager <- newManager tlsManagerSettings runConcurrently $ sequenceA_ $ replicate 16 $ Concurrently $ doSomething manager doSomething :: Manager -> IO () doSomething manager = do let request = "" response <- httpLbs request manager let msg = encodeUtf8 $ T.pack $ concat [ "Got a message with status code " , show $ statusCode $ responseStatus response , " with response body length " , show $ L.length $ responseBody response , "\n" ] S8.putStr msg
32e43fd270021ad9147b37090b2229de3d4230860453f7c78e1d3c8e2087ab99
camllight/camllight
test_nats.ml
#open "test";; #open "nat";; #open "big_int";; #open "int_misc";; let ignore _ = ();; Can compare nats less than 2**32 let equal_nat n1 n2 = eq_nat n1 0 (num_digits_nat n1 0 1) n2 0 (num_digits_nat n2 0 1);; testing_function "num_digits_nat";; test 0 eq (false,not true);; test 1 eq (true,not false);; test 2 eq_int (let r = make_nat 2 in set_digit_nat r 1 1; num_digits_nat r 0 1,1);; testing_function "length_nat";; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 0 1; length_nat r,2);; testing_function "equal_nat";; let zero_nat = make_nat 1;; test 1 equal_nat (zero_nat, zero_nat);; test 2 equal_nat (nat_of_int 1, nat_of_int 1);; test 3 equal_nat (nat_of_int 2, nat_of_int 2);; test 4 eq (equal_nat (nat_of_int 2) (nat_of_int 3),false);; testing_function "incr_nat";; let zero = nat_of_int 0 in let res = incr_nat zero 0 1 1 in test 1 equal_nat (zero, nat_of_int 1) && test 2 eq (res,0);; let n = nat_of_int 1 in let res = incr_nat n 0 1 1 in test 3 equal_nat (n, nat_of_int 2) && test 4 eq (res,0);; testing_function "decr_nat";; let n = nat_of_int 1 in let res = decr_nat n 0 1 0 in test 1 equal_nat (n, nat_of_int 0) && test 2 eq (res,1);; let n = nat_of_int 2 in let res = decr_nat n 0 1 0 in test 3 equal_nat (n, nat_of_int 1) && test 4 eq (res,1);; testing_function "is_zero_nat";; let n = nat_of_int 1 in test 1 eq (is_zero_nat n 0 1,false) && test 2 eq (is_zero_nat (make_nat 1) 0 1, true) && test 3 eq (is_zero_nat (make_nat 2) 0 2, true) && (let r = make_nat 2 in set_digit_nat r 1 1; test 4 eq (is_zero_nat r 0 1, true)) ;; testing_function "sys_string_of_nat";; let l = match length_of_int with | 30 -> 4 | 62 -> 2 | _ -> failwith "bad int length";; let n = make_nat l;; test 1 eq_string (sys_string_of_nat 10 "" n 0 l "","0");; complement_nat n 0 l;; let s = function | 2 -> "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" | 3 -> "202201102121002021012000211012011021221022212021111001022110211020010021100121010" | 4 -> "3333333333333333333333333333333333333333333333333333333333333333" | 5 -> "11031110441201303134210404233413032443021130230130231310" | 6 -> "23053353530155550541354043543542243325553444410303" | 7 -> "3115512162124626343001006330151620356026315303" | 8 -> "3777777777777777777777777777777777777777777" | 9 -> "22642532235024164257285244038424203240533" | 10 -> "340282366920938463463374607431768211455" | 11 -> "1000A504186892265432152AA27A7929366352" | 12 -> "5916B64B41143526A777873841863A6A6993" | 13 -> "47168C9C477C94BA75A2BC735955C7AA138" | 14 -> "51A45CB9506962A31983DAC25409715D03" | 15 -> "7D491176809C28848A561186D4857D320" | 16 -> "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" | _ -> invalid_arg "Wrong base" in for i = 2 to 16 do let s' = sys_string_of_nat i "" n 0 l "" in let _ = test i eq_string (s', s i) in () done;; let s = "1833520974" in test 23 eq_string (string_of_nat (nat_of_string s), s) ;; let s = "18335209741833520974" in test 24 eq_string (string_of_nat (nat_of_string s), s) ;; testing_function "string_of_digit";; test 1 eq_string (string_of_digit (nat_of_big_int (big_int_of_string "123456e2")), "12345600");; testing_function "string_of_nat and sys_nat_of_string";; for i = 1 to 20 do let s = make_string i `0` in s.[0] <- `1`; ignore (test i eq_string (string_of_nat (sys_nat_of_string 10 s 0 i), s)) done;; let s = "3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333" in test 21 equal_nat ( nat_of_string s, (let nat = make_nat 15 in set_digit_nat nat 0 3; let nat2 = nat_of_string (sub_string s 0 135) in set_mult_digit_nat nat 0 15 nat2 0 (length_nat nat2) (nat_of_int 10) 0; nat)) ;; let s = "1234567890ABCDEF" in let nat = sys_nat_of_string 16 s 0 16 in test 22 eq_string (sys_string_of_nat 16 "" nat 0 (length_nat nat) "", s) ;; testing_function "decimal_of_string";; let (sbi, size) = decimal_of_string 10 "1.2" 0 3 in test 1 eq_string (sbi, "12") && test 2 eq_int (size, -1);; let (sbi, size) = decimal_of_string 10 "1e2" 0 3 in test 3 eq_string (sbi, "1") && test 4 eq_int (size, 2);; let (sbi, size) = decimal_of_string 10 "1e-2" 0 4 in test 5 eq_string (sbi, "1") && test 6 eq_int (size, -2);; let (sbi, size) = decimal_of_string 10 "1.2e3" 0 5 in test 7 eq_string (sbi, "12") && test 8 eq_int (size, 2);; let (sbi, size) = decimal_of_string 10 "1.2e-3" 0 6 in test 9 eq_string (sbi, "12") && test 10 eq_int (size, -4);; let (sbi, size) = decimal_of_string 10 "123" 0 3 in test 11 eq_string (sbi, "123") && test 12 eq_int (size, 0);; let (sbi, size) = decimal_of_string 10 "3456" 0 4 in test 13 eq_string (sbi, "3456") && test 14 eq_int (size, 0);; let (sbi, size) = decimal_of_string 10 "12.3/34.56" 5 5 in test 15 eq_string (sbi, "3456") && test 16 eq_int (size, -2);; failwith_test 17 (decimal_of_string 10 "cklefohj" 0) 8 (Failure "invalid digit");; testing_function "nat_of_string";; test 1 equal_nat (nat_of_string "0", zero_nat);; test 2 equal_nat (nat_of_string "1", nat_of_int 1);; test 3 equal_nat (nat_of_string "100e-2", nat_of_int 1);; test 4 equal_nat (nat_of_string "1.0e0", nat_of_int 1);; test 5 equal_nat (nat_of_string "1.0e1", nat_of_int 10);; test 6 equal_nat (nat_of_string "1.0e+1", nat_of_int 10);; test 7 equal_nat (nat_of_string "+1.0e+2", nat_of_int 100);; testing_function "sqrt_nat";; test 0 equal_nat (sqrt_nat (nat_of_int 0) 0 1, nat_of_int 0);; test 1 equal_nat (sqrt_nat (nat_of_int 1) 0 1, nat_of_int 1);; let nat = nat_of_string "8589934592" in test 2 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "92681");; let nat = nat_of_string "4294967295" in test 3 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "65535");; let nat = nat_of_string "18446744065119617025" in test 4 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "4294967295");; test 5 equal_nat (sqrt_nat (nat_of_int 15) 0 1, nat_of_int 3);; test 6 equal_nat (sqrt_nat (nat_of_int 17) 0 1, nat_of_int 4);; let sqrt_biggest_int = let n = make_nat 1 in set_digit_nat n 0 1; shift_left_nat n 0 1 (make_nat 1) 0 (length_of_int / 2); set_decr_nat n 0 1 0; n;; let nat = make_nat 2 in set_digit_nat nat 1 35; set_digit_nat nat 0 16; test 7 equal_nat (sqrt_nat nat 0 1, nat_of_int 4) && test 8 equal_nat (sqrt_nat nat 1 1, nat_of_int 5) && test 9 equal_nat (sqrt_nat (nat_of_int biggest_int) 0 1, sqrt_biggest_int);; let nat = make_nat 3 in set_digit_nat nat 2 biggest_int; set_digit_nat nat 1 biggest_int; set_digit_nat nat 0 0; test 10 equal_nat (sqrt_nat (nat) 2 1, sqrt_biggest_int) && test 11 equal_nat (sqrt_nat (nat) 1 1, sqrt_biggest_int) && test 12 equal_nat (sqrt_nat (nat) 0 1, nat_of_int 0);; let nat = nat_of_string "115792089237316195423570985008687907853269984665640564039457584007913129639935" in test 13 equal_nat (sqrt_nat (nat) 0 (length_nat nat), nat_of_string "340282366920938463463374607431768211455");; testing_function "string_of_nat";; let n = make_nat l;; test 1 eq_string (string_of_nat n, "0");; complement_nat n 0 l;; test 2 eq_string (string_of_nat n, "340282366920938463463374607431768211455");; testing_function "string_of_nat and nat_of_string";; for i = 1 to 20 do let s = make_string i `0` in s.[0] <- `1`; ignore (test i eq_string (string_of_nat (nat_of_string s), s)) done;; test 22 eq_string (string_of_nat(nat_of_string "1073741824"), "1073741824");; testing_function "gcd_nat";; for i = 1 to 20 do let n1 = random__int 1000000000 and n2 = random__int 100000 in let nat1 = nat_of_int n1 and nat2 = nat_of_int n2 in ignore (gcd_nat nat1 0 1 nat2 0 1); ignore (test i eq (int_of_nat nat1, int_misc__gcd_int n1 n2)) done ;; testing_function "sys_string_list_of_nat";; let n = make_nat 2;; set_digit_nat n 0 1;; set_digit_nat n 1 2;; test 1 (prefix =) (sys_string_list_of_nat 10 zero_nat 0 1, ["0"]) && test 2 (prefix =) (sys_string_list_of_nat 10 n 0 1, ["1"]) && test 3 (prefix =) (sys_string_list_of_nat 10 n 1 1, ["2"]);;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/libnum/test/test_nats.ml
ocaml
#open "test";; #open "nat";; #open "big_int";; #open "int_misc";; let ignore _ = ();; Can compare nats less than 2**32 let equal_nat n1 n2 = eq_nat n1 0 (num_digits_nat n1 0 1) n2 0 (num_digits_nat n2 0 1);; testing_function "num_digits_nat";; test 0 eq (false,not true);; test 1 eq (true,not false);; test 2 eq_int (let r = make_nat 2 in set_digit_nat r 1 1; num_digits_nat r 0 1,1);; testing_function "length_nat";; test 1 eq_int (let r = make_nat 2 in set_digit_nat r 0 1; length_nat r,2);; testing_function "equal_nat";; let zero_nat = make_nat 1;; test 1 equal_nat (zero_nat, zero_nat);; test 2 equal_nat (nat_of_int 1, nat_of_int 1);; test 3 equal_nat (nat_of_int 2, nat_of_int 2);; test 4 eq (equal_nat (nat_of_int 2) (nat_of_int 3),false);; testing_function "incr_nat";; let zero = nat_of_int 0 in let res = incr_nat zero 0 1 1 in test 1 equal_nat (zero, nat_of_int 1) && test 2 eq (res,0);; let n = nat_of_int 1 in let res = incr_nat n 0 1 1 in test 3 equal_nat (n, nat_of_int 2) && test 4 eq (res,0);; testing_function "decr_nat";; let n = nat_of_int 1 in let res = decr_nat n 0 1 0 in test 1 equal_nat (n, nat_of_int 0) && test 2 eq (res,1);; let n = nat_of_int 2 in let res = decr_nat n 0 1 0 in test 3 equal_nat (n, nat_of_int 1) && test 4 eq (res,1);; testing_function "is_zero_nat";; let n = nat_of_int 1 in test 1 eq (is_zero_nat n 0 1,false) && test 2 eq (is_zero_nat (make_nat 1) 0 1, true) && test 3 eq (is_zero_nat (make_nat 2) 0 2, true) && (let r = make_nat 2 in set_digit_nat r 1 1; test 4 eq (is_zero_nat r 0 1, true)) ;; testing_function "sys_string_of_nat";; let l = match length_of_int with | 30 -> 4 | 62 -> 2 | _ -> failwith "bad int length";; let n = make_nat l;; test 1 eq_string (sys_string_of_nat 10 "" n 0 l "","0");; complement_nat n 0 l;; let s = function | 2 -> "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" | 3 -> "202201102121002021012000211012011021221022212021111001022110211020010021100121010" | 4 -> "3333333333333333333333333333333333333333333333333333333333333333" | 5 -> "11031110441201303134210404233413032443021130230130231310" | 6 -> "23053353530155550541354043543542243325553444410303" | 7 -> "3115512162124626343001006330151620356026315303" | 8 -> "3777777777777777777777777777777777777777777" | 9 -> "22642532235024164257285244038424203240533" | 10 -> "340282366920938463463374607431768211455" | 11 -> "1000A504186892265432152AA27A7929366352" | 12 -> "5916B64B41143526A777873841863A6A6993" | 13 -> "47168C9C477C94BA75A2BC735955C7AA138" | 14 -> "51A45CB9506962A31983DAC25409715D03" | 15 -> "7D491176809C28848A561186D4857D320" | 16 -> "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" | _ -> invalid_arg "Wrong base" in for i = 2 to 16 do let s' = sys_string_of_nat i "" n 0 l "" in let _ = test i eq_string (s', s i) in () done;; let s = "1833520974" in test 23 eq_string (string_of_nat (nat_of_string s), s) ;; let s = "18335209741833520974" in test 24 eq_string (string_of_nat (nat_of_string s), s) ;; testing_function "string_of_digit";; test 1 eq_string (string_of_digit (nat_of_big_int (big_int_of_string "123456e2")), "12345600");; testing_function "string_of_nat and sys_nat_of_string";; for i = 1 to 20 do let s = make_string i `0` in s.[0] <- `1`; ignore (test i eq_string (string_of_nat (sys_nat_of_string 10 s 0 i), s)) done;; let s = "3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333" in test 21 equal_nat ( nat_of_string s, (let nat = make_nat 15 in set_digit_nat nat 0 3; let nat2 = nat_of_string (sub_string s 0 135) in set_mult_digit_nat nat 0 15 nat2 0 (length_nat nat2) (nat_of_int 10) 0; nat)) ;; let s = "1234567890ABCDEF" in let nat = sys_nat_of_string 16 s 0 16 in test 22 eq_string (sys_string_of_nat 16 "" nat 0 (length_nat nat) "", s) ;; testing_function "decimal_of_string";; let (sbi, size) = decimal_of_string 10 "1.2" 0 3 in test 1 eq_string (sbi, "12") && test 2 eq_int (size, -1);; let (sbi, size) = decimal_of_string 10 "1e2" 0 3 in test 3 eq_string (sbi, "1") && test 4 eq_int (size, 2);; let (sbi, size) = decimal_of_string 10 "1e-2" 0 4 in test 5 eq_string (sbi, "1") && test 6 eq_int (size, -2);; let (sbi, size) = decimal_of_string 10 "1.2e3" 0 5 in test 7 eq_string (sbi, "12") && test 8 eq_int (size, 2);; let (sbi, size) = decimal_of_string 10 "1.2e-3" 0 6 in test 9 eq_string (sbi, "12") && test 10 eq_int (size, -4);; let (sbi, size) = decimal_of_string 10 "123" 0 3 in test 11 eq_string (sbi, "123") && test 12 eq_int (size, 0);; let (sbi, size) = decimal_of_string 10 "3456" 0 4 in test 13 eq_string (sbi, "3456") && test 14 eq_int (size, 0);; let (sbi, size) = decimal_of_string 10 "12.3/34.56" 5 5 in test 15 eq_string (sbi, "3456") && test 16 eq_int (size, -2);; failwith_test 17 (decimal_of_string 10 "cklefohj" 0) 8 (Failure "invalid digit");; testing_function "nat_of_string";; test 1 equal_nat (nat_of_string "0", zero_nat);; test 2 equal_nat (nat_of_string "1", nat_of_int 1);; test 3 equal_nat (nat_of_string "100e-2", nat_of_int 1);; test 4 equal_nat (nat_of_string "1.0e0", nat_of_int 1);; test 5 equal_nat (nat_of_string "1.0e1", nat_of_int 10);; test 6 equal_nat (nat_of_string "1.0e+1", nat_of_int 10);; test 7 equal_nat (nat_of_string "+1.0e+2", nat_of_int 100);; testing_function "sqrt_nat";; test 0 equal_nat (sqrt_nat (nat_of_int 0) 0 1, nat_of_int 0);; test 1 equal_nat (sqrt_nat (nat_of_int 1) 0 1, nat_of_int 1);; let nat = nat_of_string "8589934592" in test 2 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "92681");; let nat = nat_of_string "4294967295" in test 3 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "65535");; let nat = nat_of_string "18446744065119617025" in test 4 equal_nat (sqrt_nat nat 0 (length_nat nat), nat_of_string "4294967295");; test 5 equal_nat (sqrt_nat (nat_of_int 15) 0 1, nat_of_int 3);; test 6 equal_nat (sqrt_nat (nat_of_int 17) 0 1, nat_of_int 4);; let sqrt_biggest_int = let n = make_nat 1 in set_digit_nat n 0 1; shift_left_nat n 0 1 (make_nat 1) 0 (length_of_int / 2); set_decr_nat n 0 1 0; n;; let nat = make_nat 2 in set_digit_nat nat 1 35; set_digit_nat nat 0 16; test 7 equal_nat (sqrt_nat nat 0 1, nat_of_int 4) && test 8 equal_nat (sqrt_nat nat 1 1, nat_of_int 5) && test 9 equal_nat (sqrt_nat (nat_of_int biggest_int) 0 1, sqrt_biggest_int);; let nat = make_nat 3 in set_digit_nat nat 2 biggest_int; set_digit_nat nat 1 biggest_int; set_digit_nat nat 0 0; test 10 equal_nat (sqrt_nat (nat) 2 1, sqrt_biggest_int) && test 11 equal_nat (sqrt_nat (nat) 1 1, sqrt_biggest_int) && test 12 equal_nat (sqrt_nat (nat) 0 1, nat_of_int 0);; let nat = nat_of_string "115792089237316195423570985008687907853269984665640564039457584007913129639935" in test 13 equal_nat (sqrt_nat (nat) 0 (length_nat nat), nat_of_string "340282366920938463463374607431768211455");; testing_function "string_of_nat";; let n = make_nat l;; test 1 eq_string (string_of_nat n, "0");; complement_nat n 0 l;; test 2 eq_string (string_of_nat n, "340282366920938463463374607431768211455");; testing_function "string_of_nat and nat_of_string";; for i = 1 to 20 do let s = make_string i `0` in s.[0] <- `1`; ignore (test i eq_string (string_of_nat (nat_of_string s), s)) done;; test 22 eq_string (string_of_nat(nat_of_string "1073741824"), "1073741824");; testing_function "gcd_nat";; for i = 1 to 20 do let n1 = random__int 1000000000 and n2 = random__int 100000 in let nat1 = nat_of_int n1 and nat2 = nat_of_int n2 in ignore (gcd_nat nat1 0 1 nat2 0 1); ignore (test i eq (int_of_nat nat1, int_misc__gcd_int n1 n2)) done ;; testing_function "sys_string_list_of_nat";; let n = make_nat 2;; set_digit_nat n 0 1;; set_digit_nat n 1 2;; test 1 (prefix =) (sys_string_list_of_nat 10 zero_nat 0 1, ["0"]) && test 2 (prefix =) (sys_string_list_of_nat 10 n 0 1, ["1"]) && test 3 (prefix =) (sys_string_list_of_nat 10 n 1 1, ["2"]);;
c93e495c488b7f4dff7e661ef58a66c457f9270e7a9bff332d1544f897fea98f
clojars/clojars-web
group_verification_test.clj
(ns clojars.integration.group-verification-test (:require [clj-http.client :as http] [clojars.email :as email] [clojars.integration.steps :refer [register-as]] [clojars.test-helper :as help] [clojure.test :refer [deftest is use-fixtures]] [kerodon.core :as kerodon :refer [fill-in follow-redirect press visit within]] [kerodon.test :refer [has some-text?]])) (use-fixtures :each help/with-test-system*) (defn session [] (let [session (-> (kerodon/session (help/app-from-system)) (register-as "dantheman" "" "password"))] (email/expect-mock-emails 1) session)) (defn assert-admin-email [state] (email/wait-for-mock-emails) (let [emails @email/mock-emails [[address title]] emails] (is (= 1 (count emails))) (is (= "" address)) (is (= (format "[Clojars] Group verification attempt %s" (if (= :success state) "succeeded" "failed")) title)))) (deftest user-can-verify-group (help/with-TXT ["clojars dantheman"] (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.com") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example' has been verified")))) (assert-admin-email :success))) (deftest user-cannot-verify-non-corresponding-group (help/with-TXT ["clojars dantheman"] (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.org") (press "Verify Group")) (follow-redirect) (within [:div.error] (has (some-text? "Group and domain do not correspond with each other")))) (assert-admin-email :failure))) (deftest user-can-verify-sub-group (help/with-TXT ["clojars dantheman"] (let [sess (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.com") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example' has been verified"))))] (assert-admin-email :success) (email/expect-mock-emails 1) (-> sess (within [:div.via-parent] (fill-in "Group name" "com.example.ham") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example.ham' has been verified")))) (assert-admin-email :success)))) (deftest user-cannot-verify-subgroup-with-non-verified-parent (-> (session) (visit "/verify/group") (within [:div.via-parent] (fill-in "Group name" "com.example") (press "Verify Group")) (follow-redirect) (within [:div.error] (has (some-text? "The group is not a subgroup of a verified group")))) (assert-admin-email :failure)) (deftest user-can-verify-vcs-groups (with-redefs [http/head (constantly {:status 200})] (-> (session) (visit "/verify/group") (within [:div.via-vcs] (fill-in "Verification Repository URL" "-dantheman") (press "Verify Groups")) (follow-redirect) (within [:div.info] (has (some-text? "The groups 'com.github.example' & 'net.github.example' have been verified")))) (assert-admin-email :success))) (deftest user-cannot-verify-vcs-groups-with-missing-repo (with-redefs [http/head (constantly {:status 404})] (-> (session) (visit "/verify/group") (within [:div.via-vcs] (fill-in "Verification Repository URL" "-dantheman") (press "Verify Groups")) (follow-redirect) (within [:div.error] (has (some-text? "The verification repo does not exist")))) (assert-admin-email :failure)))
null
https://raw.githubusercontent.com/clojars/clojars-web/b5107cb70934299e1b7e334c02b87a6c72fc037d/test/clojars/integration/group_verification_test.clj
clojure
(ns clojars.integration.group-verification-test (:require [clj-http.client :as http] [clojars.email :as email] [clojars.integration.steps :refer [register-as]] [clojars.test-helper :as help] [clojure.test :refer [deftest is use-fixtures]] [kerodon.core :as kerodon :refer [fill-in follow-redirect press visit within]] [kerodon.test :refer [has some-text?]])) (use-fixtures :each help/with-test-system*) (defn session [] (let [session (-> (kerodon/session (help/app-from-system)) (register-as "dantheman" "" "password"))] (email/expect-mock-emails 1) session)) (defn assert-admin-email [state] (email/wait-for-mock-emails) (let [emails @email/mock-emails [[address title]] emails] (is (= 1 (count emails))) (is (= "" address)) (is (= (format "[Clojars] Group verification attempt %s" (if (= :success state) "succeeded" "failed")) title)))) (deftest user-can-verify-group (help/with-TXT ["clojars dantheman"] (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.com") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example' has been verified")))) (assert-admin-email :success))) (deftest user-cannot-verify-non-corresponding-group (help/with-TXT ["clojars dantheman"] (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.org") (press "Verify Group")) (follow-redirect) (within [:div.error] (has (some-text? "Group and domain do not correspond with each other")))) (assert-admin-email :failure))) (deftest user-can-verify-sub-group (help/with-TXT ["clojars dantheman"] (let [sess (-> (session) (visit "/verify/group") (within [:div.via-txt] (fill-in "Group name" "com.example") (fill-in "Domain with TXT record" "example.com") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example' has been verified"))))] (assert-admin-email :success) (email/expect-mock-emails 1) (-> sess (within [:div.via-parent] (fill-in "Group name" "com.example.ham") (press "Verify Group")) (follow-redirect) (within [:div.info] (has (some-text? "The group 'com.example.ham' has been verified")))) (assert-admin-email :success)))) (deftest user-cannot-verify-subgroup-with-non-verified-parent (-> (session) (visit "/verify/group") (within [:div.via-parent] (fill-in "Group name" "com.example") (press "Verify Group")) (follow-redirect) (within [:div.error] (has (some-text? "The group is not a subgroup of a verified group")))) (assert-admin-email :failure)) (deftest user-can-verify-vcs-groups (with-redefs [http/head (constantly {:status 200})] (-> (session) (visit "/verify/group") (within [:div.via-vcs] (fill-in "Verification Repository URL" "-dantheman") (press "Verify Groups")) (follow-redirect) (within [:div.info] (has (some-text? "The groups 'com.github.example' & 'net.github.example' have been verified")))) (assert-admin-email :success))) (deftest user-cannot-verify-vcs-groups-with-missing-repo (with-redefs [http/head (constantly {:status 404})] (-> (session) (visit "/verify/group") (within [:div.via-vcs] (fill-in "Verification Repository URL" "-dantheman") (press "Verify Groups")) (follow-redirect) (within [:div.error] (has (some-text? "The verification repo does not exist")))) (assert-admin-email :failure)))
2a687e14bfe278476c9056cf0a385efba49ebcd3eb370f8ab8e8ccb30991504b
spechub/Hets
ExtendedParameter.hs
| Module : ./CSL / ExtendedParameter.hs Description : This module is for selecting the favoured EP representation Copyright : ( c ) , DFKI Bremen 2010 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable This module re - exports one of the following modules GeneralExtendedParameter SimpleExtendedParameter Module : ./CSL/ExtendedParameter.hs Description : This module is for selecting the favoured EP representation Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable This module re-exports one of the following modules GeneralExtendedParameter SimpleExtendedParameter -} module CSL.ExtendedParameter ( module EP ) where -- import CSL.GeneralExtendedParameter import CSL.SimpleExtendedParameter as EP
null
https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/CSL/ExtendedParameter.hs
haskell
import CSL.GeneralExtendedParameter
| Module : ./CSL / ExtendedParameter.hs Description : This module is for selecting the favoured EP representation Copyright : ( c ) , DFKI Bremen 2010 License : GPLv2 or higher , see LICENSE.txt Maintainer : Stability : experimental Portability : portable This module re - exports one of the following modules GeneralExtendedParameter SimpleExtendedParameter Module : ./CSL/ExtendedParameter.hs Description : This module is for selecting the favoured EP representation Copyright : (c) Ewaryst Schulz, DFKI Bremen 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : Stability : experimental Portability : portable This module re-exports one of the following modules GeneralExtendedParameter SimpleExtendedParameter -} module CSL.ExtendedParameter ( module EP ) where import CSL.SimpleExtendedParameter as EP
a17bff18743096825fca27f9f93e56ff4430c966c83257205784c96241e12038
y42/clj-druid
validations.clj
(ns clj-druid.validations (:require [clj-druid.schemas.query :as sch] [schema.core :as s] [schema.coerce :as c])) (defn validate-groupby "Validate a druid groupBy query" [query] (s/validate sch/groupBy query)) (defn validate-search "Validate a druid search query" [query] (s/validate sch/search query)) (defn validate-segment-metadata "Validate a druid segment metadata query" [query] (s/validate sch/segmentMetadata query)) (defn validate-time-boundary "Validate a druid time boundary query" [query] (s/validate sch/timeBoundary query)) (defn validate-timeseries "Validate a druid timeseries query" [query] (s/validate sch/timeseries query)) (defn validate-topN "Validate a druid topN query" [query] (s/validate sch/topN query)) (defn validate [query query-type] (s/validate (query-type sch/queries) query))
null
https://raw.githubusercontent.com/y42/clj-druid/37fc967f000dc63816610695a2b6c028b7b7d8b5/src/clj_druid/validations.clj
clojure
(ns clj-druid.validations (:require [clj-druid.schemas.query :as sch] [schema.core :as s] [schema.coerce :as c])) (defn validate-groupby "Validate a druid groupBy query" [query] (s/validate sch/groupBy query)) (defn validate-search "Validate a druid search query" [query] (s/validate sch/search query)) (defn validate-segment-metadata "Validate a druid segment metadata query" [query] (s/validate sch/segmentMetadata query)) (defn validate-time-boundary "Validate a druid time boundary query" [query] (s/validate sch/timeBoundary query)) (defn validate-timeseries "Validate a druid timeseries query" [query] (s/validate sch/timeseries query)) (defn validate-topN "Validate a druid topN query" [query] (s/validate sch/topN query)) (defn validate [query query-type] (s/validate (query-type sch/queries) query))
eb2228e725ddfb701a41deb08f4739e665012e5dad5ecf5127fd7087a27545e0
scrintal/heroicons-reagent
document_arrow_down.cljs
(ns com.scrintal.heroicons.solid.document-arrow-down) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M5.625 1.5H9a3.75 3.75 0 013.75 3.75v1.875c0 1.036.84 1.875 1.875 1.875H16.5a3.75 3.75 0 013.75 3.75v7.875c0 1.035-.84 1.875-1.875 1.875H5.625a1.875 1.875 0 01-1.875-1.875V3.375c0-1.036.84-1.875 1.875-1.875zm5.845 17.03a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06l-1.72 1.72V12a.75.75 0 00-1.5 0v4.19l-1.72-1.72a.75.75 0 00-1.06 1.06l3 3z" :clipRule "evenodd"}] [:path {:d "M14.25 5.25a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963A5.23 5.23 0 0016.5 7.5h-1.875a.375.375 0 01-.375-.375V5.25z"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/document_arrow_down.cljs
clojure
(ns com.scrintal.heroicons.solid.document-arrow-down) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M5.625 1.5H9a3.75 3.75 0 013.75 3.75v1.875c0 1.036.84 1.875 1.875 1.875H16.5a3.75 3.75 0 013.75 3.75v7.875c0 1.035-.84 1.875-1.875 1.875H5.625a1.875 1.875 0 01-1.875-1.875V3.375c0-1.036.84-1.875 1.875-1.875zm5.845 17.03a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06l-1.72 1.72V12a.75.75 0 00-1.5 0v4.19l-1.72-1.72a.75.75 0 00-1.06 1.06l3 3z" :clipRule "evenodd"}] [:path {:d "M14.25 5.25a5.23 5.23 0 00-1.279-3.434 9.768 9.768 0 016.963 6.963A5.23 5.23 0 0016.5 7.5h-1.875a.375.375 0 01-.375-.375V5.25z"}]])
7e92903610c72f540af8a32c738fc76d495452b9984a4107c655031bf10371e2
runtimeverification/haskell-backend
Subsort.hs
| Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause -} module Kore.Attribute.Subsort ( Subsort (..), Subsorts (..), subsortId, subsortSymbol, subsortAttribute, ) where import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.Attribute.Parser as Parser import Kore.Debug import Prelude.Kore -- | The @subsort@ attribute. data Subsort = Subsort { subsort :: Sort , supersort :: Sort } deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (Hashable, NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) newtype Subsorts = Subsorts {getSubsorts :: [Subsort]} deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (Hashable, NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Default Subsorts where def = Subsorts [] -- | Kore identifier representing a @subsort@ attribute symbol. subsortId :: Id subsortId = "subsort" | Kore symbol representing a @subsort@ attribute head . Kore syntax : @subsort{Sub , Super}@ where @Sub@ is the subsort and @Super@ is the supersort . Kore syntax: @subsort{Sub,Super}@ where @Sub@ is the subsort and @Super@ is the supersort. -} subsortSymbol :: Sort -> Sort -> SymbolOrAlias subsortSymbol subsort supersort = SymbolOrAlias { symbolOrAliasConstructor = subsortId , symbolOrAliasParams = [subsort, supersort] } | Kore pattern representing a @subsort@ attribute . Kore syntax : @subsort{Sub , Super}()@ where @Sub@ is the subsort and @Super@ is the supersort . Kore syntax: @subsort{Sub,Super}()@ where @Sub@ is the subsort and @Super@ is the supersort. -} subsortAttribute :: Sort -> Sort -> AttributePattern subsortAttribute subsort supersort = attributePattern_ $ subsortSymbol subsort supersort | Parse @subsort@ Kore attributes , if present . It is a parse error if the @subsort@ attribute is not given exactly two sort parameters See also : ' subsortAttribute ' It is a parse error if the @subsort@ attribute is not given exactly two sort parameters See also: 'subsortAttribute' -} instance ParseAttributes Subsorts where parseAttribute = withApplication' $ \params args (Subsorts subsorts) -> do Parser.getZeroArguments args (subsort, supersort) <- Parser.getTwoParams params let relation = Subsort subsort supersort return (Subsorts $ relation : subsorts) where withApplication' = Parser.withApplication subsortId instance From Subsorts Attributes where from = Attributes . map toAttribute . getSubsorts where toAttribute = subsortAttribute <$> subsort <*> supersort
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/src/Kore/Attribute/Subsort.hs
haskell
| The @subsort@ attribute. | Kore identifier representing a @subsort@ attribute symbol.
| Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause -} module Kore.Attribute.Subsort ( Subsort (..), Subsorts (..), subsortId, subsortSymbol, subsortAttribute, ) where import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.Attribute.Parser as Parser import Kore.Debug import Prelude.Kore data Subsort = Subsort { subsort :: Sort , supersort :: Sort } deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (Hashable, NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) newtype Subsorts = Subsorts {getSubsorts :: [Subsort]} deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (Hashable, NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Default Subsorts where def = Subsorts [] subsortId :: Id subsortId = "subsort" | Kore symbol representing a @subsort@ attribute head . Kore syntax : @subsort{Sub , Super}@ where @Sub@ is the subsort and @Super@ is the supersort . Kore syntax: @subsort{Sub,Super}@ where @Sub@ is the subsort and @Super@ is the supersort. -} subsortSymbol :: Sort -> Sort -> SymbolOrAlias subsortSymbol subsort supersort = SymbolOrAlias { symbolOrAliasConstructor = subsortId , symbolOrAliasParams = [subsort, supersort] } | Kore pattern representing a @subsort@ attribute . Kore syntax : @subsort{Sub , Super}()@ where @Sub@ is the subsort and @Super@ is the supersort . Kore syntax: @subsort{Sub,Super}()@ where @Sub@ is the subsort and @Super@ is the supersort. -} subsortAttribute :: Sort -> Sort -> AttributePattern subsortAttribute subsort supersort = attributePattern_ $ subsortSymbol subsort supersort | Parse @subsort@ Kore attributes , if present . It is a parse error if the @subsort@ attribute is not given exactly two sort parameters See also : ' subsortAttribute ' It is a parse error if the @subsort@ attribute is not given exactly two sort parameters See also: 'subsortAttribute' -} instance ParseAttributes Subsorts where parseAttribute = withApplication' $ \params args (Subsorts subsorts) -> do Parser.getZeroArguments args (subsort, supersort) <- Parser.getTwoParams params let relation = Subsort subsort supersort return (Subsorts $ relation : subsorts) where withApplication' = Parser.withApplication subsortId instance From Subsorts Attributes where from = Attributes . map toAttribute . getSubsorts where toAttribute = subsortAttribute <$> subsort <*> supersort
cdf0f644413214d7af35f2bfacf724fe22a604c63cee81050a0d1bcb5839d81f
ghc/testsuite
ImpSafe01.hs
{-# LANGUAGE Safe #-} # LANGUAGE NoImplicitPrelude # module ImpSafe ( MyWord ) where While Data . Word is safe it imports trustworthy -- modules in base, hence base needs to be trusted. -- Note: Worthwhile giving out better error messages for cases -- like this if I can. import Data.Word type MyWord = Word
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/safeHaskell/check/pkg01/ImpSafe01.hs
haskell
# LANGUAGE Safe # modules in base, hence base needs to be trusted. Note: Worthwhile giving out better error messages for cases like this if I can.
# LANGUAGE NoImplicitPrelude # module ImpSafe ( MyWord ) where While Data . Word is safe it imports trustworthy import Data.Word type MyWord = Word
44704c08a202213ecb01b7b80e242d2f2f1058295293f4532bac7659d382f111
nikita-volkov/rebase
Reader.hs
module Rebase.Control.Monad.Trans.Reader ( module Control.Monad.Trans.Reader ) where import Control.Monad.Trans.Reader
null
https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Control/Monad/Trans/Reader.hs
haskell
module Rebase.Control.Monad.Trans.Reader ( module Control.Monad.Trans.Reader ) where import Control.Monad.Trans.Reader
6e6f89b5d8703e402abdde928d23c12a67ea38ac63d8af6c1002c06bd8771afb
Bertkiing/ErlangLearner
erlang_list_max.erl
-module(erlang_list_max). -export([list_max/1]). list_max([Head|Rest]) -> list_max(Rest,Head). list_max([],Res) -> Res; list_max([Head|Rest],Result_so_far) when Head>Result_so_far -> list_max(Rest,Head); list_max([Head|Rest],Result_so_far) -> list_max(Rest,Result_so_far).
null
https://raw.githubusercontent.com/Bertkiing/ErlangLearner/ce917684ee91e6d43864291f0e34050e7e004ca5/erlang%E5%88%97%E8%A1%A8%E9%83%A8%E5%88%86/erlang_list_max.erl
erlang
-module(erlang_list_max). -export([list_max/1]). list_max([Head|Rest]) -> list_max(Rest,Head). list_max([],Res) -> Res; list_max([Head|Rest],Result_so_far) when Head>Result_so_far -> list_max(Rest,Head); list_max([Head|Rest],Result_so_far) -> list_max(Rest,Result_so_far).
84c2ee43c87ee22f30b43d5e6b2dc7ef520984e5348bde0e410d58335dd948be
janegca/htdp2e
Exercise-255-n-inside-playground.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-intermediate-lambda-reader.ss" "lang")((modname Exercise-255-n-inside-playground) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp"))))) Exercise 255 . ; ; Develop n-inside-playground?, a function that generates a predicate that ensures that the length of the given list is k and that all Posns in this ; list are within a WIDTH by HEIGHT rectangle. ; ; Define random-posns/bad that satisfies n-inside-playground? and does not ; live up to the expectations implied by the above purpose statement. ; ; NOTE: This specification is incomplete. Although the word “partial” might ; come to mind, computer scientists reserve the phrase “partial specification” ; for a different purpose. (define WIDTH 300) (define HEIGHT 300) ; Number [List-of Posn] -> Boolean ; is the list of positions equal to n ; are all positions within the list within a width x height rectangle (define (n-inside-playground? n) (local (; Posn -> Boolean are the position coords within a WIDTH x HEIGHT rectangle (define (in-range? pos) (local ( (define x (posn-x pos)) (define y (posn-y pos))) (and (>= x 0) (< x WIDTH) (>= y 0) (< y HEIGHT))))) (lambda (lst) (if (and (= n (length lst)) (andmap in-range? lst)) #true #false)))) ; NOTE: for now, must define (name) the curried function if we ; want to use it in a check-satisfied statement (define t1 (n-inside-playground? 3)) (define t2 (n-inside-playground? 0)) ; N -> [List-of Posn] generate n random Posns in a WIDTH by HEIGHT rectangle (check-satisfied (random-posns 3) t1) (check-satisfied (random-posns 0) t2) (define (random-posns n) (build-list n (lambda (i) (make-posn (random WIDTH) (random HEIGHT))))) ; -- make a bad position that satifies n-inside-playground? ; the spec says nothing about identical positions within the rectangle ; reasonable assumption is that all positions in the list will be unique (define (random-posns/bad n) (list (make-posn 100 100) (make-posn 100 100))) (define t3 (n-inside-playground? 2)) (check-satisfied (random-posns/bad 2) t3)
null
https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/03-Abstractions/Exercise-255-n-inside-playground.rkt
racket
about the language level of this file in a form that our tools can easily process. Develop n-inside-playground?, a function that generates a predicate that list are within a WIDTH by HEIGHT rectangle. Define random-posns/bad that satisfies n-inside-playground? and does not live up to the expectations implied by the above purpose statement. NOTE: This specification is incomplete. Although the word “partial” might come to mind, computer scientists reserve the phrase “partial specification” for a different purpose. Number [List-of Posn] -> Boolean is the list of positions equal to n are all positions within the list within a width x height rectangle Posn -> Boolean NOTE: for now, must define (name) the curried function if we want to use it in a check-satisfied statement N -> [List-of Posn] -- make a bad position that satifies n-inside-playground? the spec says nothing about identical positions within the rectangle reasonable assumption is that all positions in the list will be unique
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname Exercise-255-n-inside-playground) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp"))))) Exercise 255 . ensures that the length of the given list is k and that all Posns in this (define WIDTH 300) (define HEIGHT 300) (define (n-inside-playground? n) are the position coords within a WIDTH x HEIGHT rectangle (define (in-range? pos) (local ( (define x (posn-x pos)) (define y (posn-y pos))) (and (>= x 0) (< x WIDTH) (>= y 0) (< y HEIGHT))))) (lambda (lst) (if (and (= n (length lst)) (andmap in-range? lst)) #true #false)))) (define t1 (n-inside-playground? 3)) (define t2 (n-inside-playground? 0)) generate n random Posns in a WIDTH by HEIGHT rectangle (check-satisfied (random-posns 3) t1) (check-satisfied (random-posns 0) t2) (define (random-posns n) (build-list n (lambda (i) (make-posn (random WIDTH) (random HEIGHT))))) (define (random-posns/bad n) (list (make-posn 100 100) (make-posn 100 100))) (define t3 (n-inside-playground? 2)) (check-satisfied (random-posns/bad 2) t3)
67f7bb0598365142ed2cabb07ed7c1cff83feb3a2017d525e411e6a36e550eb7
aesiniath/publish
Utilities.hs
# LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Utilities ( ensureDirectory, ifNewer, isNewer, ) where import Chrono.Compat (convertToUTC) import Control.Monad (when) import Core.Program import Core.System import System.Directory ( createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getModificationTime, ) import System.FilePath.Posix (takeDirectory) {- Some source files live in subdirectories. Replicate that directory structure in the temporary build space -} ensureDirectory :: FilePath -> Program t () ensureDirectory target = let subdir = takeDirectory target in liftIO $ do probe <- doesDirectoryExist subdir when (not probe) $ do createDirectoryIfMissing True subdir {- | If the source file is newer than the target file, then run an action. For example, if you want to install a file but only do so if the file has been rebuilt, then you could do this: @ copyFileIfNewer :: 'FilePath' -> 'FilePath' -> 'Program' τ () copyFileIfNewer source target = do 'ifNewer' source target $ do 'liftIO' ('copyFileWithMetadata' source target) @ This is basically a build system in a box, although the usual caveats about the brittleness of timestamps apply. TODO this could potentially move to the **unbeliever** library -} ifNewer :: FilePath -> FilePath -> Program t () -> Program t () ifNewer source target program = do changed <- isNewer source target when changed $ do program isNewer :: FilePath -> FilePath -> Program t Bool isNewer source target = liftIO $ do time1 <- getModificationTime source time2 <- doesFileExist target >>= \case True -> getModificationTime target False -> return (convertToUTC 0) -- the epoch return (time1 > time2)
null
https://raw.githubusercontent.com/aesiniath/publish/a2c0c8e339bc24d1c0f5fbef6f50a362de763508/src/Utilities.hs
haskell
# LANGUAGE OverloadedStrings # Some source files live in subdirectories. Replicate that directory structure in the temporary build space | If the source file is newer than the target file, then run an action. For example, if you want to install a file but only do so if the file has been rebuilt, then you could do this: @ copyFileIfNewer :: 'FilePath' -> 'FilePath' -> 'Program' τ () copyFileIfNewer source target = do 'ifNewer' source target $ do 'liftIO' ('copyFileWithMetadata' source target) @ This is basically a build system in a box, although the usual caveats about the brittleness of timestamps apply. TODO this could potentially move to the **unbeliever** library the epoch
# LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module Utilities ( ensureDirectory, ifNewer, isNewer, ) where import Chrono.Compat (convertToUTC) import Control.Monad (when) import Core.Program import Core.System import System.Directory ( createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getModificationTime, ) import System.FilePath.Posix (takeDirectory) ensureDirectory :: FilePath -> Program t () ensureDirectory target = let subdir = takeDirectory target in liftIO $ do probe <- doesDirectoryExist subdir when (not probe) $ do createDirectoryIfMissing True subdir ifNewer :: FilePath -> FilePath -> Program t () -> Program t () ifNewer source target program = do changed <- isNewer source target when changed $ do program isNewer :: FilePath -> FilePath -> Program t Bool isNewer source target = liftIO $ do time1 <- getModificationTime source time2 <- doesFileExist target >>= \case True -> getModificationTime target return (time1 > time2)
7eae18da1ede966f6515786d932da3a3082945f2e29e3ace1c87c85b62c09323
jspahrsummers/objective-clojure
compiler.clj
(ns objclj.compiler) (defn -main [& args] nil)
null
https://raw.githubusercontent.com/jspahrsummers/objective-clojure/3ef64a88b3a82cdc6ebb899bd409e387bfe79ca4/src/objclj/compiler.clj
clojure
(ns objclj.compiler) (defn -main [& args] nil)
a6cee55bdf9c22ee4b1fe886b4df99b9bc0948f86f7999af2e9dee1cdd6a7936
tdrhq/fiveam-matchers
lists.lisp
(uiop:define-package :fiveam-matchers/lists (:use #:cl #:alexandria) (:import-from #:fiveam-matchers/core #:is-not #:ensure-matcher #:self-describing-list #:describe-self #:esc #:describe-mismatch #:matchesp #:matcher) (:import-from #:fiveam-matchers/every-item #:every-item) (:import-from #:fiveam-matchers/delegating #:delegating-matcher) (:export #:contains #:has-item #:does-not-have-item)) (in-package :fiveam-matchers/lists) (defclass contains (matcher) ((expected :initarg :expected :accessor expected))) (defun contains (&rest expected) (let ((expected (mapcar 'ensure-matcher expected))) (make-instance 'contains :expected expected))) (defmethod matchesp ((matcher contains) (actual list)) (when (eql (length actual) (length (expected matcher))) (not (loop for a in actual for x in (expected matcher) unless (matchesp x a) return t)))) (defmethod describe-self ((matcher contains)) `("a list with values: " ,(self-describing-list (expected matcher)))) (defclass has-item (matcher) ((expected :initarg :expected :accessor expected))) (defun has-item (expected) (let ((expected (ensure-matcher expected))) (make-instance 'has-item :expected expected))) (defun does-not-have-item (expected) (let ((expected (ensure-matcher expected))) (make-instance 'delegating-matcher :matcher (every-item (is-not expected)) :describe-self (lambda () `("a sequence that does not contain: " ,(describe-self expected))) :describe-mismatch (lambda (actual) (loop for item in actual for idx from 0 if (matchesp expected item) return `("The item at idx " ,idx " matches")))))) (defmethod matchesp ((matcher has-item) (actual list)) (some (lambda (x) (matchesp (expected matcher) x)) actual)) (defmethod describe-self ((matcher has-item)) `("a sequence that contains: " ,(describe-self (expected matcher)) )) (defmethod describe-mismatch ((matcher has-item) (actual list)) `("none of the elements matched")) (defmethod describe-mismatch ((matcher contains) (actual list)) (cond ((not (eql (length actual) (length (expected matcher)))) `("was a list not of length " ,(length (expected matcher)))) (t (loop for a in actual for x in (expected matcher) for i from 0 unless (matchesp x a) return `("The element at position " ,(esc i) " " ,(describe-mismatch x a))))))
null
https://raw.githubusercontent.com/tdrhq/fiveam-matchers/576d5d05150d5f75abd93e21a0683058c52cf44c/lists.lisp
lisp
(uiop:define-package :fiveam-matchers/lists (:use #:cl #:alexandria) (:import-from #:fiveam-matchers/core #:is-not #:ensure-matcher #:self-describing-list #:describe-self #:esc #:describe-mismatch #:matchesp #:matcher) (:import-from #:fiveam-matchers/every-item #:every-item) (:import-from #:fiveam-matchers/delegating #:delegating-matcher) (:export #:contains #:has-item #:does-not-have-item)) (in-package :fiveam-matchers/lists) (defclass contains (matcher) ((expected :initarg :expected :accessor expected))) (defun contains (&rest expected) (let ((expected (mapcar 'ensure-matcher expected))) (make-instance 'contains :expected expected))) (defmethod matchesp ((matcher contains) (actual list)) (when (eql (length actual) (length (expected matcher))) (not (loop for a in actual for x in (expected matcher) unless (matchesp x a) return t)))) (defmethod describe-self ((matcher contains)) `("a list with values: " ,(self-describing-list (expected matcher)))) (defclass has-item (matcher) ((expected :initarg :expected :accessor expected))) (defun has-item (expected) (let ((expected (ensure-matcher expected))) (make-instance 'has-item :expected expected))) (defun does-not-have-item (expected) (let ((expected (ensure-matcher expected))) (make-instance 'delegating-matcher :matcher (every-item (is-not expected)) :describe-self (lambda () `("a sequence that does not contain: " ,(describe-self expected))) :describe-mismatch (lambda (actual) (loop for item in actual for idx from 0 if (matchesp expected item) return `("The item at idx " ,idx " matches")))))) (defmethod matchesp ((matcher has-item) (actual list)) (some (lambda (x) (matchesp (expected matcher) x)) actual)) (defmethod describe-self ((matcher has-item)) `("a sequence that contains: " ,(describe-self (expected matcher)) )) (defmethod describe-mismatch ((matcher has-item) (actual list)) `("none of the elements matched")) (defmethod describe-mismatch ((matcher contains) (actual list)) (cond ((not (eql (length actual) (length (expected matcher)))) `("was a list not of length " ,(length (expected matcher)))) (t (loop for a in actual for x in (expected matcher) for i from 0 unless (matchesp x a) return `("The element at position " ,(esc i) " " ,(describe-mismatch x a))))))
1a8c0eeca30bb90da290dcb85aa62a4dcb6dbba4786d2b01c0d10a64810aa544
SamirTalwar/advent-of-code
AOC_24_2.hs
import qualified Data.List as List compartments = 4 main = do weights <- map read <$> lines <$> getContents let capacity = sum weights `div` compartments let compartments = filter ((== capacity) . sum) $ distribute weights let passengerCompartmentPackageCount = minimum $ map length compartments let passengerCompartments = filter (\pc -> length pc == passengerCompartmentPackageCount) compartments let quantumEntanglements = map product passengerCompartments let quantumEntanglement = minimum quantumEntanglements print quantumEntanglement distribute :: [Int] -> [[Int]] distribute weights = concatMap (\i -> combinations i weights) [0 .. (length weights `div` compartments)] where sortedWeights = List.sortBy (flip compare) weights combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations n list = [x : xs | x : ts <- List.tails list, xs <- combinations (n - 1) ts]
null
https://raw.githubusercontent.com/SamirTalwar/advent-of-code/66bd9e31f078c9b81ece0264fb869e48964afa63/2015/AOC_24_2.hs
haskell
import qualified Data.List as List compartments = 4 main = do weights <- map read <$> lines <$> getContents let capacity = sum weights `div` compartments let compartments = filter ((== capacity) . sum) $ distribute weights let passengerCompartmentPackageCount = minimum $ map length compartments let passengerCompartments = filter (\pc -> length pc == passengerCompartmentPackageCount) compartments let quantumEntanglements = map product passengerCompartments let quantumEntanglement = minimum quantumEntanglements print quantumEntanglement distribute :: [Int] -> [[Int]] distribute weights = concatMap (\i -> combinations i weights) [0 .. (length weights `div` compartments)] where sortedWeights = List.sortBy (flip compare) weights combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations n list = [x : xs | x : ts <- List.tails list, xs <- combinations (n - 1) ts]
720c32f854803adc24b138de12a9acc16e5f64ca18e930db751741afa9c7b68d
clojure-interop/aws-api
AWSServiceMetrics.clj
(ns com.amazonaws.util.AWSServiceMetrics (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.util AWSServiceMetrics])) (def HttpClientGetConnectionTime "Enum Constant. Time taken to get a connection by the http client library. type: com.amazonaws.util.AWSServiceMetrics" AWSServiceMetrics/HttpClientGetConnectionTime) (defn *values "Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (AWSServiceMetrics c : AWSServiceMetrics.values()) System.out.println(c); returns: an array containing the constants of this enum type, in the order they are declared - `com.amazonaws.util.AWSServiceMetrics[]`" ([] (AWSServiceMetrics/values ))) (defn *value-of "Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) name - the name of the enum constant to be returned. - `java.lang.String` returns: the enum constant with the specified name - `com.amazonaws.util.AWSServiceMetrics` throws: java.lang.IllegalArgumentException - if this enum type has no constant with the specified name" (^com.amazonaws.util.AWSServiceMetrics [^java.lang.String name] (AWSServiceMetrics/valueOf name))) (defn get-service-name "returns: `java.lang.String`" (^java.lang.String [^AWSServiceMetrics this] (-> this (.getServiceName))))
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.util/src/com/amazonaws/util/AWSServiceMetrics.clj
clojure
(ns com.amazonaws.util.AWSServiceMetrics (:refer-clojure :only [require comment defn ->]) (:import [com.amazonaws.util AWSServiceMetrics])) (def HttpClientGetConnectionTime "Enum Constant. Time taken to get a connection by the http client library. type: com.amazonaws.util.AWSServiceMetrics" AWSServiceMetrics/HttpClientGetConnectionTime) (defn *values "Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (AWSServiceMetrics c : AWSServiceMetrics.values()) returns: an array containing the constants of this enum type, in the order they are declared - `com.amazonaws.util.AWSServiceMetrics[]`" ([] (AWSServiceMetrics/values ))) (defn *value-of "Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) name - the name of the enum constant to be returned. - `java.lang.String` returns: the enum constant with the specified name - `com.amazonaws.util.AWSServiceMetrics` throws: java.lang.IllegalArgumentException - if this enum type has no constant with the specified name" (^com.amazonaws.util.AWSServiceMetrics [^java.lang.String name] (AWSServiceMetrics/valueOf name))) (defn get-service-name "returns: `java.lang.String`" (^java.lang.String [^AWSServiceMetrics this] (-> this (.getServiceName))))
5691e97678bef0272e98c3c169d5959044350947465555ee394fb94317632e51
eryx67/etracker
etracker_test.erl
-module(etracker_test). -include_lib("eunit/include/eunit.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -include("../include/etracker.hrl"). -define(PEERS, test_peers). -define(TRACKER_URL, ":8181"). -define(TRACKER_PEER, {{127, 0, 0, 1}, 8181}). etracker_test_() -> {setup, fun start_apps/0, fun stop/1, fun(_SetupData) -> [{setup, fun setup_announce/0, fun (Ann) -> {inorder, [Fun(Ann) || Fun <- [fun leecher_first_started/1, fun leecher_first_invalid_requests/1, fun leecher_second_started/1, fun seeder_first_started/1, fun leecher_first_completed/1, fun scrape_all/1, fun scrape_some/1, fun leecher_second_stopped/1, fun check_stats_after_test/1 ] ]} end }] end }. etracker_cleaner_test_() -> application:load(etracker), {setup, fun cleaner_test_start/0, fun cleaner_test_stop/1, fun (SD) -> {inorder, [{timeout, 60, [ cleaner_checks1(SD), cleaner_checks2(SD) ]}, check_stats_after_clean() ]} end }. start_apps() -> application:start(asn1), application:ensure_all_started(lager), application:ensure_all_started(cowboy), etorrent:start_app(), etracker:start(), timer:sleep(5000), []. setup_announce() -> ets:new(?PEERS, [named_table, public]), random:seed(now()), random_announce(). stop(_SD) -> etracker:stop(), etorrent:stop_app() . cleaner_test_start() -> application:load(etracker), application:set_env(etracker, clean_interval, 5), etracker:start(), timer:sleep(1000), cleaner_test_start1(). cleaner_test_start1() -> InfoHash = random_string(20), PeerId1 = random_string(20), PeerId2 = random_string(20), {Mega, Sec, Micro} = now(), TI = #torrent_info{ info_hash=InfoHash, leechers=3, seeders=3 }, SeederMtime = {Mega, Sec - 2, Micro}, Seeder = #torrent_user{ id={InfoHash, PeerId1}, peer={{127, 0, 0, 1}, 6969}, finished=true, mtime=SeederMtime }, LeecherMtime = {Mega, Sec, Micro}, Leecher = #torrent_user{ id={InfoHash, PeerId2}, peer={{127, 0, 0, 1}, 6969}, finished=false, mtime=LeecherMtime }, ok = write_record(TI), ok = write_record(Seeder), ok = write_record(Leecher), [TI, Seeder, Leecher]. cleaner_test_stop([TI, _Seeder, _Leecher]) -> application:set_env(etracker, clean_interval, 2700), delete_record(TI), etracker:stop(). cleaner_checks1([#torrent_info{info_hash=IH, seeders=_S, leechers=_L}, _Seeder, _Leecher]) -> etracker_event:subscribe(), receive {etracker_event, {cleanup_completed, peers, Deleted}} -> etracker_db:torrent_peers(IH, 50), #torrent_info{seeders=S1, leechers=L1} = etracker_db:torrent_info(IH), [?_assertEqual(2, Deleted), ?_assertEqual(S1, 0), ?_assertEqual(L1, 1)] after 10000 -> exit(timeout) end. cleaner_checks2([#torrent_info{info_hash=IH, seeders=_S, leechers=_L}, _Seeder, _Leecher]) -> etracker_event:subscribe(), receive {etracker_event, {cleanup_completed, peers, Deleted}} -> etracker_db:torrent_peers(IH, 50), #torrent_info{seeders=S1, leechers=L1} = etracker_db:torrent_info(IH), [?_assertEqual(1, Deleted), ?_assertEqual(S1, 0), ?_assertEqual(L1, 0)] after 10000 -> exit(timeout) end. leecher_first_started(Ann) -> [_Ih, PeerId, Port] = [orddict:fetch(K, Ann) || K <- [info_hash, peer_id, port]], ets:insert(?PEERS, {leecher_first, PeerId, Port}), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 6789}, {event, started}, {compact, 0}]), {ok, Resp1} = send_announce_udp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann1)), Checks = [{<<"incomplete">>, 1}, {<<"complete">>, 0}, {<<"peers">>, []}], GenF = fun (R) -> [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks] end, [GenF(Resp1), GenF(Resp2), GenF(Resp3)]. leecher_first_invalid_requests(Ann) -> Ann1 = orddict:store(info_hash, <<"bad_hash">>, Ann), Ann2 = orddict:store(port, "bad_port", Ann), Ann3 = orddict:erase(info_hash, Ann), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann2)), {ok, Resp3} = (catch send_announce_tcp(orddict:to_list(Ann3))), [?_assertEqual([{<<"failure reason">>,<<"info_hash invalid value">>}], Resp1), ?_assertMatch({{400, _R}, _H, _B}, Resp2), ?_assertEqual([{<<"failure reason">>,<<"info_hash invalid value">>}], Resp3) ]. leecher_second_started(AnnDict) -> [IH, PeerId, Port] = [orddict:fetch(K, AnnDict) || K <- [info_hash, peer_id, port]], PeerId1 = random_string(20), udp last Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, AnnDict, [{peer_id, PeerId1}, {left, 456}, {event, started}, {compact, 0}]), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, AnnDict, [{peer_id, PeerId1}, {left, 456}, {event, none}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp3} = send_announce_udp(orddict:to_list(Ann2)), ?debugVal(etracker_db:torrent_peers(IH, 50)), ?debugVal(Resp3), GenF1 = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(2, proplists:get_value(<<"incomplete">>, R)), ?_assertEqual(0, proplists:get_value(<<"complete">>, R)), ?_assertMatch([_], Peers), [?_assertEqual({K, proplists:get_value(K, lists:nth(1, Peers))}, {K, V}) || {K, V} <- [{<<"ip">>,<<"127.0.0.1">>}, {<<"peer_id">>, PeerId}, {<<"port">>, Port}] ] ] end, GenF2 = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(2, proplists:get_value(<<"incomplete">>, R)), ?_assertEqual(0, proplists:get_value(<<"complete">>, R)), ?_assertMatch([_], Peers), [?_assertEqual({K, proplists:get_value(K, lists:nth(1, Peers))}, {K, V}) || {K, V} <- [{<<"ip">>, {127, 0, 0, 1}}, {<<"port">>, Port}] ] ] end, [GenF1(Resp1), GenF1(Resp2), GenF2(Resp3)]. seeder_first_started(Ann) -> [_Ih, _PeerId, Port] = [orddict:fetch(K, Ann) || K <- [info_hash, peer_id, port]], PeerId = random_string(20), ets:insert(?PEERS, {seeder_first, PeerId, Port}), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{peer_id, PeerId}, {left, 0}, {event, started}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{peer_id, PeerId}, {left, 0}, {event, completed}, {compact, 0}]), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann2)), {ok, Resp4} = send_announce_tcp(orddict:to_list(Ann2)), GenF = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(proplists:get_value(<<"incomplete">>, R), 2), ?_assertEqual(proplists:get_value(<<"complete">>, R), 1), ?_assertMatch([_, _], Peers) ] end, [GenF(Resp1), GenF(Resp2), GenF(Resp3), GenF(Resp4)]. leecher_first_completed(Ann) -> [{_, PeerId1, Port1}] = ets:lookup(?PEERS, leecher_second), [{_, PeerId2, Port2}] = ets:lookup(?PEERS, seeder_first), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, completed}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, ""}, {compact, 1}]), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann2)), Ann3 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, stopped}, {compact, 0}]), {ok, Resp4} = send_announce_tcp(orddict:to_list(Ann3)), {ok, Resp5} = send_announce_tcp(orddict:to_list(Ann3)), Checks1 = [{<<"incomplete">>, 1}, {<<"complete">>, 2}], Checks2 = [{<<"incomplete">>, 1}, {<<"complete">>, 2}], Checks3 = [{<<"incomplete">>, 1}, {<<"complete">>, 1}], GenF1 = fun (R, Checks) -> Peers = proplists:get_value(<<"peers">>, R), PeersIds = lists:filter( fun (P) -> PI = proplists:get_value(<<"peer_id">>, P), lists:member(PI, [PeerId1, PeerId2]) end, Peers), [?_assertMatch([_, _], Peers), ?_assertEqual(length(PeersIds), 2) | [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks] ] end, GenF2 = fun (R, Checks) -> Peers = decode_compact_peers(proplists:get_value(<<"peers">>, R)), [[?_assertEqual({127, 0, 0, 1}, proplists:get_value(<<"ip">>, P)) || P <- Peers], [?_assertEqual(P1, P2) || {P1, P2} <- lists:zip(lists:sort([Port1, Port2]), lists:sort([proplists:get_value(<<"port">>, P) || P <- Peers]))], [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks]] end, [GenF1(Resp1, Checks1), GenF1(Resp2, Checks1), GenF2(Resp3, Checks2), GenF1(Resp4, Checks3), GenF1(Resp5, Checks3)]. leecher_second_stopped(Ann) -> [{_, PeerId1, _}] = ets:lookup(?PEERS, leecher_second), [{_, PeerId2, _}] = ets:lookup(?PEERS, seeder_first), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {peer_id, PeerId1}, {event, stopped}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Checks1 = [{<<"incomplete">>, 0}, {<<"complete">>, 1}], GenF1 = fun (R, Checks) -> Peers = proplists:get_value(<<"peers">>, R), PeersIds = lists:filter( fun (P) -> PI = proplists:get_value(<<"peer_id">>, P), lists:member(PI, [PeerId2]) end, Peers), [?_assertMatch([_], Peers), ?_assertEqual(length(PeersIds), 1) | [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks]] end, [GenF1(Resp1, Checks1), GenF1(Resp2, Checks1)]. check_stats_after_clean() -> KV = [{<<"seeders">>, 0}, {<<"leechers">>, 0}, {<<"peers">>, 0}, {<<"unknown_queries">>, 0}, {<<"invalid_queries">>, 2}, {<<"scrapes">>, 2}, {<<"announces">>, 17}, {<<"failed_queries">>, 1}, {<<"deleted_peers">>, 3}], check_stats(KV). check_stats_after_test(_) -> KV = [{<<"seeders">>, 1}, {<<"leechers">>, 0}, {<<"peers">>, 1}, {<<"unknown_queries">>, 0}, {<<"invalid_queries">>, 2}, {<<"scrapes">>, 2}, {<<"announces">>, 17}, {<<"udp_connections">>, 2}, {<<"failed_queries">>, 1}, {<<"deleted_peers">>, 0}], check_stats(KV). check_stats(KV) -> etracker_db:stats_update(), {ok, {{200, _}, _, Resp}} = lhttpc:request(":8181/_stats", get, [{"Content-Type", "application/json"}], "", 1000), Res = jiffy:decode(Resp), ?debugFmt("~p~n", [Res]), {KV2} = Res, GetValF = fun (K) -> case proplists:get_value(K, KV2) of {KKV} -> proplists:get_value(<<"count">>, KKV); Val -> Val end end, [[?_assertEqual({K, V}, {K, GetValF(K)}) || {K, V} <- KV] ]. scrape_all(_Ann) -> {ok, Resp} = send_scrape([]), Keys = lists:sort([K || {K, _} <- Resp]), IHs = all_torrent_info_hashes(), Files = proplists:get_value(<<"files">>, Resp, []), Flags = lists:sort([K || {K, _} <- proplists:get_value(<<"flags">>, Resp, [])]), {IH, Info} = lists:nth(1, Files), InfoKeys = lists:sort([K || {K, _} <- Info]), GenF = fun (_R) -> [ ?_assertEqual([<<"files">>, <<"flags">>], Keys), ?_assertEqual(true, lists:member(IH, IHs)), ?_assertEqual([<<"complete">>, <<"downloaded">>, <<"incomplete">>], InfoKeys), ?_assertEqual([<<"min_request_interval">>], Flags) ] end, [GenF(Resp)]. scrape_some(_Ann) -> IHs = all_torrent_info_hashes(), IH1 = lists:nth(random:uniform(length(IHs)), IHs), IH2 = lists:nth(random:uniform(length(IHs)), IHs), ReqIHs = lists:sort([IH1, IH2]), {ok, Resp} = send_scrape([{info_hash, ReqIHs}]), Keys = lists:sort([K || {K, _} <- Resp]), FileKeys = lists:sort([K || {K, _} <- proplists:get_value(<<"files">>, Resp, [])]), GenF = fun (_R) -> [ ?_assertEqual([<<"files">>, <<"flags">>], Keys), ?_assertEqual(ReqIHs, FileKeys) ] end, [GenF(Resp)]. send_announce_tcp(PL) -> contact_tracker_http(announce, ?TRACKER_URL, PL). send_announce_udp(PL) -> contact_tracker_udp(announce, ?TRACKER_PEER, PL). send_scrape(PL) -> contact_tracker_http(scrape, ?TRACKER_URL, PL). random_announce() -> [ {info_hash, random_string(20)}, {peer_id, random_string(20)}, {compact, 1}, {port, 12345}, {uploaded, random:uniform(10000000000)}, {downloaded, random:uniform(10000000000)}, {left, random:uniform(10000000000)}, {key, random:uniform(16#ffff)} ]. contact_tracker_udp(announce, TrackerPeer, PL) -> TransReqF = fun (downloaded, V) -> {down, V}; (uploaded, V) -> {up, V}; (event, "") -> {event, none}; (event, V) -> {event, V}; (compact, _V) -> undefined; (K, V) -> {K, V} end, TransAnsF = fun (leechers, V) -> {<<"incomplete">>, V}; (seeders, V) -> {<<"complete">>, V}; (K, V) -> {list_to_binary(atom_to_list(K)), V} end, PL1 = [V || V <- [TransReqF(K, V) || {K, V} <- PL], V /= undefined], case etorrent_udp_tracker_mgr:announce(TrackerPeer, PL1, 5000) of {ok, {announce, Peers, Info}} -> {ok, [{<<"peers">>, [[{<<"ip">>, IP}, {<<"port">>, Port}] || {IP, Port} <- Peers]} |[TransAnsF(K, V) || {K, V} <- Info]]}; Error -> Error end. contact_tracker_http(Request, Url, PL) -> RequestStr = atom_to_list(Request), Url1 = case lists:last(Url) of $/ -> Url ++ RequestStr; _ -> Url ++ [$/|RequestStr] end, RequestUrl = build_tracker_url(Request, Url1, PL), case etorrent_http:request(RequestUrl) of {ok, {{200, _}, _, Body}} -> etorrent_bcoding:decode(Body); Error -> Error end. build_tracker_url(announce, Url, PL) -> Event = proplists:get_value(event, PL), InfoHash = proplists:get_value(info_hash, PL, []), PeerId = proplists:get_value(peer_id, PL), Uploaded = proplists:get_value(uploaded, PL), Downloaded = proplists:get_value(downloaded, PL), Left = proplists:get_value(left, PL), Port = proplists:get_value(port, PL), Compact = proplists:get_value(compact, PL), Request = [{"info_hash", etorrent_http:build_encoded_form_rfc1738(InfoHash)}, {"peer_id", etorrent_http:build_encoded_form_rfc1738(PeerId)}, {"uploaded", Uploaded}, {"downloaded", Downloaded}, {"left", Left}, {"port", Port}, {"compact", Compact}], EReq = case Event of none -> Request; "" -> Request; started -> [{"event", "started"} | Request]; stopped -> [{"event", "stopped"} | Request]; completed -> [{"event", "completed"} | Request]; _ -> [{"event", atom_to_list(Event)} | Request] end, FlatUrl = lists:flatten(Url), Delim = case lists:member($?, FlatUrl) of true -> "&"; false -> "?" end, lists:concat([Url, Delim, etorrent_http:mk_header(EReq)]); build_tracker_url(scrape, Url, PL) -> InfoHash = proplists:get_value(info_hash, PL, []), InfoHashes = if is_binary(InfoHash) -> [InfoHash]; true -> InfoHash end, Request = [{"info_hash", etorrent_http:build_encoded_form_rfc1738(IH)} || IH <- InfoHashes], FlatUrl = lists:flatten(Url), Delim = if Request == [] -> ""; true -> case lists:member($?, FlatUrl) of true -> "&"; false -> "?" end end, lists:concat([Url, Delim, etorrent_http:mk_header(Request)]). random_string(Len) -> Chrs = list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), ChrsSize = size(Chrs), F = fun(_, R) -> [element(random:uniform(ChrsSize), Chrs) | R] end, list_to_binary(lists:foldl(F, "", lists:seq(1, Len))). decode_compact_peers(Peers) -> decode_compact_peers(Peers, []). decode_compact_peers(<<>>, Acc) -> Acc; decode_compact_peers(<<I1:8,I2:8,I3:8,I4:8,Port:16,Rest/binary>>, Acc) -> decode_compact_peers(Rest, [[{<<"ip">>, {I1, I2, I3, I4}}, {<<"port">>, Port}] | Acc]). all_torrent_info_hashes() -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of etracker_pgsql -> Q = "select info_hash from torrent_info", {ok, _C, Rows} = etracker_db:db_call({equery, Q, []}), [IH || {IH} <- Rows]; etracker_ets -> ets:select(torrent_info, ets:fun2ms(fun (#torrent_info{info_hash=IH}) -> IH end)); etracker_mnesia -> Q = ets:fun2ms(fun (#torrent_info{info_hash=IH}) -> IH end), mnesia:activity(async_dirty, fun mnesia:select/2, [etracker_mnesia_mgr:table_name(torrent_info), Q], mnesia_frag) end. write_record(Rec) -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of _ -> ok = etracker_db:db_call({write, Rec}) end. delete_record(Rec) -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of _ -> etracker_db:db_call({delete, Rec}) end.
null
https://raw.githubusercontent.com/eryx67/etracker/f41f5d2172d2a0cf5aeebcc7442c7523a9338340/test/etracker_test.erl
erlang
-module(etracker_test). -include_lib("eunit/include/eunit.hrl"). -include_lib("stdlib/include/ms_transform.hrl"). -include("../include/etracker.hrl"). -define(PEERS, test_peers). -define(TRACKER_URL, ":8181"). -define(TRACKER_PEER, {{127, 0, 0, 1}, 8181}). etracker_test_() -> {setup, fun start_apps/0, fun stop/1, fun(_SetupData) -> [{setup, fun setup_announce/0, fun (Ann) -> {inorder, [Fun(Ann) || Fun <- [fun leecher_first_started/1, fun leecher_first_invalid_requests/1, fun leecher_second_started/1, fun seeder_first_started/1, fun leecher_first_completed/1, fun scrape_all/1, fun scrape_some/1, fun leecher_second_stopped/1, fun check_stats_after_test/1 ] ]} end }] end }. etracker_cleaner_test_() -> application:load(etracker), {setup, fun cleaner_test_start/0, fun cleaner_test_stop/1, fun (SD) -> {inorder, [{timeout, 60, [ cleaner_checks1(SD), cleaner_checks2(SD) ]}, check_stats_after_clean() ]} end }. start_apps() -> application:start(asn1), application:ensure_all_started(lager), application:ensure_all_started(cowboy), etorrent:start_app(), etracker:start(), timer:sleep(5000), []. setup_announce() -> ets:new(?PEERS, [named_table, public]), random:seed(now()), random_announce(). stop(_SD) -> etracker:stop(), etorrent:stop_app() . cleaner_test_start() -> application:load(etracker), application:set_env(etracker, clean_interval, 5), etracker:start(), timer:sleep(1000), cleaner_test_start1(). cleaner_test_start1() -> InfoHash = random_string(20), PeerId1 = random_string(20), PeerId2 = random_string(20), {Mega, Sec, Micro} = now(), TI = #torrent_info{ info_hash=InfoHash, leechers=3, seeders=3 }, SeederMtime = {Mega, Sec - 2, Micro}, Seeder = #torrent_user{ id={InfoHash, PeerId1}, peer={{127, 0, 0, 1}, 6969}, finished=true, mtime=SeederMtime }, LeecherMtime = {Mega, Sec, Micro}, Leecher = #torrent_user{ id={InfoHash, PeerId2}, peer={{127, 0, 0, 1}, 6969}, finished=false, mtime=LeecherMtime }, ok = write_record(TI), ok = write_record(Seeder), ok = write_record(Leecher), [TI, Seeder, Leecher]. cleaner_test_stop([TI, _Seeder, _Leecher]) -> application:set_env(etracker, clean_interval, 2700), delete_record(TI), etracker:stop(). cleaner_checks1([#torrent_info{info_hash=IH, seeders=_S, leechers=_L}, _Seeder, _Leecher]) -> etracker_event:subscribe(), receive {etracker_event, {cleanup_completed, peers, Deleted}} -> etracker_db:torrent_peers(IH, 50), #torrent_info{seeders=S1, leechers=L1} = etracker_db:torrent_info(IH), [?_assertEqual(2, Deleted), ?_assertEqual(S1, 0), ?_assertEqual(L1, 1)] after 10000 -> exit(timeout) end. cleaner_checks2([#torrent_info{info_hash=IH, seeders=_S, leechers=_L}, _Seeder, _Leecher]) -> etracker_event:subscribe(), receive {etracker_event, {cleanup_completed, peers, Deleted}} -> etracker_db:torrent_peers(IH, 50), #torrent_info{seeders=S1, leechers=L1} = etracker_db:torrent_info(IH), [?_assertEqual(1, Deleted), ?_assertEqual(S1, 0), ?_assertEqual(L1, 0)] after 10000 -> exit(timeout) end. leecher_first_started(Ann) -> [_Ih, PeerId, Port] = [orddict:fetch(K, Ann) || K <- [info_hash, peer_id, port]], ets:insert(?PEERS, {leecher_first, PeerId, Port}), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 6789}, {event, started}, {compact, 0}]), {ok, Resp1} = send_announce_udp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann1)), Checks = [{<<"incomplete">>, 1}, {<<"complete">>, 0}, {<<"peers">>, []}], GenF = fun (R) -> [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks] end, [GenF(Resp1), GenF(Resp2), GenF(Resp3)]. leecher_first_invalid_requests(Ann) -> Ann1 = orddict:store(info_hash, <<"bad_hash">>, Ann), Ann2 = orddict:store(port, "bad_port", Ann), Ann3 = orddict:erase(info_hash, Ann), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann2)), {ok, Resp3} = (catch send_announce_tcp(orddict:to_list(Ann3))), [?_assertEqual([{<<"failure reason">>,<<"info_hash invalid value">>}], Resp1), ?_assertMatch({{400, _R}, _H, _B}, Resp2), ?_assertEqual([{<<"failure reason">>,<<"info_hash invalid value">>}], Resp3) ]. leecher_second_started(AnnDict) -> [IH, PeerId, Port] = [orddict:fetch(K, AnnDict) || K <- [info_hash, peer_id, port]], PeerId1 = random_string(20), udp last Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, AnnDict, [{peer_id, PeerId1}, {left, 456}, {event, started}, {compact, 0}]), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, AnnDict, [{peer_id, PeerId1}, {left, 456}, {event, none}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp3} = send_announce_udp(orddict:to_list(Ann2)), ?debugVal(etracker_db:torrent_peers(IH, 50)), ?debugVal(Resp3), GenF1 = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(2, proplists:get_value(<<"incomplete">>, R)), ?_assertEqual(0, proplists:get_value(<<"complete">>, R)), ?_assertMatch([_], Peers), [?_assertEqual({K, proplists:get_value(K, lists:nth(1, Peers))}, {K, V}) || {K, V} <- [{<<"ip">>,<<"127.0.0.1">>}, {<<"peer_id">>, PeerId}, {<<"port">>, Port}] ] ] end, GenF2 = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(2, proplists:get_value(<<"incomplete">>, R)), ?_assertEqual(0, proplists:get_value(<<"complete">>, R)), ?_assertMatch([_], Peers), [?_assertEqual({K, proplists:get_value(K, lists:nth(1, Peers))}, {K, V}) || {K, V} <- [{<<"ip">>, {127, 0, 0, 1}}, {<<"port">>, Port}] ] ] end, [GenF1(Resp1), GenF1(Resp2), GenF2(Resp3)]. seeder_first_started(Ann) -> [_Ih, _PeerId, Port] = [orddict:fetch(K, Ann) || K <- [info_hash, peer_id, port]], PeerId = random_string(20), ets:insert(?PEERS, {seeder_first, PeerId, Port}), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{peer_id, PeerId}, {left, 0}, {event, started}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{peer_id, PeerId}, {left, 0}, {event, completed}, {compact, 0}]), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann2)), {ok, Resp4} = send_announce_tcp(orddict:to_list(Ann2)), GenF = fun (R) -> Peers = proplists:get_value(<<"peers">>, R), [ ?_assertEqual(proplists:get_value(<<"incomplete">>, R), 2), ?_assertEqual(proplists:get_value(<<"complete">>, R), 1), ?_assertMatch([_, _], Peers) ] end, [GenF(Resp1), GenF(Resp2), GenF(Resp3), GenF(Resp4)]. leecher_first_completed(Ann) -> [{_, PeerId1, Port1}] = ets:lookup(?PEERS, leecher_second), [{_, PeerId2, Port2}] = ets:lookup(?PEERS, seeder_first), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, completed}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Ann2 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, ""}, {compact, 1}]), {ok, Resp3} = send_announce_tcp(orddict:to_list(Ann2)), Ann3 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {event, stopped}, {compact, 0}]), {ok, Resp4} = send_announce_tcp(orddict:to_list(Ann3)), {ok, Resp5} = send_announce_tcp(orddict:to_list(Ann3)), Checks1 = [{<<"incomplete">>, 1}, {<<"complete">>, 2}], Checks2 = [{<<"incomplete">>, 1}, {<<"complete">>, 2}], Checks3 = [{<<"incomplete">>, 1}, {<<"complete">>, 1}], GenF1 = fun (R, Checks) -> Peers = proplists:get_value(<<"peers">>, R), PeersIds = lists:filter( fun (P) -> PI = proplists:get_value(<<"peer_id">>, P), lists:member(PI, [PeerId1, PeerId2]) end, Peers), [?_assertMatch([_, _], Peers), ?_assertEqual(length(PeersIds), 2) | [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks] ] end, GenF2 = fun (R, Checks) -> Peers = decode_compact_peers(proplists:get_value(<<"peers">>, R)), [[?_assertEqual({127, 0, 0, 1}, proplists:get_value(<<"ip">>, P)) || P <- Peers], [?_assertEqual(P1, P2) || {P1, P2} <- lists:zip(lists:sort([Port1, Port2]), lists:sort([proplists:get_value(<<"port">>, P) || P <- Peers]))], [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks]] end, [GenF1(Resp1, Checks1), GenF1(Resp2, Checks1), GenF2(Resp3, Checks2), GenF1(Resp4, Checks3), GenF1(Resp5, Checks3)]. leecher_second_stopped(Ann) -> [{_, PeerId1, _}] = ets:lookup(?PEERS, leecher_second), [{_, PeerId2, _}] = ets:lookup(?PEERS, seeder_first), Ann1 = lists:foldl(fun ({K, V}, D) -> orddict:store(K, V, D) end, Ann, [{left, 0}, {peer_id, PeerId1}, {event, stopped}, {compact, 0}]), {ok, Resp1} = send_announce_tcp(orddict:to_list(Ann1)), {ok, Resp2} = send_announce_tcp(orddict:to_list(Ann1)), Checks1 = [{<<"incomplete">>, 0}, {<<"complete">>, 1}], GenF1 = fun (R, Checks) -> Peers = proplists:get_value(<<"peers">>, R), PeersIds = lists:filter( fun (P) -> PI = proplists:get_value(<<"peer_id">>, P), lists:member(PI, [PeerId2]) end, Peers), [?_assertMatch([_], Peers), ?_assertEqual(length(PeersIds), 1) | [?_assertEqual(proplists:get_value(K, R), V) || {K, V} <- Checks]] end, [GenF1(Resp1, Checks1), GenF1(Resp2, Checks1)]. check_stats_after_clean() -> KV = [{<<"seeders">>, 0}, {<<"leechers">>, 0}, {<<"peers">>, 0}, {<<"unknown_queries">>, 0}, {<<"invalid_queries">>, 2}, {<<"scrapes">>, 2}, {<<"announces">>, 17}, {<<"failed_queries">>, 1}, {<<"deleted_peers">>, 3}], check_stats(KV). check_stats_after_test(_) -> KV = [{<<"seeders">>, 1}, {<<"leechers">>, 0}, {<<"peers">>, 1}, {<<"unknown_queries">>, 0}, {<<"invalid_queries">>, 2}, {<<"scrapes">>, 2}, {<<"announces">>, 17}, {<<"udp_connections">>, 2}, {<<"failed_queries">>, 1}, {<<"deleted_peers">>, 0}], check_stats(KV). check_stats(KV) -> etracker_db:stats_update(), {ok, {{200, _}, _, Resp}} = lhttpc:request(":8181/_stats", get, [{"Content-Type", "application/json"}], "", 1000), Res = jiffy:decode(Resp), ?debugFmt("~p~n", [Res]), {KV2} = Res, GetValF = fun (K) -> case proplists:get_value(K, KV2) of {KKV} -> proplists:get_value(<<"count">>, KKV); Val -> Val end end, [[?_assertEqual({K, V}, {K, GetValF(K)}) || {K, V} <- KV] ]. scrape_all(_Ann) -> {ok, Resp} = send_scrape([]), Keys = lists:sort([K || {K, _} <- Resp]), IHs = all_torrent_info_hashes(), Files = proplists:get_value(<<"files">>, Resp, []), Flags = lists:sort([K || {K, _} <- proplists:get_value(<<"flags">>, Resp, [])]), {IH, Info} = lists:nth(1, Files), InfoKeys = lists:sort([K || {K, _} <- Info]), GenF = fun (_R) -> [ ?_assertEqual([<<"files">>, <<"flags">>], Keys), ?_assertEqual(true, lists:member(IH, IHs)), ?_assertEqual([<<"complete">>, <<"downloaded">>, <<"incomplete">>], InfoKeys), ?_assertEqual([<<"min_request_interval">>], Flags) ] end, [GenF(Resp)]. scrape_some(_Ann) -> IHs = all_torrent_info_hashes(), IH1 = lists:nth(random:uniform(length(IHs)), IHs), IH2 = lists:nth(random:uniform(length(IHs)), IHs), ReqIHs = lists:sort([IH1, IH2]), {ok, Resp} = send_scrape([{info_hash, ReqIHs}]), Keys = lists:sort([K || {K, _} <- Resp]), FileKeys = lists:sort([K || {K, _} <- proplists:get_value(<<"files">>, Resp, [])]), GenF = fun (_R) -> [ ?_assertEqual([<<"files">>, <<"flags">>], Keys), ?_assertEqual(ReqIHs, FileKeys) ] end, [GenF(Resp)]. send_announce_tcp(PL) -> contact_tracker_http(announce, ?TRACKER_URL, PL). send_announce_udp(PL) -> contact_tracker_udp(announce, ?TRACKER_PEER, PL). send_scrape(PL) -> contact_tracker_http(scrape, ?TRACKER_URL, PL). random_announce() -> [ {info_hash, random_string(20)}, {peer_id, random_string(20)}, {compact, 1}, {port, 12345}, {uploaded, random:uniform(10000000000)}, {downloaded, random:uniform(10000000000)}, {left, random:uniform(10000000000)}, {key, random:uniform(16#ffff)} ]. contact_tracker_udp(announce, TrackerPeer, PL) -> TransReqF = fun (downloaded, V) -> {down, V}; (uploaded, V) -> {up, V}; (event, "") -> {event, none}; (event, V) -> {event, V}; (compact, _V) -> undefined; (K, V) -> {K, V} end, TransAnsF = fun (leechers, V) -> {<<"incomplete">>, V}; (seeders, V) -> {<<"complete">>, V}; (K, V) -> {list_to_binary(atom_to_list(K)), V} end, PL1 = [V || V <- [TransReqF(K, V) || {K, V} <- PL], V /= undefined], case etorrent_udp_tracker_mgr:announce(TrackerPeer, PL1, 5000) of {ok, {announce, Peers, Info}} -> {ok, [{<<"peers">>, [[{<<"ip">>, IP}, {<<"port">>, Port}] || {IP, Port} <- Peers]} |[TransAnsF(K, V) || {K, V} <- Info]]}; Error -> Error end. contact_tracker_http(Request, Url, PL) -> RequestStr = atom_to_list(Request), Url1 = case lists:last(Url) of $/ -> Url ++ RequestStr; _ -> Url ++ [$/|RequestStr] end, RequestUrl = build_tracker_url(Request, Url1, PL), case etorrent_http:request(RequestUrl) of {ok, {{200, _}, _, Body}} -> etorrent_bcoding:decode(Body); Error -> Error end. build_tracker_url(announce, Url, PL) -> Event = proplists:get_value(event, PL), InfoHash = proplists:get_value(info_hash, PL, []), PeerId = proplists:get_value(peer_id, PL), Uploaded = proplists:get_value(uploaded, PL), Downloaded = proplists:get_value(downloaded, PL), Left = proplists:get_value(left, PL), Port = proplists:get_value(port, PL), Compact = proplists:get_value(compact, PL), Request = [{"info_hash", etorrent_http:build_encoded_form_rfc1738(InfoHash)}, {"peer_id", etorrent_http:build_encoded_form_rfc1738(PeerId)}, {"uploaded", Uploaded}, {"downloaded", Downloaded}, {"left", Left}, {"port", Port}, {"compact", Compact}], EReq = case Event of none -> Request; "" -> Request; started -> [{"event", "started"} | Request]; stopped -> [{"event", "stopped"} | Request]; completed -> [{"event", "completed"} | Request]; _ -> [{"event", atom_to_list(Event)} | Request] end, FlatUrl = lists:flatten(Url), Delim = case lists:member($?, FlatUrl) of true -> "&"; false -> "?" end, lists:concat([Url, Delim, etorrent_http:mk_header(EReq)]); build_tracker_url(scrape, Url, PL) -> InfoHash = proplists:get_value(info_hash, PL, []), InfoHashes = if is_binary(InfoHash) -> [InfoHash]; true -> InfoHash end, Request = [{"info_hash", etorrent_http:build_encoded_form_rfc1738(IH)} || IH <- InfoHashes], FlatUrl = lists:flatten(Url), Delim = if Request == [] -> ""; true -> case lists:member($?, FlatUrl) of true -> "&"; false -> "?" end end, lists:concat([Url, Delim, etorrent_http:mk_header(Request)]). random_string(Len) -> Chrs = list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), ChrsSize = size(Chrs), F = fun(_, R) -> [element(random:uniform(ChrsSize), Chrs) | R] end, list_to_binary(lists:foldl(F, "", lists:seq(1, Len))). decode_compact_peers(Peers) -> decode_compact_peers(Peers, []). decode_compact_peers(<<>>, Acc) -> Acc; decode_compact_peers(<<I1:8,I2:8,I3:8,I4:8,Port:16,Rest/binary>>, Acc) -> decode_compact_peers(Rest, [[{<<"ip">>, {I1, I2, I3, I4}}, {<<"port">>, Port}] | Acc]). all_torrent_info_hashes() -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of etracker_pgsql -> Q = "select info_hash from torrent_info", {ok, _C, Rows} = etracker_db:db_call({equery, Q, []}), [IH || {IH} <- Rows]; etracker_ets -> ets:select(torrent_info, ets:fun2ms(fun (#torrent_info{info_hash=IH}) -> IH end)); etracker_mnesia -> Q = ets:fun2ms(fun (#torrent_info{info_hash=IH}) -> IH end), mnesia:activity(async_dirty, fun mnesia:select/2, [etracker_mnesia_mgr:table_name(torrent_info), Q], mnesia_frag) end. write_record(Rec) -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of _ -> ok = etracker_db:db_call({write, Rec}) end. delete_record(Rec) -> {ok, {WorkerArgs, _}} = etracker_env:get(db_pool), Mod = proplists:get_value(worker_module, WorkerArgs), case Mod of _ -> etracker_db:db_call({delete, Rec}) end.
2cf53f09ca6661934cedf9013e7da8f0545165ac477403a914726dc514b68d38
ocaml-community/zed
zed_input.ml
* * ------------ * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_input.ml * ------------ * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) module type S = sig type event type +'a t val empty : 'a t val add : event list -> 'a -> 'a t -> 'a t val remove : event list -> 'a t -> 'a t val fold : (event list -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val bindings : 'a t -> (event list * 'a) list type 'a resolver type 'a pack val pack : ('a -> 'b) -> 'a t -> 'b pack val resolver : 'a pack list -> 'a resolver type 'a result = | Accepted of 'a | Continue of 'a resolver | Rejected val resolve : event -> 'a resolver -> 'a result end module Make (Event : Map.OrderedType) = struct type event = Event.t module Event_map = Map.Make (Event) type 'a t = 'a node Event_map.t and 'a node = | Set of 'a t | Val of 'a let empty = Event_map.empty let rec add events value set = match events with | [] -> invalid_arg "Zed_input.Make.add" | [event] -> Event_map.add event (Val value) set | event :: events -> match try Some (Event_map.find event set) with Not_found -> None with | None | Some (Val _) -> Event_map.add event (Set (add events value empty)) set | Some (Set s) -> Event_map.add event (Set (add events value s)) set let rec remove events set = match events with | [] -> invalid_arg "Zed_input.Make.remove" | [event] -> Event_map.remove event set | event :: events -> match try Some (Event_map.find event set) with Not_found -> None with | None | Some (Val _) -> set | Some (Set s) -> let s = remove events s in if Event_map.is_empty s then Event_map.remove event set else Event_map.add event (Set s) set let fold f set acc = let rec loop prefix set acc = Event_map.fold (fun event node acc -> match node with | Val v -> f (List.rev (event :: prefix)) v acc | Set s -> loop (event :: prefix) s acc) set acc in loop [] set acc let bindings set = List.rev (fold (fun events action l -> (events, action) :: l) set []) module type Pack = sig type a type b val set : a t val map : a -> b end type 'a pack = (module Pack with type b = 'a) type 'a resolver = 'a pack list let pack (type u) (type v) map set = let module Pack = struct type a = u type b = v let set = set let map = map end in (module Pack : Pack with type b = v) let resolver l = l type 'a result = | Accepted of 'a | Continue of 'a resolver | Rejected let rec resolve_rec : 'a. event -> 'a pack list -> 'a pack list -> 'a result = fun (type u) event acc packs -> match packs with | [] -> if acc = [] then Rejected else Continue (List.rev acc) | p :: packs -> let module Pack = (val p : Pack with type b = u) in match try Some (Event_map.find event Pack.set) with Not_found -> None with | Some (Set set) -> resolve_rec event (pack Pack.map set :: acc) packs | Some (Val v) -> Accepted (Pack.map v) | None -> resolve_rec event acc packs let resolve event sets = resolve_rec event [] sets end
null
https://raw.githubusercontent.com/ocaml-community/zed/3d1293205db625a5ea4d29cfe214d731c2596850/src/zed_input.ml
ocaml
* * ------------ * Copyright : ( c ) 2011 , < > * Licence : BSD3 * * This file is a part of , an editor engine . * zed_input.ml * ------------ * Copyright : (c) 2011, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Zed, an editor engine. *) module type S = sig type event type +'a t val empty : 'a t val add : event list -> 'a -> 'a t -> 'a t val remove : event list -> 'a t -> 'a t val fold : (event list -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val bindings : 'a t -> (event list * 'a) list type 'a resolver type 'a pack val pack : ('a -> 'b) -> 'a t -> 'b pack val resolver : 'a pack list -> 'a resolver type 'a result = | Accepted of 'a | Continue of 'a resolver | Rejected val resolve : event -> 'a resolver -> 'a result end module Make (Event : Map.OrderedType) = struct type event = Event.t module Event_map = Map.Make (Event) type 'a t = 'a node Event_map.t and 'a node = | Set of 'a t | Val of 'a let empty = Event_map.empty let rec add events value set = match events with | [] -> invalid_arg "Zed_input.Make.add" | [event] -> Event_map.add event (Val value) set | event :: events -> match try Some (Event_map.find event set) with Not_found -> None with | None | Some (Val _) -> Event_map.add event (Set (add events value empty)) set | Some (Set s) -> Event_map.add event (Set (add events value s)) set let rec remove events set = match events with | [] -> invalid_arg "Zed_input.Make.remove" | [event] -> Event_map.remove event set | event :: events -> match try Some (Event_map.find event set) with Not_found -> None with | None | Some (Val _) -> set | Some (Set s) -> let s = remove events s in if Event_map.is_empty s then Event_map.remove event set else Event_map.add event (Set s) set let fold f set acc = let rec loop prefix set acc = Event_map.fold (fun event node acc -> match node with | Val v -> f (List.rev (event :: prefix)) v acc | Set s -> loop (event :: prefix) s acc) set acc in loop [] set acc let bindings set = List.rev (fold (fun events action l -> (events, action) :: l) set []) module type Pack = sig type a type b val set : a t val map : a -> b end type 'a pack = (module Pack with type b = 'a) type 'a resolver = 'a pack list let pack (type u) (type v) map set = let module Pack = struct type a = u type b = v let set = set let map = map end in (module Pack : Pack with type b = v) let resolver l = l type 'a result = | Accepted of 'a | Continue of 'a resolver | Rejected let rec resolve_rec : 'a. event -> 'a pack list -> 'a pack list -> 'a result = fun (type u) event acc packs -> match packs with | [] -> if acc = [] then Rejected else Continue (List.rev acc) | p :: packs -> let module Pack = (val p : Pack with type b = u) in match try Some (Event_map.find event Pack.set) with Not_found -> None with | Some (Set set) -> resolve_rec event (pack Pack.map set :: acc) packs | Some (Val v) -> Accepted (Pack.map v) | None -> resolve_rec event acc packs let resolve event sets = resolve_rec event [] sets end
9a45811f2bd2e062128545fb9e85b057fdeaaae8636429e449e0702939d32913
jaspervdj/advent-of-code
KnotHash.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} # LANGUAGE ScopedTypeVariables # module AdventOfCode.KnotHash ( knotHash , knotHashHex , single ) where import Control.Monad (foldM, forM_) import Control.Monad.ST (ST, runST) import Data.Bits (xor) import Data.Char (ord) import Data.Proxy (Proxy (..)) import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Unboxed.Mutable as VUM import Data.Word (Word8) import GHC.TypeLits (KnownNat, Nat, natVal) import Prelude hiding (round) import Text.Printf (printf) -------------------------------------------------------------------------------- newtype RingIdx (n :: Nat) = RingIdx {fromRingIdx :: Int} deriving (Show) toRingIdx :: forall n. KnownNat n => Int -> RingIdx n toRingIdx x = RingIdx (x `mod` fromIntegral (natVal (Proxy :: Proxy n))) instance forall n. KnownNat n => Semigroup (RingIdx n) where RingIdx x <> RingIdx y = toRingIdx (x + y) instance forall n. KnownNat n => Monoid (RingIdx n) where mempty = RingIdx 0 mappend = (<>) -------------------------------------------------------------------------------- data Rope n s a = Rope { rSkipSize :: !(RingIdx n) , rPosition :: !(RingIdx n) , rVec :: !(VUM.MVector s a) } sequential :: forall n s a. (KnownNat n, Num a, VUM.Unbox a) => ST s (Rope n s a) sequential = do let !len = fromIntegral (natVal (Proxy :: Proxy n)) vec <- VUM.unsafeNew len forM_ [0 .. len - 1] $ \i -> VUM.unsafeWrite vec i (fromIntegral i) return Rope {rSkipSize = mempty, rPosition = mempty, rVec = vec} knot :: (KnownNat n, VUM.Unbox a) => Int -> Rope n s a -> ST s (Rope n s a) knot len rope = do forM_ [0 .. (len `div` 2) - 1] $ \i -> let !ix = rPosition rope <> toRingIdx i !iy = rPosition rope <> toRingIdx (len - 1 - i) in VUM.unsafeSwap (rVec rope) (fromRingIdx ix) (fromRingIdx iy) return rope { rPosition = rPosition rope <> toRingIdx len <> rSkipSize rope , rSkipSize = rSkipSize rope <> toRingIdx 1 } round :: (KnownNat n, VUM.Unbox a) => [Int] -> Rope n s a -> ST s (Rope n s a) round lens rope = foldM (\r l -> knot l r) rope lens densify256 :: VU.Vector Word8 -> VU.Vector Word8 densify256 vec256 = VU.generate 16 $ \i -> let slice = VU.slice (i * 16) 16 vec256 in VU.foldl1' xor slice knotHash :: String -> VU.Vector Word8 knotHash input = let !lens2 = map ord input ++ [17, 31, 73, 47, 23] !vec2 = runST (run64 (Proxy :: Proxy 256) lens2) in densify256 vec2 where run64 :: forall s n. KnownNat n => Proxy n -> [Int] -> ST s (VU.Vector Word8) run64 _proxy lens = do rope0 <- sequential :: ST s (Rope n s Word8) rope1 <- foldM (\r _i -> round lens r) rope0 [0 .. 63 :: Int] VU.freeze $ rVec rope1 knotHashHex :: String -> String knotHashHex = concatMap (printf "%02x") . VU.toList . knotHash -- | Run a single round. single :: forall s n. KnownNat n => Proxy n -> [Int] -> ST s (VU.Vector Int) single _proxy lens = do rope0 <- sequential :: ST s (Rope n s Int) rope1 <- round lens rope0 VU.freeze $ rVec rope1
null
https://raw.githubusercontent.com/jaspervdj/advent-of-code/bdc9628d1495d4e7fdbd9cea2739b929f733e751/lib/hs/AdventOfCode/KnotHash.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE DataKinds # # LANGUAGE KindSignatures # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | Run a single round.
# LANGUAGE ScopedTypeVariables # module AdventOfCode.KnotHash ( knotHash , knotHashHex , single ) where import Control.Monad (foldM, forM_) import Control.Monad.ST (ST, runST) import Data.Bits (xor) import Data.Char (ord) import Data.Proxy (Proxy (..)) import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Unboxed.Mutable as VUM import Data.Word (Word8) import GHC.TypeLits (KnownNat, Nat, natVal) import Prelude hiding (round) import Text.Printf (printf) newtype RingIdx (n :: Nat) = RingIdx {fromRingIdx :: Int} deriving (Show) toRingIdx :: forall n. KnownNat n => Int -> RingIdx n toRingIdx x = RingIdx (x `mod` fromIntegral (natVal (Proxy :: Proxy n))) instance forall n. KnownNat n => Semigroup (RingIdx n) where RingIdx x <> RingIdx y = toRingIdx (x + y) instance forall n. KnownNat n => Monoid (RingIdx n) where mempty = RingIdx 0 mappend = (<>) data Rope n s a = Rope { rSkipSize :: !(RingIdx n) , rPosition :: !(RingIdx n) , rVec :: !(VUM.MVector s a) } sequential :: forall n s a. (KnownNat n, Num a, VUM.Unbox a) => ST s (Rope n s a) sequential = do let !len = fromIntegral (natVal (Proxy :: Proxy n)) vec <- VUM.unsafeNew len forM_ [0 .. len - 1] $ \i -> VUM.unsafeWrite vec i (fromIntegral i) return Rope {rSkipSize = mempty, rPosition = mempty, rVec = vec} knot :: (KnownNat n, VUM.Unbox a) => Int -> Rope n s a -> ST s (Rope n s a) knot len rope = do forM_ [0 .. (len `div` 2) - 1] $ \i -> let !ix = rPosition rope <> toRingIdx i !iy = rPosition rope <> toRingIdx (len - 1 - i) in VUM.unsafeSwap (rVec rope) (fromRingIdx ix) (fromRingIdx iy) return rope { rPosition = rPosition rope <> toRingIdx len <> rSkipSize rope , rSkipSize = rSkipSize rope <> toRingIdx 1 } round :: (KnownNat n, VUM.Unbox a) => [Int] -> Rope n s a -> ST s (Rope n s a) round lens rope = foldM (\r l -> knot l r) rope lens densify256 :: VU.Vector Word8 -> VU.Vector Word8 densify256 vec256 = VU.generate 16 $ \i -> let slice = VU.slice (i * 16) 16 vec256 in VU.foldl1' xor slice knotHash :: String -> VU.Vector Word8 knotHash input = let !lens2 = map ord input ++ [17, 31, 73, 47, 23] !vec2 = runST (run64 (Proxy :: Proxy 256) lens2) in densify256 vec2 where run64 :: forall s n. KnownNat n => Proxy n -> [Int] -> ST s (VU.Vector Word8) run64 _proxy lens = do rope0 <- sequential :: ST s (Rope n s Word8) rope1 <- foldM (\r _i -> round lens r) rope0 [0 .. 63 :: Int] VU.freeze $ rVec rope1 knotHashHex :: String -> String knotHashHex = concatMap (printf "%02x") . VU.toList . knotHash single :: forall s n. KnownNat n => Proxy n -> [Int] -> ST s (VU.Vector Int) single _proxy lens = do rope0 <- sequential :: ST s (Rope n s Int) rope1 <- round lens rope0 VU.freeze $ rVec rope1
775c6279e3628e44f38a8f18b7d6c967211c0455f5484384691a90ed28ad6277
chchen/comet
types.rkt
#lang rosette/safe (require "../config.rkt") (define vect? (bitvector vect-len)) (define (bool->vect b) (bool->bitvector b vect-len)) (define false-vect (bv 0 vect-len)) (define true-vect (bv 1 vect-len)) (provide vect? bool->vect false-vect true-vect)
null
https://raw.githubusercontent.com/chchen/comet/005477b761f4d35c9fce175738f4dcbb805909e7/unity-synthesis/bool-bitvec/types.rkt
racket
#lang rosette/safe (require "../config.rkt") (define vect? (bitvector vect-len)) (define (bool->vect b) (bool->bitvector b vect-len)) (define false-vect (bv 0 vect-len)) (define true-vect (bv 1 vect-len)) (provide vect? bool->vect false-vect true-vect)
f9dc5a2cf851ea29552dcdcd2ec46a489094379fbd31fb8a0992d4f4400de797
webcrank/webcrank.hs
ServerAPI.hs
module Webcrank.ServerAPI ( ServerAPI(..) , ReqData , newReqData , HasReqData(reqData) , ResourceData , newResourceData , HasResourceData(resourceData) , LogData , handleRequest ) where import Webcrank.Internal.HandleRequest import Webcrank.Internal.ReqData import Webcrank.Internal.ResourceData import Webcrank.Internal.Types
null
https://raw.githubusercontent.com/webcrank/webcrank.hs/c611a12ea129383823cc627405819537c31730e4/src/Webcrank/ServerAPI.hs
haskell
module Webcrank.ServerAPI ( ServerAPI(..) , ReqData , newReqData , HasReqData(reqData) , ResourceData , newResourceData , HasResourceData(resourceData) , LogData , handleRequest ) where import Webcrank.Internal.HandleRequest import Webcrank.Internal.ReqData import Webcrank.Internal.ResourceData import Webcrank.Internal.Types
7cfa8f9fffef1f7adf96d86f87b8edbcaad50f3daca1d4bb4d102b9b2e154b49
semilin/layoup
RSNT-GY-tests.lisp
(MAKE-LAYOUT :NAME "RSNT-GY-tests" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL :KEYBOARD NIL)
null
https://raw.githubusercontent.com/semilin/layoup/27ec9ba9a9388cd944ac46206d10424e3ab45499/data/layouts/RSNT-GY-tests.lisp
lisp
(MAKE-LAYOUT :NAME "RSNT-GY-tests" :MATRIX (APPLY #'KEY-MATRIX 'NIL) :SHIFT-MATRIX NIL :KEYBOARD NIL)
8e3a7c5bbac0f483b533eeda7167f920a454b6e3a8be01afc3e2f1655975cf54
cdepillabout/world-peace
Client.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Main where import Data.Monoid ((<>)) import Data.Proxy (Proxy(Proxy)) import Network.HTTP.Client (defaultManagerSettings, newManager) import Options.Applicative (Parser, (<**>), argument, execParser, fullDesc, help, helper, info, long, metavar, progDesc, short, str, switch) import Servant.API ((:<|>)((:<|>))) import Servant.Client (BaseUrl(BaseUrl), ClientEnv(ClientEnv), ClientM, Scheme(Http), client, runClientM) import Servant.Checked.Exceptions (Envelope, emptyEnvelope, catchesEnvelope) import Api (Api, BadSearchTermErr(BadSearchTermErr), IncorrectCapitalization(IncorrectCapitalization), SearchQuery(SearchQuery), SearchResponse(SearchResponse), port) ----------------------------------------- -- Clients generated by servant-client -- ----------------------------------------- -- We generate the client functions just like normal. Note that when we use ' Throws ' or ' ' , the client functions get generated with the -- 'Envelope' type. strictSearch :: SearchQuery -> ClientM (Envelope '[BadSearchTermErr, IncorrectCapitalization] SearchResponse) laxSearch :: SearchQuery -> ClientM (Envelope '[BadSearchTermErr] SearchResponse) noErrSearch :: SearchQuery -> ClientM (Envelope '[] SearchResponse) strictSearch :<|> laxSearch :<|> noErrSearch = client (Proxy :: Proxy Api) -------------------------------------- -- Command-line options and parsers -- -------------------------------------- -- The following are needed for using optparse-applicative to parse command -- line arguments. Most people shouldn't need to worry about how this works. data Options = Options { query :: String, useStrict :: Bool, useNoErr :: Bool } queryParser :: Parser String queryParser = argument str (metavar "QUERY") useStrictParser :: Parser Bool useStrictParser = switch $ long "strict" <> short 's' <> help "Whether or not to use the strict api" useNoErrParser :: Parser Bool useNoErrParser = switch $ long "no-err" <> short 'n' <> help "Whether or not to use the api that does not return an error" commandParser :: Parser Options commandParser = Options <$> queryParser <*> useStrictParser <*> useNoErrParser ------------------------------------------------------------------------- -- Command Runners (these use the clients generated by servant-client) -- ------------------------------------------------------------------------- | This function uses the ' strictSearch ' function to send a ' SearchQuery ' to -- the server. -- Note how ' ' is used to handle the two error reponses and the -- success response. runStrict :: ClientEnv -> String -> IO () runStrict clientEnv query = do eitherRes <- runClientM (strictSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> putStrLn $ catchesEnvelope ( \BadSearchTermErr -> "the search term was not \"Hello\"" , \IncorrectCapitalization -> "the search term was not capitalized correctly" ) (\(SearchResponse searchResponse) -> "Success: " <> searchResponse) env | This function uses the ' laxSearch ' function to send a ' SearchQuery ' to -- the server. runLax :: ClientEnv -> String -> IO () runLax clientEnv query = do eitherRes <- runClientM (laxSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> putStrLn $ catchesEnvelope (\BadSearchTermErr -> "the search term was not \"Hello\"") (\(SearchResponse searchResponse) -> "Success: " <> searchResponse) env | This function uses the ' noErrSearch ' function to send a ' SearchQuery ' to -- the server. runNoErr :: ClientEnv -> String -> IO () runNoErr clientEnv query = do eitherRes <- runClientM (noErrSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> do let (SearchResponse res) = emptyEnvelope env putStrLn $ "Success: " <> res -- | Run 'runStrict', 'runLax', or 'runNoErr' depending on the command line options. run :: ClientEnv -> Options -> IO () run clientEnv Options{query, useStrict = True, useNoErr = _} = runStrict clientEnv query run clientEnv Options{query, useStrict = _, useNoErr = True} = runNoErr clientEnv query run clientEnv Options{query, useStrict = _, useNoErr = _} = runLax clientEnv query ---------- -- Main -- ---------- main :: IO () main = do manager <- newManager defaultManagerSettings let clientEnv = ClientEnv manager baseUrl options <- execParser opts run clientEnv options where opts = info (commandParser <**> helper) $ fullDesc <> progDesc "Send the QUERY to the example server and print the response." baseUrl :: BaseUrl baseUrl = BaseUrl Http "localhost" port ""
null
https://raw.githubusercontent.com/cdepillabout/world-peace/0596da67d792ccf9f0ddbe44b5ce71b38cbde020/example/Client.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # --------------------------------------- Clients generated by servant-client -- --------------------------------------- We generate the client functions just like normal. Note that when we use 'Envelope' type. ------------------------------------ Command-line options and parsers -- ------------------------------------ The following are needed for using optparse-applicative to parse command line arguments. Most people shouldn't need to worry about how this works. ----------------------------------------------------------------------- Command Runners (these use the clients generated by servant-client) -- ----------------------------------------------------------------------- the server. success response. the server. the server. | Run 'runStrict', 'runLax', or 'runNoErr' depending on the command line options. -------- Main -- --------
# LANGUAGE DataKinds # # LANGUAGE EmptyCase # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE InstanceSigs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE UndecidableInstances # module Main where import Data.Monoid ((<>)) import Data.Proxy (Proxy(Proxy)) import Network.HTTP.Client (defaultManagerSettings, newManager) import Options.Applicative (Parser, (<**>), argument, execParser, fullDesc, help, helper, info, long, metavar, progDesc, short, str, switch) import Servant.API ((:<|>)((:<|>))) import Servant.Client (BaseUrl(BaseUrl), ClientEnv(ClientEnv), ClientM, Scheme(Http), client, runClientM) import Servant.Checked.Exceptions (Envelope, emptyEnvelope, catchesEnvelope) import Api (Api, BadSearchTermErr(BadSearchTermErr), IncorrectCapitalization(IncorrectCapitalization), SearchQuery(SearchQuery), SearchResponse(SearchResponse), port) ' Throws ' or ' ' , the client functions get generated with the strictSearch :: SearchQuery -> ClientM (Envelope '[BadSearchTermErr, IncorrectCapitalization] SearchResponse) laxSearch :: SearchQuery -> ClientM (Envelope '[BadSearchTermErr] SearchResponse) noErrSearch :: SearchQuery -> ClientM (Envelope '[] SearchResponse) strictSearch :<|> laxSearch :<|> noErrSearch = client (Proxy :: Proxy Api) data Options = Options { query :: String, useStrict :: Bool, useNoErr :: Bool } queryParser :: Parser String queryParser = argument str (metavar "QUERY") useStrictParser :: Parser Bool useStrictParser = switch $ long "strict" <> short 's' <> help "Whether or not to use the strict api" useNoErrParser :: Parser Bool useNoErrParser = switch $ long "no-err" <> short 'n' <> help "Whether or not to use the api that does not return an error" commandParser :: Parser Options commandParser = Options <$> queryParser <*> useStrictParser <*> useNoErrParser | This function uses the ' strictSearch ' function to send a ' SearchQuery ' to Note how ' ' is used to handle the two error reponses and the runStrict :: ClientEnv -> String -> IO () runStrict clientEnv query = do eitherRes <- runClientM (strictSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> putStrLn $ catchesEnvelope ( \BadSearchTermErr -> "the search term was not \"Hello\"" , \IncorrectCapitalization -> "the search term was not capitalized correctly" ) (\(SearchResponse searchResponse) -> "Success: " <> searchResponse) env | This function uses the ' laxSearch ' function to send a ' SearchQuery ' to runLax :: ClientEnv -> String -> IO () runLax clientEnv query = do eitherRes <- runClientM (laxSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> putStrLn $ catchesEnvelope (\BadSearchTermErr -> "the search term was not \"Hello\"") (\(SearchResponse searchResponse) -> "Success: " <> searchResponse) env | This function uses the ' noErrSearch ' function to send a ' SearchQuery ' to runNoErr :: ClientEnv -> String -> IO () runNoErr clientEnv query = do eitherRes <- runClientM (noErrSearch $ SearchQuery query) clientEnv case eitherRes of Left servantErr -> putStrLn $ "Got a ServantErr: " <> show servantErr Right env -> do let (SearchResponse res) = emptyEnvelope env putStrLn $ "Success: " <> res run :: ClientEnv -> Options -> IO () run clientEnv Options{query, useStrict = True, useNoErr = _} = runStrict clientEnv query run clientEnv Options{query, useStrict = _, useNoErr = True} = runNoErr clientEnv query run clientEnv Options{query, useStrict = _, useNoErr = _} = runLax clientEnv query main :: IO () main = do manager <- newManager defaultManagerSettings let clientEnv = ClientEnv manager baseUrl options <- execParser opts run clientEnv options where opts = info (commandParser <**> helper) $ fullDesc <> progDesc "Send the QUERY to the example server and print the response." baseUrl :: BaseUrl baseUrl = BaseUrl Http "localhost" port ""
49ee4f4f00f01908102714876b5458ab6c994293adeaf3e970acbd93334b9bb8
chris-taylor/Classical-Mechanics
AD.hs
# LANGUAGE FlexibleContexts # module AD ( dConst, dVar, diff, diff', diffs ) where import Control.Applicative ------------------------------ -- Numeric Applicatives ------------------------------ instance Num b => Num (a -> b) where fromInteger = pure . fromInteger (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate signum = fmap signum abs = fmap abs instance Fractional b => Fractional (a -> b) where fromRational = pure . fromRational (/) = liftA2 (/) recip = fmap recip instance Floating b => Floating (a -> b) where pi = pure pi exp = liftA exp log = liftA log sqrt = liftA sqrt sin = liftA sin cos = liftA cos asin = liftA asin acos = liftA acos atan = liftA atan sinh = liftA sinh cosh = liftA cosh asinh = liftA asinh acosh = liftA acosh atanh = liftA atanh ------------------------------ -- Numeric Maybe ------------------------------ infixl 6 +. (+.) :: Num a => Maybe a -> Maybe a -> Maybe a Nothing +. b' = b' a' +. Nothing = a' Just a' +. Just b' = Just (a' + b') infixl 6 -. (-.) :: Num a => Maybe a -> Maybe a -> Maybe a Nothing -. b' = fmap negate b' a' -. Nothing = a' Just a' -. Just b' = Just (a' - b') infixl 7 .* (.*) :: Num a => Maybe a -> a -> Maybe a Nothing .* _ = Nothing Just a' .* b = Just (a' * b) infixl 7 *. (*.) :: Num a => a -> Maybe a -> Maybe a _ *. Nothing = Nothing a *. Just b' = Just (a * b') ------------------------------ -- Automatic differentiation ------------------------------ data Dif a = D a (Maybe (Dif a)) deriving (Show) dConst :: Num a => a -> Dif a dConst x = D x Nothing dVar :: Num a => a -> Dif a dVar x = D x (Just (dConst 1)) dlift :: Num (Dif a) => (a -> a) -> (Dif a -> Dif a) -> Dif a -> Dif a dlift f f' = \ u@(D u0 u') -> D (f u0) (u' .* f' u) infix 0 >-< (>-<) :: Num (Dif a) => (a -> a) -> (Dif a -> Dif a) -> Dif a -> Dif a (>-<) = dlift sqr :: Num a => a -> a sqr x = x * x instance Functor Dif where fmap f (D a b) = D (f a) ((fmap.fmap) f b) instance Num a => Num (Dif a) where fromInteger = dConst . fromInteger D x0 x' + D y0 y' = D (x0 + y0) (x' +. y') D x0 x' - D y0 y' = D (x0 - y0) (x' -. y') x@(D x0 x') * y@(D y0 y') = D (x0 * y0) (x' .* y +. x *. y') negate = negate >-< (-1) abs = abs >-< signum signum = signum >-< 0 instance Fractional a => Fractional (Dif a) where fromRational = dConst . fromRational recip = recip >-< -(sqr recip) instance Floating a => Floating (Dif a) where pi = dConst pi exp = exp >-< exp log = log >-< recip sqrt = sqrt >-< recip (2 * sqrt) sin = sin >-< cos cos = cos >-< -sin sinh = sinh >-< cosh cosh = cosh >-< sinh asin = asin >-< recip (sqrt (1-sqr)) acos = acos >-< recip (- sqrt (1-sqr)) atan = atan >-< recip (1 + sqr) asinh = asinh >-< recip (sqrt (1+sqr)) acosh = acosh >-< recip (- sqrt (sqr-1)) atanh = atanh >-< recip (1-sqr) diff :: Num a => (Dif a -> Dif a) -> a -> a diff f x = let D a a' = f (dVar x) in case a' of Nothing -> 0 Just (D b _) -> b diff' :: Num a => (Dif a -> Dif a) -> a -> (a, a) diff' f x = let D a a' = f (dVar x) in case a' of Nothing -> (a, 0) Just (D b _) -> (a, b) diffs :: Num a => (Dif a -> Dif a) -> a -> [a] diffs f x = diffs_ $ f (dVar x) where diffs_ (D a Nothing) = [a] diffs_ (D a (Just a')) = a : diffs_ a'
null
https://raw.githubusercontent.com/chris-taylor/Classical-Mechanics/a3f085733181833ccba3cf8d1985929e762a9bec/AD.hs
haskell
---------------------------- Numeric Applicatives ---------------------------- ---------------------------- Numeric Maybe ---------------------------- ---------------------------- Automatic differentiation ----------------------------
# LANGUAGE FlexibleContexts # module AD ( dConst, dVar, diff, diff', diffs ) where import Control.Applicative instance Num b => Num (a -> b) where fromInteger = pure . fromInteger (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) negate = fmap negate signum = fmap signum abs = fmap abs instance Fractional b => Fractional (a -> b) where fromRational = pure . fromRational (/) = liftA2 (/) recip = fmap recip instance Floating b => Floating (a -> b) where pi = pure pi exp = liftA exp log = liftA log sqrt = liftA sqrt sin = liftA sin cos = liftA cos asin = liftA asin acos = liftA acos atan = liftA atan sinh = liftA sinh cosh = liftA cosh asinh = liftA asinh acosh = liftA acosh atanh = liftA atanh infixl 6 +. (+.) :: Num a => Maybe a -> Maybe a -> Maybe a Nothing +. b' = b' a' +. Nothing = a' Just a' +. Just b' = Just (a' + b') infixl 6 -. (-.) :: Num a => Maybe a -> Maybe a -> Maybe a Nothing -. b' = fmap negate b' a' -. Nothing = a' Just a' -. Just b' = Just (a' - b') infixl 7 .* (.*) :: Num a => Maybe a -> a -> Maybe a Nothing .* _ = Nothing Just a' .* b = Just (a' * b) infixl 7 *. (*.) :: Num a => a -> Maybe a -> Maybe a _ *. Nothing = Nothing a *. Just b' = Just (a * b') data Dif a = D a (Maybe (Dif a)) deriving (Show) dConst :: Num a => a -> Dif a dConst x = D x Nothing dVar :: Num a => a -> Dif a dVar x = D x (Just (dConst 1)) dlift :: Num (Dif a) => (a -> a) -> (Dif a -> Dif a) -> Dif a -> Dif a dlift f f' = \ u@(D u0 u') -> D (f u0) (u' .* f' u) infix 0 >-< (>-<) :: Num (Dif a) => (a -> a) -> (Dif a -> Dif a) -> Dif a -> Dif a (>-<) = dlift sqr :: Num a => a -> a sqr x = x * x instance Functor Dif where fmap f (D a b) = D (f a) ((fmap.fmap) f b) instance Num a => Num (Dif a) where fromInteger = dConst . fromInteger D x0 x' + D y0 y' = D (x0 + y0) (x' +. y') D x0 x' - D y0 y' = D (x0 - y0) (x' -. y') x@(D x0 x') * y@(D y0 y') = D (x0 * y0) (x' .* y +. x *. y') negate = negate >-< (-1) abs = abs >-< signum signum = signum >-< 0 instance Fractional a => Fractional (Dif a) where fromRational = dConst . fromRational recip = recip >-< -(sqr recip) instance Floating a => Floating (Dif a) where pi = dConst pi exp = exp >-< exp log = log >-< recip sqrt = sqrt >-< recip (2 * sqrt) sin = sin >-< cos cos = cos >-< -sin sinh = sinh >-< cosh cosh = cosh >-< sinh asin = asin >-< recip (sqrt (1-sqr)) acos = acos >-< recip (- sqrt (1-sqr)) atan = atan >-< recip (1 + sqr) asinh = asinh >-< recip (sqrt (1+sqr)) acosh = acosh >-< recip (- sqrt (sqr-1)) atanh = atanh >-< recip (1-sqr) diff :: Num a => (Dif a -> Dif a) -> a -> a diff f x = let D a a' = f (dVar x) in case a' of Nothing -> 0 Just (D b _) -> b diff' :: Num a => (Dif a -> Dif a) -> a -> (a, a) diff' f x = let D a a' = f (dVar x) in case a' of Nothing -> (a, 0) Just (D b _) -> (a, b) diffs :: Num a => (Dif a -> Dif a) -> a -> [a] diffs f x = diffs_ $ f (dVar x) where diffs_ (D a Nothing) = [a] diffs_ (D a (Just a')) = a : diffs_ a'
cace31aff818d1de5ec663c8aa9d40b1decda3febeccea37efeddf8f89c09afa
S8A/htdp-exercises
ex340.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-intermediate-lambda-reader.ss" "lang")((modname ex340) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f))) (define file-part1 (make-file "part1" 99 "")) (define file-part2 (make-file "part2" 52 "")) (define file-part3 (make-file "part3" 17 "")) (define file-hang (make-file "hang" 8 "")) (define file-draw (make-file "draw" 2 "")) (define file-docs-read (make-file "read!" 19 "")) (define file-ts-read (make-file "read!" 10 "")) (define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3))) (define dir-code (make-dir "Code" '() (list file-hang file-draw))) (define dir-docs (make-dir "Docs" '() (list file-docs-read))) (define dir-libs (make-dir "Libs" (list dir-code dir-docs) '())) (define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read))) ; Dir -> [List-of String] ; lists the names of all files and directories in a given dir (define (ls d) (sort (append (map (lambda (dir) (string-append (dir-name dir) "/")) (dir-dirs d)) (map file-name (dir-files d))) string<?)) (check-expect (ls dir-text) '("part1" "part2" "part3")) (check-expect (ls dir-code) '("draw" "hang")) (check-expect (ls dir-docs) '("read!")) (check-expect (ls dir-libs) '("Code/" "Docs/")) (check-expect (ls dir-ts) '("Libs/" "Text/" "read!"))
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex340.rkt
racket
about the language level of this file in a form that our tools can easily process. Dir -> [List-of String] lists the names of all files and directories in a given dir
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex340) (read-case-sensitive #t) (teachpacks ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "abstraction.rkt" "teachpack" "2htdp") (lib "dir.rkt" "teachpack" "htdp")) #f))) (define file-part1 (make-file "part1" 99 "")) (define file-part2 (make-file "part2" 52 "")) (define file-part3 (make-file "part3" 17 "")) (define file-hang (make-file "hang" 8 "")) (define file-draw (make-file "draw" 2 "")) (define file-docs-read (make-file "read!" 19 "")) (define file-ts-read (make-file "read!" 10 "")) (define dir-text (make-dir "Text" '() (list file-part1 file-part2 file-part3))) (define dir-code (make-dir "Code" '() (list file-hang file-draw))) (define dir-docs (make-dir "Docs" '() (list file-docs-read))) (define dir-libs (make-dir "Libs" (list dir-code dir-docs) '())) (define dir-ts (make-dir "TS" (list dir-text dir-libs) (list file-ts-read))) (define (ls d) (sort (append (map (lambda (dir) (string-append (dir-name dir) "/")) (dir-dirs d)) (map file-name (dir-files d))) string<?)) (check-expect (ls dir-text) '("part1" "part2" "part3")) (check-expect (ls dir-code) '("draw" "hang")) (check-expect (ls dir-docs) '("read!")) (check-expect (ls dir-libs) '("Code/" "Docs/")) (check-expect (ls dir-ts) '("Libs/" "Text/" "read!"))
44f651a6c5d7cb5c93b17d21c7e053e91830ae3ddfd20e9234c63ae4c2aa397f
google/clojure-turtle
core.cljc
Copyright 2014 Google Inc. 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. (ns clojure-turtle.core (:refer-clojure :exclude [repeat]) #?(:clj (:require [quil.core :as q]) :cljs (:require [quil.core :as q :include-macros true] [clojure-turtle.macros :refer-macros [repeat all]])) #?(:clj (:import java.util.Date))) ;; ;; constants ;; (def ^{:doc "The default color to be used (ex: if color is not specified)"} DEFAULT-COLOR [0 0 0]) ;; ;; records ;; (defrecord Turtle [x y angle pen color fill commands start-from] both for Clojure and ClojureScript , override the behavior of the ;; str fn / .toString method to "restore" the default .toString behavior for the entire Turtle record data , instead of just ;; returning whatever pr-str returns Object (toString [turt] (str (select-keys turt (keys turt))))) ;; ;; record printing definitions ;; (defn pr-str-turtle "This method determines what gets returned when passing a Turtle record instance to pr-str, which in turn affects what gets printed at the REPL" [turt] (pr-str (letfn [(format-key [key] {key #?(:clj (float (/ (bigint (* (get turt key) 10)) 10)) :cljs (/ (Math/round (* (get turt key) 10)) 10))})] (merge (select-keys turt [:pen :color :fll]) (format-key :x) (format-key :y) (format-key :angle))))) #?(:clj (defmethod print-method Turtle [turt writer] (.write writer (pr-str-turtle turt))) :cljs (extend-type Turtle IPrintWithWriter (-pr-writer [turt writer _] (-write writer (pr-str-turtle turt))))) ;; fns - turtle fns ;; (defn new-turtle "Returns an entity that represents a turtle." [] (atom (map->Turtle {:x 0 :y 0 :angle 90 :pen true :color DEFAULT-COLOR :fill false :commands [] :start-from {:x 0 :y 0}}))) (def ^{:doc "The default turtle entity used when no turtle is specified for an operation."} turtle (new-turtle)) (defn alter-turtle "A helper function used in the implementation of basic operations to abstract out the interface of applying a function to a turtle entity." [turt-state f] (swap! turt-state f) turt-state) ;; fns - colors and visual effects ;; (defn make-opaque "Take a color vector, as passed to the `color` fn, and return a color vector in the form [red blue green alpha], where all RGB and alpha values are integers in the range 0-255 inclusive. In order to make the color vector represent full opacity, the alpha value will be 255." [color-vec] (let [rgb-vec (case (count color-vec) 1 (clojure.core/repeat 3 (first color-vec)) 3 color-vec 4 (take 3 color-vec)) rgba-vec (concat rgb-vec [255])] rgba-vec)) (defn color "Set the turtle's color using [red green blue]. RGB values are in the range 0 to 255, inclusive." ([c] (color turtle c)) ([turt-state c] (letfn [(alter-fn [t] (-> t (assoc :color c) (update-in [:commands] conj [:color c])))] (alter-turtle turt-state alter-fn)))) ;; fns - basic Logo commands ;; (defn right "Rotate the turtle turt clockwise by ang degrees." ([ang] (right turtle ang)) ([turt-state ang] ;; the local fn add-angle will increment the angle but keep the resulting angle in the range [ 0,360 ) , in degrees . (letfn [(add-angle [{:keys [angle] :as t}] (let [new-angle (-> angle (- ang) (mod 360))] (-> t (assoc :angle new-angle) (update-in [:commands] conj [:setheading new-angle]))))] (alter-turtle turt-state add-angle)))) (defn left "Same as right, but turns the turtle counter-clockwise." ([ang] (right (* -1 ang))) ([turt-state ang] (right turt-state (* -1 ang)))) (def deg->radians q/radians) (def radians->deg q/degrees) (def atan q/atan) (defn forward "Move the turtle turt forward in the direction that it is facing by length len." ([len] (forward turtle len)) ([turt-state len] ;; Convert the turtle's polar coordinates (angle + radius) into Cartesian coordinates ( x , y ) for display purposes (let [rads (deg->radians (get @turt-state :angle)) dx (* len (Math/cos rads)) dy (* len (Math/sin rads)) alter-fn (fn [t] (-> t (update-in [:x] + dx) (update-in [:y] + dy) (update-in [:commands] conj [:translate [dx dy]])))] (alter-turtle turt-state alter-fn)))) (defn back "Same as forward, but move the turtle backwards, which is opposite of the direction it is facing." ([len] (forward (* -1 len))) ([turt-state len] (forward turt-state (* -1 len)))) (defn penup "Instruct the turtle to pick its pen up. Subsequent movements will not draw to screen until the pen is put down again." ([] (penup turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :pen false) (update-in [:commands] conj [:pen false])))] (alter-turtle turt-state alter-fn)))) (defn pendown "Instruct the turtle to put its pen down. Subsequent movements will draw to screen." ([] (pendown turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :pen true) (update-in [:commands] conj [:pen true])))] (alter-turtle turt-state alter-fn)))) (defn start-fill "Make the turtle fill the area created by his subsequent moves, until end-fill is called." ([] (start-fill turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :fill true) (update-in [:commands] conj [:start-fill])))] (alter-turtle turt-state alter-fn)))) (defn end-fill "Stop filling the area of turtle moves. Must be called start-fill." ([] (end-fill turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :fill false) (update-in [:commands] conj [:end-fill])))] (alter-turtle turt-state alter-fn)))) #?(:clj (defmacro all "This macro was created to substitute for the purpose served by the square brackets in Logo in a call to REPEAT. This macro returns a no-argument function that, when invoked, executes the commands described in the body inside the macro call/form. (Haskell programmers refer to the type of function returned a 'thunk'.)" [& body] `(fn [] (do ~@ body)))) #?(:clj (defmacro repeat "A macro to translate the purpose of the Logo REPEAT function." [n & body] `(let [states# (repeatedly ~n ~@body)] (dorun states#) (last states#)))) (defn wait "Sleeps for ms miliseconds. Can be used in a repeat to show commands execute in real time" [ms] (letfn [(get-time [] #?(:clj (.getTime (Date.)) :cljs (.getTime (js/Date.))))] (let [initial-time (get-time)] (while (< (get-time) (+ initial-time ms)))))) (defn clean "Clear the lines state, which effectively clears the drawing canvas." ([] (clean turtle)) ([turt-state] (letfn [(alter-fn [t] (let [curr-pos-map (select-keys t [:x :y])] (-> t (assoc :commands []) (assoc :start-from curr-pos-map))))] (alter-turtle turt-state alter-fn)))) (defn setxy "Set the position of turtle turt to x-coordinate x and y-coordinate y." ([x y] (setxy turtle x y)) ([turt-state x y] (let [pen-down? (get @turt-state :pen)] (letfn [(alter-fn [t] (-> t (assoc :x x) (assoc :y y) (update-in [:commands] conj [:setxy [x y]])))] (alter-turtle turt-state alter-fn))))) (defn setheading "Set the direction which the turtle is facing, given in degrees, where 0 is to the right, 90 is up, 180 is left, and 270 is down." ([ang] (setheading turtle ang)) ([turt-state ang] (letfn [(alter-fn [t] (-> t (assoc :angle ang) (update-in [:commands] conj [:setheading ang])))] (alter-turtle turt-state alter-fn)))) (defn home "Set the turtle at coordinates (0,0), facing up (heading = 90 degrees)" ([] (home turtle)) ([turt-state] (setxy turt-state 0 0) (setheading turt-state 90))) ;; fns - ( Quil - based ) rendering and graphics ;; (defn reset-rendering "A helper function for the Quil rendering function." [] (q/background 200) ;; Set the background colour to ;; a nice shade of grey. (q/stroke-weight 1)) (defn setup "A helper function for the Quil rendering function." [] (q/smooth) ;; Turn on anti-aliasing ;; Allow q/* functions to be used from the REPL #?(:cljs (js/setTimeout #(set! quil.sketch/*applet* (q/get-sketch-by-id "turtle-canvas")) 5)) (reset-rendering)) (defn get-turtle-sprite "A helper function that draws the triangle that represents the turtle onto the screen." ([] (get-turtle-sprite turtle)) ([turt] (let [ ;; set up a copy of the turtle to draw the triangle that ;; will represent / show the turtle on the graphics canvas short-leg 5 long-leg 12 hypoteneuse (Math/sqrt (+ (* short-leg short-leg) (* long-leg long-leg))) large-angle (-> (/ long-leg short-leg) atan radians->deg) small-angle (- 90 large-angle) turt-copy-state (-> (atom turt) pendown clean) current-color (:color turt) opaque-color (make-opaque current-color)] ;; Use the turtle copy to step through the commands required ;; to draw the triangle that represents the turtle. the ;; turtle copy will be used for the commands stored within it. (do (-> turt-copy-state (setxy (:x turt) (:y turt)) ;teleport to the current position (turtle's centre) (penup) (back (/ long-leg 3)) ;move backwards to the centre of the turtle's base (pendown) (color opaque-color) (right 90) (forward short-leg) (left (- 180 large-angle)) (forward hypoteneuse) (left (- 180 (* 2 small-angle))) (forward hypoteneuse) (left (- 180 large-angle)) (forward short-leg) (left 90))) ;; now return the turtle copy turt-copy-state))) (defn draw-turtle-commands "Takes a seq of turtle commands and converts them into Quil commands to draw onto the canvas" [turt] (let [new-turtle @(new-turtle) start-from-pos (get turt :start-from) new-turtle-with-start (-> new-turtle (assoc :x (:x start-from-pos)) (assoc :y (:y start-from-pos)))] (loop [t new-turtle-with-start commands (:commands turt)] (if (empty? commands) t (let [next-cmd (first commands) cmd-name (first next-cmd) cmd-vals (rest next-cmd) rest-cmds (rest commands)] (case cmd-name :color (let [c (first cmd-vals)] (apply q/stroke c) (apply q/fill c) (recur (assoc t :color c) rest-cmds)) :setxy (let [[x y] (first cmd-vals)] (recur (assoc t :x x :y y) rest-cmds)) :setheading (recur (assoc t :angle (first cmd-vals)) rest-cmds) :translate (let [x (:x t) y (:y t) [dx dy] (first cmd-vals) new-x (+ x dx) new-y (+ y dy)] (when (:pen t) (q/line x y new-x new-y) (when (:fill t) (q/vertex x y) (q/vertex new-x new-y))) (recur (assoc t :x new-x :y new-y) rest-cmds)) :pen (recur (assoc t :pen (first cmd-vals)) rest-cmds) :start-fill (do (when-not (:fill t) (q/begin-shape)) (recur (assoc t :fill true) rest-cmds)) :end-fill (do (when (:fill t) (q/end-shape)) (recur (assoc t :fill false) rest-cmds)) t)))))) (defn draw-turtle "The function passed to Quil for doing rendering." [turt-state] ;; Use push-matrix to apply a transformation to the graphing plane. (q/push-matrix) ;; By default, positive x is to the right, positive y is down. Here , we tell Quil to move the origin ( 0,0 ) to the center of the window . (q/translate (/ (q/width) 2) (/ (q/height) 2)) (reset-rendering) ;; Apply another transformation to the canvas. (q/push-matrix) ;; Flip the coordinates horizontally -- converts programmers' x-/y - axes into mathematicians ' x-/y - axes (q/scale 1.0 -1.0) ;; Set the default colors for line stroke and shape fill (apply q/stroke DEFAULT-COLOR) (apply q/fill DEFAULT-COLOR) ;; Draw the lines of where the turtle has been. (draw-turtle-commands @turt-state) ;; Draw the sprite (triangle) representing the turtle itself. (let [sprite (get-turtle-sprite @turt-state)] (draw-turtle-commands @sprite)) Undo the graphing plane transformation in Quil / Processing (q/pop-matrix) (q/pop-matrix)) (defn draw "The function passed to Quil for doing rendering." [] (draw-turtle turtle)) (defmacro if-cljs "Executes `then` clause iff generating ClojureScript code. Stolen from Prismatic code. Ref. , ." [then else] nil when compiling for Clojure , for ClojureScript then else)) (defmacro new-window "Opens up a new window that shows the turtle rendering canvas. In CLJS it will render to a new HTML5 canvas object. An optional config map can be provided, where the key :title indicates the window title (clj), the :size key indicates a vector of 2 values indicating the width and height of the window." [& [config]] `(if-cljs ~(let [default-config {:size [323 200]} {:keys [host size]} (merge default-config config)] `(do (quil.sketch/add-canvas "turtle-canvas") (q/defsketch ~'example :host "turtle-canvas" :setup setup :draw draw :size ~size))) ~(let [default-config {:title "Watch the turtle go!" :size [323 200]} {:keys [title size]} (merge default-config config)] `(q/defsketch ~'example :title ~title :setup setup :draw draw :size ~size))))
null
https://raw.githubusercontent.com/google/clojure-turtle/8ce2b5d25199e9e8ad08d395b16e8445dff5d55b/src/cljc/clojure_turtle/core.cljc
clojure
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. constants records str fn / .toString method to "restore" the default .toString returning whatever pr-str returns record printing definitions the local fn add-angle will increment the angle but keep the Convert the turtle's polar coordinates (angle + radius) into Set the background colour to a nice shade of grey. Turn on anti-aliasing Allow q/* functions to be used from the REPL set up a copy of the turtle to draw the triangle that will represent / show the turtle on the graphics canvas Use the turtle copy to step through the commands required to draw the triangle that represents the turtle. the turtle copy will be used for the commands stored within it. teleport to the current position (turtle's centre) move backwards to the centre of the turtle's base now return the turtle copy Use push-matrix to apply a transformation to the graphing plane. By default, positive x is to the right, positive y is down. Apply another transformation to the canvas. Flip the coordinates horizontally -- converts programmers' Set the default colors for line stroke and shape fill Draw the lines of where the turtle has been. Draw the sprite (triangle) representing the turtle itself.
Copyright 2014 Google Inc. All Rights Reserved . distributed under the License is distributed on an " AS IS " BASIS , (ns clojure-turtle.core (:refer-clojure :exclude [repeat]) #?(:clj (:require [quil.core :as q]) :cljs (:require [quil.core :as q :include-macros true] [clojure-turtle.macros :refer-macros [repeat all]])) #?(:clj (:import java.util.Date))) (def ^{:doc "The default color to be used (ex: if color is not specified)"} DEFAULT-COLOR [0 0 0]) (defrecord Turtle [x y angle pen color fill commands start-from] both for Clojure and ClojureScript , override the behavior of the behavior for the entire Turtle record data , instead of just Object (toString [turt] (str (select-keys turt (keys turt))))) (defn pr-str-turtle "This method determines what gets returned when passing a Turtle record instance to pr-str, which in turn affects what gets printed at the REPL" [turt] (pr-str (letfn [(format-key [key] {key #?(:clj (float (/ (bigint (* (get turt key) 10)) 10)) :cljs (/ (Math/round (* (get turt key) 10)) 10))})] (merge (select-keys turt [:pen :color :fll]) (format-key :x) (format-key :y) (format-key :angle))))) #?(:clj (defmethod print-method Turtle [turt writer] (.write writer (pr-str-turtle turt))) :cljs (extend-type Turtle IPrintWithWriter (-pr-writer [turt writer _] (-write writer (pr-str-turtle turt))))) fns - turtle fns (defn new-turtle "Returns an entity that represents a turtle." [] (atom (map->Turtle {:x 0 :y 0 :angle 90 :pen true :color DEFAULT-COLOR :fill false :commands [] :start-from {:x 0 :y 0}}))) (def ^{:doc "The default turtle entity used when no turtle is specified for an operation."} turtle (new-turtle)) (defn alter-turtle "A helper function used in the implementation of basic operations to abstract out the interface of applying a function to a turtle entity." [turt-state f] (swap! turt-state f) turt-state) fns - colors and visual effects (defn make-opaque "Take a color vector, as passed to the `color` fn, and return a color vector in the form [red blue green alpha], where all RGB and alpha values are integers in the range 0-255 inclusive. In order to make the color vector represent full opacity, the alpha value will be 255." [color-vec] (let [rgb-vec (case (count color-vec) 1 (clojure.core/repeat 3 (first color-vec)) 3 color-vec 4 (take 3 color-vec)) rgba-vec (concat rgb-vec [255])] rgba-vec)) (defn color "Set the turtle's color using [red green blue]. RGB values are in the range 0 to 255, inclusive." ([c] (color turtle c)) ([turt-state c] (letfn [(alter-fn [t] (-> t (assoc :color c) (update-in [:commands] conj [:color c])))] (alter-turtle turt-state alter-fn)))) fns - basic Logo commands (defn right "Rotate the turtle turt clockwise by ang degrees." ([ang] (right turtle ang)) ([turt-state ang] resulting angle in the range [ 0,360 ) , in degrees . (letfn [(add-angle [{:keys [angle] :as t}] (let [new-angle (-> angle (- ang) (mod 360))] (-> t (assoc :angle new-angle) (update-in [:commands] conj [:setheading new-angle]))))] (alter-turtle turt-state add-angle)))) (defn left "Same as right, but turns the turtle counter-clockwise." ([ang] (right (* -1 ang))) ([turt-state ang] (right turt-state (* -1 ang)))) (def deg->radians q/radians) (def radians->deg q/degrees) (def atan q/atan) (defn forward "Move the turtle turt forward in the direction that it is facing by length len." ([len] (forward turtle len)) ([turt-state len] Cartesian coordinates ( x , y ) for display purposes (let [rads (deg->radians (get @turt-state :angle)) dx (* len (Math/cos rads)) dy (* len (Math/sin rads)) alter-fn (fn [t] (-> t (update-in [:x] + dx) (update-in [:y] + dy) (update-in [:commands] conj [:translate [dx dy]])))] (alter-turtle turt-state alter-fn)))) (defn back "Same as forward, but move the turtle backwards, which is opposite of the direction it is facing." ([len] (forward (* -1 len))) ([turt-state len] (forward turt-state (* -1 len)))) (defn penup "Instruct the turtle to pick its pen up. Subsequent movements will not draw to screen until the pen is put down again." ([] (penup turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :pen false) (update-in [:commands] conj [:pen false])))] (alter-turtle turt-state alter-fn)))) (defn pendown "Instruct the turtle to put its pen down. Subsequent movements will draw to screen." ([] (pendown turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :pen true) (update-in [:commands] conj [:pen true])))] (alter-turtle turt-state alter-fn)))) (defn start-fill "Make the turtle fill the area created by his subsequent moves, until end-fill is called." ([] (start-fill turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :fill true) (update-in [:commands] conj [:start-fill])))] (alter-turtle turt-state alter-fn)))) (defn end-fill "Stop filling the area of turtle moves. Must be called start-fill." ([] (end-fill turtle)) ([turt-state] (letfn [(alter-fn [t] (-> t (assoc :fill false) (update-in [:commands] conj [:end-fill])))] (alter-turtle turt-state alter-fn)))) #?(:clj (defmacro all "This macro was created to substitute for the purpose served by the square brackets in Logo in a call to REPEAT. This macro returns a no-argument function that, when invoked, executes the commands described in the body inside the macro call/form. (Haskell programmers refer to the type of function returned a 'thunk'.)" [& body] `(fn [] (do ~@ body)))) #?(:clj (defmacro repeat "A macro to translate the purpose of the Logo REPEAT function." [n & body] `(let [states# (repeatedly ~n ~@body)] (dorun states#) (last states#)))) (defn wait "Sleeps for ms miliseconds. Can be used in a repeat to show commands execute in real time" [ms] (letfn [(get-time [] #?(:clj (.getTime (Date.)) :cljs (.getTime (js/Date.))))] (let [initial-time (get-time)] (while (< (get-time) (+ initial-time ms)))))) (defn clean "Clear the lines state, which effectively clears the drawing canvas." ([] (clean turtle)) ([turt-state] (letfn [(alter-fn [t] (let [curr-pos-map (select-keys t [:x :y])] (-> t (assoc :commands []) (assoc :start-from curr-pos-map))))] (alter-turtle turt-state alter-fn)))) (defn setxy "Set the position of turtle turt to x-coordinate x and y-coordinate y." ([x y] (setxy turtle x y)) ([turt-state x y] (let [pen-down? (get @turt-state :pen)] (letfn [(alter-fn [t] (-> t (assoc :x x) (assoc :y y) (update-in [:commands] conj [:setxy [x y]])))] (alter-turtle turt-state alter-fn))))) (defn setheading "Set the direction which the turtle is facing, given in degrees, where 0 is to the right, 90 is up, 180 is left, and 270 is down." ([ang] (setheading turtle ang)) ([turt-state ang] (letfn [(alter-fn [t] (-> t (assoc :angle ang) (update-in [:commands] conj [:setheading ang])))] (alter-turtle turt-state alter-fn)))) (defn home "Set the turtle at coordinates (0,0), facing up (heading = 90 degrees)" ([] (home turtle)) ([turt-state] (setxy turt-state 0 0) (setheading turt-state 90))) fns - ( Quil - based ) rendering and graphics (defn reset-rendering "A helper function for the Quil rendering function." [] (q/stroke-weight 1)) (defn setup "A helper function for the Quil rendering function." [] #?(:cljs (js/setTimeout #(set! quil.sketch/*applet* (q/get-sketch-by-id "turtle-canvas")) 5)) (reset-rendering)) (defn get-turtle-sprite "A helper function that draws the triangle that represents the turtle onto the screen." ([] (get-turtle-sprite turtle)) ([turt] (let [ short-leg 5 long-leg 12 hypoteneuse (Math/sqrt (+ (* short-leg short-leg) (* long-leg long-leg))) large-angle (-> (/ long-leg short-leg) atan radians->deg) small-angle (- 90 large-angle) turt-copy-state (-> (atom turt) pendown clean) current-color (:color turt) opaque-color (make-opaque current-color)] (do (-> turt-copy-state (penup) (pendown) (color opaque-color) (right 90) (forward short-leg) (left (- 180 large-angle)) (forward hypoteneuse) (left (- 180 (* 2 small-angle))) (forward hypoteneuse) (left (- 180 large-angle)) (forward short-leg) (left 90))) turt-copy-state))) (defn draw-turtle-commands "Takes a seq of turtle commands and converts them into Quil commands to draw onto the canvas" [turt] (let [new-turtle @(new-turtle) start-from-pos (get turt :start-from) new-turtle-with-start (-> new-turtle (assoc :x (:x start-from-pos)) (assoc :y (:y start-from-pos)))] (loop [t new-turtle-with-start commands (:commands turt)] (if (empty? commands) t (let [next-cmd (first commands) cmd-name (first next-cmd) cmd-vals (rest next-cmd) rest-cmds (rest commands)] (case cmd-name :color (let [c (first cmd-vals)] (apply q/stroke c) (apply q/fill c) (recur (assoc t :color c) rest-cmds)) :setxy (let [[x y] (first cmd-vals)] (recur (assoc t :x x :y y) rest-cmds)) :setheading (recur (assoc t :angle (first cmd-vals)) rest-cmds) :translate (let [x (:x t) y (:y t) [dx dy] (first cmd-vals) new-x (+ x dx) new-y (+ y dy)] (when (:pen t) (q/line x y new-x new-y) (when (:fill t) (q/vertex x y) (q/vertex new-x new-y))) (recur (assoc t :x new-x :y new-y) rest-cmds)) :pen (recur (assoc t :pen (first cmd-vals)) rest-cmds) :start-fill (do (when-not (:fill t) (q/begin-shape)) (recur (assoc t :fill true) rest-cmds)) :end-fill (do (when (:fill t) (q/end-shape)) (recur (assoc t :fill false) rest-cmds)) t)))))) (defn draw-turtle "The function passed to Quil for doing rendering." [turt-state] (q/push-matrix) Here , we tell Quil to move the origin ( 0,0 ) to the center of the window . (q/translate (/ (q/width) 2) (/ (q/height) 2)) (reset-rendering) (q/push-matrix) x-/y - axes into mathematicians ' x-/y - axes (q/scale 1.0 -1.0) (apply q/stroke DEFAULT-COLOR) (apply q/fill DEFAULT-COLOR) (draw-turtle-commands @turt-state) (let [sprite (get-turtle-sprite @turt-state)] (draw-turtle-commands @sprite)) Undo the graphing plane transformation in Quil / Processing (q/pop-matrix) (q/pop-matrix)) (defn draw "The function passed to Quil for doing rendering." [] (draw-turtle turtle)) (defmacro if-cljs "Executes `then` clause iff generating ClojureScript code. Stolen from Prismatic code. Ref. , ." [then else] nil when compiling for Clojure , for ClojureScript then else)) (defmacro new-window "Opens up a new window that shows the turtle rendering canvas. In CLJS it will render to a new HTML5 canvas object. An optional config map can be provided, where the key :title indicates the window title (clj), the :size key indicates a vector of 2 values indicating the width and height of the window." [& [config]] `(if-cljs ~(let [default-config {:size [323 200]} {:keys [host size]} (merge default-config config)] `(do (quil.sketch/add-canvas "turtle-canvas") (q/defsketch ~'example :host "turtle-canvas" :setup setup :draw draw :size ~size))) ~(let [default-config {:title "Watch the turtle go!" :size [323 200]} {:keys [title size]} (merge default-config config)] `(q/defsketch ~'example :title ~title :setup setup :draw draw :size ~size))))
021027bc986883b56783a8b00d7d3f42cc0fcc4b0611711003632dc0b443d1b0
melange-re/melange
res_ast_debugger.ml
open Import open Ast_406 module Doc = Res_doc let printEngine = Res_driver.{ printImplementation = begin fun ~width:_ ~filename:_ ~comments:_ structure -> Printast.implementation Format.std_formatter structure end; printInterface = begin fun ~width:_ ~filename:_ ~comments:_ signature -> Printast.interface Format.std_formatter signature end; } module Sexp: sig type t val atom: string -> t val list: t list -> t val toString: t -> string end = struct type t = | Atom of string | List of t list let atom s = Atom s let list l = List l let rec toDoc t = match t with | Atom s -> Doc.text s | List [] -> Doc.text "()" | List [sexpr] -> Doc.concat [Doc.lparen; toDoc sexpr; Doc.rparen;] | List (hd::tail) -> Doc.group ( Doc.concat [ Doc.lparen; toDoc hd; Doc.indent ( Doc.concat [ Doc.line; Doc.join ~sep:Doc.line (List.map toDoc tail); ] ); Doc.rparen; ] ) let toString sexpr = let doc = toDoc sexpr in Doc.toString ~width:80 doc end module SexpAst = struct open Parsetree let mapEmpty ~f items = match items with | [] -> [Sexp.list []] | items -> List.map f items let string txt = Sexp.atom ("\"" ^ txt ^ "\"") let char c = Sexp.atom ("'" ^ (Char.escaped c) ^ "'") let optChar oc = match oc with | None -> Sexp.atom "None" | Some c -> Sexp.list [ Sexp.atom "Some"; char c ] let longident l = let rec loop l = match l with | Longident.Lident ident -> Sexp.list [ Sexp.atom "Lident"; string ident; ] | Longident.Ldot (lident, txt) -> Sexp.list [ Sexp.atom "Ldot"; loop lident; string txt; ] | Longident.Lapply (l1, l2) -> Sexp.list [ Sexp.atom "Lapply"; loop l1; loop l2; ] in Sexp.list [ Sexp.atom "longident"; loop l; ] let closedFlag flag = match flag with | Asttypes.Closed -> Sexp.atom "Closed" | Open -> Sexp.atom "Open" let directionFlag flag = match flag with | Asttypes.Upto -> Sexp.atom "Upto" | Downto -> Sexp.atom "Downto" let recFlag flag = match flag with | Asttypes.Recursive -> Sexp.atom "Recursive" | Nonrecursive -> Sexp.atom "Nonrecursive" let overrideFlag flag = match flag with | Asttypes.Override -> Sexp.atom "Override" | Fresh -> Sexp.atom "Fresh" let privateFlag flag = match flag with | Asttypes.Public -> Sexp.atom "Public" | Private -> Sexp.atom "Private" let mutableFlag flag = match flag with | Asttypes.Immutable -> Sexp.atom "Immutable" | Mutable -> Sexp.atom "Mutable" let variance v = match v with | Asttypes.Covariant -> Sexp.atom "Covariant" | Contravariant -> Sexp.atom "Contravariant" | Invariant -> Sexp.atom "Invariant" let argLabel lbl = match lbl with | Asttypes.Nolabel -> Sexp.atom "Nolabel" | Labelled txt -> Sexp.list [ Sexp.atom "Labelled"; string txt; ] | Optional txt -> Sexp.list [ Sexp.atom "Optional"; string txt; ] let constant c = let sexpr = match c with | Pconst_integer (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_integer"; string txt; optChar tag; ] | Pconst_char c -> Sexp.list [ Sexp.atom "Pconst_char"; Sexp.atom (Char.escaped c); ] | Pconst_string (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_string"; string txt; match tag with | Some txt -> Sexp.list [ Sexp.atom "Some"; string txt; ] | None -> Sexp.atom "None"; ] | Pconst_float (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_float"; string txt; optChar tag; ] in Sexp.list [ Sexp.atom "constant"; sexpr ] let rec structure s = Sexp.list ( (Sexp.atom "structure")::(List.map structureItem s) ) and structureItem si = let desc = match si.pstr_desc with | Pstr_eval (expr, attrs) -> Sexp.list [ Sexp.atom "Pstr_eval"; expression expr; attributes attrs; ] | Pstr_value (flag, vbs) -> Sexp.list [ Sexp.atom "Pstr_value"; recFlag flag; Sexp.list (mapEmpty ~f:valueBinding vbs) ] | Pstr_primitive (vd) -> Sexp.list [ Sexp.atom "Pstr_primitive"; valueDescription vd; ] | Pstr_type (flag, tds) -> Sexp.list [ Sexp.atom "Pstr_type"; recFlag flag; Sexp.list (mapEmpty ~f:typeDeclaration tds) ] | Pstr_typext typext -> Sexp.list [ Sexp.atom "Pstr_type"; typeExtension typext; ] | Pstr_exception ec -> Sexp.list [ Sexp.atom "Pstr_exception"; extensionConstructor ec; ] | Pstr_module mb -> Sexp.list [ Sexp.atom "Pstr_module"; moduleBinding mb; ] | Pstr_recmodule mbs -> Sexp.list [ Sexp.atom "Pstr_recmodule"; Sexp.list (mapEmpty ~f:moduleBinding mbs); ] | Pstr_modtype modTypDecl -> Sexp.list [ Sexp.atom "Pstr_modtype"; moduleTypeDeclaration modTypDecl; ] | Pstr_open openDesc -> Sexp.list [ Sexp.atom "Pstr_open"; openDescription openDesc; ] | Pstr_class _ -> Sexp.atom "Pstr_class" | Pstr_class_type _ -> Sexp.atom "Pstr_class_type" | Pstr_include id -> Sexp.list [ Sexp.atom "Pstr_include"; includeDeclaration id; ] | Pstr_attribute attr -> Sexp.list [ Sexp.atom "Pstr_attribute"; attribute attr; ] | Pstr_extension (ext, attrs) -> Sexp.list [ Sexp.atom "Pstr_extension"; extension ext; attributes attrs; ] in Sexp.list [ Sexp.atom "structure_item"; desc; ] and includeDeclaration id = Sexp.list [ Sexp.atom "include_declaration"; moduleExpression id.pincl_mod; attributes id.pincl_attributes; ] and openDescription od = Sexp.list [ Sexp.atom "open_description"; longident od.popen_lid.Asttypes.txt; attributes od.popen_attributes; ] and moduleTypeDeclaration mtd = Sexp.list [ Sexp.atom "module_type_declaration"; string mtd.pmtd_name.Asttypes.txt; (match mtd.pmtd_type with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); attributes mtd.pmtd_attributes; ] and moduleBinding mb = Sexp.list [ Sexp.atom "module_binding"; string mb.pmb_name.Asttypes.txt; moduleExpression mb.pmb_expr; attributes mb.pmb_attributes; ] and moduleExpression me = let desc = match me.pmod_desc with | Pmod_ident modName -> Sexp.list [ Sexp.atom "Pmod_ident"; longident modName.Asttypes.txt; ] | Pmod_structure s -> Sexp.list [ Sexp.atom "Pmod_structure"; structure s; ] | Pmod_functor (lbl, optModType, modExpr) -> Sexp.list [ Sexp.atom "Pmod_functor"; string lbl.Asttypes.txt; (match optModType with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); moduleExpression modExpr; ] | Pmod_apply (callModExpr, modExprArg) -> Sexp.list [ Sexp.atom "Pmod_apply"; moduleExpression callModExpr; moduleExpression modExprArg; ] | Pmod_constraint (modExpr, modType) -> Sexp.list [ Sexp.atom "Pmod_constraint"; moduleExpression modExpr; moduleType modType; ] | Pmod_unpack expr -> Sexp.list [ Sexp.atom "Pmod_unpack"; expression expr; ] | Pmod_extension ext -> Sexp.list [ Sexp.atom "Pmod_extension"; extension ext; ] in Sexp.list [ Sexp.atom "module_expr"; desc; attributes me.pmod_attributes; ] and moduleType mt = let desc = match mt.pmty_desc with | Pmty_ident longidentLoc -> Sexp.list [ Sexp.atom "Pmty_ident"; longident longidentLoc.Asttypes.txt; ] | Pmty_signature s -> Sexp.list [ Sexp.atom "Pmty_signature"; signature s; ] | Pmty_functor (lbl, optModType, modType) -> Sexp.list [ Sexp.atom "Pmty_functor"; string lbl.Asttypes.txt; (match optModType with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); moduleType modType; ] | Pmty_alias longidentLoc -> Sexp.list [ Sexp.atom "Pmty_alias"; longident longidentLoc.Asttypes.txt; ] | Pmty_extension ext -> Sexp.list [ Sexp.atom "Pmty_extension"; extension ext; ] | Pmty_typeof modExpr -> Sexp.list [ Sexp.atom "Pmty_typeof"; moduleExpression modExpr; ] | Pmty_with (modType, withConstraints) -> Sexp.list [ Sexp.atom "Pmty_with"; moduleType modType; Sexp.list (mapEmpty ~f:withConstraint withConstraints); ] in Sexp.list [ Sexp.atom "module_type"; desc; attributes mt.pmty_attributes; ] and withConstraint wc = match wc with | Pwith_type (longidentLoc, td) -> Sexp.list [ Sexp.atom "Pmty_with"; longident longidentLoc.Asttypes.txt; typeDeclaration td; ] | Pwith_module (l1, l2) -> Sexp.list [ Sexp.atom "Pwith_module"; longident l1.Asttypes.txt; longident l2.Asttypes.txt; ] | Pwith_typesubst (longidentLoc, td) -> Sexp.list [ Sexp.atom "Pwith_typesubst"; longident longidentLoc.Asttypes.txt; typeDeclaration td; ] | Pwith_modsubst (l1, l2) -> Sexp.list [ Sexp.atom "Pwith_modsubst"; longident l1.Asttypes.txt; longident l2.Asttypes.txt; ] and signature s = Sexp.list ( (Sexp.atom "signature")::(List.map signatureItem s) ) and signatureItem si = let descr = match si.psig_desc with | Psig_value vd -> Sexp.list [ Sexp.atom "Psig_value"; valueDescription vd; ] | Psig_type (flag, typeDeclarations) -> Sexp.list [ Sexp.atom "Psig_type"; recFlag flag; Sexp.list (mapEmpty ~f:typeDeclaration typeDeclarations); ] | Psig_typext typExt -> Sexp.list [ Sexp.atom "Psig_typext"; typeExtension typExt; ] | Psig_exception extConstr -> Sexp.list [ Sexp.atom "Psig_exception"; extensionConstructor extConstr; ] | Psig_module modDecl -> Sexp.list [ Sexp.atom "Psig_module"; moduleDeclaration modDecl; ] | Psig_recmodule modDecls -> Sexp.list [ Sexp.atom "Psig_recmodule"; Sexp.list (mapEmpty ~f:moduleDeclaration modDecls); ] | Psig_modtype modTypDecl -> Sexp.list [ Sexp.atom "Psig_modtype"; moduleTypeDeclaration modTypDecl; ] | Psig_open openDesc -> Sexp.list [ Sexp.atom "Psig_open"; openDescription openDesc; ] | Psig_include inclDecl -> Sexp.list [ Sexp.atom "Psig_include"; includeDescription inclDecl ] | Psig_class _ -> Sexp.list [Sexp.atom "Psig_class";] | Psig_class_type _ -> Sexp.list [ Sexp.atom "Psig_class_type"; ] | Psig_attribute attr -> Sexp.list [ Sexp.atom "Psig_attribute"; attribute attr; ] | Psig_extension (ext, attrs) -> Sexp.list [ Sexp.atom "Psig_extension"; extension ext; attributes attrs; ] in Sexp.list [ Sexp.atom "signature_item"; descr; ] and includeDescription id = Sexp.list [ Sexp.atom "include_description"; moduleType id.pincl_mod; attributes id.pincl_attributes; ] and moduleDeclaration md = Sexp.list [ Sexp.atom "module_declaration"; string md.pmd_name.Asttypes.txt; moduleType md.pmd_type; attributes md.pmd_attributes; ] and valueBinding vb = Sexp.list [ Sexp.atom "value_binding"; pattern vb.pvb_pat; expression vb.pvb_expr; attributes vb.pvb_attributes; ] and valueDescription vd = Sexp.list [ Sexp.atom "value_description"; string vd.pval_name.Asttypes.txt; coreType vd.pval_type; Sexp.list (mapEmpty ~f:string vd.pval_prim); attributes vd.pval_attributes; ] and typeDeclaration td = Sexp.list [ Sexp.atom "type_declaration"; string td.ptype_name.Asttypes.txt; Sexp.list [ Sexp.atom "ptype_params"; Sexp.list (mapEmpty ~f:(fun (typexpr, var) -> Sexp.list [ coreType typexpr; variance var; ]) td.ptype_params) ]; Sexp.list [ Sexp.atom "ptype_cstrs"; Sexp.list (mapEmpty ~f:(fun (typ1, typ2, _loc) -> Sexp.list [ coreType typ1; coreType typ2; ]) td.ptype_cstrs) ]; Sexp.list [ Sexp.atom "ptype_kind"; typeKind td.ptype_kind; ]; Sexp.list [ Sexp.atom "ptype_manifest"; match td.ptype_manifest with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ]; Sexp.list [ Sexp.atom "ptype_private"; privateFlag td.ptype_private; ]; attributes td.ptype_attributes; ] and extensionConstructor ec = Sexp.list [ Sexp.atom "extension_constructor"; string ec.pext_name.Asttypes.txt; extensionConstructorKind ec.pext_kind; attributes ec.pext_attributes; ] and extensionConstructorKind kind = match kind with | Pext_decl (args, optTypExpr) -> Sexp.list [ Sexp.atom "Pext_decl"; constructorArguments args; match optTypExpr with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ] | Pext_rebind longidentLoc -> Sexp.list [ Sexp.atom "Pext_rebind"; longident longidentLoc.Asttypes.txt; ] and typeExtension te = Sexp.list [ Sexp.atom "type_extension"; Sexp.list [ Sexp.atom "ptyext_path"; longident te.ptyext_path.Asttypes.txt; ]; Sexp.list [ Sexp.atom "ptyext_parms"; Sexp.list (mapEmpty ~f:(fun (typexpr, var) -> Sexp.list [ coreType typexpr; variance var; ]) te.ptyext_params) ]; Sexp.list [ Sexp.atom "ptyext_constructors"; Sexp.list (mapEmpty ~f:extensionConstructor te.ptyext_constructors); ]; Sexp.list [ Sexp.atom "ptyext_private"; privateFlag te.ptyext_private; ]; attributes te.ptyext_attributes; ] and typeKind kind = match kind with | Ptype_abstract -> Sexp.atom "Ptype_abstract" | Ptype_variant constrDecls -> Sexp.list [ Sexp.atom "Ptype_variant"; Sexp.list (mapEmpty ~f:constructorDeclaration constrDecls); ] | Ptype_record lblDecls -> Sexp.list [ Sexp.atom "Ptype_record"; Sexp.list (mapEmpty ~f:labelDeclaration lblDecls); ] | Ptype_open -> Sexp.atom "Ptype_open" and constructorDeclaration cd = Sexp.list [ Sexp.atom "constructor_declaration"; string cd.pcd_name.Asttypes.txt; Sexp.list [ Sexp.atom "pcd_args"; constructorArguments cd.pcd_args; ]; Sexp.list [ Sexp.atom "pcd_res"; match cd.pcd_res with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ]; attributes cd.pcd_attributes; ] and constructorArguments args = match args with | Pcstr_tuple types -> Sexp.list [ Sexp.atom "Pcstr_tuple"; Sexp.list (mapEmpty ~f:coreType types) ] | Pcstr_record lds -> Sexp.list [ Sexp.atom "Pcstr_record"; Sexp.list (mapEmpty ~f:labelDeclaration lds) ] and labelDeclaration ld = Sexp.list [ Sexp.atom "label_declaration"; string ld.pld_name.Asttypes.txt; mutableFlag ld.pld_mutable; coreType ld.pld_type; attributes ld.pld_attributes; ] and expression expr = let desc = match expr.pexp_desc with | Pexp_ident longidentLoc -> Sexp.list [ Sexp.atom "Pexp_ident"; longident longidentLoc.Asttypes.txt; ] | Pexp_constant c -> Sexp.list [ Sexp.atom "Pexp_constant"; constant c ] | Pexp_let (flag, vbs, expr) -> Sexp.list [ Sexp.atom "Pexp_let"; recFlag flag; Sexp.list (mapEmpty ~f:valueBinding vbs); expression expr; ] | Pexp_function cases -> Sexp.list [ Sexp.atom "Pexp_function"; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_fun (argLbl, exprOpt, pat, expr) -> Sexp.list [ Sexp.atom "Pexp_fun"; argLabel argLbl; (match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); pattern pat; expression expr; ] | Pexp_apply (expr, args) -> Sexp.list [ Sexp.atom "Pexp_apply"; expression expr; Sexp.list (mapEmpty ~f:(fun (argLbl, expr) -> Sexp.list [ argLabel argLbl; expression expr ]) args); ] | Pexp_match (expr, cases) -> Sexp.list [ Sexp.atom "Pexp_match"; expression expr; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_try (expr, cases) -> Sexp.list [ Sexp.atom "Pexp_try"; expression expr; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_tuple exprs -> Sexp.list [ Sexp.atom "Pexp_tuple"; Sexp.list (mapEmpty ~f:expression exprs); ] | Pexp_construct (longidentLoc, exprOpt) -> Sexp.list [ Sexp.atom "Pexp_construct"; longident longidentLoc.Asttypes.txt; match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ] | Pexp_variant (lbl, exprOpt) -> Sexp.list [ Sexp.atom "Pexp_variant"; string lbl; match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ] | Pexp_record (rows, optExpr) -> Sexp.list [ Sexp.atom "Pexp_record"; Sexp.list (mapEmpty ~f:(fun (longidentLoc, expr) -> Sexp.list [ longident longidentLoc.Asttypes.txt; expression expr; ]) rows); (match optExpr with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); ] | Pexp_field (expr, longidentLoc) -> Sexp.list [ Sexp.atom "Pexp_field"; expression expr; longident longidentLoc.Asttypes.txt; ] | Pexp_setfield (expr1, longidentLoc, expr2) -> Sexp.list [ Sexp.atom "Pexp_setfield"; expression expr1; longident longidentLoc.Asttypes.txt; expression expr2; ] | Pexp_array exprs -> Sexp.list [ Sexp.atom "Pexp_array"; Sexp.list (mapEmpty ~f:expression exprs); ] | Pexp_ifthenelse (expr1, expr2, optExpr) -> Sexp.list [ Sexp.atom "Pexp_ifthenelse"; expression expr1; expression expr2; (match optExpr with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); ] | Pexp_sequence (expr1, expr2) -> Sexp.list [ Sexp.atom "Pexp_sequence"; expression expr1; expression expr2; ] | Pexp_while (expr1, expr2) -> Sexp.list [ Sexp.atom "Pexp_while"; expression expr1; expression expr2; ] | Pexp_for (pat, e1, e2, flag, e3) -> Sexp.list [ Sexp.atom "Pexp_for"; pattern pat; expression e1; expression e2; directionFlag flag; expression e3; ] | Pexp_constraint (expr, typexpr) -> Sexp.list [ Sexp.atom "Pexp_constraint"; expression expr; coreType typexpr; ] | Pexp_coerce (expr, optTyp, typexpr) -> Sexp.list [ Sexp.atom "Pexp_coerce"; expression expr; (match optTyp with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ]); coreType typexpr; ] | Pexp_send _ -> Sexp.list [ Sexp.atom "Pexp_send"; ] | Pexp_new _ -> Sexp.list [ Sexp.atom "Pexp_new"; ] | Pexp_setinstvar _ -> Sexp.list [ Sexp.atom "Pexp_setinstvar"; ] | Pexp_override _ -> Sexp.list [ Sexp.atom "Pexp_override"; ] | Pexp_letmodule (modName, modExpr, expr) -> Sexp.list [ Sexp.atom "Pexp_letmodule"; string modName.Asttypes.txt; moduleExpression modExpr; expression expr; ] | Pexp_letexception (extConstr, expr) -> Sexp.list [ Sexp.atom "Pexp_letexception"; extensionConstructor extConstr; expression expr; ] | Pexp_assert expr -> Sexp.list [ Sexp.atom "Pexp_assert"; expression expr; ] | Pexp_lazy expr -> Sexp.list [ Sexp.atom "Pexp_lazy"; expression expr; ] | Pexp_poly _ -> Sexp.list [ Sexp.atom "Pexp_poly"; ] | Pexp_object _ -> Sexp.list [ Sexp.atom "Pexp_object"; ] | Pexp_newtype (lbl, expr) -> Sexp.list [ Sexp.atom "Pexp_newtype"; string lbl.Asttypes.txt; expression expr; ] | Pexp_pack modExpr -> Sexp.list [ Sexp.atom "Pexp_pack"; moduleExpression modExpr; ] | Pexp_open (flag, longidentLoc, expr) -> Sexp.list [ Sexp.atom "Pexp_open"; overrideFlag flag; longident longidentLoc.Asttypes.txt; expression expr; ] | Pexp_extension ext -> Sexp.list [ Sexp.atom "Pexp_extension"; extension ext; ] | Pexp_unreachable -> Sexp.atom "Pexp_unreachable" in Sexp.list [ Sexp.atom "expression"; desc; ] and case c = Sexp.list [ Sexp.atom "case"; Sexp.list [ Sexp.atom "pc_lhs"; pattern c.pc_lhs; ]; Sexp.list [ Sexp.atom "pc_guard"; match c.pc_guard with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ]; Sexp.list [ Sexp.atom "pc_rhs"; expression c.pc_rhs; ] ] and pattern p = let descr = match p.ppat_desc with | Ppat_any -> Sexp.atom "Ppat_any" | Ppat_var var -> Sexp.list [ Sexp.atom "Ppat_var"; string var.Location.txt; ] | Ppat_alias (p, alias) -> Sexp.list [ Sexp.atom "Ppat_alias"; pattern p; string alias.txt; ] | Ppat_constant c -> Sexp.list [ Sexp.atom "Ppat_constant"; constant c; ] | Ppat_interval (lo, hi) -> Sexp.list [ Sexp.atom "Ppat_interval"; constant lo; constant hi; ] | Ppat_tuple (patterns) -> Sexp.list [ Sexp.atom "Ppat_tuple"; Sexp.list (mapEmpty ~f:pattern patterns); ] | Ppat_construct (longidentLoc, optPattern) -> Sexp.list [ Sexp.atom "Ppat_construct"; longident longidentLoc.Location.txt; match optPattern with | None -> Sexp.atom "None" | Some p -> Sexp.list [ Sexp.atom "some"; pattern p; ] ] | Ppat_variant (lbl, optPattern) -> Sexp.list [ Sexp.atom "Ppat_variant"; string lbl; match optPattern with | None -> Sexp.atom "None" | Some p -> Sexp.list [ Sexp.atom "Some"; pattern p; ] ] | Ppat_record (rows, flag) -> Sexp.list [ Sexp.atom "Ppat_record"; closedFlag flag; Sexp.list (mapEmpty ~f:(fun (longidentLoc, p) -> Sexp.list [ longident longidentLoc.Location.txt; pattern p; ] ) rows) ] | Ppat_array patterns -> Sexp.list [ Sexp.atom "Ppat_array"; Sexp.list (mapEmpty ~f:pattern patterns); ] | Ppat_or (p1, p2) -> Sexp.list [ Sexp.atom "Ppat_or"; pattern p1; pattern p2; ] | Ppat_constraint (p, typexpr) -> Sexp.list [ Sexp.atom "Ppat_constraint"; pattern p; coreType typexpr; ] | Ppat_type longidentLoc -> Sexp.list [ Sexp.atom "Ppat_type"; longident longidentLoc.Location.txt ] | Ppat_lazy p -> Sexp.list [ Sexp.atom "Ppat_lazy"; pattern p; ] | Ppat_unpack stringLoc -> Sexp.list [ Sexp.atom "Ppat_unpack"; string stringLoc.Location.txt; ] | Ppat_exception p -> Sexp.list [ Sexp.atom "Ppat_exception"; pattern p; ] | Ppat_extension ext -> Sexp.list [ Sexp.atom "Ppat_extension"; extension ext; ] | Ppat_open (longidentLoc, p) -> Sexp.list [ Sexp.atom "Ppat_open"; longident longidentLoc.Location.txt; pattern p; ] in Sexp.list [ Sexp.atom "pattern"; descr; ] and objectField field = match field with | Otag (lblLoc, attrs, typexpr) -> Sexp.list [ Sexp.atom "Otag"; string lblLoc.txt; attributes attrs; coreType typexpr; ] | Oinherit typexpr -> Sexp.list [ Sexp.atom "Oinherit"; coreType typexpr; ] and rowField field = match field with | Rtag (labelLoc, attrs, truth, types) -> Sexp.list [ Sexp.atom "Rtag"; string labelLoc.txt; attributes attrs; Sexp.atom (if truth then "true" else "false"); Sexp.list (mapEmpty ~f:coreType types); ] | Rinherit typexpr -> Sexp.list [ Sexp.atom "Rinherit"; coreType typexpr; ] and packageType (modNameLoc, packageConstraints) = Sexp.list [ Sexp.atom "package_type"; longident modNameLoc.Asttypes.txt; Sexp.list (mapEmpty ~f:(fun (modNameLoc, typexpr) -> Sexp.list [ longident modNameLoc.Asttypes.txt; coreType typexpr; ] ) packageConstraints) ] and coreType typexpr = let desc = match typexpr.ptyp_desc with | Ptyp_any -> Sexp.atom "Ptyp_any" | Ptyp_var var -> Sexp.list [ Sexp.atom "Ptyp_var"; string var ] | Ptyp_arrow (argLbl, typ1, typ2) -> Sexp.list [ Sexp.atom "Ptyp_arrow"; argLabel argLbl; coreType typ1; coreType typ2; ] | Ptyp_tuple types -> Sexp.list [ Sexp.atom "Ptyp_tuple"; Sexp.list (mapEmpty ~f:coreType types); ] | Ptyp_constr (longidentLoc, types) -> Sexp.list [ Sexp.atom "Ptyp_constr"; longident longidentLoc.txt; Sexp.list (mapEmpty ~f:coreType types); ] | Ptyp_alias (typexpr, alias) -> Sexp.list [ Sexp.atom "Ptyp_alias"; coreType typexpr; string alias; ] | Ptyp_object (fields, flag) -> Sexp.list [ Sexp.atom "Ptyp_object"; closedFlag flag; Sexp.list (mapEmpty ~f:objectField fields) ] | Ptyp_class (longidentLoc, types) -> Sexp.list [ Sexp.atom "Ptyp_class"; longident longidentLoc.Location.txt; Sexp.list (mapEmpty ~f:coreType types) ] | Ptyp_variant (fields, flag, optLabels) -> Sexp.list [ Sexp.atom "Ptyp_variant"; Sexp.list (mapEmpty ~f:rowField fields); closedFlag flag; match optLabels with | None -> Sexp.atom "None" | Some lbls -> Sexp.list (mapEmpty ~f:string lbls); ] | Ptyp_poly (lbls, typexpr) -> Sexp.list [ Sexp.atom "Ptyp_poly"; Sexp.list (mapEmpty ~f:(fun lbl -> string lbl.Asttypes.txt) lbls); coreType typexpr; ] | Ptyp_package (package) -> Sexp.list [ Sexp.atom "Ptyp_package"; packageType package; ] | Ptyp_extension (ext) -> Sexp.list [ Sexp.atom "Ptyp_extension"; extension ext; ] in Sexp.list [ Sexp.atom "core_type"; desc; ] and payload p = match p with | PStr s -> Sexp.list ( (Sexp.atom "PStr")::(mapEmpty ~f:structureItem s) ) | PSig s -> Sexp.list [ Sexp.atom "PSig"; signature s; ] | PTyp ct -> Sexp.list [ Sexp.atom "PTyp"; coreType ct ] | PPat (pat, optExpr) -> Sexp.list [ Sexp.atom "PPat"; pattern pat; match optExpr with | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] | None -> Sexp.atom "None"; ] and attribute (stringLoc, p) = Sexp.list [ Sexp.atom "attribute"; Sexp.atom stringLoc.Asttypes.txt; payload p; ] and extension (stringLoc, p) = Sexp.list [ Sexp.atom "extension"; Sexp.atom stringLoc.Asttypes.txt; payload p; ] and attributes attrs = let sexprs = mapEmpty ~f:attribute attrs in Sexp.list ((Sexp.atom "attributes")::sexprs) let printEngine = Res_driver.{ printImplementation = begin fun ~width:_ ~filename:_ ~comments:_ parsetree -> parsetree |> From_current.copy_structure |> structure |> Sexp.toString |> print_string end; printInterface = begin fun ~width:_ ~filename:_ ~comments:_ parsetree -> parsetree |> From_current.copy_signature |> signature |> Sexp.toString |> print_string end; } end let sexpPrintEngine = SexpAst.printEngine
null
https://raw.githubusercontent.com/melange-re/melange/d6f41989ec092eea5a623171fe5e54e17fde0d10/jscomp/napkin/res_ast_debugger.ml
ocaml
open Import open Ast_406 module Doc = Res_doc let printEngine = Res_driver.{ printImplementation = begin fun ~width:_ ~filename:_ ~comments:_ structure -> Printast.implementation Format.std_formatter structure end; printInterface = begin fun ~width:_ ~filename:_ ~comments:_ signature -> Printast.interface Format.std_formatter signature end; } module Sexp: sig type t val atom: string -> t val list: t list -> t val toString: t -> string end = struct type t = | Atom of string | List of t list let atom s = Atom s let list l = List l let rec toDoc t = match t with | Atom s -> Doc.text s | List [] -> Doc.text "()" | List [sexpr] -> Doc.concat [Doc.lparen; toDoc sexpr; Doc.rparen;] | List (hd::tail) -> Doc.group ( Doc.concat [ Doc.lparen; toDoc hd; Doc.indent ( Doc.concat [ Doc.line; Doc.join ~sep:Doc.line (List.map toDoc tail); ] ); Doc.rparen; ] ) let toString sexpr = let doc = toDoc sexpr in Doc.toString ~width:80 doc end module SexpAst = struct open Parsetree let mapEmpty ~f items = match items with | [] -> [Sexp.list []] | items -> List.map f items let string txt = Sexp.atom ("\"" ^ txt ^ "\"") let char c = Sexp.atom ("'" ^ (Char.escaped c) ^ "'") let optChar oc = match oc with | None -> Sexp.atom "None" | Some c -> Sexp.list [ Sexp.atom "Some"; char c ] let longident l = let rec loop l = match l with | Longident.Lident ident -> Sexp.list [ Sexp.atom "Lident"; string ident; ] | Longident.Ldot (lident, txt) -> Sexp.list [ Sexp.atom "Ldot"; loop lident; string txt; ] | Longident.Lapply (l1, l2) -> Sexp.list [ Sexp.atom "Lapply"; loop l1; loop l2; ] in Sexp.list [ Sexp.atom "longident"; loop l; ] let closedFlag flag = match flag with | Asttypes.Closed -> Sexp.atom "Closed" | Open -> Sexp.atom "Open" let directionFlag flag = match flag with | Asttypes.Upto -> Sexp.atom "Upto" | Downto -> Sexp.atom "Downto" let recFlag flag = match flag with | Asttypes.Recursive -> Sexp.atom "Recursive" | Nonrecursive -> Sexp.atom "Nonrecursive" let overrideFlag flag = match flag with | Asttypes.Override -> Sexp.atom "Override" | Fresh -> Sexp.atom "Fresh" let privateFlag flag = match flag with | Asttypes.Public -> Sexp.atom "Public" | Private -> Sexp.atom "Private" let mutableFlag flag = match flag with | Asttypes.Immutable -> Sexp.atom "Immutable" | Mutable -> Sexp.atom "Mutable" let variance v = match v with | Asttypes.Covariant -> Sexp.atom "Covariant" | Contravariant -> Sexp.atom "Contravariant" | Invariant -> Sexp.atom "Invariant" let argLabel lbl = match lbl with | Asttypes.Nolabel -> Sexp.atom "Nolabel" | Labelled txt -> Sexp.list [ Sexp.atom "Labelled"; string txt; ] | Optional txt -> Sexp.list [ Sexp.atom "Optional"; string txt; ] let constant c = let sexpr = match c with | Pconst_integer (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_integer"; string txt; optChar tag; ] | Pconst_char c -> Sexp.list [ Sexp.atom "Pconst_char"; Sexp.atom (Char.escaped c); ] | Pconst_string (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_string"; string txt; match tag with | Some txt -> Sexp.list [ Sexp.atom "Some"; string txt; ] | None -> Sexp.atom "None"; ] | Pconst_float (txt, tag) -> Sexp.list [ Sexp.atom "Pconst_float"; string txt; optChar tag; ] in Sexp.list [ Sexp.atom "constant"; sexpr ] let rec structure s = Sexp.list ( (Sexp.atom "structure")::(List.map structureItem s) ) and structureItem si = let desc = match si.pstr_desc with | Pstr_eval (expr, attrs) -> Sexp.list [ Sexp.atom "Pstr_eval"; expression expr; attributes attrs; ] | Pstr_value (flag, vbs) -> Sexp.list [ Sexp.atom "Pstr_value"; recFlag flag; Sexp.list (mapEmpty ~f:valueBinding vbs) ] | Pstr_primitive (vd) -> Sexp.list [ Sexp.atom "Pstr_primitive"; valueDescription vd; ] | Pstr_type (flag, tds) -> Sexp.list [ Sexp.atom "Pstr_type"; recFlag flag; Sexp.list (mapEmpty ~f:typeDeclaration tds) ] | Pstr_typext typext -> Sexp.list [ Sexp.atom "Pstr_type"; typeExtension typext; ] | Pstr_exception ec -> Sexp.list [ Sexp.atom "Pstr_exception"; extensionConstructor ec; ] | Pstr_module mb -> Sexp.list [ Sexp.atom "Pstr_module"; moduleBinding mb; ] | Pstr_recmodule mbs -> Sexp.list [ Sexp.atom "Pstr_recmodule"; Sexp.list (mapEmpty ~f:moduleBinding mbs); ] | Pstr_modtype modTypDecl -> Sexp.list [ Sexp.atom "Pstr_modtype"; moduleTypeDeclaration modTypDecl; ] | Pstr_open openDesc -> Sexp.list [ Sexp.atom "Pstr_open"; openDescription openDesc; ] | Pstr_class _ -> Sexp.atom "Pstr_class" | Pstr_class_type _ -> Sexp.atom "Pstr_class_type" | Pstr_include id -> Sexp.list [ Sexp.atom "Pstr_include"; includeDeclaration id; ] | Pstr_attribute attr -> Sexp.list [ Sexp.atom "Pstr_attribute"; attribute attr; ] | Pstr_extension (ext, attrs) -> Sexp.list [ Sexp.atom "Pstr_extension"; extension ext; attributes attrs; ] in Sexp.list [ Sexp.atom "structure_item"; desc; ] and includeDeclaration id = Sexp.list [ Sexp.atom "include_declaration"; moduleExpression id.pincl_mod; attributes id.pincl_attributes; ] and openDescription od = Sexp.list [ Sexp.atom "open_description"; longident od.popen_lid.Asttypes.txt; attributes od.popen_attributes; ] and moduleTypeDeclaration mtd = Sexp.list [ Sexp.atom "module_type_declaration"; string mtd.pmtd_name.Asttypes.txt; (match mtd.pmtd_type with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); attributes mtd.pmtd_attributes; ] and moduleBinding mb = Sexp.list [ Sexp.atom "module_binding"; string mb.pmb_name.Asttypes.txt; moduleExpression mb.pmb_expr; attributes mb.pmb_attributes; ] and moduleExpression me = let desc = match me.pmod_desc with | Pmod_ident modName -> Sexp.list [ Sexp.atom "Pmod_ident"; longident modName.Asttypes.txt; ] | Pmod_structure s -> Sexp.list [ Sexp.atom "Pmod_structure"; structure s; ] | Pmod_functor (lbl, optModType, modExpr) -> Sexp.list [ Sexp.atom "Pmod_functor"; string lbl.Asttypes.txt; (match optModType with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); moduleExpression modExpr; ] | Pmod_apply (callModExpr, modExprArg) -> Sexp.list [ Sexp.atom "Pmod_apply"; moduleExpression callModExpr; moduleExpression modExprArg; ] | Pmod_constraint (modExpr, modType) -> Sexp.list [ Sexp.atom "Pmod_constraint"; moduleExpression modExpr; moduleType modType; ] | Pmod_unpack expr -> Sexp.list [ Sexp.atom "Pmod_unpack"; expression expr; ] | Pmod_extension ext -> Sexp.list [ Sexp.atom "Pmod_extension"; extension ext; ] in Sexp.list [ Sexp.atom "module_expr"; desc; attributes me.pmod_attributes; ] and moduleType mt = let desc = match mt.pmty_desc with | Pmty_ident longidentLoc -> Sexp.list [ Sexp.atom "Pmty_ident"; longident longidentLoc.Asttypes.txt; ] | Pmty_signature s -> Sexp.list [ Sexp.atom "Pmty_signature"; signature s; ] | Pmty_functor (lbl, optModType, modType) -> Sexp.list [ Sexp.atom "Pmty_functor"; string lbl.Asttypes.txt; (match optModType with | None -> Sexp.atom "None" | Some modType -> Sexp.list [ Sexp.atom "Some"; moduleType modType; ]); moduleType modType; ] | Pmty_alias longidentLoc -> Sexp.list [ Sexp.atom "Pmty_alias"; longident longidentLoc.Asttypes.txt; ] | Pmty_extension ext -> Sexp.list [ Sexp.atom "Pmty_extension"; extension ext; ] | Pmty_typeof modExpr -> Sexp.list [ Sexp.atom "Pmty_typeof"; moduleExpression modExpr; ] | Pmty_with (modType, withConstraints) -> Sexp.list [ Sexp.atom "Pmty_with"; moduleType modType; Sexp.list (mapEmpty ~f:withConstraint withConstraints); ] in Sexp.list [ Sexp.atom "module_type"; desc; attributes mt.pmty_attributes; ] and withConstraint wc = match wc with | Pwith_type (longidentLoc, td) -> Sexp.list [ Sexp.atom "Pmty_with"; longident longidentLoc.Asttypes.txt; typeDeclaration td; ] | Pwith_module (l1, l2) -> Sexp.list [ Sexp.atom "Pwith_module"; longident l1.Asttypes.txt; longident l2.Asttypes.txt; ] | Pwith_typesubst (longidentLoc, td) -> Sexp.list [ Sexp.atom "Pwith_typesubst"; longident longidentLoc.Asttypes.txt; typeDeclaration td; ] | Pwith_modsubst (l1, l2) -> Sexp.list [ Sexp.atom "Pwith_modsubst"; longident l1.Asttypes.txt; longident l2.Asttypes.txt; ] and signature s = Sexp.list ( (Sexp.atom "signature")::(List.map signatureItem s) ) and signatureItem si = let descr = match si.psig_desc with | Psig_value vd -> Sexp.list [ Sexp.atom "Psig_value"; valueDescription vd; ] | Psig_type (flag, typeDeclarations) -> Sexp.list [ Sexp.atom "Psig_type"; recFlag flag; Sexp.list (mapEmpty ~f:typeDeclaration typeDeclarations); ] | Psig_typext typExt -> Sexp.list [ Sexp.atom "Psig_typext"; typeExtension typExt; ] | Psig_exception extConstr -> Sexp.list [ Sexp.atom "Psig_exception"; extensionConstructor extConstr; ] | Psig_module modDecl -> Sexp.list [ Sexp.atom "Psig_module"; moduleDeclaration modDecl; ] | Psig_recmodule modDecls -> Sexp.list [ Sexp.atom "Psig_recmodule"; Sexp.list (mapEmpty ~f:moduleDeclaration modDecls); ] | Psig_modtype modTypDecl -> Sexp.list [ Sexp.atom "Psig_modtype"; moduleTypeDeclaration modTypDecl; ] | Psig_open openDesc -> Sexp.list [ Sexp.atom "Psig_open"; openDescription openDesc; ] | Psig_include inclDecl -> Sexp.list [ Sexp.atom "Psig_include"; includeDescription inclDecl ] | Psig_class _ -> Sexp.list [Sexp.atom "Psig_class";] | Psig_class_type _ -> Sexp.list [ Sexp.atom "Psig_class_type"; ] | Psig_attribute attr -> Sexp.list [ Sexp.atom "Psig_attribute"; attribute attr; ] | Psig_extension (ext, attrs) -> Sexp.list [ Sexp.atom "Psig_extension"; extension ext; attributes attrs; ] in Sexp.list [ Sexp.atom "signature_item"; descr; ] and includeDescription id = Sexp.list [ Sexp.atom "include_description"; moduleType id.pincl_mod; attributes id.pincl_attributes; ] and moduleDeclaration md = Sexp.list [ Sexp.atom "module_declaration"; string md.pmd_name.Asttypes.txt; moduleType md.pmd_type; attributes md.pmd_attributes; ] and valueBinding vb = Sexp.list [ Sexp.atom "value_binding"; pattern vb.pvb_pat; expression vb.pvb_expr; attributes vb.pvb_attributes; ] and valueDescription vd = Sexp.list [ Sexp.atom "value_description"; string vd.pval_name.Asttypes.txt; coreType vd.pval_type; Sexp.list (mapEmpty ~f:string vd.pval_prim); attributes vd.pval_attributes; ] and typeDeclaration td = Sexp.list [ Sexp.atom "type_declaration"; string td.ptype_name.Asttypes.txt; Sexp.list [ Sexp.atom "ptype_params"; Sexp.list (mapEmpty ~f:(fun (typexpr, var) -> Sexp.list [ coreType typexpr; variance var; ]) td.ptype_params) ]; Sexp.list [ Sexp.atom "ptype_cstrs"; Sexp.list (mapEmpty ~f:(fun (typ1, typ2, _loc) -> Sexp.list [ coreType typ1; coreType typ2; ]) td.ptype_cstrs) ]; Sexp.list [ Sexp.atom "ptype_kind"; typeKind td.ptype_kind; ]; Sexp.list [ Sexp.atom "ptype_manifest"; match td.ptype_manifest with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ]; Sexp.list [ Sexp.atom "ptype_private"; privateFlag td.ptype_private; ]; attributes td.ptype_attributes; ] and extensionConstructor ec = Sexp.list [ Sexp.atom "extension_constructor"; string ec.pext_name.Asttypes.txt; extensionConstructorKind ec.pext_kind; attributes ec.pext_attributes; ] and extensionConstructorKind kind = match kind with | Pext_decl (args, optTypExpr) -> Sexp.list [ Sexp.atom "Pext_decl"; constructorArguments args; match optTypExpr with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ] | Pext_rebind longidentLoc -> Sexp.list [ Sexp.atom "Pext_rebind"; longident longidentLoc.Asttypes.txt; ] and typeExtension te = Sexp.list [ Sexp.atom "type_extension"; Sexp.list [ Sexp.atom "ptyext_path"; longident te.ptyext_path.Asttypes.txt; ]; Sexp.list [ Sexp.atom "ptyext_parms"; Sexp.list (mapEmpty ~f:(fun (typexpr, var) -> Sexp.list [ coreType typexpr; variance var; ]) te.ptyext_params) ]; Sexp.list [ Sexp.atom "ptyext_constructors"; Sexp.list (mapEmpty ~f:extensionConstructor te.ptyext_constructors); ]; Sexp.list [ Sexp.atom "ptyext_private"; privateFlag te.ptyext_private; ]; attributes te.ptyext_attributes; ] and typeKind kind = match kind with | Ptype_abstract -> Sexp.atom "Ptype_abstract" | Ptype_variant constrDecls -> Sexp.list [ Sexp.atom "Ptype_variant"; Sexp.list (mapEmpty ~f:constructorDeclaration constrDecls); ] | Ptype_record lblDecls -> Sexp.list [ Sexp.atom "Ptype_record"; Sexp.list (mapEmpty ~f:labelDeclaration lblDecls); ] | Ptype_open -> Sexp.atom "Ptype_open" and constructorDeclaration cd = Sexp.list [ Sexp.atom "constructor_declaration"; string cd.pcd_name.Asttypes.txt; Sexp.list [ Sexp.atom "pcd_args"; constructorArguments cd.pcd_args; ]; Sexp.list [ Sexp.atom "pcd_res"; match cd.pcd_res with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ] ]; attributes cd.pcd_attributes; ] and constructorArguments args = match args with | Pcstr_tuple types -> Sexp.list [ Sexp.atom "Pcstr_tuple"; Sexp.list (mapEmpty ~f:coreType types) ] | Pcstr_record lds -> Sexp.list [ Sexp.atom "Pcstr_record"; Sexp.list (mapEmpty ~f:labelDeclaration lds) ] and labelDeclaration ld = Sexp.list [ Sexp.atom "label_declaration"; string ld.pld_name.Asttypes.txt; mutableFlag ld.pld_mutable; coreType ld.pld_type; attributes ld.pld_attributes; ] and expression expr = let desc = match expr.pexp_desc with | Pexp_ident longidentLoc -> Sexp.list [ Sexp.atom "Pexp_ident"; longident longidentLoc.Asttypes.txt; ] | Pexp_constant c -> Sexp.list [ Sexp.atom "Pexp_constant"; constant c ] | Pexp_let (flag, vbs, expr) -> Sexp.list [ Sexp.atom "Pexp_let"; recFlag flag; Sexp.list (mapEmpty ~f:valueBinding vbs); expression expr; ] | Pexp_function cases -> Sexp.list [ Sexp.atom "Pexp_function"; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_fun (argLbl, exprOpt, pat, expr) -> Sexp.list [ Sexp.atom "Pexp_fun"; argLabel argLbl; (match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); pattern pat; expression expr; ] | Pexp_apply (expr, args) -> Sexp.list [ Sexp.atom "Pexp_apply"; expression expr; Sexp.list (mapEmpty ~f:(fun (argLbl, expr) -> Sexp.list [ argLabel argLbl; expression expr ]) args); ] | Pexp_match (expr, cases) -> Sexp.list [ Sexp.atom "Pexp_match"; expression expr; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_try (expr, cases) -> Sexp.list [ Sexp.atom "Pexp_try"; expression expr; Sexp.list (mapEmpty ~f:case cases); ] | Pexp_tuple exprs -> Sexp.list [ Sexp.atom "Pexp_tuple"; Sexp.list (mapEmpty ~f:expression exprs); ] | Pexp_construct (longidentLoc, exprOpt) -> Sexp.list [ Sexp.atom "Pexp_construct"; longident longidentLoc.Asttypes.txt; match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ] | Pexp_variant (lbl, exprOpt) -> Sexp.list [ Sexp.atom "Pexp_variant"; string lbl; match exprOpt with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ] | Pexp_record (rows, optExpr) -> Sexp.list [ Sexp.atom "Pexp_record"; Sexp.list (mapEmpty ~f:(fun (longidentLoc, expr) -> Sexp.list [ longident longidentLoc.Asttypes.txt; expression expr; ]) rows); (match optExpr with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); ] | Pexp_field (expr, longidentLoc) -> Sexp.list [ Sexp.atom "Pexp_field"; expression expr; longident longidentLoc.Asttypes.txt; ] | Pexp_setfield (expr1, longidentLoc, expr2) -> Sexp.list [ Sexp.atom "Pexp_setfield"; expression expr1; longident longidentLoc.Asttypes.txt; expression expr2; ] | Pexp_array exprs -> Sexp.list [ Sexp.atom "Pexp_array"; Sexp.list (mapEmpty ~f:expression exprs); ] | Pexp_ifthenelse (expr1, expr2, optExpr) -> Sexp.list [ Sexp.atom "Pexp_ifthenelse"; expression expr1; expression expr2; (match optExpr with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ]); ] | Pexp_sequence (expr1, expr2) -> Sexp.list [ Sexp.atom "Pexp_sequence"; expression expr1; expression expr2; ] | Pexp_while (expr1, expr2) -> Sexp.list [ Sexp.atom "Pexp_while"; expression expr1; expression expr2; ] | Pexp_for (pat, e1, e2, flag, e3) -> Sexp.list [ Sexp.atom "Pexp_for"; pattern pat; expression e1; expression e2; directionFlag flag; expression e3; ] | Pexp_constraint (expr, typexpr) -> Sexp.list [ Sexp.atom "Pexp_constraint"; expression expr; coreType typexpr; ] | Pexp_coerce (expr, optTyp, typexpr) -> Sexp.list [ Sexp.atom "Pexp_coerce"; expression expr; (match optTyp with | None -> Sexp.atom "None" | Some typ -> Sexp.list [ Sexp.atom "Some"; coreType typ; ]); coreType typexpr; ] | Pexp_send _ -> Sexp.list [ Sexp.atom "Pexp_send"; ] | Pexp_new _ -> Sexp.list [ Sexp.atom "Pexp_new"; ] | Pexp_setinstvar _ -> Sexp.list [ Sexp.atom "Pexp_setinstvar"; ] | Pexp_override _ -> Sexp.list [ Sexp.atom "Pexp_override"; ] | Pexp_letmodule (modName, modExpr, expr) -> Sexp.list [ Sexp.atom "Pexp_letmodule"; string modName.Asttypes.txt; moduleExpression modExpr; expression expr; ] | Pexp_letexception (extConstr, expr) -> Sexp.list [ Sexp.atom "Pexp_letexception"; extensionConstructor extConstr; expression expr; ] | Pexp_assert expr -> Sexp.list [ Sexp.atom "Pexp_assert"; expression expr; ] | Pexp_lazy expr -> Sexp.list [ Sexp.atom "Pexp_lazy"; expression expr; ] | Pexp_poly _ -> Sexp.list [ Sexp.atom "Pexp_poly"; ] | Pexp_object _ -> Sexp.list [ Sexp.atom "Pexp_object"; ] | Pexp_newtype (lbl, expr) -> Sexp.list [ Sexp.atom "Pexp_newtype"; string lbl.Asttypes.txt; expression expr; ] | Pexp_pack modExpr -> Sexp.list [ Sexp.atom "Pexp_pack"; moduleExpression modExpr; ] | Pexp_open (flag, longidentLoc, expr) -> Sexp.list [ Sexp.atom "Pexp_open"; overrideFlag flag; longident longidentLoc.Asttypes.txt; expression expr; ] | Pexp_extension ext -> Sexp.list [ Sexp.atom "Pexp_extension"; extension ext; ] | Pexp_unreachable -> Sexp.atom "Pexp_unreachable" in Sexp.list [ Sexp.atom "expression"; desc; ] and case c = Sexp.list [ Sexp.atom "case"; Sexp.list [ Sexp.atom "pc_lhs"; pattern c.pc_lhs; ]; Sexp.list [ Sexp.atom "pc_guard"; match c.pc_guard with | None -> Sexp.atom "None" | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] ]; Sexp.list [ Sexp.atom "pc_rhs"; expression c.pc_rhs; ] ] and pattern p = let descr = match p.ppat_desc with | Ppat_any -> Sexp.atom "Ppat_any" | Ppat_var var -> Sexp.list [ Sexp.atom "Ppat_var"; string var.Location.txt; ] | Ppat_alias (p, alias) -> Sexp.list [ Sexp.atom "Ppat_alias"; pattern p; string alias.txt; ] | Ppat_constant c -> Sexp.list [ Sexp.atom "Ppat_constant"; constant c; ] | Ppat_interval (lo, hi) -> Sexp.list [ Sexp.atom "Ppat_interval"; constant lo; constant hi; ] | Ppat_tuple (patterns) -> Sexp.list [ Sexp.atom "Ppat_tuple"; Sexp.list (mapEmpty ~f:pattern patterns); ] | Ppat_construct (longidentLoc, optPattern) -> Sexp.list [ Sexp.atom "Ppat_construct"; longident longidentLoc.Location.txt; match optPattern with | None -> Sexp.atom "None" | Some p -> Sexp.list [ Sexp.atom "some"; pattern p; ] ] | Ppat_variant (lbl, optPattern) -> Sexp.list [ Sexp.atom "Ppat_variant"; string lbl; match optPattern with | None -> Sexp.atom "None" | Some p -> Sexp.list [ Sexp.atom "Some"; pattern p; ] ] | Ppat_record (rows, flag) -> Sexp.list [ Sexp.atom "Ppat_record"; closedFlag flag; Sexp.list (mapEmpty ~f:(fun (longidentLoc, p) -> Sexp.list [ longident longidentLoc.Location.txt; pattern p; ] ) rows) ] | Ppat_array patterns -> Sexp.list [ Sexp.atom "Ppat_array"; Sexp.list (mapEmpty ~f:pattern patterns); ] | Ppat_or (p1, p2) -> Sexp.list [ Sexp.atom "Ppat_or"; pattern p1; pattern p2; ] | Ppat_constraint (p, typexpr) -> Sexp.list [ Sexp.atom "Ppat_constraint"; pattern p; coreType typexpr; ] | Ppat_type longidentLoc -> Sexp.list [ Sexp.atom "Ppat_type"; longident longidentLoc.Location.txt ] | Ppat_lazy p -> Sexp.list [ Sexp.atom "Ppat_lazy"; pattern p; ] | Ppat_unpack stringLoc -> Sexp.list [ Sexp.atom "Ppat_unpack"; string stringLoc.Location.txt; ] | Ppat_exception p -> Sexp.list [ Sexp.atom "Ppat_exception"; pattern p; ] | Ppat_extension ext -> Sexp.list [ Sexp.atom "Ppat_extension"; extension ext; ] | Ppat_open (longidentLoc, p) -> Sexp.list [ Sexp.atom "Ppat_open"; longident longidentLoc.Location.txt; pattern p; ] in Sexp.list [ Sexp.atom "pattern"; descr; ] and objectField field = match field with | Otag (lblLoc, attrs, typexpr) -> Sexp.list [ Sexp.atom "Otag"; string lblLoc.txt; attributes attrs; coreType typexpr; ] | Oinherit typexpr -> Sexp.list [ Sexp.atom "Oinherit"; coreType typexpr; ] and rowField field = match field with | Rtag (labelLoc, attrs, truth, types) -> Sexp.list [ Sexp.atom "Rtag"; string labelLoc.txt; attributes attrs; Sexp.atom (if truth then "true" else "false"); Sexp.list (mapEmpty ~f:coreType types); ] | Rinherit typexpr -> Sexp.list [ Sexp.atom "Rinherit"; coreType typexpr; ] and packageType (modNameLoc, packageConstraints) = Sexp.list [ Sexp.atom "package_type"; longident modNameLoc.Asttypes.txt; Sexp.list (mapEmpty ~f:(fun (modNameLoc, typexpr) -> Sexp.list [ longident modNameLoc.Asttypes.txt; coreType typexpr; ] ) packageConstraints) ] and coreType typexpr = let desc = match typexpr.ptyp_desc with | Ptyp_any -> Sexp.atom "Ptyp_any" | Ptyp_var var -> Sexp.list [ Sexp.atom "Ptyp_var"; string var ] | Ptyp_arrow (argLbl, typ1, typ2) -> Sexp.list [ Sexp.atom "Ptyp_arrow"; argLabel argLbl; coreType typ1; coreType typ2; ] | Ptyp_tuple types -> Sexp.list [ Sexp.atom "Ptyp_tuple"; Sexp.list (mapEmpty ~f:coreType types); ] | Ptyp_constr (longidentLoc, types) -> Sexp.list [ Sexp.atom "Ptyp_constr"; longident longidentLoc.txt; Sexp.list (mapEmpty ~f:coreType types); ] | Ptyp_alias (typexpr, alias) -> Sexp.list [ Sexp.atom "Ptyp_alias"; coreType typexpr; string alias; ] | Ptyp_object (fields, flag) -> Sexp.list [ Sexp.atom "Ptyp_object"; closedFlag flag; Sexp.list (mapEmpty ~f:objectField fields) ] | Ptyp_class (longidentLoc, types) -> Sexp.list [ Sexp.atom "Ptyp_class"; longident longidentLoc.Location.txt; Sexp.list (mapEmpty ~f:coreType types) ] | Ptyp_variant (fields, flag, optLabels) -> Sexp.list [ Sexp.atom "Ptyp_variant"; Sexp.list (mapEmpty ~f:rowField fields); closedFlag flag; match optLabels with | None -> Sexp.atom "None" | Some lbls -> Sexp.list (mapEmpty ~f:string lbls); ] | Ptyp_poly (lbls, typexpr) -> Sexp.list [ Sexp.atom "Ptyp_poly"; Sexp.list (mapEmpty ~f:(fun lbl -> string lbl.Asttypes.txt) lbls); coreType typexpr; ] | Ptyp_package (package) -> Sexp.list [ Sexp.atom "Ptyp_package"; packageType package; ] | Ptyp_extension (ext) -> Sexp.list [ Sexp.atom "Ptyp_extension"; extension ext; ] in Sexp.list [ Sexp.atom "core_type"; desc; ] and payload p = match p with | PStr s -> Sexp.list ( (Sexp.atom "PStr")::(mapEmpty ~f:structureItem s) ) | PSig s -> Sexp.list [ Sexp.atom "PSig"; signature s; ] | PTyp ct -> Sexp.list [ Sexp.atom "PTyp"; coreType ct ] | PPat (pat, optExpr) -> Sexp.list [ Sexp.atom "PPat"; pattern pat; match optExpr with | Some expr -> Sexp.list [ Sexp.atom "Some"; expression expr; ] | None -> Sexp.atom "None"; ] and attribute (stringLoc, p) = Sexp.list [ Sexp.atom "attribute"; Sexp.atom stringLoc.Asttypes.txt; payload p; ] and extension (stringLoc, p) = Sexp.list [ Sexp.atom "extension"; Sexp.atom stringLoc.Asttypes.txt; payload p; ] and attributes attrs = let sexprs = mapEmpty ~f:attribute attrs in Sexp.list ((Sexp.atom "attributes")::sexprs) let printEngine = Res_driver.{ printImplementation = begin fun ~width:_ ~filename:_ ~comments:_ parsetree -> parsetree |> From_current.copy_structure |> structure |> Sexp.toString |> print_string end; printInterface = begin fun ~width:_ ~filename:_ ~comments:_ parsetree -> parsetree |> From_current.copy_signature |> signature |> Sexp.toString |> print_string end; } end let sexpPrintEngine = SexpAst.printEngine
d146e1839cf828a113ff310699759a4f95b4b7914794053fac1475c59e8c2484
yfractal/chartkick
project.clj
(defproject chartkick "0.1.0" :description "Create beautiful JavaScript charts with one line of Clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/data.json "0.2.6"]])
null
https://raw.githubusercontent.com/yfractal/chartkick/5e69dba4bb9c6afb3a3257c9fb14836a190658ed/project.clj
clojure
(defproject chartkick "0.1.0" :description "Create beautiful JavaScript charts with one line of Clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/data.json "0.2.6"]])
10c5ba911bb52b4232b0591e437ffeb4b2218e53654010e78b7928e4d0e36b4c
meooow25/haccepted
AhoCorasickBench.hs
module AhoCorasickBench where import Control.Monad import qualified Data.ByteString.Char8 as C import Criterion import AhoCorasick import Util ( RandStd, evalR, randLowerCaseString, sizedBench ) benchmark :: Benchmark benchmark = bgroup "AhoCorasick" Build the Aho - Corasick automaton from 20 a - z strings of length n/20 . bgroup "build from few long" $ map (benchBuild genFew) sizes Match an Aho - Corasick automaton built from 20 a - z strings of length n/20 on a string of -- length n. , bgroup "match few long" $ map (benchMatch genFew) sizes Build the Aho - Corasick automaton from n/20 a - z strings of length 20 . , bgroup "build from many short" $ map (benchBuild genMany) sizes Match an Aho - Corasick automaton built from n/20 a - z strings of length 20 on a string of -- length n. , bgroup "match many short" $ map (benchMatch genMany) sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchBuild :: (Int -> RandStd [(C.ByteString, Int)]) -> Int -> Benchmark benchBuild genps n = sizedBench n gen $ nf (fromTrieAC . fromListTAC) where gen = evalR $ genps n benchMatch :: (Int -> RandStd [(C.ByteString, Int)]) -> Int -> Benchmark benchMatch genps n = sizedBench n gen $ \(ac, ps) -> nf (matchAC ac) ps where gen = evalR $ (,) <$> (fromTrieAC . fromListTAC <$> genps n) <*> (C.pack <$> randLowerCaseString n) genFew :: Int -> RandStd [(C.ByteString, Int)] genFew n = do let n' = div n 20 ps <- replicateM 20 $ C.pack <$> randLowerCaseString n' pure $ zip ps [1..] genMany :: Int -> RandStd [(C.ByteString, Int)] genMany n = do let n' = div n 20 ps <- replicateM n' $ C.pack <$> randLowerCaseString 20 pure $ zip ps [1..]
null
https://raw.githubusercontent.com/meooow25/haccepted/58398d849b6e68c3588b18997d9d39529829c396/bench/AhoCorasickBench.hs
haskell
length n. length n.
module AhoCorasickBench where import Control.Monad import qualified Data.ByteString.Char8 as C import Criterion import AhoCorasick import Util ( RandStd, evalR, randLowerCaseString, sizedBench ) benchmark :: Benchmark benchmark = bgroup "AhoCorasick" Build the Aho - Corasick automaton from 20 a - z strings of length n/20 . bgroup "build from few long" $ map (benchBuild genFew) sizes Match an Aho - Corasick automaton built from 20 a - z strings of length n/20 on a string of , bgroup "match few long" $ map (benchMatch genFew) sizes Build the Aho - Corasick automaton from n/20 a - z strings of length 20 . , bgroup "build from many short" $ map (benchBuild genMany) sizes Match an Aho - Corasick automaton built from n/20 a - z strings of length 20 on a string of , bgroup "match many short" $ map (benchMatch genMany) sizes ] sizes :: [Int] sizes = [100, 10000, 1000000] benchBuild :: (Int -> RandStd [(C.ByteString, Int)]) -> Int -> Benchmark benchBuild genps n = sizedBench n gen $ nf (fromTrieAC . fromListTAC) where gen = evalR $ genps n benchMatch :: (Int -> RandStd [(C.ByteString, Int)]) -> Int -> Benchmark benchMatch genps n = sizedBench n gen $ \(ac, ps) -> nf (matchAC ac) ps where gen = evalR $ (,) <$> (fromTrieAC . fromListTAC <$> genps n) <*> (C.pack <$> randLowerCaseString n) genFew :: Int -> RandStd [(C.ByteString, Int)] genFew n = do let n' = div n 20 ps <- replicateM 20 $ C.pack <$> randLowerCaseString n' pure $ zip ps [1..] genMany :: Int -> RandStd [(C.ByteString, Int)] genMany n = do let n' = div n 20 ps <- replicateM n' $ C.pack <$> randLowerCaseString 20 pure $ zip ps [1..]
3d215cc223c7aa6fdfa0bed8756cb02de9384313d8b9e7bbe752db3aa40129b0
ArthurGarnier/turtl-docker
launch.lisp
(pushnew "./" asdf:*central-registry* :test #'equal) (load "start")
null
https://raw.githubusercontent.com/ArthurGarnier/turtl-docker/2be6e7ed0007df069126a646b7ede411df3f4f63/launch.lisp
lisp
(pushnew "./" asdf:*central-registry* :test #'equal) (load "start")
f2bf6e55682770400a80f703a949706a7777872b5dee56900d9a6bdd7cd3a35d
plumatic/grab-bag
linear_test.clj
(ns classify.linear-test (:use plumbing.core plumbing.test clojure.test) (:require [classify.learn :as learn] [classify.linear :as linear])) (def test-data [[0 0 1] [1 0 10] [1 2 10] [2 2 1]]) (deftest l2-evaluator-test (is-= {:num-obs 22.0 :sum-xs 0.0 :sum-sq-xs 22.0} (select-keys (learn/evaluate-all linear/l2-evaluator (linear/->ConstantModel 1) test-data) [:num-obs :sum-xs :sum-sq-xs])) (is-= {:num-obs 22.0 :sum-xs 22.0 :sum-sq-xs 44.0} (select-keys (learn/evaluate-all linear/l2-evaluator (linear/->ConstantModel 0) test-data) [:num-obs :sum-xs :sum-sq-xs]))) (deftest constant-trainer-test (is-approx-= 1.0 (:mean (linear/+constant-trainer+ test-data)) 1.0e-10)) (deftest bucket-trainer-test (is-approx-= {:mean-map {true (/ 20 21) false 2} :overall-mean 1.0} (select-keys ((linear/bucket-trainer #(<= % 1.5)) test-data) [:mean-map :overall-mean]) 1.0e-10)) (deftest linear-trainer-test (is-approx-= {:bias 0.0 :a 1.0} (linear/explain ((linear/linear-trainer #(hash-map :a %) {:sigma-sq 1000000}) test-data)) 1.0e-6))
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/classify/test/classify/linear_test.clj
clojure
(ns classify.linear-test (:use plumbing.core plumbing.test clojure.test) (:require [classify.learn :as learn] [classify.linear :as linear])) (def test-data [[0 0 1] [1 0 10] [1 2 10] [2 2 1]]) (deftest l2-evaluator-test (is-= {:num-obs 22.0 :sum-xs 0.0 :sum-sq-xs 22.0} (select-keys (learn/evaluate-all linear/l2-evaluator (linear/->ConstantModel 1) test-data) [:num-obs :sum-xs :sum-sq-xs])) (is-= {:num-obs 22.0 :sum-xs 22.0 :sum-sq-xs 44.0} (select-keys (learn/evaluate-all linear/l2-evaluator (linear/->ConstantModel 0) test-data) [:num-obs :sum-xs :sum-sq-xs]))) (deftest constant-trainer-test (is-approx-= 1.0 (:mean (linear/+constant-trainer+ test-data)) 1.0e-10)) (deftest bucket-trainer-test (is-approx-= {:mean-map {true (/ 20 21) false 2} :overall-mean 1.0} (select-keys ((linear/bucket-trainer #(<= % 1.5)) test-data) [:mean-map :overall-mean]) 1.0e-10)) (deftest linear-trainer-test (is-approx-= {:bias 0.0 :a 1.0} (linear/explain ((linear/linear-trainer #(hash-map :a %) {:sigma-sq 1000000}) test-data)) 1.0e-6))
9655fe7a69915fd15f2318007d474ee736b1e1b2d78e55a6fc70940742eeb506
oakes/Dynadoc
project.clj
(defproject dynadoc/lein-dynadoc "1.7.5.1" :description "A conveninent Dynadoc launcher for Leiningen projects" :url "" :license {:name "Public Domain" :url ""} :dependencies [[dynadoc "1.7.5"] [leinjacker "0.4.3"] [org.clojure/tools.cli "1.0.214"]] :repositories [["clojars" {:url "" :sign-releases false}]] :eval-in-leiningen true)
null
https://raw.githubusercontent.com/oakes/Dynadoc/eac412e3ffb3a03798220d2d4e1dc7d0f822effd/lein-dynadoc/project.clj
clojure
(defproject dynadoc/lein-dynadoc "1.7.5.1" :description "A conveninent Dynadoc launcher for Leiningen projects" :url "" :license {:name "Public Domain" :url ""} :dependencies [[dynadoc "1.7.5"] [leinjacker "0.4.3"] [org.clojure/tools.cli "1.0.214"]] :repositories [["clojars" {:url "" :sign-releases false}]] :eval-in-leiningen true)
6bead766f3be418cbc79fa6b0a361630944e5dbbca95a0f20be3cb7e3c7de0df
technomancy/leiningen
sirius.clj
(ns leiningen.sirius) (defn ^:pass-through-help sirius [project & args] args)
null
https://raw.githubusercontent.com/technomancy/leiningen/24fb93936133bd7fc30c393c127e9e69bb5f2392/leiningen-core/test/leiningen/sirius.clj
clojure
(ns leiningen.sirius) (defn ^:pass-through-help sirius [project & args] args)
0889e85c55bb74f0ce30976984bce3a84112bb76b391566a5ac0c849c7dc31e0
jarohen/yoyo
project.clj
(defproject yoyo-webapp/lein-template "0.0.6" :description "A template to generate a yo-yo webapp project" :url "-henderson/yoyo" :license {:name "Eclipse Public License" :url "-v10.html"} :eval-in-leiningen true)
null
https://raw.githubusercontent.com/jarohen/yoyo/b579d21becd06b5330dee9f5963708db03ce1e25/templates/yoyo-webapp/project.clj
clojure
(defproject yoyo-webapp/lein-template "0.0.6" :description "A template to generate a yo-yo webapp project" :url "-henderson/yoyo" :license {:name "Eclipse Public License" :url "-v10.html"} :eval-in-leiningen true)
642f89590354f2afd013e3858750d08ca877da182c75720f92d31b13c83fac7c
lpw25/ecaml
value.ml
type value = | Const of Const.t | Tuple of value list | Closure of closure and result = | Value of value | Perform of Syntax.effect * value * closure and closure = value -> result let rec print v ppf = match v with | Const c -> Const.print c ppf | Tuple vs -> Print.print ppf "(@[<hov>%t@])" (Print.sequence ", " print vs) | Closure _ -> Print.print ppf "<fun>"
null
https://raw.githubusercontent.com/lpw25/ecaml/4588abb18436fb8a4983a353923ee667bf8c90a0/src/value.ml
ocaml
type value = | Const of Const.t | Tuple of value list | Closure of closure and result = | Value of value | Perform of Syntax.effect * value * closure and closure = value -> result let rec print v ppf = match v with | Const c -> Const.print c ppf | Tuple vs -> Print.print ppf "(@[<hov>%t@])" (Print.sequence ", " print vs) | Closure _ -> Print.print ppf "<fun>"
9ee2081fc1f0a431d5adbe24f7f704a1deca3d5299102876fd8e4db1eb9eeef6
aria42/infer
measures.clj
(ns infer.measures (:use clojure.contrib.math) (:use clojure.contrib.map-utils) (:use clojure.set) (:use infer.core) (:use infer.matrix) (:use [infer.probability :only [gt lt binary]]) (:import org.apache.commons.math.stat.StatUtils) (:import [org.apache.commons.math.stat.correlation PearsonsCorrelation Covariance]) (:import org.apache.commons.math.stat.descriptive.summary.Sum) (:import [org.apache.commons.math.stat.descriptive.moment Mean StandardDeviation Variance])) (defn sum [xs] (StatUtils/sum (double-array xs))) (defn weighted-sum [xs weights] (sum (map #(* %1 %2) xs weights))) (defn mean [xs] (.evaluate (Mean.) (double-array xs))) (defn correlation [xs ys] (.correlation (PearsonsCorrelation.) (double-array xs) (double-array ys))) (defn covariance [xs ys] (.covariance (Covariance.) (double-array xs) (double-array ys))) (defn variance [xs] (.evaluate (Variance.) (double-array xs))) (defn st-dev [xs] (.evaluate (StandardDeviation.) (double-array xs))) ;;TODO: finish gamma, kendall's-w and ;;look for old impl, or reimpliment. TODO mote this to a new task in tracker : nonparametric stuff such as : DEPENDENCE (statistics ) ;; (probability_theory) ;; ;; :Statistical_dependence ;; ;; ;;TODO: ;;TODO: further work in mutivariate dependence ;; ;;TODO: more research on spellchecking, string similarity ;; (defn within " y is within z of x in metric space. " [z x y] (< (abs (- x y)) z)) (defn square-devs-from-mean "takes either a sample or a sample and a precalculated mean. returns the squares of the difference between each observation and the sample mean." ([x] (square-devs-from-mean x (mean x))) ([x m] (map #(pow (- % m) 2) x))) (defn sum-of-square-devs-from-mean "takes either a sample or a sample and a precalculated mean. returns the sum of the squares of the difference between each observation and the sample mean." ([x] (sum-of-square-devs-from-mean x (mean x))) ([x m] (apply + (square-devs-from-mean x m)))) (defn odds-ratio " Definition in terms of group-wise odds The odds ratio is the ratio of the odds of an event occurring in one group to the odds of it occurring in another group, or to a sample-based estimate of that ratio. Suppose that in a sample of 100 men, 90 have drunk wine in the previous week, while in a sample of 100 women only 20 have drunk wine in the same period. The odds of a man drinking wine are 90 to 10, or 9:1, while the odds of a woman drinking wine are only 20 to 80, or 1:4 = 0.25:1. The odds ratio is thus 9/0.25, or 36, showing that men are much more likely to drink wine than women. Relation to statistical independence If X and Y are independent, their joint probabilities can be expressed in terms of their marginal probabilities. In this case, the odds ratio equals one, and conversely the odds ratio can only equal one if the joint probabilities can be factored in this way. Thus the odds ratio equals one if and only if X and Y are independent. " [p1 p2] (/ (* p1 (- 1 p2)) (* p2 (- 1 p1)))) (defn correlation-ratio " In statistics, the correlation ratio is a measure of the relationship between the statistical dispersion within individual categories and the dispersion across the whole population or sample. i.e. the weighted variance of the category means divided by the variance of all samples. Example Suppose there is a distribution of test scores in three topics (categories): * Algebra: 45, 70, 29, 15 and 21 (5 scores) * Geometry: 40, 20, 30 and 42 (4 scores) * Statistics: 65, 95, 80, 70, 85 and 73 (6 scores). Then the subject averages are 36, 33 and 78, with an overall average of 52. The sums of squares of the differences from the subject averages are 1952 for Algebra, 308 for Geometry and 600 for Statistics, adding to 2860, while the overall sum of squares of the differences from the overall average is 9640. The difference between these of 6780 is also the weighted sum of the square of the differences between the subject averages and the overall average: 5(36 − 52)2 + 4(33 − 52)2 + 6(78 − 52)2 = 6780 This gives eta^2 =6780/9640=0.7033 suggesting that most of the overall dispersion is a result of differences between topics, rather than within topics. Taking the square root eta = sqrt 6780/9640=0.8386 Observe that for η = 1 the overall sample dispersion is purely due to dispersion among the categories and not at all due to dispersion within the individual categories. For a quick comprehension simply imagine all Algebra, Geometry, and Statistics scores being the same respectively, e.g. 5 times 36, 4 times 33, 6 times 78. " [& xs] (let [sos (map sum-of-square-devs-from-mean xs) all (apply concat xs) overall-sos (sum-of-square-devs-from-mean all)] (sqrt (/ (- overall-sos (apply + sos)) overall-sos)))) (defn correlation-linearity-test " It is worth noting that if the relationship between values of and values of overline y_x is linear (which is certainly true when there are only two possibilities for x) this will give the same result as the square of the correlation coefficient, otherwise the correlation ratio will be larger in magnitude. It can therefore be used for judging non-linear relationships. " [a b] (- (correlation-ratio a b) (correlation a b))) (defn rank-index " given a seq, returns a map where the keys are the values of the seq and the values are the positional rank of each member o the seq. " [x] (zipmap (sort x) (range 1 (+ 1 (count x))))) (defn spearmans-rho " In statistics, Spearman's rank correlation coefficient or Spearman's rho, is a non-parametric measure of correlation – that is, it assesses how well an arbitrary monotonic function could describe the relationship between two variables, without making any other assumptions about the particular nature of the relationship between the variables. Certain other measures of correlation are parametric in the sense of being based on possible relationships of a parameterised form, such as a linear relationship. " [a b] (let [_ (assert (same-length? a b)) n (count a) arank (rank-index a) brank (rank-index b) dsos (apply + (map (fn [x y] (pow (- (arank x) (brank y)) 2)) a b))] (- 1 (/ (* 6 dsos) (* n (- (pow n 2) 1)))))) (defn kendalls-tau " -dev/2009-March/011589.html best explanation and example is in \"cluster analysis for researchers\" page 165. -Analysis-Researchers-Charles-Romesburg/dp/1411606175 " [a b] (let [_ (assert (same-length? a b)) n (count a) ranked (reverse (sort-map (zipmap a b))) ;;dcd is the meat of the calculation, the difference between the doncordant and discordant pairs dcd (second (reduce (fn [[vals total] [k v]] (let [diff (- (count (filter (gt v) vals)) (count (filter (lt v) vals)))] [(conj vals v) (+ total diff)])) [[] 0] ranked))] (/ (* 2 dcd) (* n (- n 1))))) (defn pairs "returns unique pairs of a and b where members of a and b can not be paired with the correspoding slot in the other list." [a b] ((fn combine [combos ra rb] (let [heada (first ra) level-combos (for [bx (rest rb)] [heada bx]) all-combos (concat combos level-combos)] (if (= 0 (count (rest ra))) all-combos (combine all-combos (rest ra) (rest rb))))) [] a b)) (defn pairings "confusing ass name." [a b] (let [tuples (zipmap a b)] (pairs tuples tuples))) (defn concordant? [[[a1 b1][a2 b2]]] (= (compare a1 a2) (compare b1 b2))) (def discordant? (comp not concordant?)) (defn discordant-pairs "" [a b] (let [tuples (zipmap a b) ps (pairs tuples tuples)] (count (filter discordant? ps)))) (def kendalls-tau-distance discordant-pairs) TODO : factor out duplication between the distance metric and regular 's tau (defn normalized-kendall-tau-distance " Kendall tau distance is the total number of discordant pairs. " [a b] (let [n (count a) discords (discordant-pairs a b)] (/ (* 2 discords) (* n (- n 1))))) (defn gamma-coefficient " The gamma coefficient is given as a measure of association that is highly resistant to tied data (Goodman and Kruskal, 1963): " [] ) (defn kendalls-w " Suppose that object i is given the rank ri,j by judge number j, where there are in total n objects and m judges. Then the total rank given to object i is Ri = sum Rij and the mean value of these total ranks is Rbar = 1/2 m (n + 1) The sum of squared deviations, S, is defined as S=sum1-n (Ri - Rbar) and then Kendall's W is defined as[1] W= 12S / m^2(n^3-n) If the test statistic W is 1, then all the survey respondents have been unanimous, and each respondent has assigned the same order to the list of concerns. If W is 0, then there is no overall trend of agreement among the respondents, and their responses may be regarded as essentially random. Intermediate values of W indicate a greater or lesser degree of unanimity among the various responses. Legendre[2] discusses a variant of the W statistic which accommodates ties in the rankings and also describes methods of making significance tests based on W. [{:observation [1 2 3]} {} ... {}] -> W " []) (defn sum-variance-test "the variance of the sum of n independent variables is equal to the sum of their variances. (variance-independence-test [[1 2 3 4] [1 2 3 4]]) -> 5/2 " [vs] (- (variance (apply map + vs)) (apply + (map variance vs)))) ;;TODO: don't impliment until fully understanding whether thse are just f-divergences. (defn product-marginal-test "the joint PMF of independent variables is equal to the product of their marginal PMFs." [j] ) ;;TODO: seems very useful for clustering: and ;;TODO: add -Winkler ;;TODO: add graphical approaches to similarity: ;;TODO: string similarity measures: (defn minkowski-distance " The Minkowski distance is a metric on Euclidean space which can be considered as a generalization of both the Euclidean distance and the Manhattan distance. Minkowski distance is typically used with p being 1 or 2. The latter is the Euclidean distance, while the former is sometimes known as the Manhattan distance. ` In the limiting case of p reaching infinity we obtain the Chebyshev distance." [a b p] (let [_ (assert (same-length? a b))] (pow (apply tree-comp-each + (fn [[x y]] (pow (abs (- x y)) p)) (map vector a b)) (/ 1 p)))) (defn euclidean-distance " the Euclidean distance or Euclidean metric is the ordinary distance between two points that one would measure with a ruler, and is given by the Pythagorean formula. By using this formula as distance, Euclidean space (or even any inner product space) becomes a metric space. The associated norm is called the Euclidean norm. Older literature refers to the metric as Pythagorean metric." [a b] (minkowski-distance a b 2)) (defn dot-product [x y] (apply + (map * x y))) (defn chebyshev-distance "In the limiting case of Lp reaching infinity we obtain the Chebyshev distance." [a b] (let [_ (assert (same-length? a b))] (apply tree-comp-each max (fn [[x y]] (- x y)) (map vector a b)))) (defn manhattan-distance " usual metric of Euclidean geometry is replaced by a new metric in which the distance between two points is the sum of the (absolute) differences of their coordinates. The taxicab metric is also known as rectilinear distance, L1 distance or l1 norm (see Lp space), city block distance, Manhattan distance, or Manhattan length" [a b] (minkowski-distance a b 1)) (defn cosine-similarity " The Cosine Similarity of two vectors a and b is the ratio: a dot b / ||a|| ||b|| Let d1 = {2 4 3 1 6} Let d2 = {3 5 1 2 5} Cosine Similarity (d1, d2) = dot(d1, d2) / ||d1|| ||d2|| dot(d1, d2) = (2)*(3) + (4)*(5) + (3)*(1) + (1)*(2) + (6)*(5) = 61 ||d1|| = sqrt((2)^2 + (4)^2 + (3)^2 + (1)^2 + (6)^2) = 8.12403840464 ||d2|| = sqrt((3)^2 + (5)^2 + (1)^2 + (2)^2 + (5)^2) = 8 Cosine Similarity (d1, d2) = 61 / (8.12403840464) * (8) = 61 / 64.9923072371 = 0.938572618717 " [a b] (let [counts (apply merge-with + (map (fn [[x y]] {:dot (* x y) :a (pow x 2) :b (pow y 2)}) (map vector a b)))] (/ (:dot counts) (* (sqrt (:a counts)) (sqrt (:a counts)))))) (defn tanimoto-coefficient " The cosine similarity metric may be extended such that it yields the Jaccard coefficient in the case of binary attributes. This is the Tanimoto coefficient. " [a b] (let [counts (apply merge-with + (map (fn [[x y]] {:dot (* x y) :a (pow x 2) :b (pow y 2)}) (map vector a b)))] (/ (:dot counts) (- (+ (:a counts) (:a counts)) (:dot counts))))) (defn jaccard-index " The Jaccard index, also known as the Jaccard similarity coefficient (originally coined coefficient de communauté by Paul Jaccard), is a statistic used for comparing the similarity and diversity of sample sets. The Jaccard coefficient measures similarity between sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets." [a b] (/ (count (intersection a b)) (count (union a b)))) (defn jaccard-distance " The Jaccard distance, which measures dissimilarity between sample sets, is complementary to the Jaccard coefficient and is obtained by subtracting the Jaccard coefficient from 1, or, equivalently, by dividing the difference of the sizes of the union and the intersection of two sets by the size of the union." [a b] (- 1 (jaccard-index a b))) (defn dice-coefficient " Dice's coefficient (also known as the Dice coefficient) is a similarity measure related to the Jaccard index. " [a b] (let [an (count a) bn (count b) cn (count (intersection a b))] (/ (* 2 cn) (+ an bn)))) (defn n-grams "returns a set of the unique n-grams in a string. this is using actual sets here, discards dupicate n-grams? " [n s] (into #{} (map #(apply str %) (partition n 1 s)))) (defn bigrams [s] (n-grams 2 s)) (defn dice-coefficient-str " When taken as a string similarity measure, the coefficient may be calculated for two strings, x and y using bigrams. here nt is the number of character bigrams found in both strings, nx is the number of bigrams in string x and ny is the number of bigrams in string y. For example, to calculate the similarity between: night nacht We would find the set of bigrams in each word: {ni,ig,gh,ht} {na,ac,ch,ht} Each set has four elements, and the intersection of these two sets has only one element: ht. Plugging this into the formula, we calculate, s = (2 · 1) / (4 + 4) = 0.25. " [a b] (dice-coefficient (bigrams a) (bigrams b))) (defn hamming-distance " In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Put another way, it measures the minimum number of substitutions required to change one string into the other, or the number of errors that transformed one string into the other." [a b] (if (and (integer? a) (integer? b)) (hamming-distance (str a) (str b)) (let [_ (assert (same-length? a b))] (apply tree-comp-each + #(binary (not (apply = %))) (map vector a b))))) (defn lee-distance " In coding theory, the Lee distance is a distance between two strings x1x2...xn and y1y2...yn of equal length n over the q-ary alphabet {0,1,…,q-1} of size q >= 2. It is metric. If q = 2 or q = 3 the Lee distance coincides with the Hamming distance. The metric space induced by the Lee distance is a discrete analog of the elliptic space. " [a b q] (if (and (integer? a) (integer? b)) (lee-distance (str a) (str b) q) (let [_ (assert (same-length? a b))] (apply tree-comp-each + (fn [x] (let [diff (abs (apply - (map int x)))] (min diff (- q diff)))) (map vector a b))))) (defn sorensen-index " #cite_note-4 The Sørensen index, also known as Sørensen’s similarity coefficient, is a statistic used for comparing the similarity of two samples. where A and B are the species numbers in samples A and B, respectively, and C is the number of species shared by the two samples. The Sørensen index is identical to Dice's coefficient which is always in [0, 1] range. Sørensen index used as a distance measure, 1 − QS, is identical to Hellinger distance and Bray–Curtis dissimilarity. The Sørensen coefficient is mainly useful for ecological community data (e.g. Looman & Campbell, 1960[3]). Justification for its use is primarily empirical rather than theoretical (although it can be justified theoretically as the intersection of two fuzzy sets[4]). As compared to Euclidean distance, Sørensen distance retains sensitivity in more heterogeneous data sets and gives less weight to outliers This function assumes you pass in a and b as sets. The sorensen index extended to abundance instead of incidence of species is called the Czekanowski index." [a b] (dice-coefficient a b)) (defn levenshtein-distance " internal representation is a table d with m+1 rows and n+1 columns where m is the length of a and m is the length of b. In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences (i.e., the so called edit distance). The Levenshtein distance between two strings is given by the minimum number of operations needed to transform one string into the other, where an operation is an insertion, deletion, or substitution of a single character. For example, the Levenshtein distance between \"kitten\" and \"sitting\" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: 1. kitten → sitten (substitution of 's' for 'k') 2. sitten → sittin (substitution of 'i' for 'e') 3. sittin → sitting (insert 'g' at the end). The Levenshtein distance has several simple upper and lower bounds that are useful in applications which compute many of them and compare them. These include: * It is always at least the difference of the sizes of the two strings. * It is at most the length of the longer string. * It is zero if and only if the strings are identical. * If the strings are the same size, the Hamming distance is an upper bound on the Levenshtein distance. " [a b] (let [m (count a) n (count b) init (apply deep-merge-with (fn [a b] b) (concat ;;deletion (for [i (range 0 (+ 1 m))] {i {0 i}}) ;;insertion (for [j (range 0 (+ 1 n))] {0 {j j}}))) table (reduce (fn [d [i j]] (deep-merge-with (fn [a b] b) d {i {j (if (= (nth a (- i 1)) (nth b (- j 1))) ((d (- i 1)) (- j 1)) (min (+ ((d (- i 1)) j) 1) ;;deletion (+ ((d i) (- j 1)) 1) ;;insertion (+ ((d (- i 1)) (- j 1)) 1))) ;;substitution)) }})) init (for [j (range 1 (+ 1 n)) i (range 1 (+ 1 m))] [i j]))] ((table m) n))) (defn damerau-levenshtein-distance [a b] (let [m (count a) n (count b) init (apply deep-merge-with (fn [a b] b) (concat ;;deletion (for [i (range 0 (+ 1 m))] {i {0 i}}) ;;insertion (for [j (range 0 (+ 1 n))] {0 {j j}}))) table (reduce (fn [d [i j]] (deep-merge-with (fn [a b] b) d (let [cost (binary (not (= (nth a (- i 1)) (nth b (- j 1))))) x (min (+ ((d (- i 1)) j) 1) ;;deletion (+ ((d i) (- j 1)) 1) ;;insertion (+ ((d (- i 1)) (- j 1)) cost)) ;;substitution)) val (if (and (> i 1) (> j 1) (= (nth a (- i 1)) (nth b (- j 2))) (= (nth a (- i 2)) (nth b (- j 1)))) (min x (+ ((d (- i 2)) (- j 2)) ;;transposition cost)) x)] {i {j val}}))) init (for [j (range 1 (+ 1 n)) i (range 1 (+ 1 m))] [i j]))] ((table m) n))) (defn logistic-link [yhat] (/ 1 (+ 1 (exp (- yhat))))) (defn binomial-variance [p] (* p (- 1 p))) (defn poisson-link [yhat] (exp yhat)) (defn poisson-variance [mu] mu) ;; TODO: these matrix norms are still incredibly naive. ;; Need to update them accordingly. (defn nuclear-norm "Sum of the singular values of a matrix A. Naive approach." [A] (let [[_ S _] (svd A) S* (from-matrix S) nn (reduce + (filter (complement zero?) (flatten S*)))] nn)) (defn frobenius-norm "Square root of the sum of squared entries of matrix A. Naive approach." [A] (let [Af (sqrt (reduce + (map #(* % %) (flatten (from-matrix A)))))] Af))
null
https://raw.githubusercontent.com/aria42/infer/9849325a27770794b91415592a8706fd90777469/src/infer/measures.clj
clojure
TODO: finish gamma, kendall's-w and look for old impl, or reimpliment. (probability_theory) :Statistical_dependence TODO: TODO: further work in mutivariate dependence TODO: more research on spellchecking, string similarity dcd is the meat of the calculation, the difference between the doncordant and discordant pairs TODO: don't impliment until fully understanding whether thse are just f-divergences. TODO: seems very useful for clustering: and TODO: add -Winkler TODO: add graphical approaches to similarity: TODO: string similarity measures: deletion insertion deletion insertion substitution)) deletion insertion deletion insertion substitution)) transposition TODO: these matrix norms are still incredibly naive. Need to update them accordingly.
(ns infer.measures (:use clojure.contrib.math) (:use clojure.contrib.map-utils) (:use clojure.set) (:use infer.core) (:use infer.matrix) (:use [infer.probability :only [gt lt binary]]) (:import org.apache.commons.math.stat.StatUtils) (:import [org.apache.commons.math.stat.correlation PearsonsCorrelation Covariance]) (:import org.apache.commons.math.stat.descriptive.summary.Sum) (:import [org.apache.commons.math.stat.descriptive.moment Mean StandardDeviation Variance])) (defn sum [xs] (StatUtils/sum (double-array xs))) (defn weighted-sum [xs weights] (sum (map #(* %1 %2) xs weights))) (defn mean [xs] (.evaluate (Mean.) (double-array xs))) (defn correlation [xs ys] (.correlation (PearsonsCorrelation.) (double-array xs) (double-array ys))) (defn covariance [xs ys] (.covariance (Covariance.) (double-array xs) (double-array ys))) (defn variance [xs] (.evaluate (Variance.) (double-array xs))) (defn st-dev [xs] (.evaluate (StandardDeviation.) (double-array xs))) TODO mote this to a new task in tracker : nonparametric stuff such as : DEPENDENCE (statistics ) (defn within " y is within z of x in metric space. " [z x y] (< (abs (- x y)) z)) (defn square-devs-from-mean "takes either a sample or a sample and a precalculated mean. returns the squares of the difference between each observation and the sample mean." ([x] (square-devs-from-mean x (mean x))) ([x m] (map #(pow (- % m) 2) x))) (defn sum-of-square-devs-from-mean "takes either a sample or a sample and a precalculated mean. returns the sum of the squares of the difference between each observation and the sample mean." ([x] (sum-of-square-devs-from-mean x (mean x))) ([x m] (apply + (square-devs-from-mean x m)))) (defn odds-ratio " Definition in terms of group-wise odds The odds ratio is the ratio of the odds of an event occurring in one group to the odds of it occurring in another group, or to a sample-based estimate of that ratio. Suppose that in a sample of 100 men, 90 have drunk wine in the previous week, while in a sample of 100 women only 20 have drunk wine in the same period. The odds of a man drinking wine are 90 to 10, or 9:1, while the odds of a woman drinking wine are only 20 to 80, or 1:4 = 0.25:1. The odds ratio is thus 9/0.25, or 36, showing that men are much more likely to drink wine than women. Relation to statistical independence If X and Y are independent, their joint probabilities can be expressed in terms of their marginal probabilities. In this case, the odds ratio equals one, and conversely the odds ratio can only equal one if the joint probabilities can be factored in this way. Thus the odds ratio equals one if and only if X and Y are independent. " [p1 p2] (/ (* p1 (- 1 p2)) (* p2 (- 1 p1)))) (defn correlation-ratio " In statistics, the correlation ratio is a measure of the relationship between the statistical dispersion within individual categories and the dispersion across the whole population or sample. i.e. the weighted variance of the category means divided by the variance of all samples. Example Suppose there is a distribution of test scores in three topics (categories): * Algebra: 45, 70, 29, 15 and 21 (5 scores) * Geometry: 40, 20, 30 and 42 (4 scores) * Statistics: 65, 95, 80, 70, 85 and 73 (6 scores). Then the subject averages are 36, 33 and 78, with an overall average of 52. The sums of squares of the differences from the subject averages are 1952 for Algebra, 308 for Geometry and 600 for Statistics, adding to 2860, while the overall sum of squares of the differences from the overall average is 9640. The difference between these of 6780 is also the weighted sum of the square of the differences between the subject averages and the overall average: 5(36 − 52)2 + 4(33 − 52)2 + 6(78 − 52)2 = 6780 This gives eta^2 =6780/9640=0.7033 suggesting that most of the overall dispersion is a result of differences between topics, rather than within topics. Taking the square root eta = sqrt 6780/9640=0.8386 Observe that for η = 1 the overall sample dispersion is purely due to dispersion among the categories and not at all due to dispersion within the individual categories. For a quick comprehension simply imagine all Algebra, Geometry, and Statistics scores being the same respectively, e.g. 5 times 36, 4 times 33, 6 times 78. " [& xs] (let [sos (map sum-of-square-devs-from-mean xs) all (apply concat xs) overall-sos (sum-of-square-devs-from-mean all)] (sqrt (/ (- overall-sos (apply + sos)) overall-sos)))) (defn correlation-linearity-test " It is worth noting that if the relationship between values of and values of overline y_x is linear (which is certainly true when there are only two possibilities for x) this will give the same result as the square of the correlation coefficient, otherwise the correlation ratio will be larger in magnitude. It can therefore be used for judging non-linear relationships. " [a b] (- (correlation-ratio a b) (correlation a b))) (defn rank-index " given a seq, returns a map where the keys are the values of the seq and the values are the positional rank of each member o the seq. " [x] (zipmap (sort x) (range 1 (+ 1 (count x))))) (defn spearmans-rho " In statistics, Spearman's rank correlation coefficient or Spearman's rho, is a non-parametric measure of correlation – that is, it assesses how well an arbitrary monotonic function could describe the relationship between two variables, without making any other assumptions about the particular nature of the relationship between the variables. Certain other measures of correlation are parametric in the sense of being based on possible relationships of a parameterised form, such as a linear relationship. " [a b] (let [_ (assert (same-length? a b)) n (count a) arank (rank-index a) brank (rank-index b) dsos (apply + (map (fn [x y] (pow (- (arank x) (brank y)) 2)) a b))] (- 1 (/ (* 6 dsos) (* n (- (pow n 2) 1)))))) (defn kendalls-tau " -dev/2009-March/011589.html best explanation and example is in \"cluster analysis for researchers\" page 165. -Analysis-Researchers-Charles-Romesburg/dp/1411606175 " [a b] (let [_ (assert (same-length? a b)) n (count a) ranked (reverse (sort-map (zipmap a b))) dcd (second (reduce (fn [[vals total] [k v]] (let [diff (- (count (filter (gt v) vals)) (count (filter (lt v) vals)))] [(conj vals v) (+ total diff)])) [[] 0] ranked))] (/ (* 2 dcd) (* n (- n 1))))) (defn pairs "returns unique pairs of a and b where members of a and b can not be paired with the correspoding slot in the other list." [a b] ((fn combine [combos ra rb] (let [heada (first ra) level-combos (for [bx (rest rb)] [heada bx]) all-combos (concat combos level-combos)] (if (= 0 (count (rest ra))) all-combos (combine all-combos (rest ra) (rest rb))))) [] a b)) (defn pairings "confusing ass name." [a b] (let [tuples (zipmap a b)] (pairs tuples tuples))) (defn concordant? [[[a1 b1][a2 b2]]] (= (compare a1 a2) (compare b1 b2))) (def discordant? (comp not concordant?)) (defn discordant-pairs "" [a b] (let [tuples (zipmap a b) ps (pairs tuples tuples)] (count (filter discordant? ps)))) (def kendalls-tau-distance discordant-pairs) TODO : factor out duplication between the distance metric and regular 's tau (defn normalized-kendall-tau-distance " Kendall tau distance is the total number of discordant pairs. " [a b] (let [n (count a) discords (discordant-pairs a b)] (/ (* 2 discords) (* n (- n 1))))) (defn gamma-coefficient " The gamma coefficient is given as a measure of association that is highly resistant to tied data (Goodman and Kruskal, 1963): " [] ) (defn kendalls-w " Suppose that object i is given the rank ri,j by judge number j, where there are in total n objects and m judges. Then the total rank given to object i is Ri = sum Rij and the mean value of these total ranks is Rbar = 1/2 m (n + 1) The sum of squared deviations, S, is defined as S=sum1-n (Ri - Rbar) and then Kendall's W is defined as[1] W= 12S / m^2(n^3-n) If the test statistic W is 1, then all the survey respondents have been unanimous, and each respondent has assigned the same order to the list of concerns. If W is 0, then there is no overall trend of agreement among the respondents, and their responses may be regarded as essentially random. Intermediate values of W indicate a greater or lesser degree of unanimity among the various responses. Legendre[2] discusses a variant of the W statistic which accommodates ties in the rankings and also describes methods of making significance tests based on W. [{:observation [1 2 3]} {} ... {}] -> W " []) (defn sum-variance-test "the variance of the sum of n independent variables is equal to the sum of their variances. (variance-independence-test [[1 2 3 4] [1 2 3 4]]) -> 5/2 " [vs] (- (variance (apply map + vs)) (apply + (map variance vs)))) (defn product-marginal-test "the joint PMF of independent variables is equal to the product of their marginal PMFs." [j] ) (defn minkowski-distance " The Minkowski distance is a metric on Euclidean space which can be considered as a generalization of both the Euclidean distance and the Manhattan distance. Minkowski distance is typically used with p being 1 or 2. The latter is the Euclidean distance, while the former is sometimes known as the Manhattan distance. ` In the limiting case of p reaching infinity we obtain the Chebyshev distance." [a b p] (let [_ (assert (same-length? a b))] (pow (apply tree-comp-each + (fn [[x y]] (pow (abs (- x y)) p)) (map vector a b)) (/ 1 p)))) (defn euclidean-distance " the Euclidean distance or Euclidean metric is the ordinary distance between two points that one would measure with a ruler, and is given by the Pythagorean formula. By using this formula as distance, Euclidean space (or even any inner product space) becomes a metric space. The associated norm is called the Euclidean norm. Older literature refers to the metric as Pythagorean metric." [a b] (minkowski-distance a b 2)) (defn dot-product [x y] (apply + (map * x y))) (defn chebyshev-distance "In the limiting case of Lp reaching infinity we obtain the Chebyshev distance." [a b] (let [_ (assert (same-length? a b))] (apply tree-comp-each max (fn [[x y]] (- x y)) (map vector a b)))) (defn manhattan-distance " usual metric of Euclidean geometry is replaced by a new metric in which the distance between two points is the sum of the (absolute) differences of their coordinates. The taxicab metric is also known as rectilinear distance, L1 distance or l1 norm (see Lp space), city block distance, Manhattan distance, or Manhattan length" [a b] (minkowski-distance a b 1)) (defn cosine-similarity " The Cosine Similarity of two vectors a and b is the ratio: a dot b / ||a|| ||b|| Let d1 = {2 4 3 1 6} Let d2 = {3 5 1 2 5} Cosine Similarity (d1, d2) = dot(d1, d2) / ||d1|| ||d2|| dot(d1, d2) = (2)*(3) + (4)*(5) + (3)*(1) + (1)*(2) + (6)*(5) = 61 ||d1|| = sqrt((2)^2 + (4)^2 + (3)^2 + (1)^2 + (6)^2) = 8.12403840464 ||d2|| = sqrt((3)^2 + (5)^2 + (1)^2 + (2)^2 + (5)^2) = 8 Cosine Similarity (d1, d2) = 61 / (8.12403840464) * (8) = 61 / 64.9923072371 = 0.938572618717 " [a b] (let [counts (apply merge-with + (map (fn [[x y]] {:dot (* x y) :a (pow x 2) :b (pow y 2)}) (map vector a b)))] (/ (:dot counts) (* (sqrt (:a counts)) (sqrt (:a counts)))))) (defn tanimoto-coefficient " The cosine similarity metric may be extended such that it yields the Jaccard coefficient in the case of binary attributes. This is the Tanimoto coefficient. " [a b] (let [counts (apply merge-with + (map (fn [[x y]] {:dot (* x y) :a (pow x 2) :b (pow y 2)}) (map vector a b)))] (/ (:dot counts) (- (+ (:a counts) (:a counts)) (:dot counts))))) (defn jaccard-index " The Jaccard index, also known as the Jaccard similarity coefficient (originally coined coefficient de communauté by Paul Jaccard), is a statistic used for comparing the similarity and diversity of sample sets. The Jaccard coefficient measures similarity between sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets." [a b] (/ (count (intersection a b)) (count (union a b)))) (defn jaccard-distance " The Jaccard distance, which measures dissimilarity between sample sets, is complementary to the Jaccard coefficient and is obtained by subtracting the Jaccard coefficient from 1, or, equivalently, by dividing the difference of the sizes of the union and the intersection of two sets by the size of the union." [a b] (- 1 (jaccard-index a b))) (defn dice-coefficient " Dice's coefficient (also known as the Dice coefficient) is a similarity measure related to the Jaccard index. " [a b] (let [an (count a) bn (count b) cn (count (intersection a b))] (/ (* 2 cn) (+ an bn)))) (defn n-grams "returns a set of the unique n-grams in a string. this is using actual sets here, discards dupicate n-grams? " [n s] (into #{} (map #(apply str %) (partition n 1 s)))) (defn bigrams [s] (n-grams 2 s)) (defn dice-coefficient-str " When taken as a string similarity measure, the coefficient may be calculated for two strings, x and y using bigrams. here nt is the number of character bigrams found in both strings, nx is the number of bigrams in string x and ny is the number of bigrams in string y. For example, to calculate the similarity between: night nacht We would find the set of bigrams in each word: {ni,ig,gh,ht} {na,ac,ch,ht} Each set has four elements, and the intersection of these two sets has only one element: ht. Plugging this into the formula, we calculate, s = (2 · 1) / (4 + 4) = 0.25. " [a b] (dice-coefficient (bigrams a) (bigrams b))) (defn hamming-distance " In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Put another way, it measures the minimum number of substitutions required to change one string into the other, or the number of errors that transformed one string into the other." [a b] (if (and (integer? a) (integer? b)) (hamming-distance (str a) (str b)) (let [_ (assert (same-length? a b))] (apply tree-comp-each + #(binary (not (apply = %))) (map vector a b))))) (defn lee-distance " In coding theory, the Lee distance is a distance between two strings x1x2...xn and y1y2...yn of equal length n over the q-ary alphabet {0,1,…,q-1} of size q >= 2. It is metric. If q = 2 or q = 3 the Lee distance coincides with the Hamming distance. The metric space induced by the Lee distance is a discrete analog of the elliptic space. " [a b q] (if (and (integer? a) (integer? b)) (lee-distance (str a) (str b) q) (let [_ (assert (same-length? a b))] (apply tree-comp-each + (fn [x] (let [diff (abs (apply - (map int x)))] (min diff (- q diff)))) (map vector a b))))) (defn sorensen-index " #cite_note-4 The Sørensen index, also known as Sørensen’s similarity coefficient, is a statistic used for comparing the similarity of two samples. where A and B are the species numbers in samples A and B, respectively, and C is the number of species shared by the two samples. The Sørensen index is identical to Dice's coefficient which is always in [0, 1] range. Sørensen index used as a distance measure, 1 − QS, is identical to Hellinger distance and Bray–Curtis dissimilarity. The Sørensen coefficient is mainly useful for ecological community data (e.g. Looman & Campbell, 1960[3]). Justification for its use is primarily empirical rather than theoretical (although it can be justified theoretically as the intersection of two fuzzy sets[4]). As compared to Euclidean distance, Sørensen distance retains sensitivity in more heterogeneous data sets and gives less weight to outliers This function assumes you pass in a and b as sets. The sorensen index extended to abundance instead of incidence of species is called the Czekanowski index." [a b] (dice-coefficient a b)) (defn levenshtein-distance " internal representation is a table d with m+1 rows and n+1 columns where m is the length of a and m is the length of b. In information theory and computer science, the Levenshtein distance is a metric for measuring the amount of difference between two sequences (i.e., the so called edit distance). The Levenshtein distance between two strings is given by the minimum number of operations needed to transform one string into the other, where an operation is an insertion, deletion, or substitution of a single character. For example, the Levenshtein distance between \"kitten\" and \"sitting\" is 3, since the following three edits change one into the other, and there is no way to do it with fewer than three edits: 1. kitten → sitten (substitution of 's' for 'k') 2. sitten → sittin (substitution of 'i' for 'e') 3. sittin → sitting (insert 'g' at the end). The Levenshtein distance has several simple upper and lower bounds that are useful in applications which compute many of them and compare them. These include: * It is always at least the difference of the sizes of the two strings. * It is at most the length of the longer string. * It is zero if and only if the strings are identical. * If the strings are the same size, the Hamming distance is an upper bound on the Levenshtein distance. " [a b] (let [m (count a) n (count b) init (apply deep-merge-with (fn [a b] b) (concat (for [i (range 0 (+ 1 m))] {i {0 i}}) (for [j (range 0 (+ 1 n))] {0 {j j}}))) table (reduce (fn [d [i j]] (deep-merge-with (fn [a b] b) d {i {j (if (= (nth a (- i 1)) (nth b (- j 1))) ((d (- i 1)) (- j 1)) (min (+ ((d (- i 1)) (+ ((d i) (+ ((d (- i 1)) }})) init (for [j (range 1 (+ 1 n)) i (range 1 (+ 1 m))] [i j]))] ((table m) n))) (defn damerau-levenshtein-distance [a b] (let [m (count a) n (count b) init (apply deep-merge-with (fn [a b] b) (concat (for [i (range 0 (+ 1 m))] {i {0 i}}) (for [j (range 0 (+ 1 n))] {0 {j j}}))) table (reduce (fn [d [i j]] (deep-merge-with (fn [a b] b) d (let [cost (binary (not (= (nth a (- i 1)) (nth b (- j 1))))) x (min (+ ((d (- i 1)) (+ ((d i) (+ ((d (- i 1)) val (if (and (> i 1) (> j 1) (= (nth a (- i 1)) (nth b (- j 2))) (= (nth a (- i 2)) (nth b (- j 1)))) (min x (+ ((d (- i 2)) cost)) x)] {i {j val}}))) init (for [j (range 1 (+ 1 n)) i (range 1 (+ 1 m))] [i j]))] ((table m) n))) (defn logistic-link [yhat] (/ 1 (+ 1 (exp (- yhat))))) (defn binomial-variance [p] (* p (- 1 p))) (defn poisson-link [yhat] (exp yhat)) (defn poisson-variance [mu] mu) (defn nuclear-norm "Sum of the singular values of a matrix A. Naive approach." [A] (let [[_ S _] (svd A) S* (from-matrix S) nn (reduce + (filter (complement zero?) (flatten S*)))] nn)) (defn frobenius-norm "Square root of the sum of squared entries of matrix A. Naive approach." [A] (let [Af (sqrt (reduce + (map #(* % %) (flatten (from-matrix A)))))] Af))
386dda2d35d2d62f0e6812c2487ada22703f9fba2898d04e8ce5fcd2ccf13ce1
pykello/racket-visualization
memory-layout.rkt
#lang racket (require metapict racket/math "../common.rkt") ;; Similar to -a-memory-layout-diagram-with-tikz (define (memory-layout items) (current-curly-brace-indent 1.5) ;; draw a bit (define (draw-bit x0 color) (brushcolor color (filldraw (rectangle (pt x0 0) (pt (+ x0 1) 2))))) draws n bit cells starting from with the given color (define (draw-bits n x0 color) (for/draw ([i (in-range n)]) (draw-bit (+ x0 i) color))) draws memory segment described by color label ) (define (draw-item v x0) (let* ([n (first v)] [color (second v)] [label (third v)] [x1 (+ x0 n)]) (list (draw-bits n x0 color) (curve (pt x1 0) -- (pt x1 3)) (label-top (~v x1) (pt x1 3)) (if label (curly-brace (pt x1 -0.2) (pt x0 -0.2) label) `())))) ;; how to draw a memory layout? (draw-rec (for/fold ([x0 0] [acc (list (label-top "0" (pt 0 3)) (curve (pt 0 0) -- (pt 0 3)))] #:result acc) ([item items]) (values (+ x0 (car item)) (cons (draw-item item x0) acc))))) (set-curve-pict-size 640 100) (define mem-layout (with-window (window 63 -1 -5 5) (font-size 10 (memory-layout `((12 "LightBlue" "A") (9 "Moccasin" "B") (9 "LightPink" "C") (9 "Khaki" "D") (9 "PaleGreen" "E") (14 "white" #f)))))) mem-layout (save-svg "memory-layout.svg" mem-layout)
null
https://raw.githubusercontent.com/pykello/racket-visualization/7c4dccfd59123fcb7c144ad8ed89dffdc57290df/metapict-examples/software/memory-layout.rkt
racket
Similar to -a-memory-layout-diagram-with-tikz draw a bit how to draw a memory layout?
#lang racket (require metapict racket/math "../common.rkt") (define (memory-layout items) (current-curly-brace-indent 1.5) (define (draw-bit x0 color) (brushcolor color (filldraw (rectangle (pt x0 0) (pt (+ x0 1) 2))))) draws n bit cells starting from with the given color (define (draw-bits n x0 color) (for/draw ([i (in-range n)]) (draw-bit (+ x0 i) color))) draws memory segment described by color label ) (define (draw-item v x0) (let* ([n (first v)] [color (second v)] [label (third v)] [x1 (+ x0 n)]) (list (draw-bits n x0 color) (curve (pt x1 0) -- (pt x1 3)) (label-top (~v x1) (pt x1 3)) (if label (curly-brace (pt x1 -0.2) (pt x0 -0.2) label) `())))) (draw-rec (for/fold ([x0 0] [acc (list (label-top "0" (pt 0 3)) (curve (pt 0 0) -- (pt 0 3)))] #:result acc) ([item items]) (values (+ x0 (car item)) (cons (draw-item item x0) acc))))) (set-curve-pict-size 640 100) (define mem-layout (with-window (window 63 -1 -5 5) (font-size 10 (memory-layout `((12 "LightBlue" "A") (9 "Moccasin" "B") (9 "LightPink" "C") (9 "Khaki" "D") (9 "PaleGreen" "E") (14 "white" #f)))))) mem-layout (save-svg "memory-layout.svg" mem-layout)
92895e16421686dac3dda70a33f543f34ebf650b1ec53cc511a79b3a4c33b545
lpeterse/haskell-utc
Date.hs
module Data.UTC.Type.Date ( Date () ) where import Control.Monad.Catch import Data.Ratio import Data.UTC.Class.Epoch import Data.UTC.Class.IsDate import Data.UTC.Class.IsUnixTime import Data.UTC.Internal import Data.UTC.Type.Exception | This type represents dates in the _ _ Gregorian Calendar _ _ . -- -- * It can represent any date in the past and in the future by using ' Prelude . Integer ' internally . -- * The internal structure is not exposed to avoid the construction of invalid values. -- Use 'Data.UTC.epoch' or a parser to construct values. * The instance of ' Prelude . Show ' is only meant for debugging purposes -- and is subject to change. -- -- > > show (epoch :: Date) > 1970 - 01 - 01 data Date = Date { dYear :: Integer , dMonth :: Integer , dDay :: Integer } deriving (Eq, Ord) instance Show Date where show (Date yy mm dd) = concat [ if yy < 0 then "-" else "" , if abs yy > 9999 then show (abs yy) else fixedDecimal 4 (abs yy) , "-" , fixedDecimal 2 mm , "-" , fixedDecimal 2 dd ] instance Epoch Date where epoch = Date { dYear = 1970 , dMonth = 1 , dDay = 1 } instance IsUnixTime Date where unixSeconds t = (days * secsPerDay % 1) - deltaUnixEpochCommonEpoch where days = yearMonthDayToDays (year t, month t, day t) fromUnixSeconds u = return $ Date { dYear = y , dMonth = m , dDay = d } where s = u + deltaUnixEpochCommonEpoch (y, m, d) = daysToYearMonthDay (truncate s `div` secsPerDay) instance IsDate Date where year = dYear month = dMonth day = dDay setYear x t = if isValidDate (x, month t, day t) then return $ t { dYear = x } else throwM $ UtcException $ "IsDate Date: setYear " ++ show x ++ " " ++ show t setMonth x t = if isValidDate (year t, x, day t) then return $ t { dMonth = x } else throwM $ UtcException $ "IsDate Date: setMonth " ++ show x ++ " " ++ show t setDay x t = if isValidDate (year t, month t, x) then return $ t { dDay = x } else throwM $ UtcException $ "IsDate Date: setDay " ++ show x ++ " " ++ show t
null
https://raw.githubusercontent.com/lpeterse/haskell-utc/e4502c08591e80d411129bb7c0414539f6302aaf/Data/UTC/Type/Date.hs
haskell
* It can represent any date in the past and in the future by using * The internal structure is not exposed to avoid the construction of invalid values. Use 'Data.UTC.epoch' or a parser to construct values. and is subject to change. > > show (epoch :: Date)
module Data.UTC.Type.Date ( Date () ) where import Control.Monad.Catch import Data.Ratio import Data.UTC.Class.Epoch import Data.UTC.Class.IsDate import Data.UTC.Class.IsUnixTime import Data.UTC.Internal import Data.UTC.Type.Exception | This type represents dates in the _ _ Gregorian Calendar _ _ . ' Prelude . Integer ' internally . * The instance of ' Prelude . Show ' is only meant for debugging purposes > 1970 - 01 - 01 data Date = Date { dYear :: Integer , dMonth :: Integer , dDay :: Integer } deriving (Eq, Ord) instance Show Date where show (Date yy mm dd) = concat [ if yy < 0 then "-" else "" , if abs yy > 9999 then show (abs yy) else fixedDecimal 4 (abs yy) , "-" , fixedDecimal 2 mm , "-" , fixedDecimal 2 dd ] instance Epoch Date where epoch = Date { dYear = 1970 , dMonth = 1 , dDay = 1 } instance IsUnixTime Date where unixSeconds t = (days * secsPerDay % 1) - deltaUnixEpochCommonEpoch where days = yearMonthDayToDays (year t, month t, day t) fromUnixSeconds u = return $ Date { dYear = y , dMonth = m , dDay = d } where s = u + deltaUnixEpochCommonEpoch (y, m, d) = daysToYearMonthDay (truncate s `div` secsPerDay) instance IsDate Date where year = dYear month = dMonth day = dDay setYear x t = if isValidDate (x, month t, day t) then return $ t { dYear = x } else throwM $ UtcException $ "IsDate Date: setYear " ++ show x ++ " " ++ show t setMonth x t = if isValidDate (year t, x, day t) then return $ t { dMonth = x } else throwM $ UtcException $ "IsDate Date: setMonth " ++ show x ++ " " ++ show t setDay x t = if isValidDate (year t, month t, x) then return $ t { dDay = x } else throwM $ UtcException $ "IsDate Date: setDay " ++ show x ++ " " ++ show t
616cbd20962e48c62ee0cb713639004abc79f8e88601d4d29f3fec1c849c9789
uwplse/oddity
debugger.clj
(ns oddity.debugger (:require [aleph.http :as http] [aleph.tcp :as tcp] [manifold.stream :as s] [manifold.deferred :as d] [gloss.core :as gloss] [gloss.io :as io] [clojure.data.json :as json] [clojure.core.async :refer [go >! <! chan]] [compojure.core :refer [routes GET]] [compojure.route :as route] [ring.middleware.params :as params] [com.stuartsierra.component :as component] [oddity.modelchecker :as mc] [oddity.dsmodelchecker :as dsmc] [oddity.coerce :as coerce] [clojure.walk :refer [stringify-keys]] [taoensso.tufte :refer [p]]) (:import (java.util.concurrent TimeoutException TimeUnit FutureTask))) (def DEFAULT_ID "1") (def protocol (gloss/compile-frame (gloss/finite-frame :uint32 (gloss/string :utf-8)) json/write-str json/read-str)) (defn wrap-duplex-stream [protocol s] (let [out (s/stream)] (s/connect (s/map #(io/encode protocol %) out) s) (s/splice out (io/decode-stream s protocol)))) (defn start-tcp-server [handler port & args] (tcp/start-server (fn [s info] (apply handler (wrap-duplex-stream protocol s) info args)) {:port port})) (defn register [s info st] (let [msg (s/take! s)] (go (let [m @msg] (let [id (or (get m "id") DEFAULT_ID)] (when-let [name (get m "name")] (swap! st assoc-in [:sessions id :sockets name] s)) (when-let [trace (get m "trace")] (swap! st assoc-in [:sessions id :trace] trace)) (when-let [names (get m "names")] (doseq [name names] (swap! st assoc-in [:sessions id :sockets name] s))) (s/put! s {:ok true})))))) (defn quit-all-sessions [st] (doseq [[id session] (get @st :sessions) [_ socket] (get session :sockets)] (s/put! socket {:msgtype "quit"}) (s/close! socket)) (swap! st assoc :sessions {})) (defrecord Debugger [port server state] component/Lifecycle (start [component] (when-not (:server component) (let [st (atom nil) server (start-tcp-server register port st)] (assoc component :server server :state st)))) (stop [component] (when (:server component) (quit-all-sessions state) (.close server) (assoc component :server nil :state nil)))) (defn debugger [port] (map->Debugger {:port port})) (defn st [dbg] @(get dbg :state)) (defn send-message [dbg msg] (let [socket (get-in (st dbg) [:sessions (get msg "id") :sockets (get msg "to")])] (s/put! socket (dissoc msg "id")) @(s/take! socket))) (defn combine-returns [returns] {:responses returns}) (defn send-start [dbg id] (combine-returns (doall (map ; TODO: use pmap and disallow multiple nodes w/ same socket (fn [[server socket]] (do (s/put! socket {:msgtype "start" :to server}) [server @(s/take! socket)])) (get-in (st dbg) [:sessions id :sockets]))))) (defn send-reset [dbg id log] (send-start dbg id) (doseq [msg (rest log)] (if (contains? msg "to") (let [socket (get-in (st dbg) [:sessions id :sockets (get msg "to")])] (s/put! socket msg) @(s/take! socket)))) {:ok true}) (defn quit [dbg] (quit-all-sessions (:state dbg))) (defn model-checker-state-for [dbg id prefix] (dsmc/make-dsstate (reify dsmc/ISystemControl (send-message! [this message] (send-message dbg (assoc (stringify-keys message) "id" id))) (restart-system! [this] (send-start dbg id))) prefix)) (defn run-model-checker [dbg id prefix pred opts] (let [st (model-checker-state-for dbg id prefix) max-depth (get opts :max-depth 24) delta-depth (get opts :delta-depth 6) timeout (get opts :timeout 10000) thunk (bound-fn [] (mc/dfs st pred max-depth delta-depth)) task (FutureTask. thunk) thr (Thread. task)] (try (.start thr) (let [res (.get task timeout TimeUnit/MILLISECONDS)] (mc/restart! st) {:ok true :trace (:trace res)}) (catch TimeoutException e (.cancel task true) (.stop thr) (mc/restart! st) {:ok false :error "Timeout"}) (catch Exception e (.cancel task true) (.stop thr) (mc/restart! st) {:ok false :error (.str e)})))) (defn handle-debug-msg [dbg msg] (let [msg (json/read-str msg) resp (cond (= "servers" (get msg "msgtype")) (into {} (for [[id s] (:sessions (st dbg))] [id {:servers (sort (keys (get s :sockets))) :trace (get s :trace)}])) (= "start" (get msg "msgtype")) (send-start dbg (get msg "id")) (= "reset" (get msg "msgtype")) (send-reset dbg (get msg "id") (get msg "log")) (= "run-until" (get msg "msgtype")) (run-model-checker dbg (get msg "id") (get msg "prefix") (coerce/coerce-pred (get msg "pred")) {}) :else (send-message dbg msg))] (json/write-str resp))) (def non-websocket-request {:status 400 :headers {"content-type" "application/text"} :body "Expected a websocket request."}) (defn debug-handler [dbg] (fn [req] (if-let [socket (try @(http/websocket-connection req) (catch Exception e nil))] (d/loop [] ;; take a message, and define a default value that tells us if the connection is closed (-> (s/take! socket ::none) (d/chain ;; first, check if there even was a message, and then get a response on another thread (fn [msg] (if (= ::none msg) (d/future (quit dbg)) (d/future (handle-debug-msg dbg msg)))) ;; once we have a response, write it back to the client (fn [msg'] (when msg' (s/put! socket msg'))) ;; if we were successful in our response, recur and repeat (fn [result] (if result (d/recur)))) ;; if there were any issues on the far end, send a stringified exception back ;; and close the connection (d/catch (fn [ex] (d/future (quit dbg)) (s/put! socket (json/write-str {"ok" false "error" (apply str "ERROR: " ex "\n" (map str (.getStackTrace ex)))})) (s/close! socket))))) non-websocket-request))) (defn handler [dbg] (params/wrap-params (routes (GET "/debug" [] (debug-handler dbg)) (route/not-found "No such page.")))) (defrecord DebuggerWebsocketServer [port debugger] component/Lifecycle (start [component] (when-not (:server component) (let [server (http/start-server (handler debugger) {:port port})] (assoc component :server server)))) (stop [component] (when (:server component) (.close (:server component)) (assoc component :server nil)))) (defn debugger-websocket-server [port] (map->DebuggerWebsocketServer {:port port}))
null
https://raw.githubusercontent.com/uwplse/oddity/81c1a6af203a0d8e71138a27655e3c4003357127/oddity/src/clj/oddity/debugger.clj
clojure
TODO: use pmap and disallow multiple nodes w/ same socket take a message, and define a default value that tells us if the connection is closed first, check if there even was a message, and then get a response on another thread once we have a response, write it back to the client if we were successful in our response, recur and repeat if there were any issues on the far end, send a stringified exception back and close the connection
(ns oddity.debugger (:require [aleph.http :as http] [aleph.tcp :as tcp] [manifold.stream :as s] [manifold.deferred :as d] [gloss.core :as gloss] [gloss.io :as io] [clojure.data.json :as json] [clojure.core.async :refer [go >! <! chan]] [compojure.core :refer [routes GET]] [compojure.route :as route] [ring.middleware.params :as params] [com.stuartsierra.component :as component] [oddity.modelchecker :as mc] [oddity.dsmodelchecker :as dsmc] [oddity.coerce :as coerce] [clojure.walk :refer [stringify-keys]] [taoensso.tufte :refer [p]]) (:import (java.util.concurrent TimeoutException TimeUnit FutureTask))) (def DEFAULT_ID "1") (def protocol (gloss/compile-frame (gloss/finite-frame :uint32 (gloss/string :utf-8)) json/write-str json/read-str)) (defn wrap-duplex-stream [protocol s] (let [out (s/stream)] (s/connect (s/map #(io/encode protocol %) out) s) (s/splice out (io/decode-stream s protocol)))) (defn start-tcp-server [handler port & args] (tcp/start-server (fn [s info] (apply handler (wrap-duplex-stream protocol s) info args)) {:port port})) (defn register [s info st] (let [msg (s/take! s)] (go (let [m @msg] (let [id (or (get m "id") DEFAULT_ID)] (when-let [name (get m "name")] (swap! st assoc-in [:sessions id :sockets name] s)) (when-let [trace (get m "trace")] (swap! st assoc-in [:sessions id :trace] trace)) (when-let [names (get m "names")] (doseq [name names] (swap! st assoc-in [:sessions id :sockets name] s))) (s/put! s {:ok true})))))) (defn quit-all-sessions [st] (doseq [[id session] (get @st :sessions) [_ socket] (get session :sockets)] (s/put! socket {:msgtype "quit"}) (s/close! socket)) (swap! st assoc :sessions {})) (defrecord Debugger [port server state] component/Lifecycle (start [component] (when-not (:server component) (let [st (atom nil) server (start-tcp-server register port st)] (assoc component :server server :state st)))) (stop [component] (when (:server component) (quit-all-sessions state) (.close server) (assoc component :server nil :state nil)))) (defn debugger [port] (map->Debugger {:port port})) (defn st [dbg] @(get dbg :state)) (defn send-message [dbg msg] (let [socket (get-in (st dbg) [:sessions (get msg "id") :sockets (get msg "to")])] (s/put! socket (dissoc msg "id")) @(s/take! socket))) (defn combine-returns [returns] {:responses returns}) (defn send-start [dbg id] (combine-returns (doall (fn [[server socket]] (do (s/put! socket {:msgtype "start" :to server}) [server @(s/take! socket)])) (get-in (st dbg) [:sessions id :sockets]))))) (defn send-reset [dbg id log] (send-start dbg id) (doseq [msg (rest log)] (if (contains? msg "to") (let [socket (get-in (st dbg) [:sessions id :sockets (get msg "to")])] (s/put! socket msg) @(s/take! socket)))) {:ok true}) (defn quit [dbg] (quit-all-sessions (:state dbg))) (defn model-checker-state-for [dbg id prefix] (dsmc/make-dsstate (reify dsmc/ISystemControl (send-message! [this message] (send-message dbg (assoc (stringify-keys message) "id" id))) (restart-system! [this] (send-start dbg id))) prefix)) (defn run-model-checker [dbg id prefix pred opts] (let [st (model-checker-state-for dbg id prefix) max-depth (get opts :max-depth 24) delta-depth (get opts :delta-depth 6) timeout (get opts :timeout 10000) thunk (bound-fn [] (mc/dfs st pred max-depth delta-depth)) task (FutureTask. thunk) thr (Thread. task)] (try (.start thr) (let [res (.get task timeout TimeUnit/MILLISECONDS)] (mc/restart! st) {:ok true :trace (:trace res)}) (catch TimeoutException e (.cancel task true) (.stop thr) (mc/restart! st) {:ok false :error "Timeout"}) (catch Exception e (.cancel task true) (.stop thr) (mc/restart! st) {:ok false :error (.str e)})))) (defn handle-debug-msg [dbg msg] (let [msg (json/read-str msg) resp (cond (= "servers" (get msg "msgtype")) (into {} (for [[id s] (:sessions (st dbg))] [id {:servers (sort (keys (get s :sockets))) :trace (get s :trace)}])) (= "start" (get msg "msgtype")) (send-start dbg (get msg "id")) (= "reset" (get msg "msgtype")) (send-reset dbg (get msg "id") (get msg "log")) (= "run-until" (get msg "msgtype")) (run-model-checker dbg (get msg "id") (get msg "prefix") (coerce/coerce-pred (get msg "pred")) {}) :else (send-message dbg msg))] (json/write-str resp))) (def non-websocket-request {:status 400 :headers {"content-type" "application/text"} :body "Expected a websocket request."}) (defn debug-handler [dbg] (fn [req] (if-let [socket (try @(http/websocket-connection req) (catch Exception e nil))] (d/loop [] (-> (s/take! socket ::none) (d/chain (fn [msg] (if (= ::none msg) (d/future (quit dbg)) (d/future (handle-debug-msg dbg msg)))) (fn [msg'] (when msg' (s/put! socket msg'))) (fn [result] (if result (d/recur)))) (d/catch (fn [ex] (d/future (quit dbg)) (s/put! socket (json/write-str {"ok" false "error" (apply str "ERROR: " ex "\n" (map str (.getStackTrace ex)))})) (s/close! socket))))) non-websocket-request))) (defn handler [dbg] (params/wrap-params (routes (GET "/debug" [] (debug-handler dbg)) (route/not-found "No such page.")))) (defrecord DebuggerWebsocketServer [port debugger] component/Lifecycle (start [component] (when-not (:server component) (let [server (http/start-server (handler debugger) {:port port})] (assoc component :server server)))) (stop [component] (when (:server component) (.close (:server component)) (assoc component :server nil)))) (defn debugger-websocket-server [port] (map->DebuggerWebsocketServer {:port port}))
c24f354ee61aa013d2aac39e79e66f29a43fc9e56fbef3c5233a14285d5eb33b
gnarroway/hato
websocket.clj
(ns hato.websocket (:import (java.net.http WebSocket$Listener WebSocket$Builder HttpClient WebSocket) (java.time Duration) (java.net URI) (java.util.concurrent CompletableFuture) (java.nio ByteBuffer) (java.util.function Function))) (defn request->WebSocketListener "Constructs a new WebSocket listener to receive events for a given WebSocket connection. Takes a map of: - `:on-open` Called when a `WebSocket` has been connected. Called with the WebSocket instance. - `:on-message` A textual/binary data has been received. Called with the WebSocket instance, the data, and whether this invocation completes the message. - `:on-ping` A Ping message has been received. Called with the WebSocket instance and the ping message. - `:on-pong` A Pong message has been received. Called with the WebSocket instance and the pong message. - `:on-close` Receives a Close message indicating the WebSocket's input has been closed. Called with the WebSocket instance, the status code, and the reason. - `:on-error` An error has occurred. Called with the WebSocket instance and the error." [{:keys [on-open on-message on-ping on-pong on-close on-error]}] The .requests below is from the implementation of the default listener (reify WebSocket$Listener (onOpen [_ ws] (.request ws 1) (when on-open (on-open ws))) (onText [_ ws data last?] (.request ws 1) (when on-message (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-message ws data last?)))))) (onBinary [_ ws data last?] (.request ws 1) (when on-message (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-message ws data last?)))))) (onPing [_ ws data] (.request ws 1) (when on-ping (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-ping ws data)))))) (onPong [_ ws data] (.request ws 1) (when on-pong (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-pong ws data)))))) (onClose [_ ws status reason] (when on-close (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-close ws status reason)))))) (onError [_ ws err] (when on-error (on-error ws err))))) (defn- with-headers ^WebSocket$Builder [builder headers] (reduce-kv (fn [^WebSocket$Builder b ^String hk ^String hv] (.header b hk hv)) builder headers)) (defn websocket* "Same as `websocket` but take all arguments as a single map" [{:keys [uri listener http-client headers connect-timeout subprotocols] :as opts}] (let [^HttpClient http-client (if (instance? HttpClient http-client) http-client (HttpClient/newHttpClient)) ^WebSocket$Listener listener (if (instance? WebSocket$Listener listener) listener (request->WebSocketListener opts))] (cond-> (.newWebSocketBuilder http-client) connect-timeout (.connectTimeout (Duration/ofMillis connect-timeout)) (seq subprotocols) (.subprotocols (first subprotocols) (into-array String (rest subprotocols))) headers (with-headers headers) true (.buildAsync (URI/create uri) listener)))) (defn websocket "Builds a new WebSocket connection from a request object and returns a future connection. Arguments: - `uri` a websocket uri - `opts` (optional), a map of: - `:http-client` An HttpClient - will use a default HttpClient if not provided - `:listener` A WebSocket$Listener - alternatively will be created from the handlers passed into opts: :on-open, :on-message, :on-ping, :on-pong, :on-close, :on-error - `:headers` Adds the given name-value pair to the list of additional HTTP headers sent during the opening handshake. - `:connect-timeout` Sets a timeout for establishing a WebSocket connection (in millis). - `:subprotocols` Sets a request for the given subprotocols." [uri opts] (websocket* (assoc opts :uri uri))) (defprotocol Sendable "Protocol to represent sendable message types for a WebSocket. Useful for custom extensions." (-send! [data last? ws])) (extend-protocol Sendable (Class/forName "[B") (-send! [data last? ^WebSocket ws] (.sendBinary ws (ByteBuffer/wrap data) last?)) ByteBuffer (-send! [data last? ^WebSocket ws] (.sendBinary ws data last?)) CharSequence (-send! [data last? ^WebSocket ws] (.sendText ws data last?))) (defn send! "Sends a message to the WebSocket. `data` can be a CharSequence (e.g. string) or ByteBuffer" ([^WebSocket ws data] (send! ws data nil)) ([^WebSocket ws data {:keys [last?] :or {last? true}}] (-send! data last? ws))) (defn ^CompletableFuture ping! "Sends a Ping message with bytes from the given buffer." [^WebSocket ws ^ByteBuffer data] (.sendPing ws data)) (defn ^CompletableFuture pong! "Sends a Pong message with bytes from the given buffer." [^WebSocket ws ^ByteBuffer data] (.sendPong ws data)) (defn ^CompletableFuture close! "Initiates an orderly closure of this WebSocket's output by sending a Close message with the given status code and the reason." ([^WebSocket ws] (close! ws WebSocket/NORMAL_CLOSURE "")) ([^WebSocket ws status-code ^String reason] (.sendClose ws status-code reason))) (defn abort! "Closes this WebSocket's input and output abruptly." [^WebSocket ws] (.abort ws))
null
https://raw.githubusercontent.com/gnarroway/hato/ef829066afdaf458dd0299609e20162e65d32380/src/hato/websocket.clj
clojure
(ns hato.websocket (:import (java.net.http WebSocket$Listener WebSocket$Builder HttpClient WebSocket) (java.time Duration) (java.net URI) (java.util.concurrent CompletableFuture) (java.nio ByteBuffer) (java.util.function Function))) (defn request->WebSocketListener "Constructs a new WebSocket listener to receive events for a given WebSocket connection. Takes a map of: - `:on-open` Called when a `WebSocket` has been connected. Called with the WebSocket instance. - `:on-message` A textual/binary data has been received. Called with the WebSocket instance, the data, and whether this invocation completes the message. - `:on-ping` A Ping message has been received. Called with the WebSocket instance and the ping message. - `:on-pong` A Pong message has been received. Called with the WebSocket instance and the pong message. - `:on-close` Receives a Close message indicating the WebSocket's input has been closed. Called with the WebSocket instance, the status code, and the reason. - `:on-error` An error has occurred. Called with the WebSocket instance and the error." [{:keys [on-open on-message on-ping on-pong on-close on-error]}] The .requests below is from the implementation of the default listener (reify WebSocket$Listener (onOpen [_ ws] (.request ws 1) (when on-open (on-open ws))) (onText [_ ws data last?] (.request ws 1) (when on-message (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-message ws data last?)))))) (onBinary [_ ws data last?] (.request ws 1) (when on-message (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-message ws data last?)))))) (onPing [_ ws data] (.request ws 1) (when on-ping (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-ping ws data)))))) (onPong [_ ws data] (.request ws 1) (when on-pong (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-pong ws data)))))) (onClose [_ ws status reason] (when on-close (.thenApply (CompletableFuture/completedFuture nil) (reify Function (apply [_ _] (on-close ws status reason)))))) (onError [_ ws err] (when on-error (on-error ws err))))) (defn- with-headers ^WebSocket$Builder [builder headers] (reduce-kv (fn [^WebSocket$Builder b ^String hk ^String hv] (.header b hk hv)) builder headers)) (defn websocket* "Same as `websocket` but take all arguments as a single map" [{:keys [uri listener http-client headers connect-timeout subprotocols] :as opts}] (let [^HttpClient http-client (if (instance? HttpClient http-client) http-client (HttpClient/newHttpClient)) ^WebSocket$Listener listener (if (instance? WebSocket$Listener listener) listener (request->WebSocketListener opts))] (cond-> (.newWebSocketBuilder http-client) connect-timeout (.connectTimeout (Duration/ofMillis connect-timeout)) (seq subprotocols) (.subprotocols (first subprotocols) (into-array String (rest subprotocols))) headers (with-headers headers) true (.buildAsync (URI/create uri) listener)))) (defn websocket "Builds a new WebSocket connection from a request object and returns a future connection. Arguments: - `uri` a websocket uri - `opts` (optional), a map of: - `:http-client` An HttpClient - will use a default HttpClient if not provided - `:listener` A WebSocket$Listener - alternatively will be created from the handlers passed into opts: :on-open, :on-message, :on-ping, :on-pong, :on-close, :on-error - `:headers` Adds the given name-value pair to the list of additional HTTP headers sent during the opening handshake. - `:connect-timeout` Sets a timeout for establishing a WebSocket connection (in millis). - `:subprotocols` Sets a request for the given subprotocols." [uri opts] (websocket* (assoc opts :uri uri))) (defprotocol Sendable "Protocol to represent sendable message types for a WebSocket. Useful for custom extensions." (-send! [data last? ws])) (extend-protocol Sendable (Class/forName "[B") (-send! [data last? ^WebSocket ws] (.sendBinary ws (ByteBuffer/wrap data) last?)) ByteBuffer (-send! [data last? ^WebSocket ws] (.sendBinary ws data last?)) CharSequence (-send! [data last? ^WebSocket ws] (.sendText ws data last?))) (defn send! "Sends a message to the WebSocket. `data` can be a CharSequence (e.g. string) or ByteBuffer" ([^WebSocket ws data] (send! ws data nil)) ([^WebSocket ws data {:keys [last?] :or {last? true}}] (-send! data last? ws))) (defn ^CompletableFuture ping! "Sends a Ping message with bytes from the given buffer." [^WebSocket ws ^ByteBuffer data] (.sendPing ws data)) (defn ^CompletableFuture pong! "Sends a Pong message with bytes from the given buffer." [^WebSocket ws ^ByteBuffer data] (.sendPong ws data)) (defn ^CompletableFuture close! "Initiates an orderly closure of this WebSocket's output by sending a Close message with the given status code and the reason." ([^WebSocket ws] (close! ws WebSocket/NORMAL_CLOSURE "")) ([^WebSocket ws status-code ^String reason] (.sendClose ws status-code reason))) (defn abort! "Closes this WebSocket's input and output abruptly." [^WebSocket ws] (.abort ws))
abb6d741619e3896cf1a1df357c1979383f13d6d6fbb0613d144585adb0c3308
Frama-C/Frama-C-snapshot
sign_domain.ml
(**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Cil_types module Sign_Value = struct include Sign_value (* In this domain, we only track integer variables. *) let track_variable vi = Cil.isIntegralType vi.vtype (* The base lattice is finite, we can use join to perform widening *) let widen = join let builtins = [] end include Simple_memory.Make_Domain (struct let name = "sign" end) (Sign_Value)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/value/domains/sign_domain.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ In this domain, we only track integer variables. The base lattice is finite, we can use join to perform widening
This file is part of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types module Sign_Value = struct include Sign_value let track_variable vi = Cil.isIntegralType vi.vtype let widen = join let builtins = [] end include Simple_memory.Make_Domain (struct let name = "sign" end) (Sign_Value)
250dea5ce92b675d1a2f847b65439d26af0cd8f4000e37fc37b4f48d6c5eb029
gentoo-haskell/hackport
EBuild.hs
| Module : Portage . EBuild License : GPL-3 + Maintainer : Functions and types related to interpreting and manipulating an ebuild , as understood by the Portage package manager . Module : Portage.EBuild License : GPL-3+ Maintainer : Functions and types related to interpreting and manipulating an ebuild, as understood by the Portage package manager. -} # LANGUAGE CPP # module Portage.EBuild ( EBuild(..) , ebuildTemplate , showEBuild hspec exports , sort_iuse , drop_tdot , quote , toHttps ) where import Portage.Dependency import Portage.EBuild.CabalFeature import Portage.EBuild.Render import qualified Portage.Dependency.Normalize as PN import qualified Data.Time.Clock as TC import qualified Data.Time.Format as TC import qualified Data.Function as F import qualified Data.List as L import qualified Data.List.Split as LS import Data.Version(Version(..)) import Network.URI import qualified Paths_hackport(version) #if ! MIN_VERSION_time(1,5,0) import qualified System.Locale as TC #endif | Type representing the information contained in an @.ebuild@. data EBuild = EBuild { name :: String , category :: String , hackage_name :: String -- might differ a bit (we mangle case) , version :: String , revision :: String , hackportVersion :: String , sourceURIs :: [String] , description :: String , homepage :: String , license :: Either String String , slot :: String , keywords :: [String] , iuse :: [String] , depend :: Dependency , depend_extra :: [String] , rdepend :: Dependency , rdepend_extra :: [String] , features :: [CabalFeature] , cabal_pn :: Maybe String -- ^ Just 'myOldName' if the package name contains upper characters , src_prepare :: [String] -- ^ raw block for src_prepare() contents ^ raw block for src_configure ( ) contents , used_options :: [(String, String)] -- ^ hints to ebuild writers/readers -- on what hackport options were used to produce an ebuild } getHackportVersion :: Version -> String getHackportVersion Version {versionBranch=(x:s)} = foldl (\y z -> y ++ "." ++ (show z)) (show x) s getHackportVersion Version {versionBranch=[]} = "" -- | Generate a minimal 'EBuild' template. ebuildTemplate :: EBuild ebuildTemplate = EBuild { name = "foobar", category = "dev-haskell", hackage_name = "FooBar", version = "0.1", revision = "0", sourceURIs = [], hackportVersion = getHackportVersion Paths_hackport.version, description = "", homepage = "/${HACKAGE_N}", license = Left "unassigned license?", slot = "0", keywords = ["~amd64","~x86"], iuse = [], depend = empty_dependency, depend_extra = [], rdepend = empty_dependency, rdepend_extra = [], features = [], cabal_pn = Nothing , src_prepare = [] , src_configure = [] , used_options = [] } -- | Pretty-print an 'EBuild' as a 'String'. showEBuild :: TC.UTCTime -> EBuild -> String showEBuild now ebuild = ss ("# Copyright 1999-" ++ this_year ++ " Gentoo Authors"). nl. ss "# Distributed under the terms of the GNU General Public License v2". nl. nl. ss "EAPI=8". nl. nl. ss ("# ebuild generated by hackport " ++ hackportVersion ebuild). nl. sconcat (map (\(k, v) -> ss "#hackport: " . ss k . ss ": " . ss v . nl) $ used_options ebuild). nl. beforeInherit. ss "CABAL_FEATURES=". quote' (sepBy " " $ map render (features ebuild)). nl. ss "inherit haskell-cabal". nl. nl. ss "DESCRIPTION=". quote (drop_tdot $ description ebuild). nl. ss "HOMEPAGE=". quote (toHttps $ expandVars (homepage ebuild)). nl. nl. ss "LICENSE=". (either (\err -> quote "" . ss ("\t# FIXME: " ++ err)) quote (license ebuild)). nl. ss "SLOT=". quote (slot ebuild). nl. ss "KEYWORDS=". quote' (sepBy " " $ keywords ebuild).nl. (if null (iuse ebuild) then nl else ss "IUSE=". quote' (sepBy " " . sort_iuse $ L.nub $ iuse ebuild). nl. nl ) . dep_str "RDEPEND" (rdepend_extra ebuild) (rdepend ebuild). dep_str "DEPEND" ( depend_extra ebuild) ( depend ebuild). verbatim (nl . ss "src_prepare() {" . nl) (src_prepare ebuild) (ss "}" . nl). verbatim (nl. ss "src_configure() {" . nl) (src_configure ebuild) (ss "}" . nl). id $ [] where expandVars = replaceMultiVars [ ( name ebuild, "${PN}") , (hackage_name ebuild, "${HACKAGE_N}") ] this_year :: String this_year = TC.formatTime TC.defaultTimeLocale "%Y" now beforeInherit = case (revision ebuild, cabal_pn ebuild) of ("0", Nothing) -> id (r , pn ) -> revLine r. pnLine pn. nl revLine "0" = id revLine r = ss ("CABAL_HACKAGE_REVISION=" ++ r). nl pnLine Nothing = id pnLine (Just pn) = ss "CABAL_PN=". quote pn. nl -- | Convert http urls into https urls, unless whitelisted as http-only. -- -- >>> toHttps "" -- "" -- >>> toHttps "" -- "" -- >>> toHttps "" -- "" toHttps :: String -> String toHttps x = case parseURI x of Just uri -> if uriScheme uri == "http:" && (uriRegName <$> uriAuthority uri) `notElem` httpOnlyHomepages then replace "http" "https" x else x Nothing -> x where replace old new = L.intercalate new . LS.splitOn old -- add to this list with any non https-aware websites httpOnlyHomepages = Just <$> [ "leksah.org" , "darcs.net" , "khumba.net" ] | Sort IUSE alphabetically -- -- >>> sort_iuse ["+a","b"] -- ["+a","b"] sort_iuse :: [String] -> [String] sort_iuse = L.sortBy (compare `F.on` dropWhile ( `elem` "+")) -- | Drop trailing dot(s). -- -- >>> drop_tdot "foo." -- "foo" -- >>> drop_tdot "foo..." -- "foo" drop_tdot :: String -> String drop_tdot = reverse . dropWhile (== '.') . reverse type DString = String -> String ss :: String -> DString ss = showString sc :: Char -> DString sc = showChar nl :: DString nl = sc '\n' verbatim :: DString -> [String] -> DString -> DString verbatim pre s post = if null s then id else pre . (foldl (\acc v -> acc . ss "\t" . ss v . nl) id s) . post sconcat :: [DString] -> DString sconcat = L.foldl' (.) id -- takes string and substitutes tabs to spaces ebuild 's convention is 4 spaces for one tab , -- BUT! nested USE flags get moved too much to right . Thus 8 :] tab_size :: Int tab_size = 8 tabify_line :: String -> String tabify_line l = replicate need_tabs '\t' ++ nonsp where (sp, nonsp) = break (/= ' ') l (full_tabs, t) = length sp `divMod` tab_size need_tabs = full_tabs + if t > 0 then 1 else 0 tabify :: String -> String tabify = unlines . map tabify_line . lines dep_str :: String -> [String] -> Dependency -> DString dep_str var extra dep = ss var. sc '='. quote' (ss $ drop_leadings $ unlines extra ++ deps_s). nl where indent = 1 * tab_size deps_s = tabify (dep2str indent $ PN.normalize_depend dep) drop_leadings = dropWhile (== '\t') -- | Place a 'String' between quotes, and correctly handle special characters. quote :: String -> DString quote str = sc '"'. ss (esc str). sc '"' where esc = concatMap esc' esc' c = case c of '\\' -> "\\\\" '"' -> "\\\"" '\n' -> " " '`' -> "'" _ -> [c] quote' :: DString -> DString quote' str = sc '"'. str. sc '"' sepBy :: String -> [String] -> ShowS sepBy _ [] = id sepBy _ [x] = ss x sepBy s (x:xs) = ss x. ss s. sepBy s xs getRestIfPrefix :: String -- ^ the prefix -> String -- ^ the string -> Maybe String getRestIfPrefix (p:ps) (x:xs) = if p==x then getRestIfPrefix ps xs else Nothing getRestIfPrefix [] rest = Just rest getRestIfPrefix _ [] = Nothing subStr :: String -- ^ the search string -> String -- ^ the string to be searched -> Maybe (String,String) -- ^ Just (pre,post) if string is found subStr sstr str = case getRestIfPrefix sstr str of Nothing -> if null str then Nothing else case subStr sstr (tail str) of Nothing -> Nothing Just (pre,post) -> Just (head str:pre,post) Just rest -> Just ([],rest) replaceMultiVars :: [(String,String)] -- ^ pairs of variable name and content -> String -- ^ string to be searched -> String -- ^ the result replaceMultiVars [] str = str replaceMultiVars whole@((pname,cont):rest) str = case subStr cont str of Nothing -> replaceMultiVars rest str Just (pre,post) -> (replaceMultiVars rest pre)++pname++(replaceMultiVars whole post)
null
https://raw.githubusercontent.com/gentoo-haskell/hackport/558298950ed1e1f0c0b51f0595212a857fa373e4/src/Portage/EBuild.hs
haskell
might differ a bit (we mangle case) ^ Just 'myOldName' if the package name contains upper characters ^ raw block for src_prepare() contents ^ hints to ebuild writers/readers on what hackport options were used to produce an ebuild | Generate a minimal 'EBuild' template. | Pretty-print an 'EBuild' as a 'String'. | Convert http urls into https urls, unless whitelisted as http-only. >>> toHttps "" "" >>> toHttps "" "" >>> toHttps "" "" add to this list with any non https-aware websites >>> sort_iuse ["+a","b"] ["+a","b"] | Drop trailing dot(s). >>> drop_tdot "foo." "foo" >>> drop_tdot "foo..." "foo" takes string and substitutes tabs to spaces BUT! nested USE flags get moved too much to | Place a 'String' between quotes, and correctly handle special characters. ^ the prefix ^ the string ^ the search string ^ the string to be searched ^ Just (pre,post) if string is found ^ pairs of variable name and content ^ string to be searched ^ the result
| Module : Portage . EBuild License : GPL-3 + Maintainer : Functions and types related to interpreting and manipulating an ebuild , as understood by the Portage package manager . Module : Portage.EBuild License : GPL-3+ Maintainer : Functions and types related to interpreting and manipulating an ebuild, as understood by the Portage package manager. -} # LANGUAGE CPP # module Portage.EBuild ( EBuild(..) , ebuildTemplate , showEBuild hspec exports , sort_iuse , drop_tdot , quote , toHttps ) where import Portage.Dependency import Portage.EBuild.CabalFeature import Portage.EBuild.Render import qualified Portage.Dependency.Normalize as PN import qualified Data.Time.Clock as TC import qualified Data.Time.Format as TC import qualified Data.Function as F import qualified Data.List as L import qualified Data.List.Split as LS import Data.Version(Version(..)) import Network.URI import qualified Paths_hackport(version) #if ! MIN_VERSION_time(1,5,0) import qualified System.Locale as TC #endif | Type representing the information contained in an @.ebuild@. data EBuild = EBuild { name :: String , category :: String , version :: String , revision :: String , hackportVersion :: String , sourceURIs :: [String] , description :: String , homepage :: String , license :: Either String String , slot :: String , keywords :: [String] , iuse :: [String] , depend :: Dependency , depend_extra :: [String] , rdepend :: Dependency , rdepend_extra :: [String] , features :: [CabalFeature] ^ raw block for src_configure ( ) contents } getHackportVersion :: Version -> String getHackportVersion Version {versionBranch=(x:s)} = foldl (\y z -> y ++ "." ++ (show z)) (show x) s getHackportVersion Version {versionBranch=[]} = "" ebuildTemplate :: EBuild ebuildTemplate = EBuild { name = "foobar", category = "dev-haskell", hackage_name = "FooBar", version = "0.1", revision = "0", sourceURIs = [], hackportVersion = getHackportVersion Paths_hackport.version, description = "", homepage = "/${HACKAGE_N}", license = Left "unassigned license?", slot = "0", keywords = ["~amd64","~x86"], iuse = [], depend = empty_dependency, depend_extra = [], rdepend = empty_dependency, rdepend_extra = [], features = [], cabal_pn = Nothing , src_prepare = [] , src_configure = [] , used_options = [] } showEBuild :: TC.UTCTime -> EBuild -> String showEBuild now ebuild = ss ("# Copyright 1999-" ++ this_year ++ " Gentoo Authors"). nl. ss "# Distributed under the terms of the GNU General Public License v2". nl. nl. ss "EAPI=8". nl. nl. ss ("# ebuild generated by hackport " ++ hackportVersion ebuild). nl. sconcat (map (\(k, v) -> ss "#hackport: " . ss k . ss ": " . ss v . nl) $ used_options ebuild). nl. beforeInherit. ss "CABAL_FEATURES=". quote' (sepBy " " $ map render (features ebuild)). nl. ss "inherit haskell-cabal". nl. nl. ss "DESCRIPTION=". quote (drop_tdot $ description ebuild). nl. ss "HOMEPAGE=". quote (toHttps $ expandVars (homepage ebuild)). nl. nl. ss "LICENSE=". (either (\err -> quote "" . ss ("\t# FIXME: " ++ err)) quote (license ebuild)). nl. ss "SLOT=". quote (slot ebuild). nl. ss "KEYWORDS=". quote' (sepBy " " $ keywords ebuild).nl. (if null (iuse ebuild) then nl else ss "IUSE=". quote' (sepBy " " . sort_iuse $ L.nub $ iuse ebuild). nl. nl ) . dep_str "RDEPEND" (rdepend_extra ebuild) (rdepend ebuild). dep_str "DEPEND" ( depend_extra ebuild) ( depend ebuild). verbatim (nl . ss "src_prepare() {" . nl) (src_prepare ebuild) (ss "}" . nl). verbatim (nl. ss "src_configure() {" . nl) (src_configure ebuild) (ss "}" . nl). id $ [] where expandVars = replaceMultiVars [ ( name ebuild, "${PN}") , (hackage_name ebuild, "${HACKAGE_N}") ] this_year :: String this_year = TC.formatTime TC.defaultTimeLocale "%Y" now beforeInherit = case (revision ebuild, cabal_pn ebuild) of ("0", Nothing) -> id (r , pn ) -> revLine r. pnLine pn. nl revLine "0" = id revLine r = ss ("CABAL_HACKAGE_REVISION=" ++ r). nl pnLine Nothing = id pnLine (Just pn) = ss "CABAL_PN=". quote pn. nl toHttps :: String -> String toHttps x = case parseURI x of Just uri -> if uriScheme uri == "http:" && (uriRegName <$> uriAuthority uri) `notElem` httpOnlyHomepages then replace "http" "https" x else x Nothing -> x where replace old new = L.intercalate new . LS.splitOn old httpOnlyHomepages = Just <$> [ "leksah.org" , "darcs.net" , "khumba.net" ] | Sort IUSE alphabetically sort_iuse :: [String] -> [String] sort_iuse = L.sortBy (compare `F.on` dropWhile ( `elem` "+")) drop_tdot :: String -> String drop_tdot = reverse . dropWhile (== '.') . reverse type DString = String -> String ss :: String -> DString ss = showString sc :: Char -> DString sc = showChar nl :: DString nl = sc '\n' verbatim :: DString -> [String] -> DString -> DString verbatim pre s post = if null s then id else pre . (foldl (\acc v -> acc . ss "\t" . ss v . nl) id s) . post sconcat :: [DString] -> DString sconcat = L.foldl' (.) id ebuild 's convention is 4 spaces for one tab , right . Thus 8 :] tab_size :: Int tab_size = 8 tabify_line :: String -> String tabify_line l = replicate need_tabs '\t' ++ nonsp where (sp, nonsp) = break (/= ' ') l (full_tabs, t) = length sp `divMod` tab_size need_tabs = full_tabs + if t > 0 then 1 else 0 tabify :: String -> String tabify = unlines . map tabify_line . lines dep_str :: String -> [String] -> Dependency -> DString dep_str var extra dep = ss var. sc '='. quote' (ss $ drop_leadings $ unlines extra ++ deps_s). nl where indent = 1 * tab_size deps_s = tabify (dep2str indent $ PN.normalize_depend dep) drop_leadings = dropWhile (== '\t') quote :: String -> DString quote str = sc '"'. ss (esc str). sc '"' where esc = concatMap esc' esc' c = case c of '\\' -> "\\\\" '"' -> "\\\"" '\n' -> " " '`' -> "'" _ -> [c] quote' :: DString -> DString quote' str = sc '"'. str. sc '"' sepBy :: String -> [String] -> ShowS sepBy _ [] = id sepBy _ [x] = ss x sepBy s (x:xs) = ss x. ss s. sepBy s xs -> Maybe String getRestIfPrefix (p:ps) (x:xs) = if p==x then getRestIfPrefix ps xs else Nothing getRestIfPrefix [] rest = Just rest getRestIfPrefix _ [] = Nothing subStr sstr str = case getRestIfPrefix sstr str of Nothing -> if null str then Nothing else case subStr sstr (tail str) of Nothing -> Nothing Just (pre,post) -> Just (head str:pre,post) Just rest -> Just ([],rest) replaceMultiVars :: replaceMultiVars [] str = str replaceMultiVars whole@((pname,cont):rest) str = case subStr cont str of Nothing -> replaceMultiVars rest str Just (pre,post) -> (replaceMultiVars rest pre)++pname++(replaceMultiVars whole post)
2c5a6f475301c09f658d7e26ee01567e68156874115172392503f6fa4d4d0f96
thephoeron/quipper-language
Lifting.hs
This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the -- file COPYRIGHT for a list of authors, copyright holders, licensing, -- and other details. All rights reserved. -- -- ====================================================================== # LANGUAGE TemplateHaskell # {-# LANGUAGE RankNTypes #-} | This module describes stripped - down Template Haskell abstract syntax trees ( ASTs ) for a subset of Haskell . module Libraries.Template.Lifting where import Control.Monad.State import qualified Data.Map as Map import Data.Map (Map) import qualified Data.List as List import Data.Maybe (catMaybes) import qualified Data.Set as Set import Data.Set (Set) import qualified Language.Haskell.TH as TH import Language.Haskell.TH (Name) -- Get the monad to build the lifting. import Libraries.Template.LiftQ -- * Abstract syntax trees of a simplified language | There are no \"guarded bodies\ " . One net effect is to make the -- \"where\" construct equivalent to a simple \"let\". type Body = Exp -- | Literals. data Lit = CharL Char -- ^ Characters. | IntegerL Integer -- ^ Integers. | RationalL Rational -- ^ Reals. deriving (Show) -- | Patterns. data Pat = LitP Lit -- ^ Literal. | VarP Name -- ^ Variable name. | TupP [Pat] -- ^ Tuple. ^ . ^ List as @[ ... ]@. | ConP Name [Pat] -- ^ Cons: @h:t@. deriving (Show) -- | Match term construct. data Match = Match Pat Body deriving (Show) | First - level declaration . data Dec = ValD Name Body deriving (Show) -- | Expression data Exp = VarE Name -- ^ Variable name. | ConE Name -- ^ Constant name. | LitE Lit -- ^ Literal. | AppE Exp Exp -- ^ Application. | LamE Name Exp -- ^ Lambda abstraction. | TupE [Exp] -- ^ Tuple. | CondE Exp Exp Exp -- ^ If-then-else. | LetE [Dec] Exp -- ^ Let-construct. | CaseE Exp [Match] -- ^ Case distinction ^ List : @[ ... ]@. ^ hardcoded constant for @'return'@. ^ hardcoded constant for @'>>='@. deriving (Show) $ Syntactic sugar to recover do - notation . | Datatype to encode the notation @x < - expr@. data BindS = BindS Name Exp | A simple @do@ : list of monadic followed by a computation . doE :: [BindS] -> Exp -> Exp doE binds exp = foldr doOne exp binds where doOne :: BindS -> Exp -> Exp doOne (BindS n value) computation = AppE (AppE MAppE value) (LamE n computation) -- * Variable substitution -- | Get the set of variable names in a pattern. getVarNames :: Pat -> Set Name getVarNames (VarP n) = Set.singleton n getVarNames (TupP pats) = Set.unions $ map getVarNames pats getVarNames (ListP pats) = Set.unions $ map getVarNames pats getVarNames _ = Set.empty -- | Substitution in a @'Match'@. substMatch :: Name -> Exp -> Match -> Match substMatch n s (Match p e) | Set.member n (getVarNames p) = Match p e | True = Match p (substExp n s e) | Substitution in a @'Dec'@. substDec :: Name -> Exp -> Dec -> Dec substDec n s (ValD m e) | n == m = ValD m e | True = ValD m (substExp n s e) | Substitution in an @'Exp'@. substExp :: Name -> Exp -> Exp -> Exp substExp n s (VarE m) | n == m = s | True = (VarE m) substExp n s (ConE m) = ConE m substExp n s (LitE l) = LitE l substExp n s (AppE e1 e2) = AppE (substExp n s e1) (substExp n s e2) substExp n s (LamE m exp) | n == m = LamE m exp | True = LamE m $ substExp n s exp substExp n s (TupE exps) = TupE $ map (substExp n s) exps substExp n s (CondE e1 e2 e3) = CondE (substExp n s e1) (substExp n s e2) (substExp n s e3) substExp n s (LetE decs exp) = LetE (map (substDec n s) decs) (substExp n s exp) substExp n s (CaseE exp matches) = CaseE (substExp n s exp) $ map (substMatch n s) matches substExp n s (ListE exps) = ListE $ map (substExp n s) exps substExp n s ReturnE = ReturnE substExp n s MAppE = MAppE -- | Substitution of several variables in one go. mapSubstExp :: (Map Name Exp) -> Exp -> Exp mapSubstExp map exp = List.foldl (\exp (x,y) -> substExp x y exp) exp $ Map.toList map -- * Downgrading Template Haskell to AST -- | Downgrading TH literals to @'Exp'@. litTHtoExpAST :: TH.Lit -> LiftQ Exp litTHtoExpAST (TH.CharL c) = return $ LitE $ CharL c litTHtoExpAST (TH.StringL s) = return $ ListE $ map (LitE . CharL) s litTHtoExpAST (TH.IntegerL i) = return $ LitE $ IntegerL i litTHtoExpAST (TH.RationalL r) = return $ LitE $ RationalL r litTHtoExpAST x = errorMsg ("lifting not handled for " ++ (show x)) -- | Downgrading TH literals to @'Pat'@. litTHtoPatAST :: TH.Lit -> LiftQ Pat litTHtoPatAST (TH.CharL c) = return $ LitP $ CharL c litTHtoPatAST (TH.StringL s) = return $ ListP $ map (LitP . CharL) s litTHtoPatAST (TH.IntegerL i) = return $ LitP $ IntegerL i litTHtoPatAST (TH.RationalL r) = return $ LitP $ RationalL r litTHtoPatAST x = errorMsg ("lifting not handled for " ++ (show x)) -- | Take a list of patterns coming from a @where@ section and output a list of fresh names for normalized @let@s . Also gives a mapping -- for substituting inside the expressions. Assume all names in the -- list of patterns are distinct. normalizePatInExp :: [Pat] -> LiftQ ([Name], Map Name Exp) normalizePatInExp pats = do fresh_names <- mapM newName $ replicate (length pats) "normalizePat" let sets_of_old_names = List.map getVarNames pats let old_to_fresh old_name = List.lookup True $ zip (List.map (Set.member old_name) sets_of_old_names) fresh_names let old_to_pat old_name = List.lookup True $ zip (List.map (Set.member old_name) sets_of_old_names) pats let list_of_old_names = List.concat $ List.map Set.toList sets_of_old_names let maybe_list_map = mapM (\x -> do fresh <- old_to_fresh x pat <- old_to_pat x return (x, CaseE (VarE fresh) [Match pat (VarE x)])) list_of_old_names case maybe_list_map of Nothing -> errorMsg "error in patterns..." Just l -> return $ (fresh_names, Map.fromList l) -- | Build a @let@-expression out of pieces. whereToLet :: Exp -> [(Pat,Exp)] -> LiftQ Exp whereToLet exp [] = return exp whereToLet exp list = do (fresh_names, pmap) <- normalizePatInExp $ map fst list let decs'' = map (uncurry ValD) $ zip fresh_names $ map snd list let decs' = map (\(ValD n e) -> ValD n $ mapSubstExp pmap e) decs'' return $ LetE decs' $ CaseE (TupE $ map VarE fresh_names) [Match (TupP $ map fst list) exp] | Build a @'Match'@ out of a TH clause clauseToMatch :: TH.Clause -> LiftQ Match clauseToMatch (TH.Clause pats body decs) = do pats' <- mapM patTHtoAST pats body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ Match (TupP pats') exp | From a list of TH clauses , make a case - distinction wrapped in a -- lambda abstraction. clausesToLambda :: [TH.Clause] -> LiftQ Exp clausesToLambda clauses = do -- get length of patterns pats_length <- clausesLengthPats clauses -- make a list of new names from the function name fresh_names <- mapM newName $ replicate pats_length "x" -- make matches out of the clauses. matches <- mapM clauseToMatch clauses -- return a simple function with a case-distinction return $ foldr LamE (CaseE (TupE $ map VarE fresh_names) matches) fresh_names -- | Downgrade expressions. expTHtoAST :: TH.Exp -> LiftQ Exp expTHtoAST (TH.VarE v) = return $ VarE v expTHtoAST (TH.ConE n) = return $ ConE n expTHtoAST (TH.LitE l) = litTHtoExpAST l expTHtoAST (TH.AppE e1 e2) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 return $ AppE e1' e2' expTHtoAST (TH.InfixE (Just e1) e2 (Just e3)) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 return $ AppE (AppE e2' e1') e3' expTHtoAST (TH.InfixE Nothing e2 (Just e3)) = do e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 n <- newName "x" return $ LamE n $ AppE (AppE e2' (VarE n)) e3' expTHtoAST (TH.InfixE (Just e1) e2 Nothing) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 return $ AppE e2' e1' expTHtoAST (TH.InfixE Nothing e2 Nothing) = do e2' <- expTHtoAST e2 return e2' expTHtoAST (TH.LamE pats exp) = clausesToLambda [TH.Clause pats (TH.NormalB exp) []] expTHtoAST (TH.TupE exps) = do exps' <- mapM expTHtoAST exps return (TupE exps') expTHtoAST (TH.CondE e1 e2 e3) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 return $ CondE e1' e2' e3' expTHtoAST (TH.LetE decs exp) = do decs' <- mapM decTHtoAST decs exp' <- expTHtoAST exp whereToLet exp' decs' expTHtoAST (TH.CaseE exp matches) = do exp' <- expTHtoAST exp matches' <- mapM matchTHtoAST matches return $ CaseE exp' matches' expTHtoAST (TH.ListE exps) = do exps' <- mapM expTHtoAST exps return $ ListE exps' expTHtoAST (TH.SigE e _) = expTHtoAST e expTHtoAST x = errorMsg ("lifting not handled for " ++ (show x)) -- | Downgrade match-constructs. matchTHtoAST :: TH.Match -> LiftQ Match matchTHtoAST (TH.Match pat body decs) = do pat' <- patTHtoAST pat body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ Match pat' exp -- | Downgrade bodies into expressions. bodyTHtoAST :: TH.Body -> LiftQ Exp bodyTHtoAST (TH.NormalB exp) = expTHtoAST exp bodyTHtoAST (TH.GuardedB x) = errorMsg ("guarded body not allowed in lifting: " ++ (show x)) -- | Downgrade patterns. patTHtoAST :: TH.Pat -> LiftQ Pat patTHtoAST (TH.LitP l) = litTHtoPatAST l patTHtoAST (TH.VarP n) = return $ VarP n patTHtoAST (TH.TupP pats) = do pats' <- mapM patTHtoAST pats; return $ TupP pats' patTHtoAST (TH.WildP) = return WildP patTHtoAST (TH.ListP pats) = do pats' <- mapM patTHtoAST pats; return $ ListP pats' patTHtoAST (TH.ConP n pats) = do pats' <- mapM patTHtoAST pats; return $ ConP n pats' patTHtoAST (TH.InfixP p1 n p2) = do p1' <- patTHtoAST p1 p2' <- patTHtoAST p2 return $ ConP n [p1',p2'] patTHtoAST x = errorMsg ("non-implemented lifting: " ++ (show x)) | Downgrade first - level declarations . firstLevelDecTHtoAST :: TH.Dec -> Maybe (LiftQ Dec) firstLevelDecTHtoAST (TH.FunD name clauses) = Just $ do exp <- clausesToLambda clauses name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp firstLevelDecTHtoAST (TH.ValD (TH.VarP name) body decs) = Just $ do body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp firstLevelDecTHtoAST (TH.ValD _ _ _) = Just $ errorMsg ("only variables and functions can be lifted as first-level declarations") firstLevelDecTHtoAST (TH.SigD _ _) = Nothing firstLevelDecTHtoAST x = Just $ errorMsg ("non-implemented lifting: " ++ (show x)) -- | Downgrade any declarations (including the ones in @where@-constructs). decTHtoAST :: TH.Dec -> LiftQ (Pat,Exp) decTHtoAST (TH.FunD name clauses) = do exp <- clausesToLambda clauses return $ (VarP name, exp) decTHtoAST (TH.ValD pat body decs) = do pat' <- patTHtoAST pat body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ (pat', exp) decTHtoAST x = errorMsg ("non-implemented lifting: " ++ (show x)) -- * Upgrade AST to Template Haskell -- | Abstract syntax tree of the type of the function 'return'. typReturnE :: LiftQ TH.Type typReturnE = do m_string <- getMonadName let m = TH.conT (mkName m_string) embedQ [t| forall x. x -> $(m) x |] -- | Abstract syntax tree of the type of the function '>>='. typMAppE :: LiftQ TH.Type typMAppE = do m_string <- getMonadName let m = TH.conT (mkName m_string) embedQ [t| forall x y. $(m) x -> (x -> $(m) y) -> $(m) y |] -- | Upgrade literals litASTtoTH :: Lit -> TH.Lit litASTtoTH (CharL c) = TH.CharL c litASTtoTH (IntegerL i) = TH.IntegerL i litASTtoTH (RationalL r) = TH.RationalL r -- | Upgrade patterns. patASTtoTH :: Pat -> TH.Pat patASTtoTH (LitP l) = TH.LitP $ litASTtoTH l patASTtoTH (VarP n) = TH.VarP n patASTtoTH (TupP pats) = TH.TupP $ map patASTtoTH pats patASTtoTH WildP = TH.WildP patASTtoTH (ListP pats) = TH.ListP $ map patASTtoTH pats patASTtoTH (ConP n pats) = TH.ConP n $ map patASTtoTH pats -- | Upgrade match-constructs. matchASTtoTH :: Match -> LiftQ TH.Match matchASTtoTH (Match p b) = do exp <- expASTtoTH b return $ TH.Match (patASTtoTH p) (TH.NormalB exp) [] -- | Upgrade declarations. decASTtoTH :: Dec -> LiftQ TH.Dec decASTtoTH (ValD n b) = do exp <- expASTtoTH b return $ TH.ValD (TH.VarP n) (TH.NormalB exp) [] -- | Upgrade expressions. expASTtoTH :: Exp -> LiftQ TH.Exp expASTtoTH (VarE n) = return $ TH.VarE n expASTtoTH (ConE n) = return $ TH.ConE n expASTtoTH (LitE l) = return $ TH.LitE $ litASTtoTH l expASTtoTH (AppE e1 e2) = do e1' <- expASTtoTH e1 e2' <- expASTtoTH e2 return $ TH.AppE e1' e2' expASTtoTH (LamE n e) = do e' <- expASTtoTH e return $ TH.LamE [TH.VarP n] e' expASTtoTH (TupE exps) = do exps' <- mapM expASTtoTH exps return $ TH.TupE exps' expASTtoTH (CondE e1 e2 e3) = do e1' <- expASTtoTH e1 e2' <- expASTtoTH e2 e3' <- expASTtoTH e3 return $ TH.CondE e1' e2' e3' expASTtoTH (LetE decs e) = do decs' <- mapM decASTtoTH decs e' <- expASTtoTH e return $ TH.LetE decs' e' expASTtoTH (CaseE e matches) = do e' <- expASTtoTH e m' <- mapM matchASTtoTH matches return $ TH.CaseE e' m' expASTtoTH (ListE exps) = do exps' <- mapM expASTtoTH exps return $ TH.ListE exps' expASTtoTH ReturnE = do t <- typReturnE maybe_r <- embedQ $ TH.lookupValueName "return" case maybe_r of Just r -> return $ TH.SigE (TH.VarE r) t Nothing -> errorMsg "\'return\' undefined" expASTtoTH MAppE = do t <- typMAppE maybe_a <- embedQ $ TH.lookupValueName ">>=" case maybe_a of Just a -> return $ TH.SigE (TH.VarE a) t Nothing -> errorMsg "\'>>=\' undefined" * Lifting AST terms ( into AST terms ) -- | Variable referring to the lifting function for integers. liftIntegerL :: Exp liftIntegerL = VarE $ mkName "template_integer" -- | Variable referring to the lifting function for reals. liftRationalL :: Exp liftRationalL = VarE $ mkName "template_rational" -- | Lifting literals. liftLitAST :: Lit -> LiftQ Exp liftLitAST (CharL c) = return (AppE ReturnE (LitE $ CharL c)) liftLitAST (IntegerL i) = return $ AppE liftIntegerL (LitE $ IntegerL i) liftLitAST (RationalL r) = return $ AppE liftRationalL (LitE $ RationalL r) -- | Lifting patterns. liftPatAST :: Pat -> LiftQ Pat liftPatAST pat = return pat -- | Lifting match-constructs. liftMatchAST :: Match -> LiftQ Match liftMatchAST (Match pat exp) = do exp' <- liftExpAST exp return $ Match pat exp' -- | Lifting declarations. liftDecAST :: Dec -> LiftQ Dec liftDecAST (ValD name exp) = do exp' <- liftExpAST exp return $ ValD name exp' | Lifting first - level declarations . liftFirstLevelDecAST :: Dec -> LiftQ Dec liftFirstLevelDecAST (ValD name exp) = withBoundVar name $ do exp' <- liftExpAST exp return $ ValD name exp' -- | Lifting expressions. liftExpAST :: Exp -> LiftQ Exp liftExpAST (VarE x) = do template_name <- lookForTemplate x case template_name of Nothing -> do b <- isBoundVar x if b then return $ VarE x else return $ AppE ReturnE $ VarE x Just t -> return $ VarE t liftExpAST (ConE n) = do template_name <- lookForTemplate n case template_name of Nothing -> do t <- templateString $ TH.nameBase n errorMsg ("variable " ++ t ++ " undefined") Just t -> return $ VarE t liftExpAST (LitE l) = liftLitAST l liftExpAST (AppE e1 e2) = do e1' <- liftExpAST e1 e2' <- liftExpAST e2 n1 <- newName "app1" n2 <- newName "app2" return $ doE [BindS n1 e1', BindS n2 e2'] $ AppE (VarE n1) (VarE n2) liftExpAST (LamE n exp) = do exp' <- liftExpAST exp return $ AppE ReturnE $ LamE n exp' liftExpAST (TupE exps) = do exps' <- mapM liftExpAST exps fresh_names <- mapM newName $ replicate (length exps) "tupe" return $ doE (map (uncurry BindS) $ zip fresh_names exps') (AppE ReturnE $ TupE $ map VarE fresh_names) liftExpAST (CondE e1 e2 e3) = do e1' <- liftExpAST e1 e2' <- liftExpAST e2 e3' <- liftExpAST e3 return $ AppE (AppE (AppE (VarE (mkName "template_if")) (e1')) (e2')) (e3') liftExpAST (LetE decs exp) = let existing_names = map (\(ValD n _) -> n) decs in withBoundVars existing_names $ do decs' <- mapM liftDecAST decs exp' <- liftExpAST exp return $ LetE decs' exp' liftExpAST (CaseE exp matches) = do exp' <- liftExpAST exp matches' <- mapM liftMatchAST matches fresh_name <- newName "case" return $ doE [BindS fresh_name exp'] $ CaseE (VarE fresh_name) matches' liftExpAST (ListE exps) = do exps' <- mapM liftExpAST exps fresh_names <- mapM newName $ replicate (length exps) "liste" return $ doE (map (uncurry BindS) $ zip fresh_names exps') $ AppE ReturnE $ ListE $ map VarE fresh_names These two are not supposed to be there ! liftExpAST ReturnE = undefined liftExpAST MAppE = undefined -- | make a declaration into a template-declaration (by renaming with -- the template-prefix). makeDecTemplate :: Dec -> LiftQ Dec makeDecTemplate (ValD name exp) = do name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp -- * Various pretty printing functions | pretty - printing Template Haskell declarations . prettyPrintAST :: TH.Q [TH.Dec] -> IO () prettyPrintAST x = prettyPrint $ do x' <- embedQ x y <- sequence $ catMaybes $ map firstLevelDecTHtoAST x' mapM decASTtoTH y | Pretty - printing Template Haskell expressions . prettyPrintLiftExpTH :: TH.Q (TH.Exp) -> IO () prettyPrintLiftExpTH x = prettyPrint $ do x' <- embedQ x y <- expTHtoAST x' z <- liftExpAST y expASTtoTH z -- | Pretty-printing expressions. prettyPrintLiftExpAST :: LiftQ (Exp) -> IO () prettyPrintLiftExpAST x = prettyPrint $ do z <- x z' <- liftExpAST z expASTtoTH z' -- * The main lifting functions. | Lift a list of declarations . The first argument is the name of -- the monad to lift into. decToMonad :: String -> TH.Q [TH.Dec] -> TH.Q [TH.Dec] decToMonad s x = extractQ "decToMonad: " $ do setMonadName s setPrefix "template_" dec <- embedQ x decAST <- sequence $ catMaybes $ map firstLevelDecTHtoAST dec liftedAST <- mapM liftFirstLevelDecAST decAST mapM decASTtoTH liftedAST | Lift an expression . The first argument is the name of the monad -- to lift into. expToMonad :: String -> TH.Q TH.Exp -> TH.Q TH.Exp expToMonad s x = extractQ "expToMonad: " $ do setMonadName s setPrefix "template_" dec <- embedQ x decAST <- expTHtoAST dec liftedAST <- liftExpAST decAST expASTtoTH liftedAST
null
https://raw.githubusercontent.com/thephoeron/quipper-language/15e555343a15c07b9aa97aced1ada22414f04af6/Libraries/Template/Lifting.hs
haskell
file COPYRIGHT for a list of authors, copyright holders, licensing, and other details. All rights reserved. ====================================================================== # LANGUAGE RankNTypes # Get the monad to build the lifting. * Abstract syntax trees of a simplified language \"where\" construct equivalent to a simple \"let\". | Literals. ^ Characters. ^ Integers. ^ Reals. | Patterns. ^ Literal. ^ Variable name. ^ Tuple. ^ Cons: @h:t@. | Match term construct. | Expression ^ Variable name. ^ Constant name. ^ Literal. ^ Application. ^ Lambda abstraction. ^ Tuple. ^ If-then-else. ^ Let-construct. ^ Case distinction * Variable substitution | Get the set of variable names in a pattern. | Substitution in a @'Match'@. | Substitution of several variables in one go. * Downgrading Template Haskell to AST | Downgrading TH literals to @'Exp'@. | Downgrading TH literals to @'Pat'@. | Take a list of patterns coming from a @where@ section and output for substituting inside the expressions. Assume all names in the list of patterns are distinct. | Build a @let@-expression out of pieces. lambda abstraction. get length of patterns make a list of new names from the function name make matches out of the clauses. return a simple function with a case-distinction | Downgrade expressions. | Downgrade match-constructs. | Downgrade bodies into expressions. | Downgrade patterns. | Downgrade any declarations (including the ones in @where@-constructs). * Upgrade AST to Template Haskell | Abstract syntax tree of the type of the function 'return'. | Abstract syntax tree of the type of the function '>>='. | Upgrade literals | Upgrade patterns. | Upgrade match-constructs. | Upgrade declarations. | Upgrade expressions. | Variable referring to the lifting function for integers. | Variable referring to the lifting function for reals. | Lifting literals. | Lifting patterns. | Lifting match-constructs. | Lifting declarations. | Lifting expressions. | make a declaration into a template-declaration (by renaming with the template-prefix). * Various pretty printing functions | Pretty-printing expressions. * The main lifting functions. the monad to lift into. to lift into.
This file is part of Quipper . Copyright ( C ) 2011 - 2014 . Please see the # LANGUAGE TemplateHaskell # | This module describes stripped - down Template Haskell abstract syntax trees ( ASTs ) for a subset of Haskell . module Libraries.Template.Lifting where import Control.Monad.State import qualified Data.Map as Map import Data.Map (Map) import qualified Data.List as List import Data.Maybe (catMaybes) import qualified Data.Set as Set import Data.Set (Set) import qualified Language.Haskell.TH as TH import Language.Haskell.TH (Name) import Libraries.Template.LiftQ | There are no \"guarded bodies\ " . One net effect is to make the type Body = Exp data Lit = deriving (Show) data Pat = ^ . ^ List as @[ ... ]@. deriving (Show) data Match = Match Pat Body deriving (Show) | First - level declaration . data Dec = ValD Name Body deriving (Show) data Exp = ^ List : @[ ... ]@. ^ hardcoded constant for @'return'@. ^ hardcoded constant for @'>>='@. deriving (Show) $ Syntactic sugar to recover do - notation . | Datatype to encode the notation @x < - expr@. data BindS = BindS Name Exp | A simple @do@ : list of monadic followed by a computation . doE :: [BindS] -> Exp -> Exp doE binds exp = foldr doOne exp binds where doOne :: BindS -> Exp -> Exp doOne (BindS n value) computation = AppE (AppE MAppE value) (LamE n computation) getVarNames :: Pat -> Set Name getVarNames (VarP n) = Set.singleton n getVarNames (TupP pats) = Set.unions $ map getVarNames pats getVarNames (ListP pats) = Set.unions $ map getVarNames pats getVarNames _ = Set.empty substMatch :: Name -> Exp -> Match -> Match substMatch n s (Match p e) | Set.member n (getVarNames p) = Match p e | True = Match p (substExp n s e) | Substitution in a @'Dec'@. substDec :: Name -> Exp -> Dec -> Dec substDec n s (ValD m e) | n == m = ValD m e | True = ValD m (substExp n s e) | Substitution in an @'Exp'@. substExp :: Name -> Exp -> Exp -> Exp substExp n s (VarE m) | n == m = s | True = (VarE m) substExp n s (ConE m) = ConE m substExp n s (LitE l) = LitE l substExp n s (AppE e1 e2) = AppE (substExp n s e1) (substExp n s e2) substExp n s (LamE m exp) | n == m = LamE m exp | True = LamE m $ substExp n s exp substExp n s (TupE exps) = TupE $ map (substExp n s) exps substExp n s (CondE e1 e2 e3) = CondE (substExp n s e1) (substExp n s e2) (substExp n s e3) substExp n s (LetE decs exp) = LetE (map (substDec n s) decs) (substExp n s exp) substExp n s (CaseE exp matches) = CaseE (substExp n s exp) $ map (substMatch n s) matches substExp n s (ListE exps) = ListE $ map (substExp n s) exps substExp n s ReturnE = ReturnE substExp n s MAppE = MAppE mapSubstExp :: (Map Name Exp) -> Exp -> Exp mapSubstExp map exp = List.foldl (\exp (x,y) -> substExp x y exp) exp $ Map.toList map litTHtoExpAST :: TH.Lit -> LiftQ Exp litTHtoExpAST (TH.CharL c) = return $ LitE $ CharL c litTHtoExpAST (TH.StringL s) = return $ ListE $ map (LitE . CharL) s litTHtoExpAST (TH.IntegerL i) = return $ LitE $ IntegerL i litTHtoExpAST (TH.RationalL r) = return $ LitE $ RationalL r litTHtoExpAST x = errorMsg ("lifting not handled for " ++ (show x)) litTHtoPatAST :: TH.Lit -> LiftQ Pat litTHtoPatAST (TH.CharL c) = return $ LitP $ CharL c litTHtoPatAST (TH.StringL s) = return $ ListP $ map (LitP . CharL) s litTHtoPatAST (TH.IntegerL i) = return $ LitP $ IntegerL i litTHtoPatAST (TH.RationalL r) = return $ LitP $ RationalL r litTHtoPatAST x = errorMsg ("lifting not handled for " ++ (show x)) a list of fresh names for normalized @let@s . Also gives a mapping normalizePatInExp :: [Pat] -> LiftQ ([Name], Map Name Exp) normalizePatInExp pats = do fresh_names <- mapM newName $ replicate (length pats) "normalizePat" let sets_of_old_names = List.map getVarNames pats let old_to_fresh old_name = List.lookup True $ zip (List.map (Set.member old_name) sets_of_old_names) fresh_names let old_to_pat old_name = List.lookup True $ zip (List.map (Set.member old_name) sets_of_old_names) pats let list_of_old_names = List.concat $ List.map Set.toList sets_of_old_names let maybe_list_map = mapM (\x -> do fresh <- old_to_fresh x pat <- old_to_pat x return (x, CaseE (VarE fresh) [Match pat (VarE x)])) list_of_old_names case maybe_list_map of Nothing -> errorMsg "error in patterns..." Just l -> return $ (fresh_names, Map.fromList l) whereToLet :: Exp -> [(Pat,Exp)] -> LiftQ Exp whereToLet exp [] = return exp whereToLet exp list = do (fresh_names, pmap) <- normalizePatInExp $ map fst list let decs'' = map (uncurry ValD) $ zip fresh_names $ map snd list let decs' = map (\(ValD n e) -> ValD n $ mapSubstExp pmap e) decs'' return $ LetE decs' $ CaseE (TupE $ map VarE fresh_names) [Match (TupP $ map fst list) exp] | Build a @'Match'@ out of a TH clause clauseToMatch :: TH.Clause -> LiftQ Match clauseToMatch (TH.Clause pats body decs) = do pats' <- mapM patTHtoAST pats body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ Match (TupP pats') exp | From a list of TH clauses , make a case - distinction wrapped in a clausesToLambda :: [TH.Clause] -> LiftQ Exp clausesToLambda clauses = do pats_length <- clausesLengthPats clauses fresh_names <- mapM newName $ replicate pats_length "x" matches <- mapM clauseToMatch clauses return $ foldr LamE (CaseE (TupE $ map VarE fresh_names) matches) fresh_names expTHtoAST :: TH.Exp -> LiftQ Exp expTHtoAST (TH.VarE v) = return $ VarE v expTHtoAST (TH.ConE n) = return $ ConE n expTHtoAST (TH.LitE l) = litTHtoExpAST l expTHtoAST (TH.AppE e1 e2) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 return $ AppE e1' e2' expTHtoAST (TH.InfixE (Just e1) e2 (Just e3)) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 return $ AppE (AppE e2' e1') e3' expTHtoAST (TH.InfixE Nothing e2 (Just e3)) = do e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 n <- newName "x" return $ LamE n $ AppE (AppE e2' (VarE n)) e3' expTHtoAST (TH.InfixE (Just e1) e2 Nothing) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 return $ AppE e2' e1' expTHtoAST (TH.InfixE Nothing e2 Nothing) = do e2' <- expTHtoAST e2 return e2' expTHtoAST (TH.LamE pats exp) = clausesToLambda [TH.Clause pats (TH.NormalB exp) []] expTHtoAST (TH.TupE exps) = do exps' <- mapM expTHtoAST exps return (TupE exps') expTHtoAST (TH.CondE e1 e2 e3) = do e1' <- expTHtoAST e1 e2' <- expTHtoAST e2 e3' <- expTHtoAST e3 return $ CondE e1' e2' e3' expTHtoAST (TH.LetE decs exp) = do decs' <- mapM decTHtoAST decs exp' <- expTHtoAST exp whereToLet exp' decs' expTHtoAST (TH.CaseE exp matches) = do exp' <- expTHtoAST exp matches' <- mapM matchTHtoAST matches return $ CaseE exp' matches' expTHtoAST (TH.ListE exps) = do exps' <- mapM expTHtoAST exps return $ ListE exps' expTHtoAST (TH.SigE e _) = expTHtoAST e expTHtoAST x = errorMsg ("lifting not handled for " ++ (show x)) matchTHtoAST :: TH.Match -> LiftQ Match matchTHtoAST (TH.Match pat body decs) = do pat' <- patTHtoAST pat body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ Match pat' exp bodyTHtoAST :: TH.Body -> LiftQ Exp bodyTHtoAST (TH.NormalB exp) = expTHtoAST exp bodyTHtoAST (TH.GuardedB x) = errorMsg ("guarded body not allowed in lifting: " ++ (show x)) patTHtoAST :: TH.Pat -> LiftQ Pat patTHtoAST (TH.LitP l) = litTHtoPatAST l patTHtoAST (TH.VarP n) = return $ VarP n patTHtoAST (TH.TupP pats) = do pats' <- mapM patTHtoAST pats; return $ TupP pats' patTHtoAST (TH.WildP) = return WildP patTHtoAST (TH.ListP pats) = do pats' <- mapM patTHtoAST pats; return $ ListP pats' patTHtoAST (TH.ConP n pats) = do pats' <- mapM patTHtoAST pats; return $ ConP n pats' patTHtoAST (TH.InfixP p1 n p2) = do p1' <- patTHtoAST p1 p2' <- patTHtoAST p2 return $ ConP n [p1',p2'] patTHtoAST x = errorMsg ("non-implemented lifting: " ++ (show x)) | Downgrade first - level declarations . firstLevelDecTHtoAST :: TH.Dec -> Maybe (LiftQ Dec) firstLevelDecTHtoAST (TH.FunD name clauses) = Just $ do exp <- clausesToLambda clauses name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp firstLevelDecTHtoAST (TH.ValD (TH.VarP name) body decs) = Just $ do body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp firstLevelDecTHtoAST (TH.ValD _ _ _) = Just $ errorMsg ("only variables and functions can be lifted as first-level declarations") firstLevelDecTHtoAST (TH.SigD _ _) = Nothing firstLevelDecTHtoAST x = Just $ errorMsg ("non-implemented lifting: " ++ (show x)) decTHtoAST :: TH.Dec -> LiftQ (Pat,Exp) decTHtoAST (TH.FunD name clauses) = do exp <- clausesToLambda clauses return $ (VarP name, exp) decTHtoAST (TH.ValD pat body decs) = do pat' <- patTHtoAST pat body' <- bodyTHtoAST body decs' <- mapM decTHtoAST decs exp <- whereToLet body' decs' return $ (pat', exp) decTHtoAST x = errorMsg ("non-implemented lifting: " ++ (show x)) typReturnE :: LiftQ TH.Type typReturnE = do m_string <- getMonadName let m = TH.conT (mkName m_string) embedQ [t| forall x. x -> $(m) x |] typMAppE :: LiftQ TH.Type typMAppE = do m_string <- getMonadName let m = TH.conT (mkName m_string) embedQ [t| forall x y. $(m) x -> (x -> $(m) y) -> $(m) y |] litASTtoTH :: Lit -> TH.Lit litASTtoTH (CharL c) = TH.CharL c litASTtoTH (IntegerL i) = TH.IntegerL i litASTtoTH (RationalL r) = TH.RationalL r patASTtoTH :: Pat -> TH.Pat patASTtoTH (LitP l) = TH.LitP $ litASTtoTH l patASTtoTH (VarP n) = TH.VarP n patASTtoTH (TupP pats) = TH.TupP $ map patASTtoTH pats patASTtoTH WildP = TH.WildP patASTtoTH (ListP pats) = TH.ListP $ map patASTtoTH pats patASTtoTH (ConP n pats) = TH.ConP n $ map patASTtoTH pats matchASTtoTH :: Match -> LiftQ TH.Match matchASTtoTH (Match p b) = do exp <- expASTtoTH b return $ TH.Match (patASTtoTH p) (TH.NormalB exp) [] decASTtoTH :: Dec -> LiftQ TH.Dec decASTtoTH (ValD n b) = do exp <- expASTtoTH b return $ TH.ValD (TH.VarP n) (TH.NormalB exp) [] expASTtoTH :: Exp -> LiftQ TH.Exp expASTtoTH (VarE n) = return $ TH.VarE n expASTtoTH (ConE n) = return $ TH.ConE n expASTtoTH (LitE l) = return $ TH.LitE $ litASTtoTH l expASTtoTH (AppE e1 e2) = do e1' <- expASTtoTH e1 e2' <- expASTtoTH e2 return $ TH.AppE e1' e2' expASTtoTH (LamE n e) = do e' <- expASTtoTH e return $ TH.LamE [TH.VarP n] e' expASTtoTH (TupE exps) = do exps' <- mapM expASTtoTH exps return $ TH.TupE exps' expASTtoTH (CondE e1 e2 e3) = do e1' <- expASTtoTH e1 e2' <- expASTtoTH e2 e3' <- expASTtoTH e3 return $ TH.CondE e1' e2' e3' expASTtoTH (LetE decs e) = do decs' <- mapM decASTtoTH decs e' <- expASTtoTH e return $ TH.LetE decs' e' expASTtoTH (CaseE e matches) = do e' <- expASTtoTH e m' <- mapM matchASTtoTH matches return $ TH.CaseE e' m' expASTtoTH (ListE exps) = do exps' <- mapM expASTtoTH exps return $ TH.ListE exps' expASTtoTH ReturnE = do t <- typReturnE maybe_r <- embedQ $ TH.lookupValueName "return" case maybe_r of Just r -> return $ TH.SigE (TH.VarE r) t Nothing -> errorMsg "\'return\' undefined" expASTtoTH MAppE = do t <- typMAppE maybe_a <- embedQ $ TH.lookupValueName ">>=" case maybe_a of Just a -> return $ TH.SigE (TH.VarE a) t Nothing -> errorMsg "\'>>=\' undefined" * Lifting AST terms ( into AST terms ) liftIntegerL :: Exp liftIntegerL = VarE $ mkName "template_integer" liftRationalL :: Exp liftRationalL = VarE $ mkName "template_rational" liftLitAST :: Lit -> LiftQ Exp liftLitAST (CharL c) = return (AppE ReturnE (LitE $ CharL c)) liftLitAST (IntegerL i) = return $ AppE liftIntegerL (LitE $ IntegerL i) liftLitAST (RationalL r) = return $ AppE liftRationalL (LitE $ RationalL r) liftPatAST :: Pat -> LiftQ Pat liftPatAST pat = return pat liftMatchAST :: Match -> LiftQ Match liftMatchAST (Match pat exp) = do exp' <- liftExpAST exp return $ Match pat exp' liftDecAST :: Dec -> LiftQ Dec liftDecAST (ValD name exp) = do exp' <- liftExpAST exp return $ ValD name exp' | Lifting first - level declarations . liftFirstLevelDecAST :: Dec -> LiftQ Dec liftFirstLevelDecAST (ValD name exp) = withBoundVar name $ do exp' <- liftExpAST exp return $ ValD name exp' liftExpAST :: Exp -> LiftQ Exp liftExpAST (VarE x) = do template_name <- lookForTemplate x case template_name of Nothing -> do b <- isBoundVar x if b then return $ VarE x else return $ AppE ReturnE $ VarE x Just t -> return $ VarE t liftExpAST (ConE n) = do template_name <- lookForTemplate n case template_name of Nothing -> do t <- templateString $ TH.nameBase n errorMsg ("variable " ++ t ++ " undefined") Just t -> return $ VarE t liftExpAST (LitE l) = liftLitAST l liftExpAST (AppE e1 e2) = do e1' <- liftExpAST e1 e2' <- liftExpAST e2 n1 <- newName "app1" n2 <- newName "app2" return $ doE [BindS n1 e1', BindS n2 e2'] $ AppE (VarE n1) (VarE n2) liftExpAST (LamE n exp) = do exp' <- liftExpAST exp return $ AppE ReturnE $ LamE n exp' liftExpAST (TupE exps) = do exps' <- mapM liftExpAST exps fresh_names <- mapM newName $ replicate (length exps) "tupe" return $ doE (map (uncurry BindS) $ zip fresh_names exps') (AppE ReturnE $ TupE $ map VarE fresh_names) liftExpAST (CondE e1 e2 e3) = do e1' <- liftExpAST e1 e2' <- liftExpAST e2 e3' <- liftExpAST e3 return $ AppE (AppE (AppE (VarE (mkName "template_if")) (e1')) (e2')) (e3') liftExpAST (LetE decs exp) = let existing_names = map (\(ValD n _) -> n) decs in withBoundVars existing_names $ do decs' <- mapM liftDecAST decs exp' <- liftExpAST exp return $ LetE decs' exp' liftExpAST (CaseE exp matches) = do exp' <- liftExpAST exp matches' <- mapM liftMatchAST matches fresh_name <- newName "case" return $ doE [BindS fresh_name exp'] $ CaseE (VarE fresh_name) matches' liftExpAST (ListE exps) = do exps' <- mapM liftExpAST exps fresh_names <- mapM newName $ replicate (length exps) "liste" return $ doE (map (uncurry BindS) $ zip fresh_names exps') $ AppE ReturnE $ ListE $ map VarE fresh_names These two are not supposed to be there ! liftExpAST ReturnE = undefined liftExpAST MAppE = undefined makeDecTemplate :: Dec -> LiftQ Dec makeDecTemplate (ValD name exp) = do name' <- makeTemplateName name return $ ValD name' $ substExp name (VarE name') exp | pretty - printing Template Haskell declarations . prettyPrintAST :: TH.Q [TH.Dec] -> IO () prettyPrintAST x = prettyPrint $ do x' <- embedQ x y <- sequence $ catMaybes $ map firstLevelDecTHtoAST x' mapM decASTtoTH y | Pretty - printing Template Haskell expressions . prettyPrintLiftExpTH :: TH.Q (TH.Exp) -> IO () prettyPrintLiftExpTH x = prettyPrint $ do x' <- embedQ x y <- expTHtoAST x' z <- liftExpAST y expASTtoTH z prettyPrintLiftExpAST :: LiftQ (Exp) -> IO () prettyPrintLiftExpAST x = prettyPrint $ do z <- x z' <- liftExpAST z expASTtoTH z' | Lift a list of declarations . The first argument is the name of decToMonad :: String -> TH.Q [TH.Dec] -> TH.Q [TH.Dec] decToMonad s x = extractQ "decToMonad: " $ do setMonadName s setPrefix "template_" dec <- embedQ x decAST <- sequence $ catMaybes $ map firstLevelDecTHtoAST dec liftedAST <- mapM liftFirstLevelDecAST decAST mapM decASTtoTH liftedAST | Lift an expression . The first argument is the name of the monad expToMonad :: String -> TH.Q TH.Exp -> TH.Q TH.Exp expToMonad s x = extractQ "expToMonad: " $ do setMonadName s setPrefix "template_" dec <- embedQ x decAST <- expTHtoAST dec liftedAST <- liftExpAST decAST expASTtoTH liftedAST
9f5cf4d498a4d5bf3fb71e18925d82fdc8f0951317944b9063c0a142646c2c98
haskell-effectful/tracing-effectful
Tracing.hs
# LANGUAGE UndecidableInstances # # OPTIONS_GHC -Wno - orphans # module Effectful.Tracing ( -- * Effect Tracing , MonadTrace (..) -- * Handlers , runTrace -- * Functions , rootSpan , childSpan , clientSpan , clientSpanWith , serverSpan , serverSpanWith , producerSpanWith , consumerSpanWith , tag , annotate , annotateAt ) where import Control.Monad.Trace import Effectful import Effectful.Dispatch.Static import Monitor.Tracing data Tracing :: Effect type instance DispatchOf Tracing = Static WithSideEffects newtype instance StaticRep Tracing = Tracing () runTrace :: IOE :> es => Eff (Tracing : es) a -> Tracer -> Eff es a runTrace action tracer = evalStaticRep (Tracing ()) ---------------------------------------- -- Orphan instance deriving via (TraceT m) instance Tracing :> es => MonadTrace (Eff es)
null
https://raw.githubusercontent.com/haskell-effectful/tracing-effectful/3a3204393d31a43c626e7c8bed9282f1e3071e20/src/Effectful/Tracing.hs
haskell
* Effect * Handlers * Functions -------------------------------------- Orphan instance
# LANGUAGE UndecidableInstances # # OPTIONS_GHC -Wno - orphans # module Effectful.Tracing Tracing , MonadTrace (..) , runTrace , rootSpan , childSpan , clientSpan , clientSpanWith , serverSpan , serverSpanWith , producerSpanWith , consumerSpanWith , tag , annotate , annotateAt ) where import Control.Monad.Trace import Effectful import Effectful.Dispatch.Static import Monitor.Tracing data Tracing :: Effect type instance DispatchOf Tracing = Static WithSideEffects newtype instance StaticRep Tracing = Tracing () runTrace :: IOE :> es => Eff (Tracing : es) a -> Tracer -> Eff es a runTrace action tracer = evalStaticRep (Tracing ()) deriving via (TraceT m) instance Tracing :> es => MonadTrace (Eff es)
ccbdf184b708c44ca0355ca5a5f9910b8e0240176dfc40a5f804c8b2e3fa947c
qnikst/okasaki
ex_2_5a.hs
data Tree a = E | T (Tree a) a (Tree a) deriving (Eq, Show) mkTree :: (Ord a) => a -> Int -> Tree a mkTree x 0 = E mkTree x l = let n = mkTree x (l-1) in T n x n
null
https://raw.githubusercontent.com/qnikst/okasaki/f6f3c4211df16e4dde3a5cb4d6aaf19a68b99b0e/ch02/ex_2_5a.hs
haskell
data Tree a = E | T (Tree a) a (Tree a) deriving (Eq, Show) mkTree :: (Ord a) => a -> Int -> Tree a mkTree x 0 = E mkTree x l = let n = mkTree x (l-1) in T n x n
e78ac4de5eb9e8660e85de38a885f79ff685a854b8e11bb7346bc5ce57d6e05e
Gabriella439/servant-crud
Client.hs
{-# LANGUAGE OverloadedStrings #-} import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Either (runEitherT) import Servant.Crud (API, DeleteFile, GetFile, PutFile) import Servant.Client (BaseUrl(..), Client, Scheme(..), client) import Servant (Proxy(..), (:<|>)(..)) import Turtle (argInt, options) import qualified Data.Text.IO as Text -- | Example use of autogenerated `API` bindings main :: IO () main = do port <- options "CRUD client" (argInt "port" "The port to connect to") -- Note that you can use `servant` to bind to any web API, not just APIs -- hosted by a `servant` server. For example, here is some code using ` servant ` to create bindings to the Google Translate API : -- -- -translate/blob/master/src/Web/Google/Translate.hs let -- | Autogenerated API binding for the `PutFile` endpoint putFile :: Client PutFile | Autogenerated API binding for the ` GetFile ` endpoint getFile :: Client GetFile | Autogenerated API binding for the ` DeleteFile ` endpoint deleteFile :: Client DeleteFile (putFile :<|> getFile :<|> deleteFile) = client (Proxy :: Proxy API) (BaseUrl Http "localhost" port) e <- runEitherT (do -- This issues a `PUT` request against the `/foo.txt` endpoint with -- a request body of `"Hello, world!"` encoded as JSON -- -- Our server will interpret this as a command to create a file named -- `foo.txt` with the contents `"Hello, world!"` putFile "foo.txt" "Hello, world!" -- This issues a `GET` request against the `/foo.txt` endpoint -- -- Our server will interpret this as a command to fetch the contents of -- the file named `foo.txt` and return a response body containing -- `"Hello, world!"` encoded as JSON txt <- getFile "foo.txt" liftIO (Text.putStrLn txt) -- This issues a `DELETE` request against the `/foo.txt` endpoint -- -- Our server will interpret this as a command to delete the file named -- `foo.txt` deleteFile "foo.txt" ) case e of Left err -> print err Right r -> return r
null
https://raw.githubusercontent.com/Gabriella439/servant-crud/ce852827e9ea3d74a8ce18c8996feb577a770979/exec/Client.hs
haskell
# LANGUAGE OverloadedStrings # | Example use of autogenerated `API` bindings Note that you can use `servant` to bind to any web API, not just APIs hosted by a `servant` server. For example, here is some code using -translate/blob/master/src/Web/Google/Translate.hs | Autogenerated API binding for the `PutFile` endpoint This issues a `PUT` request against the `/foo.txt` endpoint with a request body of `"Hello, world!"` encoded as JSON Our server will interpret this as a command to create a file named `foo.txt` with the contents `"Hello, world!"` This issues a `GET` request against the `/foo.txt` endpoint Our server will interpret this as a command to fetch the contents of the file named `foo.txt` and return a response body containing `"Hello, world!"` encoded as JSON This issues a `DELETE` request against the `/foo.txt` endpoint Our server will interpret this as a command to delete the file named `foo.txt`
import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Either (runEitherT) import Servant.Crud (API, DeleteFile, GetFile, PutFile) import Servant.Client (BaseUrl(..), Client, Scheme(..), client) import Servant (Proxy(..), (:<|>)(..)) import Turtle (argInt, options) import qualified Data.Text.IO as Text main :: IO () main = do port <- options "CRUD client" (argInt "port" "The port to connect to") ` servant ` to create bindings to the Google Translate API : putFile :: Client PutFile | Autogenerated API binding for the ` GetFile ` endpoint getFile :: Client GetFile | Autogenerated API binding for the ` DeleteFile ` endpoint deleteFile :: Client DeleteFile (putFile :<|> getFile :<|> deleteFile) = client (Proxy :: Proxy API) (BaseUrl Http "localhost" port) e <- runEitherT (do putFile "foo.txt" "Hello, world!" txt <- getFile "foo.txt" liftIO (Text.putStrLn txt) deleteFile "foo.txt" ) case e of Left err -> print err Right r -> return r
02c471bf6dc113564573f5966d158ec07e085915058aa45409d5a487facb4980
Kalimehtar/gtk-cffi
accel-label.lisp
;;; ;;; accel-label.lisp -- GtkAccelLabel ;;; Copyright ( C ) 2012 , < > ;;; (in-package :gtk-cffi) (defclass accel-label (label) ()) (defcfun gtk-accel-label-new :pointer (text :string)) (defmethod gconstructor ((accel-label accel-label) &key text) (gtk-accel-label-new text)) (defslots accel-label accel-widget pobject) (deffuns accel-label (:set accel-closure :pointer) (:get accel-width :uint) (refetch :boolean)) (init-slots accel-label)
null
https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/accel-label.lisp
lisp
accel-label.lisp -- GtkAccelLabel
Copyright ( C ) 2012 , < > (in-package :gtk-cffi) (defclass accel-label (label) ()) (defcfun gtk-accel-label-new :pointer (text :string)) (defmethod gconstructor ((accel-label accel-label) &key text) (gtk-accel-label-new text)) (defslots accel-label accel-widget pobject) (deffuns accel-label (:set accel-closure :pointer) (:get accel-width :uint) (refetch :boolean)) (init-slots accel-label)
1af0761149c1772155ec174fe488d0ebd26f2997333585d8d542fdcf382157d8
AbstractMachinesLab/caramel
appendable_list.mli
(** Appendable lists: concatenation takes O(1) time, conversion to a list takes O(n). *) type 'a t val empty : 'a t val singleton : 'a -> 'a t val ( @ ) : 'a t -> 'a t -> 'a t val to_list : 'a t -> 'a list
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/vendor/stdune/appendable_list.mli
ocaml
* Appendable lists: concatenation takes O(1) time, conversion to a list takes O(n).
type 'a t val empty : 'a t val singleton : 'a -> 'a t val ( @ ) : 'a t -> 'a t -> 'a t val to_list : 'a t -> 'a list
728fe4912ed63e37503963955f4c0016debc4ed152b5b5009d14f77c394d5cda
jonsterling/dreamtt
Equate.ml
open Basis open Syntax open Effect exception UnequalTypes exception UnequalTerms exception Impossible exception Todo open Monad.Notation (L) let guard m = let* thy = L.theory in match Logic.consistency thy with | `Inconsistent -> L.ret () | `Consistent -> m let gfam_to_gtele gbase lfam env = GTlCons (gbase, LTlCons (lfam, LTlNil), env) let rec equate_gtp : gtp -> gtp -> unit L.m = fun gtp0 gtp1 -> guard @@ let* gtp0 = L.global @@ Eval.whnf_tp gtp0 in let* gtp1 = L.global @@ Eval.whnf_tp gtp0 in match gtp0, gtp1 with | GBool, GBool -> L.ret () | GPi (gbase0, lfam0, env0), GPi (gbase1, lfam1, env1) -> let gtl0 = gfam_to_gtele gbase0 lfam0 env0 in let gtl1 = gfam_to_gtele gbase1 lfam1 env1 in equate_gtele gtl0 gtl1 | GRcdTp (lbls0, gtl0), GRcdTp (lbls1, gtl1) when lbls0 = lbls1 -> equate_gtele gtl0 gtl1 | _ -> L.throw UnequalTypes and equate_gtele : gtele -> gtele -> unit L.m = fun gtl0 gtl1 -> guard @@ match gtl0, gtl1 with | GTlNil, GTlNil -> L.ret () | GTlCons (gtp0, ltl0, env0), GTlCons (gtp1, ltl1, env1) -> let gfib env gtp ltl = L.global @@ G.local env @@ L.bind_tm gtp @@ fun _ -> Eval.eval_tele ltl in let* gfib0 = gfib env0 gtp0 ltl0 in let* gfib1 = gfib env1 gtp1 ltl1 in equate_gtele gfib0 gfib1 | _ -> L.throw UnequalTypes and equate_gtm : gtp -> gtm -> gtm -> unit L.m = fun gtp gtm0 gtm1 -> L.global @@ Eval.whnf_tp gtp |>> function | GPi (gbase, lfam, env) -> equate_fun gbase lfam env gtm0 gtm1 | GRcdTp (lbls, gtl) -> equate_rcd lbls gtl gtm0 gtm1 | GBool -> equate_base gtm0 gtm1 | GAbortTp -> L.ret () and equate_base gtm0 gtm1 = let* gtm0 = L.global @@ Eval.whnf gtm0 in let* gtm1 = L.global @@ Eval.whnf gtm1 in match gtm0, gtm1 with | GTt, GTt | GFf, GFf -> L.ret () | Glued _, Glued _ -> raise Todo | _ -> raise UnequalTerms and equate_fun gbase lfam env gf0 gf1 = L.bind_tm gbase @@ fun var -> let* gv0 = L.global @@ Eval.gapp gf0 var in let* gv1 = L.global @@ Eval.gapp gf1 var in let* gfib = L.global @@ G.local env @@ L.append_tm var @@ Eval.eval_tp lfam in equate_gtm gfib gv0 gv1 and equate_rcd lbls gtl gr0 gr1 = let rec loop lbls gtl = match lbls, gtl with | [], GTlNil -> L.ret () | lbl::lbls, GTlCons (gbase, ltl, env) -> let* gv0 = L.global @@ Eval.gproj lbl gr0 in let* gv1 = L.global @@ Eval.gproj lbl gr1 in let* () = equate_gtm gbase gv0 gv1 in let* gfib = L.global @@ G.local env @@ L.append_tm gv0 @@ Eval.eval_tele ltl in loop lbls gfib | _ -> L.throw Impossible in loop lbls gtl
null
https://raw.githubusercontent.com/jonsterling/dreamtt/aa30a57ca869e91a295e586773a892c6601b5ddb/core/Equate.ml
ocaml
open Basis open Syntax open Effect exception UnequalTypes exception UnequalTerms exception Impossible exception Todo open Monad.Notation (L) let guard m = let* thy = L.theory in match Logic.consistency thy with | `Inconsistent -> L.ret () | `Consistent -> m let gfam_to_gtele gbase lfam env = GTlCons (gbase, LTlCons (lfam, LTlNil), env) let rec equate_gtp : gtp -> gtp -> unit L.m = fun gtp0 gtp1 -> guard @@ let* gtp0 = L.global @@ Eval.whnf_tp gtp0 in let* gtp1 = L.global @@ Eval.whnf_tp gtp0 in match gtp0, gtp1 with | GBool, GBool -> L.ret () | GPi (gbase0, lfam0, env0), GPi (gbase1, lfam1, env1) -> let gtl0 = gfam_to_gtele gbase0 lfam0 env0 in let gtl1 = gfam_to_gtele gbase1 lfam1 env1 in equate_gtele gtl0 gtl1 | GRcdTp (lbls0, gtl0), GRcdTp (lbls1, gtl1) when lbls0 = lbls1 -> equate_gtele gtl0 gtl1 | _ -> L.throw UnequalTypes and equate_gtele : gtele -> gtele -> unit L.m = fun gtl0 gtl1 -> guard @@ match gtl0, gtl1 with | GTlNil, GTlNil -> L.ret () | GTlCons (gtp0, ltl0, env0), GTlCons (gtp1, ltl1, env1) -> let gfib env gtp ltl = L.global @@ G.local env @@ L.bind_tm gtp @@ fun _ -> Eval.eval_tele ltl in let* gfib0 = gfib env0 gtp0 ltl0 in let* gfib1 = gfib env1 gtp1 ltl1 in equate_gtele gfib0 gfib1 | _ -> L.throw UnequalTypes and equate_gtm : gtp -> gtm -> gtm -> unit L.m = fun gtp gtm0 gtm1 -> L.global @@ Eval.whnf_tp gtp |>> function | GPi (gbase, lfam, env) -> equate_fun gbase lfam env gtm0 gtm1 | GRcdTp (lbls, gtl) -> equate_rcd lbls gtl gtm0 gtm1 | GBool -> equate_base gtm0 gtm1 | GAbortTp -> L.ret () and equate_base gtm0 gtm1 = let* gtm0 = L.global @@ Eval.whnf gtm0 in let* gtm1 = L.global @@ Eval.whnf gtm1 in match gtm0, gtm1 with | GTt, GTt | GFf, GFf -> L.ret () | Glued _, Glued _ -> raise Todo | _ -> raise UnequalTerms and equate_fun gbase lfam env gf0 gf1 = L.bind_tm gbase @@ fun var -> let* gv0 = L.global @@ Eval.gapp gf0 var in let* gv1 = L.global @@ Eval.gapp gf1 var in let* gfib = L.global @@ G.local env @@ L.append_tm var @@ Eval.eval_tp lfam in equate_gtm gfib gv0 gv1 and equate_rcd lbls gtl gr0 gr1 = let rec loop lbls gtl = match lbls, gtl with | [], GTlNil -> L.ret () | lbl::lbls, GTlCons (gbase, ltl, env) -> let* gv0 = L.global @@ Eval.gproj lbl gr0 in let* gv1 = L.global @@ Eval.gproj lbl gr1 in let* () = equate_gtm gbase gv0 gv1 in let* gfib = L.global @@ G.local env @@ L.append_tm gv0 @@ Eval.eval_tele ltl in loop lbls gfib | _ -> L.throw Impossible in loop lbls gtl