_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
696f53670676892fd09873bc731993200a036d5b6c5bd1e7ba1877da39d7b465
eugeneia/athens
stylesheet.lisp
;;; stylesheet.lisp ;;; ;;; This file is part of the cl-libxml2 library, released under Lisp-LGPL. ;;; See file COPYING for details. ;;; Author : < > (in-package #:libxml2.xslt) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; stylesheet ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass stylesheet (libxml2.tree::libxml2-cffi-object-wrapper) ((params :initform nil))) (define-libxml2-function ("xsltFreeStylesheet" %xsltFreeStylesheet) :void (style %xsltStylesheetPtr)) (defmethod libxml2.tree::release/impl ((style stylesheet)) (%xsltFreeStylesheet (pointer style))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; stylesheet-set-param ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun stylesheet-set-param (style name value &optional (isstring t)) (unless (slot-value style 'params) (setf (slot-value style 'params) (make-hash-table :test 'equal))) (setf (gethash name (slot-value style 'params)) (if isstring (format nil "\"~A\"" value) value))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; stylesheet-remove-param ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun stylesheet-remove-param (style name) (let ((params (slot-value style 'params))) (if params (remhash name params)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; stylesheet-clear-params ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun stylesheet-clear-params (style) (setf (slot-value style 'params) nil)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; parse-stylesheet ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun parse-stylesheet (obj) (let ((%style (parse-stylesheet/impl obj))) (if %style (make-instance 'stylesheet :pointer %style) (error "This is not stylesheet")))) (defgeneric parse-stylesheet/impl (obj)) ;;; parse-stylehseet ((filename pathname)) (define-libxml2-function ("xsltParseStylesheetFile" %xsltParseStylesheetFile) %xsltStylesheetPtr (filename libxml2.tree::%xmlCharPtr)) (defmethod parse-stylesheet/impl ((filename pathname)) (with-foreign-string (%filename (format nil "~A" filename)) (%xsltParseStylesheetFile %filename))) ;;; parse-stylesheet ((doc document)) (define-libxml2-function ("xsltParseStylesheetDoc" %xsltParseStylesheetDoc) %xsltStylesheetPtr (doc libxml2.tree::%xmlDocPtr)) (defmethod parse-stylesheet/impl ((doc document)) (%xsltParseStylesheetDoc (pointer doc))) ;;; parse-stylesheet (obj) (defmethod parse-stylesheet/impl (obj) (with-garbage-pool () (let* ((doc (object-register (parse obj))) (%style (parse-stylesheet/impl (parse obj)))) (unless (null-pointer-p %style) (progn (cancel-object-cleanup doc) %style))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; with-stylesheet ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro with-stylesheet ((style obj) &body body) `(let ((,style (parse-stylesheet ,obj))) (unwind-protect (progn ,@body) (release ,style)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; defxsl ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro defxsl (var src) (if (boundp (quote var)) (xtree:release var)) `(defparameter ,var (xslt:parse-stylesheet ,src))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; transform ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun prepare-xsl-params (params) (if params (let* ((array-length (1+ (* 2 (hash-table-count params)))) (%array (cleanup-register (foreign-alloc :pointer :count array-length :initial-element (null-pointer)) #'foreign-free))) (iter (for (name value) in-hashtable params) (for i upfrom 0 by 2) (setf (mem-aref %array :pointer i) (cleanup-register (foreign-string-alloc name) #'foreign-string-free)) (setf (mem-aref %array :pointer (1+ i)) (cleanup-register (foreign-string-alloc value) #'foreign-string-free))) %array) (null-pointer))) (define-libxml2-function ("xsltApplyStylesheetUser" %xsltApplyStylesheetUser) libxml2.tree::%xmlDocPtr (style %xsltStylesheetPtr) (doc libxml2.tree::%xmlDocPtr) (args :pointer) (output :pointer) (profile :pointer) (userCtxt %xsltTransformContextPtr)) (defgeneric transform (style obj)) ;;; transform (style (doc document)) (defmethod transform (style (doc document)) (with-garbage-pool () (with-transform-context (%ctxt (style doc)) (libxml2.tree::make-libxml2-cffi-object-wrapper/impl (%xsltApplyStylesheetUser (pointer style) (pointer doc) (prepare-xsl-params (slot-value style 'params)) (null-pointer) (null-pointer) %ctxt) 'document)))) transform ( style ( el node ) ) (defmethod transform (style (el node)) (with-fake-document (doc el) (transform style doc))) ;;; transform (style doc) (defmethod transform (style document) (with-parse-document (doc document) (transform style doc))) ;;; transfomr (path obj) (defmethod transform ((path pathname) (doc document)) (with-stylesheet (style path) (transform style doc))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; with-tranform-result ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmacro with-transform-result ((res (style doc)) &body body) `(let ((,res (transform ,style ,doc))) (unwind-protect (progn ,@body) (release ,res))))
null
https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/cl-libxml2-20130615-git/xslt/stylesheet.lisp
lisp
stylesheet.lisp This file is part of the cl-libxml2 library, released under Lisp-LGPL. See file COPYING for details. stylesheet stylesheet-set-param stylesheet-remove-param stylesheet-clear-params parse-stylesheet parse-stylehseet ((filename pathname)) parse-stylesheet ((doc document)) parse-stylesheet (obj) with-stylesheet defxsl transform transform (style (doc document)) transform (style doc) transfomr (path obj) with-tranform-result
Author : < > (in-package #:libxml2.xslt) (defclass stylesheet (libxml2.tree::libxml2-cffi-object-wrapper) ((params :initform nil))) (define-libxml2-function ("xsltFreeStylesheet" %xsltFreeStylesheet) :void (style %xsltStylesheetPtr)) (defmethod libxml2.tree::release/impl ((style stylesheet)) (%xsltFreeStylesheet (pointer style))) (defun stylesheet-set-param (style name value &optional (isstring t)) (unless (slot-value style 'params) (setf (slot-value style 'params) (make-hash-table :test 'equal))) (setf (gethash name (slot-value style 'params)) (if isstring (format nil "\"~A\"" value) value))) (defun stylesheet-remove-param (style name) (let ((params (slot-value style 'params))) (if params (remhash name params)))) (defun stylesheet-clear-params (style) (setf (slot-value style 'params) nil)) (defun parse-stylesheet (obj) (let ((%style (parse-stylesheet/impl obj))) (if %style (make-instance 'stylesheet :pointer %style) (error "This is not stylesheet")))) (defgeneric parse-stylesheet/impl (obj)) (define-libxml2-function ("xsltParseStylesheetFile" %xsltParseStylesheetFile) %xsltStylesheetPtr (filename libxml2.tree::%xmlCharPtr)) (defmethod parse-stylesheet/impl ((filename pathname)) (with-foreign-string (%filename (format nil "~A" filename)) (%xsltParseStylesheetFile %filename))) (define-libxml2-function ("xsltParseStylesheetDoc" %xsltParseStylesheetDoc) %xsltStylesheetPtr (doc libxml2.tree::%xmlDocPtr)) (defmethod parse-stylesheet/impl ((doc document)) (%xsltParseStylesheetDoc (pointer doc))) (defmethod parse-stylesheet/impl (obj) (with-garbage-pool () (let* ((doc (object-register (parse obj))) (%style (parse-stylesheet/impl (parse obj)))) (unless (null-pointer-p %style) (progn (cancel-object-cleanup doc) %style))))) (defmacro with-stylesheet ((style obj) &body body) `(let ((,style (parse-stylesheet ,obj))) (unwind-protect (progn ,@body) (release ,style)))) (defmacro defxsl (var src) (if (boundp (quote var)) (xtree:release var)) `(defparameter ,var (xslt:parse-stylesheet ,src))) (defun prepare-xsl-params (params) (if params (let* ((array-length (1+ (* 2 (hash-table-count params)))) (%array (cleanup-register (foreign-alloc :pointer :count array-length :initial-element (null-pointer)) #'foreign-free))) (iter (for (name value) in-hashtable params) (for i upfrom 0 by 2) (setf (mem-aref %array :pointer i) (cleanup-register (foreign-string-alloc name) #'foreign-string-free)) (setf (mem-aref %array :pointer (1+ i)) (cleanup-register (foreign-string-alloc value) #'foreign-string-free))) %array) (null-pointer))) (define-libxml2-function ("xsltApplyStylesheetUser" %xsltApplyStylesheetUser) libxml2.tree::%xmlDocPtr (style %xsltStylesheetPtr) (doc libxml2.tree::%xmlDocPtr) (args :pointer) (output :pointer) (profile :pointer) (userCtxt %xsltTransformContextPtr)) (defgeneric transform (style obj)) (defmethod transform (style (doc document)) (with-garbage-pool () (with-transform-context (%ctxt (style doc)) (libxml2.tree::make-libxml2-cffi-object-wrapper/impl (%xsltApplyStylesheetUser (pointer style) (pointer doc) (prepare-xsl-params (slot-value style 'params)) (null-pointer) (null-pointer) %ctxt) 'document)))) transform ( style ( el node ) ) (defmethod transform (style (el node)) (with-fake-document (doc el) (transform style doc))) (defmethod transform (style document) (with-parse-document (doc document) (transform style doc))) (defmethod transform ((path pathname) (doc document)) (with-stylesheet (style path) (transform style doc))) (defmacro with-transform-result ((res (style doc)) &body body) `(let ((,res (transform ,style ,doc))) (unwind-protect (progn ,@body) (release ,res))))
f394b0d36c56d03fc2c96ce7749b22d5f5bbf60993f441f803e160f6acf1efa2
MyDataFlow/ttalk-server
privacy_helper.erl
-module(privacy_helper). -include_lib("exml/include/exml.hrl"). -include_lib("escalus/include/escalus.hrl"). -include_lib("escalus/include/escalus_xmlns.hrl"). -include_lib("common_test/include/ct.hrl"). -import(escalus_compat, [bin/1]). -export([set_and_activate/2, set_list/2, send_set_list/2, activate_list/2, set_default_list/2, privacy_list/1, is_privacy_list_push/1, is_presence_error/1]). %% Sets the list on server and makes it the active one. set_and_activate(Client, ListName) -> set_list(Client, ListName), activate_list(Client, ListName). send_set_list(Client, ListName) -> Stanza = escalus_stanza:privacy_set_list(privacy_list(ListName)), escalus:send(Client, Stanza), Stanza. %% Sets the list on server. set_list(Client, ListName) -> Stanza = send_set_list(Client, ListName), Responses = escalus:wait_for_stanzas(Client, 2), escalus:assert_many([is_iq_result, is_privacy_set], Responses), GetStanza = escalus_stanza:privacy_get_lists([ListName]), escalus:send(Client, GetStanza), GetResultStanza = escalus:wait_for_stanza(Client), escalus:assert(fun does_result_match_request/3, [Stanza, GetStanza], GetResultStanza). does_result_match_request(SetRequest, GetRequest, Result) -> escalus_pred:is_iq_result(GetRequest, Result) andalso does_privacy_list_match(SetRequest, Result). does_privacy_list_match(Request, Result) -> does_privacy_list_name_match(Request, Result) andalso does_privacy_list_children_match(Request, Result). does_privacy_list_name_match(Request, Result) -> NamePath = [{element, <<"query">>}, {element, <<"list">>}, {attr, <<"name">>}], ListName = exml_query:path(Request, NamePath), ListName == exml_query:path(Result, NamePath). does_privacy_list_children_match(Request, Result) -> ChildrenPath = [{element, <<"query">>}, {element, <<"list">>}], RequestChildren = exml_query:subelements(exml_query:path(Request, ChildrenPath), <<"item">>), ResultChildren = exml_query:subelements(exml_query:path(Result, ChildrenPath), <<"item">>), lists:all(fun do_items_match/1, lists:zip(RequestChildren, ResultChildren)). do_items_match({#xmlel{attrs = Props1}, #xmlel{attrs = Props2}}) -> L = [attr_match(Name, Value, Props2) || {Name, Value} <- Props1], lists:all(fun(E) -> true == E end, L). attr_match(<<"value">>, Value, Props) -> ValueL = escalus_utils:jid_to_lower(Value), ValueL == escalus_utils:jid_to_lower(proplists:get_value(<<"value">>, Props)); attr_match(Name, Value, Props) -> Value == proplists:get_value(Name, Props). %% Make the list the active one. activate_list(Client, ListName) -> escalus:send(Client, escalus_stanza:privacy_activate(ListName)), escalus:assert(is_iq_result, escalus:wait_for_stanza(Client)). %% Make the list the default one. set_default_list(Client, ListName) -> escalus:send(Client, escalus_stanza:privacy_set_default(ListName)), escalus:assert(is_iq_result, escalus:wait_for_stanza(Client)). %% Is this iq a notification about a privacy list being changed? is_privacy_list_push(Iq) -> escalus_pred:is_iq(<<"set">>, ?NS_PRIVACY, Iq) andalso undefined /= exml_query:path(Iq, [{element, <<"query">>}, {element, <<"list">>}]). is_presence_error(Stanza) -> escalus_pred:is_presence(Stanza) andalso escalus_pred:is_error(<<"modify">>, <<"not-acceptable">>, Stanza). privacy_list(Name) -> escalus_stanza:privacy_list(Name, list_content(Name)). list_content(<<"deny_bob">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []) ]; list_content(<<"allow_bob">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"allow">>, bob, []) ]; list_content(<<"deny_bob_message">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"message">>]) ]; list_content(<<"deny_group_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"message">>]) ]; list_content(<<"deny_unsubscribed_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"message">>]) ]; list_content(<<"deny_all_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_from">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"from">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_to">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"to">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_both">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"both">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_bob_presence_in">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"presence-in">>]) ]; list_content(<<"deny_group_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"presence-in">>]) ]; list_content(<<"deny_unsubscribed_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"presence-in">>]) ]; list_content(<<"deny_all_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"presence-in">>]) ]; list_content(<<"deny_bob_presence_out">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"presence-out">>]) ]; list_content(<<"deny_group_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"presence-out">>]) ]; list_content(<<"deny_unsubscribed_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"presence-out">>]) ]; list_content(<<"deny_all_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"presence-out">>]) ]; list_content(<<"deny_localhost_iq">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, <<"localhost">>, [<<"iq">>]) ]; list_content(<<"deny_group_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"iq">>]) ]; list_content(<<"deny_unsubscribed_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"iq">>]) ]; list_content(<<"deny_all_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"iq">>]) ]; list_content(<<"deny_jid_all">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []), escalus_stanza:privacy_list_jid_item(<<"2">>, <<"deny">>, <<"localhost">>, []) ]; list_content(<<"deny_group_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, []) ]; list_content(<<"deny_unsubscribed_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, []) ]; list_content(<<"deny_all_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, []) ]; list_content(<<"deny_3_items">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []), escalus_stanza:privacy_list_jid_item(<<"2">>, <<"deny">>, <<"steve@localhost">>, []), escalus_stanza:privacy_list_jid_item(<<"3">>, <<"deny">>, <<"john@localhost">>, []) ].
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/test/ejabberd_tests/tests/privacy_helper.erl
erlang
Sets the list on server and makes it the active one. Sets the list on server. Make the list the active one. Make the list the default one. Is this iq a notification about a privacy list being changed?
-module(privacy_helper). -include_lib("exml/include/exml.hrl"). -include_lib("escalus/include/escalus.hrl"). -include_lib("escalus/include/escalus_xmlns.hrl"). -include_lib("common_test/include/ct.hrl"). -import(escalus_compat, [bin/1]). -export([set_and_activate/2, set_list/2, send_set_list/2, activate_list/2, set_default_list/2, privacy_list/1, is_privacy_list_push/1, is_presence_error/1]). set_and_activate(Client, ListName) -> set_list(Client, ListName), activate_list(Client, ListName). send_set_list(Client, ListName) -> Stanza = escalus_stanza:privacy_set_list(privacy_list(ListName)), escalus:send(Client, Stanza), Stanza. set_list(Client, ListName) -> Stanza = send_set_list(Client, ListName), Responses = escalus:wait_for_stanzas(Client, 2), escalus:assert_many([is_iq_result, is_privacy_set], Responses), GetStanza = escalus_stanza:privacy_get_lists([ListName]), escalus:send(Client, GetStanza), GetResultStanza = escalus:wait_for_stanza(Client), escalus:assert(fun does_result_match_request/3, [Stanza, GetStanza], GetResultStanza). does_result_match_request(SetRequest, GetRequest, Result) -> escalus_pred:is_iq_result(GetRequest, Result) andalso does_privacy_list_match(SetRequest, Result). does_privacy_list_match(Request, Result) -> does_privacy_list_name_match(Request, Result) andalso does_privacy_list_children_match(Request, Result). does_privacy_list_name_match(Request, Result) -> NamePath = [{element, <<"query">>}, {element, <<"list">>}, {attr, <<"name">>}], ListName = exml_query:path(Request, NamePath), ListName == exml_query:path(Result, NamePath). does_privacy_list_children_match(Request, Result) -> ChildrenPath = [{element, <<"query">>}, {element, <<"list">>}], RequestChildren = exml_query:subelements(exml_query:path(Request, ChildrenPath), <<"item">>), ResultChildren = exml_query:subelements(exml_query:path(Result, ChildrenPath), <<"item">>), lists:all(fun do_items_match/1, lists:zip(RequestChildren, ResultChildren)). do_items_match({#xmlel{attrs = Props1}, #xmlel{attrs = Props2}}) -> L = [attr_match(Name, Value, Props2) || {Name, Value} <- Props1], lists:all(fun(E) -> true == E end, L). attr_match(<<"value">>, Value, Props) -> ValueL = escalus_utils:jid_to_lower(Value), ValueL == escalus_utils:jid_to_lower(proplists:get_value(<<"value">>, Props)); attr_match(Name, Value, Props) -> Value == proplists:get_value(Name, Props). activate_list(Client, ListName) -> escalus:send(Client, escalus_stanza:privacy_activate(ListName)), escalus:assert(is_iq_result, escalus:wait_for_stanza(Client)). set_default_list(Client, ListName) -> escalus:send(Client, escalus_stanza:privacy_set_default(ListName)), escalus:assert(is_iq_result, escalus:wait_for_stanza(Client)). is_privacy_list_push(Iq) -> escalus_pred:is_iq(<<"set">>, ?NS_PRIVACY, Iq) andalso undefined /= exml_query:path(Iq, [{element, <<"query">>}, {element, <<"list">>}]). is_presence_error(Stanza) -> escalus_pred:is_presence(Stanza) andalso escalus_pred:is_error(<<"modify">>, <<"not-acceptable">>, Stanza). privacy_list(Name) -> escalus_stanza:privacy_list(Name, list_content(Name)). list_content(<<"deny_bob">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []) ]; list_content(<<"allow_bob">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"allow">>, bob, []) ]; list_content(<<"deny_bob_message">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"message">>]) ]; list_content(<<"deny_group_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"message">>]) ]; list_content(<<"deny_unsubscribed_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"message">>]) ]; list_content(<<"deny_all_message">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_from">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"from">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_to">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"to">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_all_message_but_subscription_both">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"allow">>, <<"subscription">>, <<"both">>, [<<"message">>]), escalus_stanza:privacy_list_item(<<"2">>, <<"deny">>, [<<"message">>]) ]; list_content(<<"deny_bob_presence_in">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"presence-in">>]) ]; list_content(<<"deny_group_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"presence-in">>]) ]; list_content(<<"deny_unsubscribed_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"presence-in">>]) ]; list_content(<<"deny_all_presence_in">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"presence-in">>]) ]; list_content(<<"deny_bob_presence_out">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, [<<"presence-out">>]) ]; list_content(<<"deny_group_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"presence-out">>]) ]; list_content(<<"deny_unsubscribed_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"presence-out">>]) ]; list_content(<<"deny_all_presence_out">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"presence-out">>]) ]; list_content(<<"deny_localhost_iq">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, <<"localhost">>, [<<"iq">>]) ]; list_content(<<"deny_group_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, [<<"iq">>]) ]; list_content(<<"deny_unsubscribed_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, [<<"iq">>]) ]; list_content(<<"deny_all_iq">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, [<<"iq">>]) ]; list_content(<<"deny_jid_all">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []), escalus_stanza:privacy_list_jid_item(<<"2">>, <<"deny">>, <<"localhost">>, []) ]; list_content(<<"deny_group_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"group">>, <<"ignored">>, []) ]; list_content(<<"deny_unsubscribed_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, <<"subscription">>, <<"none">>, []) ]; list_content(<<"deny_all_all">>) -> [ escalus_stanza:privacy_list_item(<<"1">>, <<"deny">>, []) ]; list_content(<<"deny_3_items">>) -> [ escalus_stanza:privacy_list_jid_item(<<"1">>, <<"deny">>, bob, []), escalus_stanza:privacy_list_jid_item(<<"2">>, <<"deny">>, <<"steve@localhost">>, []), escalus_stanza:privacy_list_jid_item(<<"3">>, <<"deny">>, <<"john@localhost">>, []) ].
971096d9f554dd2325c3710225aff94ada2c4500dd62164b1c27c3eb9464ef18
vimus/libmpd-haskell
Database.hs
{-# LANGUAGE OverloadedStrings #-} | Module : Network . MPD.Commands . Database Copyright : ( c ) 2005 - 2009 , 2012 License : MIT ( see LICENSE ) Maintainer : Stability : stable Portability : unportable The music database . Module : Network.MPD.Commands.Database Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2012 License : MIT (see LICENSE) Maintainer : Stability : stable Portability : unportable The music database. -} module Network.MPD.Commands.Database ( count , find , findAdd , list , listAll , listAllInfo , lsInfo , readComments , search , searchAdd , searchAddPl , update , rescan ) where import qualified Network.MPD.Applicative.Internal as A import qualified Network.MPD.Applicative.Database as A import Network.MPD.Commands.Query import Network.MPD.Commands.Types import Network.MPD.Core -- | Count the number of entries matching a query. count :: MonadMPD m => Query -> m Count count = A.runCommand . A.count -- | Search the database for entries exactly matching a query. find :: MonadMPD m => Query -> m [Song] find = A.runCommand . A.find -- | Adds songs matching a query to the current playlist. findAdd :: MonadMPD m => Query -> m () findAdd = A.runCommand . A.findAdd -- | List all tags of the specified type of songs that that satisfy the query. -- -- @since 0.10.0.0 list :: MonadMPD m => Metadata -- ^ Metadata to list -> Query -> m [Value] list m = A.runCommand . A.list m -- | List the songs (without metadata) in a database directory recursively. listAll :: MonadMPD m => Path -> m [Path] listAll = A.runCommand . A.listAll -- | Recursive 'lsInfo'. listAllInfo :: MonadMPD m => Path -> m [LsResult] listAllInfo = A.runCommand . A.listAllInfo -- | Non-recursively list the contents of a database directory. lsInfo :: MonadMPD m => Path -> m [LsResult] lsInfo = A.runCommand . A.lsInfo -- | Read comments from file at path. readComments :: MonadMPD m => Path -> m [(String, String)] readComments = A.runCommand . A.readComments -- | Search the database using case insensitive matching. search :: MonadMPD m => Query -> m [Song] search = A.runCommand . A.search -- | Like 'search' but adds the results to the current playlist. -- -- @since 0.10.0.0 searchAdd :: MonadMPD m => Query -> m () searchAdd = A.runCommand . A.searchAdd -- | Like 'searchAdd' but adds results to the named playlist. -- -- @since 0.10.0.0 searchAddPl :: MonadMPD m => PlaylistName -> Query -> m () searchAddPl pl = A.runCommand . A.searchAddPl pl -- | Update the server's database. -- If no path is given , the whole library will be scanned . Unreadable or -- non-existent paths are silently ignored. -- -- The update job id is returned. update :: MonadMPD m => Maybe Path -> m Integer update = A.runCommand . A.update | Like ' update ' but also rescans unmodified files . rescan :: MonadMPD m => Maybe Path -> m Integer rescan = A.runCommand . A.rescan
null
https://raw.githubusercontent.com/vimus/libmpd-haskell/1ec02deba33ce2a16012d8f0954e648eb4b5c485/src/Network/MPD/Commands/Database.hs
haskell
# LANGUAGE OverloadedStrings # | Count the number of entries matching a query. | Search the database for entries exactly matching a query. | Adds songs matching a query to the current playlist. | List all tags of the specified type of songs that that satisfy the query. @since 0.10.0.0 ^ Metadata to list | List the songs (without metadata) in a database directory recursively. | Recursive 'lsInfo'. | Non-recursively list the contents of a database directory. | Read comments from file at path. | Search the database using case insensitive matching. | Like 'search' but adds the results to the current playlist. @since 0.10.0.0 | Like 'searchAdd' but adds results to the named playlist. @since 0.10.0.0 | Update the server's database. non-existent paths are silently ignored. The update job id is returned.
| Module : Network . MPD.Commands . Database Copyright : ( c ) 2005 - 2009 , 2012 License : MIT ( see LICENSE ) Maintainer : Stability : stable Portability : unportable The music database . Module : Network.MPD.Commands.Database Copyright : (c) Ben Sinclair 2005-2009, Joachim Fasting 2012 License : MIT (see LICENSE) Maintainer : Stability : stable Portability : unportable The music database. -} module Network.MPD.Commands.Database ( count , find , findAdd , list , listAll , listAllInfo , lsInfo , readComments , search , searchAdd , searchAddPl , update , rescan ) where import qualified Network.MPD.Applicative.Internal as A import qualified Network.MPD.Applicative.Database as A import Network.MPD.Commands.Query import Network.MPD.Commands.Types import Network.MPD.Core count :: MonadMPD m => Query -> m Count count = A.runCommand . A.count find :: MonadMPD m => Query -> m [Song] find = A.runCommand . A.find findAdd :: MonadMPD m => Query -> m () findAdd = A.runCommand . A.findAdd list :: MonadMPD m -> Query -> m [Value] list m = A.runCommand . A.list m listAll :: MonadMPD m => Path -> m [Path] listAll = A.runCommand . A.listAll listAllInfo :: MonadMPD m => Path -> m [LsResult] listAllInfo = A.runCommand . A.listAllInfo lsInfo :: MonadMPD m => Path -> m [LsResult] lsInfo = A.runCommand . A.lsInfo readComments :: MonadMPD m => Path -> m [(String, String)] readComments = A.runCommand . A.readComments search :: MonadMPD m => Query -> m [Song] search = A.runCommand . A.search searchAdd :: MonadMPD m => Query -> m () searchAdd = A.runCommand . A.searchAdd searchAddPl :: MonadMPD m => PlaylistName -> Query -> m () searchAddPl pl = A.runCommand . A.searchAddPl pl If no path is given , the whole library will be scanned . Unreadable or update :: MonadMPD m => Maybe Path -> m Integer update = A.runCommand . A.update | Like ' update ' but also rescans unmodified files . rescan :: MonadMPD m => Maybe Path -> m Integer rescan = A.runCommand . A.rescan
14e22bcebdfae6dbb7e090f94641a6fee355b15384e908b71091de3cf0469629
peterhudec/cljsx
main.cljs
(ns shadow-cljs-example.main (:require ["react" :as react] ["react-dom" :as react-dom] [cljsx.core :refer [react> defcomponent]])) (def common-props {:style {:color "olive" :background "honeydew" :borderRadius "0.2em" :padding "0.4em"}}) (react> (defcomponent Button {:keys [title children] :as props} (<button ... common-props ... props :onClick #(js/alert title) > children)) (defn Header [] (<h1 ... common-props > "Hello CLJSX!")) (defcomponent ButtonList {:keys [children]} (<ul> (map #(<li :key % > (<Button :title % :disabled (= % "Bar") > %)) children))) (defn Content [] (<> (<p ... common-props > "Lorem ipsum dolor sit amet") (<ButtonList> "Foo" "Bar" "Baz"))) (defn Footer [] (<h2 ... common-props > "Enjoy!")) (defcomponent App _ (<div :style {:border "3px dashed olive" :padding "2rem" :borderRadius "1rem" :maxWidth "400px" :margin "2rem auto"} > (<Header>) (<Content>) (<Footer>))) (react-dom/render (<App>) (js/document.querySelector "#mount-point")))
null
https://raw.githubusercontent.com/peterhudec/cljsx/3a23dbc085fed0c79d4e865c88ae7da55bdaa789/examples/shadow_cljs_example/main.cljs
clojure
(ns shadow-cljs-example.main (:require ["react" :as react] ["react-dom" :as react-dom] [cljsx.core :refer [react> defcomponent]])) (def common-props {:style {:color "olive" :background "honeydew" :borderRadius "0.2em" :padding "0.4em"}}) (react> (defcomponent Button {:keys [title children] :as props} (<button ... common-props ... props :onClick #(js/alert title) > children)) (defn Header [] (<h1 ... common-props > "Hello CLJSX!")) (defcomponent ButtonList {:keys [children]} (<ul> (map #(<li :key % > (<Button :title % :disabled (= % "Bar") > %)) children))) (defn Content [] (<> (<p ... common-props > "Lorem ipsum dolor sit amet") (<ButtonList> "Foo" "Bar" "Baz"))) (defn Footer [] (<h2 ... common-props > "Enjoy!")) (defcomponent App _ (<div :style {:border "3px dashed olive" :padding "2rem" :borderRadius "1rem" :maxWidth "400px" :margin "2rem auto"} > (<Header>) (<Content>) (<Footer>))) (react-dom/render (<App>) (js/document.querySelector "#mount-point")))
2cf2846708cf6ede18290be1ad66ff902ad3e4b555b09cad7e7657d360fe3d95
racket/macro-debugger
test-setup.rkt
#lang racket/base (require macro-debugger/model/debug) ;; Testing facilities for macro debugger (provide trace/ns trace/t trace/k testing-namespace hide-all-policy hide-none-policy T-policy Tm-policy stx/hide-none stx/hide-all stx/hide-standard stx/hide-T stx/hide-Tm) (define (trace/t expr) (trace/ns expr #f)) (define (trace/k expr) (trace/ns expr #t)) ;; Use just 'expand', not 'expand/compile-time-evals', ;; for test backward compatibility ;; FIXME: add tests that use 'expand/compile-time-evals' (define (trace/ns expr kernel?) (parameterize ((current-namespace (choose-namespace kernel?))) (trace expr expand))) (define (choose-namespace kernel?) (if kernel? kernel-namespace testing-namespace)) (define helper-module '(module helper racket/base (require tests/macro-debugger/helper/helper) (provide (all-from-out tests/macro-debugger/helper/helper)))) (define kernel-namespace (make-base-empty-namespace)) (parameterize ((current-namespace kernel-namespace)) (namespace-require ''#%kernel) (eval '(#%require (for-syntax '#%kernel))) (eval helper-module) (eval '(define-syntaxes (id) (lambda (stx) (cadr (syntax->list stx))))) (eval '(define-syntaxes (Tid) (lambda (stx) (cadr (syntax->list stx))))) (eval '(define-syntaxes (Tlist) (lambda (stx) (datum->syntax (quote-syntax here) (list (quote-syntax list) (cadr (syntax->list stx))))))) (eval '(define-syntaxes (wrong) (lambda (stx) (raise-syntax-error #f "wrong" stx))))) (define testing-namespace (make-base-namespace)) (parameterize ((current-namespace testing-namespace)) (eval '(require scheme/base)) (eval '(require (for-syntax scheme/base))) (eval helper-module) (eval '(require 'helper))) Specialized macro hiding tests (define (stx/hide-policy d policy) (define-values (_steps _binders _uses stx _exn) (parameterize ((macro-policy policy)) (reductions+ d))) stx) (define (stx/hide-none d) (stx/hide-policy d hide-none-policy)) (define (stx/hide-all d) (stx/hide-policy d hide-all-policy)) (define (stx/hide-standard d) (stx/hide-policy d standard-policy)) (define (stx/hide-T d) (stx/hide-policy d T-policy)) (define (stx/hide-Tm d) (stx/hide-policy d Tm-policy)) ;; T hiding policy ;; ALL macros & primitives are hidden EXCEPT those starting with T ( Tlist and ) (define (T-policy id) (or (memq (syntax-e id) '()) (regexp-match #rx"^T" (symbol->string (syntax-e id))))) ;; Tm hiding policy ALL MACROS & primitive tags are hidden EXCEPT those starting with T ( Tlist and ) EXCEPT module (= > # % module - begin gets tagged ) (define (Tm-policy id) (or (memq (syntax-e id) '(module)) (regexp-match #rx"^T" (symbol->string (syntax-e id)))))
null
https://raw.githubusercontent.com/racket/macro-debugger/d4e2325e6d8eced81badf315048ff54f515110d5/macro-debugger/tests/macro-debugger/test-setup.rkt
racket
Testing facilities for macro debugger Use just 'expand', not 'expand/compile-time-evals', for test backward compatibility FIXME: add tests that use 'expand/compile-time-evals' T hiding policy ALL macros & primitives are hidden Tm hiding policy
#lang racket/base (require macro-debugger/model/debug) (provide trace/ns trace/t trace/k testing-namespace hide-all-policy hide-none-policy T-policy Tm-policy stx/hide-none stx/hide-all stx/hide-standard stx/hide-T stx/hide-Tm) (define (trace/t expr) (trace/ns expr #f)) (define (trace/k expr) (trace/ns expr #t)) (define (trace/ns expr kernel?) (parameterize ((current-namespace (choose-namespace kernel?))) (trace expr expand))) (define (choose-namespace kernel?) (if kernel? kernel-namespace testing-namespace)) (define helper-module '(module helper racket/base (require tests/macro-debugger/helper/helper) (provide (all-from-out tests/macro-debugger/helper/helper)))) (define kernel-namespace (make-base-empty-namespace)) (parameterize ((current-namespace kernel-namespace)) (namespace-require ''#%kernel) (eval '(#%require (for-syntax '#%kernel))) (eval helper-module) (eval '(define-syntaxes (id) (lambda (stx) (cadr (syntax->list stx))))) (eval '(define-syntaxes (Tid) (lambda (stx) (cadr (syntax->list stx))))) (eval '(define-syntaxes (Tlist) (lambda (stx) (datum->syntax (quote-syntax here) (list (quote-syntax list) (cadr (syntax->list stx))))))) (eval '(define-syntaxes (wrong) (lambda (stx) (raise-syntax-error #f "wrong" stx))))) (define testing-namespace (make-base-namespace)) (parameterize ((current-namespace testing-namespace)) (eval '(require scheme/base)) (eval '(require (for-syntax scheme/base))) (eval helper-module) (eval '(require 'helper))) Specialized macro hiding tests (define (stx/hide-policy d policy) (define-values (_steps _binders _uses stx _exn) (parameterize ((macro-policy policy)) (reductions+ d))) stx) (define (stx/hide-none d) (stx/hide-policy d hide-none-policy)) (define (stx/hide-all d) (stx/hide-policy d hide-all-policy)) (define (stx/hide-standard d) (stx/hide-policy d standard-policy)) (define (stx/hide-T d) (stx/hide-policy d T-policy)) (define (stx/hide-Tm d) (stx/hide-policy d Tm-policy)) EXCEPT those starting with T ( Tlist and ) (define (T-policy id) (or (memq (syntax-e id) '()) (regexp-match #rx"^T" (symbol->string (syntax-e id))))) ALL MACROS & primitive tags are hidden EXCEPT those starting with T ( Tlist and ) EXCEPT module (= > # % module - begin gets tagged ) (define (Tm-policy id) (or (memq (syntax-e id) '(module)) (regexp-match #rx"^T" (symbol->string (syntax-e id)))))
248b0ef1260bb672b64d7fc8b60a7a83755b3d9bf312db61cfe774176e46dc1b
haskell/ghcide
PositionMapping.hs
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 module Development.IDE.Core.PositionMapping ( PositionMapping(..) , PositionResult(..) , lowerRange , upperRange , positionResultToMaybe , fromCurrentPosition , toCurrentPosition , PositionDelta(..) , addDelta , mkDelta , toCurrentRange , fromCurrentRange , applyChange , zeroMapping -- toCurrent and fromCurrent are mainly exposed for testing , toCurrent , fromCurrent ) where import Control.Monad import qualified Data.Text as T import Language.Haskell.LSP.Types import Data.List -- | Either an exact position, or the range of text that was substituted data PositionResult a = PositionRange -- ^ Fields need to be non-strict otherwise bind is exponential { unsafeLowerRange :: a , unsafeUpperRange :: a } | PositionExact !a deriving (Eq,Ord,Show,Functor) lowerRange :: PositionResult a -> a lowerRange (PositionExact a) = a lowerRange (PositionRange lower _) = lower upperRange :: PositionResult a -> a upperRange (PositionExact a) = a upperRange (PositionRange _ upper) = upper positionResultToMaybe :: PositionResult a -> Maybe a positionResultToMaybe (PositionExact a) = Just a positionResultToMaybe _ = Nothing instance Applicative PositionResult where pure = PositionExact (PositionExact f) <*> a = fmap f a (PositionRange f g) <*> (PositionExact a) = PositionRange (f a) (g a) (PositionRange f g) <*> (PositionRange lower upper) = PositionRange (f lower) (g upper) instance Monad PositionResult where (PositionExact a) >>= f = f a (PositionRange lower upper) >>= f = PositionRange lower' upper' where lower' = lowerRange $ f lower upper' = upperRange $ f upper The position delta is the difference between two versions data PositionDelta = PositionDelta { toDelta :: !(Position -> PositionResult Position) , fromDelta :: !(Position -> PositionResult Position) } fromCurrentPosition :: PositionMapping -> Position -> Maybe Position fromCurrentPosition (PositionMapping pm) = positionResultToMaybe . fromDelta pm toCurrentPosition :: PositionMapping -> Position -> Maybe Position toCurrentPosition (PositionMapping pm) = positionResultToMaybe . toDelta pm -- A position mapping is the difference from the current version to -- a specific version newtype PositionMapping = PositionMapping PositionDelta toCurrentRange :: PositionMapping -> Range -> Maybe Range toCurrentRange mapping (Range a b) = Range <$> toCurrentPosition mapping a <*> toCurrentPosition mapping b fromCurrentRange :: PositionMapping -> Range -> Maybe Range fromCurrentRange mapping (Range a b) = Range <$> fromCurrentPosition mapping a <*> fromCurrentPosition mapping b zeroMapping :: PositionMapping zeroMapping = PositionMapping idDelta | Compose two position mappings . Composes in the same way as function composition ( ie the second argument is applyed to the position first ) . composeDelta :: PositionDelta -> PositionDelta -> PositionDelta composeDelta (PositionDelta to1 from1) (PositionDelta to2 from2) = PositionDelta (to1 <=< to2) (from1 >=> from2) idDelta :: PositionDelta idDelta = PositionDelta pure pure -- | Convert a set of changes into a delta from k to k + 1 mkDelta :: [TextDocumentContentChangeEvent] -> PositionDelta mkDelta cs = foldl' applyChange idDelta cs -- | Add a new delta onto a Mapping k n to make a Mapping (k - 1) n addDelta :: PositionDelta -> PositionMapping -> PositionMapping addDelta delta (PositionMapping pm) = PositionMapping (composeDelta delta pm) applyChange :: PositionDelta -> TextDocumentContentChangeEvent -> PositionDelta applyChange PositionDelta{..} (TextDocumentContentChangeEvent (Just r) _ t) = PositionDelta { toDelta = toCurrent r t <=< toDelta , fromDelta = fromDelta <=< fromCurrent r t } applyChange posMapping _ = posMapping toCurrent :: Range -> T.Text -> Position -> PositionResult Position toCurrent (Range start@(Position startLine startColumn) end@(Position endLine endColumn)) t (Position line column) | line < startLine || line == startLine && column < startColumn = -- Position is before the change and thereby unchanged. PositionExact $ Position line column | line > endLine || line == endLine && column >= endColumn = -- Position is after the change so increase line and column number -- as necessary. PositionExact $ newLine `seq` newColumn `seq` Position newLine newColumn | otherwise = PositionRange start end -- Position is in the region that was changed. where lineDiff = linesNew - linesOld linesNew = T.count "\n" t linesOld = endLine - startLine newEndColumn | linesNew == 0 = startColumn + T.length t | otherwise = T.length $ T.takeWhileEnd (/= '\n') t newColumn | line == endLine = column + newEndColumn - endColumn | otherwise = column newLine = line + lineDiff fromCurrent :: Range -> T.Text -> Position -> PositionResult Position fromCurrent (Range start@(Position startLine startColumn) end@(Position endLine endColumn)) t (Position line column) | line < startLine || line == startLine && column < startColumn = -- Position is before the change and thereby unchanged PositionExact $ Position line column | line > newEndLine || line == newEndLine && column >= newEndColumn = -- Position is after the change so increase line and column number -- as necessary. PositionExact $ newLine `seq` newColumn `seq` Position newLine newColumn | otherwise = PositionRange start end -- Position is in the region that was changed. where lineDiff = linesNew - linesOld linesNew = T.count "\n" t linesOld = endLine - startLine newEndLine = endLine + lineDiff newEndColumn | linesNew == 0 = startColumn + T.length t | otherwise = T.length $ T.takeWhileEnd (/= '\n') t newColumn | line == newEndLine = column - (newEndColumn - endColumn) | otherwise = column newLine = line - lineDiff
null
https://raw.githubusercontent.com/haskell/ghcide/3ef4ef99c4b9cde867d29180c32586947df64b9e/src/Development/IDE/Core/PositionMapping.hs
haskell
toCurrent and fromCurrent are mainly exposed for testing | Either an exact position, or the range of text that was substituted ^ Fields need to be non-strict otherwise bind is exponential A position mapping is the difference from the current version to a specific version | Convert a set of changes into a delta from k to k + 1 | Add a new delta onto a Mapping k n to make a Mapping (k - 1) n Position is before the change and thereby unchanged. Position is after the change so increase line and column number as necessary. Position is in the region that was changed. Position is before the change and thereby unchanged Position is after the change so increase line and column number as necessary. Position is in the region that was changed.
Copyright ( c ) 2019 The DAML Authors . All rights reserved . SPDX - License - Identifier : Apache-2.0 module Development.IDE.Core.PositionMapping ( PositionMapping(..) , PositionResult(..) , lowerRange , upperRange , positionResultToMaybe , fromCurrentPosition , toCurrentPosition , PositionDelta(..) , addDelta , mkDelta , toCurrentRange , fromCurrentRange , applyChange , zeroMapping , toCurrent , fromCurrent ) where import Control.Monad import qualified Data.Text as T import Language.Haskell.LSP.Types import Data.List data PositionResult a { unsafeLowerRange :: a , unsafeUpperRange :: a } | PositionExact !a deriving (Eq,Ord,Show,Functor) lowerRange :: PositionResult a -> a lowerRange (PositionExact a) = a lowerRange (PositionRange lower _) = lower upperRange :: PositionResult a -> a upperRange (PositionExact a) = a upperRange (PositionRange _ upper) = upper positionResultToMaybe :: PositionResult a -> Maybe a positionResultToMaybe (PositionExact a) = Just a positionResultToMaybe _ = Nothing instance Applicative PositionResult where pure = PositionExact (PositionExact f) <*> a = fmap f a (PositionRange f g) <*> (PositionExact a) = PositionRange (f a) (g a) (PositionRange f g) <*> (PositionRange lower upper) = PositionRange (f lower) (g upper) instance Monad PositionResult where (PositionExact a) >>= f = f a (PositionRange lower upper) >>= f = PositionRange lower' upper' where lower' = lowerRange $ f lower upper' = upperRange $ f upper The position delta is the difference between two versions data PositionDelta = PositionDelta { toDelta :: !(Position -> PositionResult Position) , fromDelta :: !(Position -> PositionResult Position) } fromCurrentPosition :: PositionMapping -> Position -> Maybe Position fromCurrentPosition (PositionMapping pm) = positionResultToMaybe . fromDelta pm toCurrentPosition :: PositionMapping -> Position -> Maybe Position toCurrentPosition (PositionMapping pm) = positionResultToMaybe . toDelta pm newtype PositionMapping = PositionMapping PositionDelta toCurrentRange :: PositionMapping -> Range -> Maybe Range toCurrentRange mapping (Range a b) = Range <$> toCurrentPosition mapping a <*> toCurrentPosition mapping b fromCurrentRange :: PositionMapping -> Range -> Maybe Range fromCurrentRange mapping (Range a b) = Range <$> fromCurrentPosition mapping a <*> fromCurrentPosition mapping b zeroMapping :: PositionMapping zeroMapping = PositionMapping idDelta | Compose two position mappings . Composes in the same way as function composition ( ie the second argument is applyed to the position first ) . composeDelta :: PositionDelta -> PositionDelta -> PositionDelta composeDelta (PositionDelta to1 from1) (PositionDelta to2 from2) = PositionDelta (to1 <=< to2) (from1 >=> from2) idDelta :: PositionDelta idDelta = PositionDelta pure pure mkDelta :: [TextDocumentContentChangeEvent] -> PositionDelta mkDelta cs = foldl' applyChange idDelta cs addDelta :: PositionDelta -> PositionMapping -> PositionMapping addDelta delta (PositionMapping pm) = PositionMapping (composeDelta delta pm) applyChange :: PositionDelta -> TextDocumentContentChangeEvent -> PositionDelta applyChange PositionDelta{..} (TextDocumentContentChangeEvent (Just r) _ t) = PositionDelta { toDelta = toCurrent r t <=< toDelta , fromDelta = fromDelta <=< fromCurrent r t } applyChange posMapping _ = posMapping toCurrent :: Range -> T.Text -> Position -> PositionResult Position toCurrent (Range start@(Position startLine startColumn) end@(Position endLine endColumn)) t (Position line column) | line < startLine || line == startLine && column < startColumn = PositionExact $ Position line column | line > endLine || line == endLine && column >= endColumn = PositionExact $ newLine `seq` newColumn `seq` Position newLine newColumn | otherwise = PositionRange start end where lineDiff = linesNew - linesOld linesNew = T.count "\n" t linesOld = endLine - startLine newEndColumn | linesNew == 0 = startColumn + T.length t | otherwise = T.length $ T.takeWhileEnd (/= '\n') t newColumn | line == endLine = column + newEndColumn - endColumn | otherwise = column newLine = line + lineDiff fromCurrent :: Range -> T.Text -> Position -> PositionResult Position fromCurrent (Range start@(Position startLine startColumn) end@(Position endLine endColumn)) t (Position line column) | line < startLine || line == startLine && column < startColumn = PositionExact $ Position line column | line > newEndLine || line == newEndLine && column >= newEndColumn = PositionExact $ newLine `seq` newColumn `seq` Position newLine newColumn | otherwise = PositionRange start end where lineDiff = linesNew - linesOld linesNew = T.count "\n" t linesOld = endLine - startLine newEndLine = endLine + lineDiff newEndColumn | linesNew == 0 = startColumn + T.length t | otherwise = T.length $ T.takeWhileEnd (/= '\n') t newColumn | line == newEndLine = column - (newEndColumn - endColumn) | otherwise = column newLine = line - lineDiff
02b58bed7ae8a9c6fcdb98c169c2e348a5a3c36a6aac4934f8032c2cbbb9f329
TrustInSoft/tis-kernel
bottom.mli
(**************************************************************************) (* *) This file is part of . (* *) is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 (* *) is released under GPLv2 (* *) (**************************************************************************) (**************************************************************************) (* *) This file is part of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) * Types , monads and utilitary functions for lattices in which the bottom is managed separately from other values . managed separately from other values. *) module Type : sig type 'a or_bottom = [ `Value of 'a | `Bottom ] (** This monad propagates the `Bottom value if needed. *) val (>>-) : 'a or_bottom -> ('a -> 'b or_bottom) -> 'b or_bottom (** Use this monad if the following function returns a simple value. *) val (>>-:) : 'a or_bottom -> ('a -> 'b) -> 'b or_bottom end include module type of Type val non_bottom: 'a or_bottom -> 'a val equal: ('a -> 'a -> bool) -> 'a or_bottom -> 'a or_bottom -> bool val is_included: ('a -> 'a -> bool) -> 'a or_bottom -> 'a or_bottom -> bool val join: ('a -> 'a -> 'a) -> 'a or_bottom -> 'a or_bottom -> 'a or_bottom val pretty : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a or_bottom -> unit * Datatype constructor . module Make_Datatype (Domain: Datatype.S) : Datatype.S with type t = Domain.t or_bottom (** Bounds a semi-lattice. *) module Bound_Lattice (Lattice: Lattice_type.Join_Semi_Lattice) : Lattice_type.Bounded_Join_Semi_Lattice with type t = Lattice.t or_bottom (** In a lattice where the elements are lists of non-bottom values, the empty list is the bottom case. *) (** Conversion functions. *) val bot_of_list: 'a list -> 'a list or_bottom val list_of_bot: 'a list or_bottom -> 'a list (** [elt >:: list] adds [elt] to the [list] if it is not bottom. *) val add_to_list : 'a or_bottom -> 'a list -> 'a list
null
https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/kernel_services/abstract_interp/bottom.mli
ocaml
************************************************************************ ************************************************************************ ************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ * This monad propagates the `Bottom value if needed. * Use this monad if the following function returns a simple value. * Bounds a semi-lattice. * In a lattice where the elements are lists of non-bottom values, the empty list is the bottom case. * Conversion functions. * [elt >:: list] adds [elt] to the [list] if it is not bottom.
This file is part of . is a fork of Frama - C. All the differences are : Copyright ( C ) 2016 - 2017 is released under GPLv2 This file is part of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . * Types , monads and utilitary functions for lattices in which the bottom is managed separately from other values . managed separately from other values. *) module Type : sig type 'a or_bottom = [ `Value of 'a | `Bottom ] val (>>-) : 'a or_bottom -> ('a -> 'b or_bottom) -> 'b or_bottom val (>>-:) : 'a or_bottom -> ('a -> 'b) -> 'b or_bottom end include module type of Type val non_bottom: 'a or_bottom -> 'a val equal: ('a -> 'a -> bool) -> 'a or_bottom -> 'a or_bottom -> bool val is_included: ('a -> 'a -> bool) -> 'a or_bottom -> 'a or_bottom -> bool val join: ('a -> 'a -> 'a) -> 'a or_bottom -> 'a or_bottom -> 'a or_bottom val pretty : (Format.formatter -> 'a -> unit) -> Format.formatter -> 'a or_bottom -> unit * Datatype constructor . module Make_Datatype (Domain: Datatype.S) : Datatype.S with type t = Domain.t or_bottom module Bound_Lattice (Lattice: Lattice_type.Join_Semi_Lattice) : Lattice_type.Bounded_Join_Semi_Lattice with type t = Lattice.t or_bottom val bot_of_list: 'a list -> 'a list or_bottom val list_of_bot: 'a list or_bottom -> 'a list val add_to_list : 'a or_bottom -> 'a list -> 'a list
41267a8784e36c88bc02ecd863bdc1ea2bac6a9af815927955113beb046d119f
codecov/codecov-racket
info.rkt
#lang setup/infotab (define name "cover-codecov") (define collection 'multi) (define version "0.1.1") (define deps '( ("base" #:version "6.1.1") "cover")) (define build-deps '("rackunit-lib"))
null
https://raw.githubusercontent.com/codecov/codecov-racket/50388b36071d54b2beffc0cfd8ad17cad940f7a8/info.rkt
racket
#lang setup/infotab (define name "cover-codecov") (define collection 'multi) (define version "0.1.1") (define deps '( ("base" #:version "6.1.1") "cover")) (define build-deps '("rackunit-lib"))
4e4f31d70a2ee069524f66bfbb3fbc68ec6f1c97f375ef476b8a8a383bf7b0d0
racket/typed-racket
flonum.rkt
#lang racket/base (module t typed/racket/base/optional ;; Test case-> type (require racket/flonum) (provide flprobability?) (: flprobability? (case-> (Flonum -> Boolean) (Flonum Any -> Boolean))) (define (flprobability? p [log? #f]) (cond [log? (and (p . fl>= . -inf.0) (p . fl<= . 0.0))] [else (and (p . fl>= . 0.0) (p . fl<= . 1.0))]))) (require 't rackunit) (check-not-exn (lambda () (flprobability? 0.5))) (check-exn #rx"fl>=: contract violation" (lambda () (flprobability? "seven")))
null
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/flonum.rkt
racket
Test case-> type
#lang racket/base (module t typed/racket/base/optional (require racket/flonum) (provide flprobability?) (: flprobability? (case-> (Flonum -> Boolean) (Flonum Any -> Boolean))) (define (flprobability? p [log? #f]) (cond [log? (and (p . fl>= . -inf.0) (p . fl<= . 0.0))] [else (and (p . fl>= . 0.0) (p . fl<= . 1.0))]))) (require 't rackunit) (check-not-exn (lambda () (flprobability? 0.5))) (check-exn #rx"fl>=: contract violation" (lambda () (flprobability? "seven")))
037618d0129b0bd5d29ba143e95f027bf82ce23c019c0f7453a61330affaf49b
robert-strandh/SICL
data.lisp
(cl:in-package #:cleavir-ir) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Data. ;;; ;;; Only Common Lisp objects are used as data in the high-level intermediate representation , but they can be BOXED or . ;;; Two kinds of data are possible in the high - level intermediate ;;; representation: ;;; ;;; * CONSTANT-INPUT. This type of data can only be used as input ;;; to instructions. It is used for any Common Lisp object ;;; considered to be literal data. ;;; ;;; * LEXICAL-LOCATION. This type of data can be used both as input ;;; and output to instructions. It holds a single Lisp datum, but that datum can be BOXED or . ;;; An instruction I REFERS TO a lexical location L if and only if L is either one of the inputs or one of the outputs of I. ;;; ;;; A lexical location can be referred to by several different ;;; instructions that belong to procedures at different nesting ;;; depths. Because of the way lexical locations are created, if a lexical location is referred to by two different instructions belonging to two different procedures , P and Q , and neither P is ;;; nested inside Q nor is Q nested inside P, then the lexical ;;; location is also referred to by some instruction belonging to a ;;; procedure C inside which both A and B are nested. ;;; A lexical location L is said to be PRESENT in a procedure P if and only if some instruction belonging to P refers to lexical location L is said to BELONG to a procedure P if L is present in P , and L is not present in a procedure inside which P is nested . ;;; Because of the restriction in the previous paragraph, every ;;; lexical location belongs to some unique procedure. The procedure ;;; P to which a lexical location belongs is called the OWNER of the ;;; lexical location. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class CONSTANT - INPUT . (defclass constant-input (datum) ((%value :initarg :value :reader value))) (defun make-constant-input (value) (make-instance 'constant-input :value value)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class LEXICAL - LOCATION . ;;; ;;; This datum class is used when the initial HIR program is created ;;; for any lexical variable. (defclass lexical-location (datum) ((%name :initarg :name :reader name))) (defun make-lexical-location (name &optional (class 'lexical-location)) (make-instance class :name name)) (defmethod print-object ((object lexical-location) stream) (print-unreadable-object (object stream :type t) (format stream "~a" (name object)))) (defmethod element-type ((object lexical-location)) 't) ;;; Generate a new lexical location (defun new-temporary (&optional (thing nil thing-p) (class 'lexical-location)) (make-lexical-location (if thing-p (gensym thing) (gensym)) class)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class RAW - DATUM . ;;; ;;; This class is the base class for all raw data. It contains a size ;;; attribute that determines the number of bits that this datum ;;; consists of. (defclass raw-datum (lexical-location) ((%size :initarg :size :reader size)) (:default-initargs :name (gensym "RAW"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class RAW - INTEGER . (defclass raw-integer (raw-datum) ()) (defmethod element-type ((raw raw-integer)) 't) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class RAW - FLOAT . (defclass raw-float (raw-datum) ()) (defmethod element-type ((raw raw-float)) 'double-float) Return a class specifier for a subclass of RAW - DATUM which could ;;; store a value of the given type. (defun raw-datum-class-for-type (type) (cond ((member type '(single-float double-float)) 'cleavir-ir:raw-float) ((subtypep type '(or (signed-byte 64) (unsigned-byte 64))) 'cleavir-ir:raw-integer) (t (error "What location class would a ~s fit in?" type)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Datum class IMMEDIATE - INPUT . ;;; ;;; The IMMEDIATE-INPUT datum corresponds to a raw machine interger ;;; that is considered sufficiently small that it can occur directly ;;; in the instruction stream. The machine integer is represented in ;;; the instance as a Lisp integer. The machine integer can represent ;;; some raw numeric information, or it can represent a tagged ;;; immediate Lisp datum such as a fixnum or a character. ;;; ;;; Data of this type are introduced by backend-specific code, ;;; because whether or not some datum can be represented as immediate ;;; input depends on the backend. (defclass immediate-input (datum) ((%value :initarg :value :reader value))) (defun make-immediate-input (value) (make-instance 'immediate-input :value value))
null
https://raw.githubusercontent.com/robert-strandh/SICL/bd3ec8f991d9455541d1629a3c672ae3d46dc16d/Code/Cleavir/Intermediate-representation/HIR/data.lisp
lisp
Data. Only Common Lisp objects are used as data in the high-level representation: * CONSTANT-INPUT. This type of data can only be used as input to instructions. It is used for any Common Lisp object considered to be literal data. * LEXICAL-LOCATION. This type of data can be used both as input and output to instructions. It holds a single Lisp datum, but A lexical location can be referred to by several different instructions that belong to procedures at different nesting depths. Because of the way lexical locations are created, if a nested inside Q nor is Q nested inside P, then the lexical location is also referred to by some instruction belonging to a procedure C inside which both A and B are nested. Because of the restriction in the previous paragraph, every lexical location belongs to some unique procedure. The procedure P to which a lexical location belongs is called the OWNER of the lexical location. This datum class is used when the initial HIR program is created for any lexical variable. Generate a new lexical location This class is the base class for all raw data. It contains a size attribute that determines the number of bits that this datum consists of. store a value of the given type. The IMMEDIATE-INPUT datum corresponds to a raw machine interger that is considered sufficiently small that it can occur directly in the instruction stream. The machine integer is represented in the instance as a Lisp integer. The machine integer can represent some raw numeric information, or it can represent a tagged immediate Lisp datum such as a fixnum or a character. Data of this type are introduced by backend-specific code, because whether or not some datum can be represented as immediate input depends on the backend.
(cl:in-package #:cleavir-ir) intermediate representation , but they can be BOXED or . Two kinds of data are possible in the high - level intermediate that datum can be BOXED or . An instruction I REFERS TO a lexical location L if and only if L is either one of the inputs or one of the outputs of I. lexical location is referred to by two different instructions belonging to two different procedures , P and Q , and neither P is A lexical location L is said to be PRESENT in a procedure P if and only if some instruction belonging to P refers to lexical location L is said to BELONG to a procedure P if L is present in P , and L is not present in a procedure inside which P is nested . Datum class CONSTANT - INPUT . (defclass constant-input (datum) ((%value :initarg :value :reader value))) (defun make-constant-input (value) (make-instance 'constant-input :value value)) Datum class LEXICAL - LOCATION . (defclass lexical-location (datum) ((%name :initarg :name :reader name))) (defun make-lexical-location (name &optional (class 'lexical-location)) (make-instance class :name name)) (defmethod print-object ((object lexical-location) stream) (print-unreadable-object (object stream :type t) (format stream "~a" (name object)))) (defmethod element-type ((object lexical-location)) 't) (defun new-temporary (&optional (thing nil thing-p) (class 'lexical-location)) (make-lexical-location (if thing-p (gensym thing) (gensym)) class)) Datum class RAW - DATUM . (defclass raw-datum (lexical-location) ((%size :initarg :size :reader size)) (:default-initargs :name (gensym "RAW"))) Datum class RAW - INTEGER . (defclass raw-integer (raw-datum) ()) (defmethod element-type ((raw raw-integer)) 't) Datum class RAW - FLOAT . (defclass raw-float (raw-datum) ()) (defmethod element-type ((raw raw-float)) 'double-float) Return a class specifier for a subclass of RAW - DATUM which could (defun raw-datum-class-for-type (type) (cond ((member type '(single-float double-float)) 'cleavir-ir:raw-float) ((subtypep type '(or (signed-byte 64) (unsigned-byte 64))) 'cleavir-ir:raw-integer) (t (error "What location class would a ~s fit in?" type)))) Datum class IMMEDIATE - INPUT . (defclass immediate-input (datum) ((%value :initarg :value :reader value))) (defun make-immediate-input (value) (make-instance 'immediate-input :value value))
a04f06bdae8f08bde96e6a7231ba8cc91804eb519b0c85b7d43391dfa35572c9
eareese/htdp-exercises
207-total-time-list.rkt
#lang htdp/bsl+ ;;--------------------------------------------------------------------------------------------------- (require 2htdp/itunes) (define ITUNES-LOCATION "itunes.xml") LLists (define library (read-itunes-as-lists ITUNES-LOCATION)) (define test-llist (list (list (list "Album" "TNT") (list "Artist" "Tortoise") (list "Name" "Four-Day Interval") (list "Total Time" 285440)) (list (list "Album" "TNT") (list "Artist" "Tortoise") (list "Name" "The Equator") (list "Total Time" 222928)) )) Exercise 207 . Design total - time / list , which consumes an LLists and produces the total amount of play time . Hint Solve exercise 206 first . ;; Once you have completed the design, compute the total play time of your iTunes collection. Compare this result with the time that the total - time function from exercise 200 computes . Why is ;; there a difference? An LLists is one of : ; – '() – ( cons LAssoc LLists ) ; An LAssoc is one of: ; – '() – ( cons Association LAssoc ) ; An Association is a list of two items : ( cons String ( cons BSDN ' ( ) ) ) A BSDN is one of : ; – Boolean ; – Number ; – String ; – Date LLists - > Number consumes an LLists and produces the total amount of play time (check-expect (total-time/list test-llist) (+ 285440 222928)) (check-expect (total-time/list '()) 0) (define (total-time/list llist) (cond [(empty? llist) 0] [else (+ (second (assoc "Total Time" (first llist))) (total-time/list (rest llist)))])) (total-time/list library) 2773511206 a bit over 32 days ( because this list includes podcasts and other non-"Track " media ? )
null
https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part02-arbitrarily-large-data/207-total-time-list.rkt
racket
--------------------------------------------------------------------------------------------------- Once you have completed the design, compute the total play time of your iTunes collection. there a difference? – '() An LAssoc is one of: – '() – Boolean – Number – String – Date
#lang htdp/bsl+ (require 2htdp/itunes) (define ITUNES-LOCATION "itunes.xml") LLists (define library (read-itunes-as-lists ITUNES-LOCATION)) (define test-llist (list (list (list "Album" "TNT") (list "Artist" "Tortoise") (list "Name" "Four-Day Interval") (list "Total Time" 285440)) (list (list "Album" "TNT") (list "Artist" "Tortoise") (list "Name" "The Equator") (list "Total Time" 222928)) )) Exercise 207 . Design total - time / list , which consumes an LLists and produces the total amount of play time . Hint Solve exercise 206 first . Compare this result with the time that the total - time function from exercise 200 computes . Why is An LLists is one of : – ( cons LAssoc LLists ) – ( cons Association LAssoc ) An Association is a list of two items : ( cons String ( cons BSDN ' ( ) ) ) A BSDN is one of : LLists - > Number consumes an LLists and produces the total amount of play time (check-expect (total-time/list test-llist) (+ 285440 222928)) (check-expect (total-time/list '()) 0) (define (total-time/list llist) (cond [(empty? llist) 0] [else (+ (second (assoc "Total Time" (first llist))) (total-time/list (rest llist)))])) (total-time/list library) 2773511206 a bit over 32 days ( because this list includes podcasts and other non-"Track " media ? )
0b3d862f18d21a83d625bb50c9db6c9b453a3c825b1686512a4873f787799436
active-group/active-clojure
record_spec.cljc
(ns active.clojure.record-spec "A re-implementation of `active.clojure.record` that makes use of Clojure's new spec library. Define records the same ways as in the old implementation or use the new syntax to automatically generate specs. If a field has no explicit spec, defaults to `any?`." #?@ (:clj [(:require [active.clojure.condition :as c] [active.clojure.lens :as lens] [active.clojure.macro :refer [if-cljs]] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen])] :cljs [(:require [active.clojure.condition :as c] [cljs.spec.alpha :as s :include-macros true] [cljs.spec.gen.alpha :as gen :include-macros true] [clojure.set :as set]) (:require-macros [active.clojure.macro :refer [if-cljs]])])) (defn throw-illegal-argument-exception [msg] (c/assertion-violation `throw-illegal-argument-exception "Illegal argument" msg)) Only needed in ClojureScript , does nothing in Clojure (defn check-type [type rec] #?(:clj (do)) #?(:cljs (when-not (instance? type rec) (throw (js/Error. (str "Wrong record type passed to accessor." rec type)))))) (defn ns-keyword "Takes a symbol or string `the-name-sym` and returns a namespaced keyword based on that symbol. Example: `(ns-keyword 'foo) => :calling.name.space/foo`" [the-name-sym] (if the-name-sym (keyword (str (ns-name *ns*)) (str the-name-sym)) (c/assertion-violation `ns-keyword "argument must not be nil" the-name-sym))) (defmacro s-def [& args] `(if-cljs (cljs.spec.alpha/def ~@args) (clojure.spec.alpha/def ~@args))) (s-def :active.clojure.record-spec/pass (constantly true)) (defmacro s-fdef [& args] `(if-cljs (cljs.spec.alpha/fdef ~@args) (clojure.spec.alpha/fdef ~@args))) (defmacro s-and [& args] `(if-cljs (cljs.spec.alpha/and ~@args) (clojure.spec.alpha/and ~@args))) (defmacro s-cat [& args] `(if-cljs (cljs.spec.alpha/cat ~@args) (clojure.spec.alpha/cat ~@args))) (defmacro s-spec [& args] `(if-cljs (cljs.spec.alpha/spec ~@args) (clojure.spec.alpha/spec ~@args))) (defmacro s-keys [& args] `(if-cljs (cljs.spec.alpha/keys ~@args) (clojure.spec.alpha/keys ~@args))) (defmacro s-gen [& args] `(if-cljs (cljs.spec.alpha/gen ~@args) (clojure.spec.alpha/gen ~@args))) (defmacro s-fmap [& args] `(if-cljs (cljs.spec.gen.alpha/fmap ~@args) (clojure.spec.gen.alpha/fmap ~@args))) (defmacro s-valid? [& args] `(if-cljs (cljs.spec.alpha/valid? ~@args) (clojure.spec.alpha/valid? ~@args))) #?(:clj (defmacro define-record-type "Attach doc properties to the type and the field names to get reasonable docstrings." [?type ?constructor-call ?predicate ?field-specs & ?opt+specs] (when-not (and (list? ?constructor-call) (not (empty? ?constructor-call))) (throw-illegal-argument-exception (str "constructor call must be a list in " *ns* " " (meta &form)))) (when-not (vector? ?field-specs) (throw-illegal-argument-exception (str "field specs must be a vector in " *ns* " " (meta &form)))) (when-not (even? (count (remove seq? ?field-specs))) (throw-illegal-argument-exception (str "odd number of elements in field specs in " *ns* " " (meta &form)))) (when-not (every? true? (map #(= 3 (count %)) (filter seq? ?field-specs))) (throw-illegal-argument-exception (str "wrong number of elements in field specs with lens in " *ns* " " (meta &form)))) (let [?field-triples (loop [specs (seq ?field-specs) triples '()] (if (empty? specs) (reverse triples) (let [spec (first specs)] (cond (list? spec) (do (when-not (and (= 3 (count spec)) (every? symbol spec)) (IllegalArgumentException. (str "invalid field spec " spec " in " *ns* " " (meta &form)))) (recur (rest specs) (list* spec triples))) (symbol? spec) (do (when (empty? (rest specs)) (throw (IllegalArgumentException. (str "incomplete field spec for " spec " in " *ns* " " (meta &form))))) (when-not (symbol? (fnext specs)) (throw (IllegalArgumentException. (str "invalid accessor " (fnext specs) " for " spec " in " *ns* " " (meta &form))))) (recur (nnext specs) (list* [spec (fnext specs) nil] triples))) :else (throw (IllegalArgumentException. (str "invalid field spec " spec " in " *ns* " " (meta &form)))))))) ?constructor (first ?constructor-call) ?constructor-args (rest ?constructor-call) ?constructor-args-set (set ?constructor-args) document (fn [n doc] (vary-meta n (fn [m] (if (contains? m :doc) m (assoc m :doc doc))))) document-with-arglist (fn [n arglist doc] (vary-meta n (fn [m] (let [m (if (contains? m :doc) m (assoc m :doc doc))] (if (contains? m :arglists) m (assoc m :arglists `'(~arglist))))))) name-doc (fn [field] (if-let [doc (:doc (meta field))] (str " (" doc ")") "")) ?field-names (map first ?field-triples) reference (fn [name] (str "[[" (ns-name *ns*) "/" name "]]")) ?docref (str "See " (reference ?constructor) ".")] (let [?field-names-set (set ?field-names)] (doseq [?constructor-arg ?constructor-args] (when-not (contains? ?field-names-set ?constructor-arg) (throw-illegal-argument-exception (str "constructor argument " ?constructor-arg " is not a field in " *ns* " " (meta &form)))))) `(do (defrecord ~?type [~@(map first ?field-triples)] ~@?opt+specs) (def ~(document-with-arglist ?predicate '[thing] (str "Is object a `" ?type "` record? " ?docref)) (fn [x#] (instance? ~?type x#))) (def ~(document-with-arglist ?constructor (vec ?constructor-args) (str "Construct a `" ?type "`" (name-doc ?type) " record.\n" (apply str (map (fn [[?field ?accessor ?lens]] (str "\n`" ?field "`" (name-doc ?field) ": access via " (reference ?accessor) (if ?lens (str ", lens " (reference ?lens)) ""))) ?field-triples)))) (fn [~@?constructor-args] (new ~?type ~@(map (fn [[?field _]] (if (contains? ?constructor-args-set ?field) `~?field `nil)) ?field-triples)))) (declare ~@(map (fn [[?field ?accessor ?lens]] ?accessor) ?field-triples)) ~@(mapcat (fn [[?field ?accessor ?lens]] (let [?rec (with-meta `rec# {:tag ?type})] `((def ~(document-with-arglist ?accessor (vector ?type) (str "Access `" ?field "` field" (name-doc ?field) " from a [[" ?type "]] record. " ?docref)) (fn [~?rec] (check-type ~?type ~?rec) (. ~?rec ~(symbol (str "-" ?field))))) ~@(if ?lens (let [?data `data# ?v `v#] `((def ~(document ?lens (str "Lens for the `" ?field "` field" (name-doc ?field) " from a [[" ?type "]] record." ?docref)) (lens/lens ~?accessor (fn [~?data ~?v] (~?constructor ~@(map (fn [[?shove-field ?shove-accessor]] (if (= ?field ?shove-field) ?v `(~?shove-accessor ~?data))) ?field-triples))))))))))) ?field-triples) ;; specs ~(letfn [(spec-or-true [?field] (or (:spec (meta ?field)) '(constantly true)))] (let [?field-specs (mapv (fn [[?field _ _]] (ns-keyword (str ?type "-" ?field))) ?field-triples)] ;; Generate a spec for each constructor arg. Uses each constructor arg and prepends the type name + "-" as the name. `(do ~@(mapv (fn [[?field _ _] ?field-spec] `(s-def ~?field-spec ~(spec-or-true ?field))) ?field-triples ?field-specs) (s-def ~(ns-keyword ?type) (s-spec (s-and ~?predicate ~@(mapv (fn [[?field ?accessor _] ?field-spec] `#(s-valid? ~?field-spec (~?accessor %))) ?field-triples ?field-specs)) :gen (fn [] (->> (s-gen (s-keys :req [~@(map #(ns-keyword (str ?type "-" %)) ?constructor-args)])) (s-fmap (fn [ks#] (~(symbol (str "map->" ?type)) (clojure.set/rename-keys ks# ~(into {} (for [constructor-arg ?constructor-args] [(ns-keyword (str ?type "-" constructor-arg)) (keyword constructor-arg)])))))))))) (s-fdef ~?constructor :args (s-cat ~@(apply concat (for [[?field ?spec] (map (fn [constructor-arg] (let [field (first (filter #(= constructor-arg %) (map first ?field-triples)))] [field (spec-or-true field)])) ?constructor-args)] [(keyword ?field) ?spec]))) :ret ~(ns-keyword ?type)) ~@(mapv (fn [[?field ?accessor _]] `(s-fdef ~?accessor :args (s-cat ~(keyword ?type) ~(ns-keyword ?type)) :ret ~(spec-or-true ?field))) ?field-triples))))))))
null
https://raw.githubusercontent.com/active-group/active-clojure/44050a1292fa610dde732d5fbfc42c37ad976d3a/src/active/clojure/record_spec.cljc
clojure
specs Generate a spec for each constructor arg. Uses each constructor arg and prepends the type name + "-" as the name.
(ns active.clojure.record-spec "A re-implementation of `active.clojure.record` that makes use of Clojure's new spec library. Define records the same ways as in the old implementation or use the new syntax to automatically generate specs. If a field has no explicit spec, defaults to `any?`." #?@ (:clj [(:require [active.clojure.condition :as c] [active.clojure.lens :as lens] [active.clojure.macro :refer [if-cljs]] [clojure.spec.alpha :as s] [clojure.spec.gen.alpha :as gen])] :cljs [(:require [active.clojure.condition :as c] [cljs.spec.alpha :as s :include-macros true] [cljs.spec.gen.alpha :as gen :include-macros true] [clojure.set :as set]) (:require-macros [active.clojure.macro :refer [if-cljs]])])) (defn throw-illegal-argument-exception [msg] (c/assertion-violation `throw-illegal-argument-exception "Illegal argument" msg)) Only needed in ClojureScript , does nothing in Clojure (defn check-type [type rec] #?(:clj (do)) #?(:cljs (when-not (instance? type rec) (throw (js/Error. (str "Wrong record type passed to accessor." rec type)))))) (defn ns-keyword "Takes a symbol or string `the-name-sym` and returns a namespaced keyword based on that symbol. Example: `(ns-keyword 'foo) => :calling.name.space/foo`" [the-name-sym] (if the-name-sym (keyword (str (ns-name *ns*)) (str the-name-sym)) (c/assertion-violation `ns-keyword "argument must not be nil" the-name-sym))) (defmacro s-def [& args] `(if-cljs (cljs.spec.alpha/def ~@args) (clojure.spec.alpha/def ~@args))) (s-def :active.clojure.record-spec/pass (constantly true)) (defmacro s-fdef [& args] `(if-cljs (cljs.spec.alpha/fdef ~@args) (clojure.spec.alpha/fdef ~@args))) (defmacro s-and [& args] `(if-cljs (cljs.spec.alpha/and ~@args) (clojure.spec.alpha/and ~@args))) (defmacro s-cat [& args] `(if-cljs (cljs.spec.alpha/cat ~@args) (clojure.spec.alpha/cat ~@args))) (defmacro s-spec [& args] `(if-cljs (cljs.spec.alpha/spec ~@args) (clojure.spec.alpha/spec ~@args))) (defmacro s-keys [& args] `(if-cljs (cljs.spec.alpha/keys ~@args) (clojure.spec.alpha/keys ~@args))) (defmacro s-gen [& args] `(if-cljs (cljs.spec.alpha/gen ~@args) (clojure.spec.alpha/gen ~@args))) (defmacro s-fmap [& args] `(if-cljs (cljs.spec.gen.alpha/fmap ~@args) (clojure.spec.gen.alpha/fmap ~@args))) (defmacro s-valid? [& args] `(if-cljs (cljs.spec.alpha/valid? ~@args) (clojure.spec.alpha/valid? ~@args))) #?(:clj (defmacro define-record-type "Attach doc properties to the type and the field names to get reasonable docstrings." [?type ?constructor-call ?predicate ?field-specs & ?opt+specs] (when-not (and (list? ?constructor-call) (not (empty? ?constructor-call))) (throw-illegal-argument-exception (str "constructor call must be a list in " *ns* " " (meta &form)))) (when-not (vector? ?field-specs) (throw-illegal-argument-exception (str "field specs must be a vector in " *ns* " " (meta &form)))) (when-not (even? (count (remove seq? ?field-specs))) (throw-illegal-argument-exception (str "odd number of elements in field specs in " *ns* " " (meta &form)))) (when-not (every? true? (map #(= 3 (count %)) (filter seq? ?field-specs))) (throw-illegal-argument-exception (str "wrong number of elements in field specs with lens in " *ns* " " (meta &form)))) (let [?field-triples (loop [specs (seq ?field-specs) triples '()] (if (empty? specs) (reverse triples) (let [spec (first specs)] (cond (list? spec) (do (when-not (and (= 3 (count spec)) (every? symbol spec)) (IllegalArgumentException. (str "invalid field spec " spec " in " *ns* " " (meta &form)))) (recur (rest specs) (list* spec triples))) (symbol? spec) (do (when (empty? (rest specs)) (throw (IllegalArgumentException. (str "incomplete field spec for " spec " in " *ns* " " (meta &form))))) (when-not (symbol? (fnext specs)) (throw (IllegalArgumentException. (str "invalid accessor " (fnext specs) " for " spec " in " *ns* " " (meta &form))))) (recur (nnext specs) (list* [spec (fnext specs) nil] triples))) :else (throw (IllegalArgumentException. (str "invalid field spec " spec " in " *ns* " " (meta &form)))))))) ?constructor (first ?constructor-call) ?constructor-args (rest ?constructor-call) ?constructor-args-set (set ?constructor-args) document (fn [n doc] (vary-meta n (fn [m] (if (contains? m :doc) m (assoc m :doc doc))))) document-with-arglist (fn [n arglist doc] (vary-meta n (fn [m] (let [m (if (contains? m :doc) m (assoc m :doc doc))] (if (contains? m :arglists) m (assoc m :arglists `'(~arglist))))))) name-doc (fn [field] (if-let [doc (:doc (meta field))] (str " (" doc ")") "")) ?field-names (map first ?field-triples) reference (fn [name] (str "[[" (ns-name *ns*) "/" name "]]")) ?docref (str "See " (reference ?constructor) ".")] (let [?field-names-set (set ?field-names)] (doseq [?constructor-arg ?constructor-args] (when-not (contains? ?field-names-set ?constructor-arg) (throw-illegal-argument-exception (str "constructor argument " ?constructor-arg " is not a field in " *ns* " " (meta &form)))))) `(do (defrecord ~?type [~@(map first ?field-triples)] ~@?opt+specs) (def ~(document-with-arglist ?predicate '[thing] (str "Is object a `" ?type "` record? " ?docref)) (fn [x#] (instance? ~?type x#))) (def ~(document-with-arglist ?constructor (vec ?constructor-args) (str "Construct a `" ?type "`" (name-doc ?type) " record.\n" (apply str (map (fn [[?field ?accessor ?lens]] (str "\n`" ?field "`" (name-doc ?field) ": access via " (reference ?accessor) (if ?lens (str ", lens " (reference ?lens)) ""))) ?field-triples)))) (fn [~@?constructor-args] (new ~?type ~@(map (fn [[?field _]] (if (contains? ?constructor-args-set ?field) `~?field `nil)) ?field-triples)))) (declare ~@(map (fn [[?field ?accessor ?lens]] ?accessor) ?field-triples)) ~@(mapcat (fn [[?field ?accessor ?lens]] (let [?rec (with-meta `rec# {:tag ?type})] `((def ~(document-with-arglist ?accessor (vector ?type) (str "Access `" ?field "` field" (name-doc ?field) " from a [[" ?type "]] record. " ?docref)) (fn [~?rec] (check-type ~?type ~?rec) (. ~?rec ~(symbol (str "-" ?field))))) ~@(if ?lens (let [?data `data# ?v `v#] `((def ~(document ?lens (str "Lens for the `" ?field "` field" (name-doc ?field) " from a [[" ?type "]] record." ?docref)) (lens/lens ~?accessor (fn [~?data ~?v] (~?constructor ~@(map (fn [[?shove-field ?shove-accessor]] (if (= ?field ?shove-field) ?v `(~?shove-accessor ~?data))) ?field-triples))))))))))) ?field-triples) ~(letfn [(spec-or-true [?field] (or (:spec (meta ?field)) '(constantly true)))] (let [?field-specs (mapv (fn [[?field _ _]] (ns-keyword (str ?type "-" ?field))) ?field-triples)] `(do ~@(mapv (fn [[?field _ _] ?field-spec] `(s-def ~?field-spec ~(spec-or-true ?field))) ?field-triples ?field-specs) (s-def ~(ns-keyword ?type) (s-spec (s-and ~?predicate ~@(mapv (fn [[?field ?accessor _] ?field-spec] `#(s-valid? ~?field-spec (~?accessor %))) ?field-triples ?field-specs)) :gen (fn [] (->> (s-gen (s-keys :req [~@(map #(ns-keyword (str ?type "-" %)) ?constructor-args)])) (s-fmap (fn [ks#] (~(symbol (str "map->" ?type)) (clojure.set/rename-keys ks# ~(into {} (for [constructor-arg ?constructor-args] [(ns-keyword (str ?type "-" constructor-arg)) (keyword constructor-arg)])))))))))) (s-fdef ~?constructor :args (s-cat ~@(apply concat (for [[?field ?spec] (map (fn [constructor-arg] (let [field (first (filter #(= constructor-arg %) (map first ?field-triples)))] [field (spec-or-true field)])) ?constructor-args)] [(keyword ?field) ?spec]))) :ret ~(ns-keyword ?type)) ~@(mapv (fn [[?field ?accessor _]] `(s-fdef ~?accessor :args (s-cat ~(keyword ?type) ~(ns-keyword ?type)) :ret ~(spec-or-true ?field))) ?field-triples))))))))
54c7f183f1bb2c704df7c0780765a630e2e9b0e30d3488bbf718f9b666721d3d
acowley/Frames
TutorialMain.hs
main :: IO () main = return ()
null
https://raw.githubusercontent.com/acowley/Frames/aeca953fe608de38d827b8a078ebf2d329edae04/demo/TutorialMain.hs
haskell
main :: IO () main = return ()
f678ad4605c5f2f76b6a2c3918fa77581aceef9ce8d6d12699a8b52d2f8680ac
deadtrickster/prometheus.erl
prometheus_histogram_tests.erl
-module(prometheus_histogram_tests). -include_lib("eunit/include/eunit.hrl"). -include("prometheus_model.hrl"). prometheus_format_test_() -> {foreach, fun prometheus_eunit_common:start/0, fun prometheus_eunit_common:stop/1, [fun test_registration/1, fun test_errors/1, fun test_buckets/1, fun test_observe/1, fun test_observe_duration_seconds/1, fun test_observe_duration_milliseconds/1, fun test_deregister/1, fun test_remove/1, fun test_default_value/1, fun test_values/1, fun test_collector1/1, fun test_collector2/1, fun test_collector3/1]}. test_registration(_)-> Name = request_duration, SpecWithRegistry = [{name, Name}, {buckets, [100, 300, 500, 750, 1000]}, {help, ""}, {registry, qwe}], [?_assertEqual(true, prometheus_histogram:declare(SpecWithRegistry)), ?_assertError({mf_already_exists, {qwe, Name}, "Consider using declare instead."}, prometheus_histogram:new(SpecWithRegistry))]. test_errors(_) -> prometheus_histogram:new([{name, request_duration}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Track requests duration"}]), prometheus_histogram:new([{name, db_query_duration}, {labels, [repo]}, {help, ""}]), [%% basic name/labels/help validations test ?_assertError({invalid_metric_name, 12, "metric name is not a string"}, prometheus_histogram:new([{name, 12}, {help, ""}])), ?_assertError({invalid_metric_labels, 12, "not list"}, prometheus_histogram:new([{name, "qwe"}, {labels, 12}, {help, ""}])), ?_assertError({invalid_metric_label_name, "le", "histogram cannot have a label named \"le\""}, prometheus_histogram:new([{name, "qwe"}, {labels, ["qwe", "le"]}, {help, ""}])), ?_assertError({invalid_metric_help, 12, "metric help is not a string"}, prometheus_histogram:new([{name, "qwe"}, {help, 12}])), %% mf/arity errors ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:observe(unknown_metric, 1)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:observe(db_query_duration, [repo, db], 1)), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:observe_duration(unknown_metric, fun() -> 1 end)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:observe_duration(db_query_duration, [repo, db], fun() -> 1 end)), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:reset(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:reset(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:value(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:value(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:buckets(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:buckets(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:remove(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:remove(db_query_duration, [repo, db])), %% histogram specific errors ?_assertError({no_buckets, []}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, []}])), ?_assertError({no_buckets, undefined}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, undefined}])), ?_assertError({invalid_buckets, 1, "not a list"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, 1}])), ?_assertError({invalid_bound, "qwe"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, ["qwe"]}])), ?_assertError({invalid_buckets, [1, 3, 2], "buckets not sorted"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, [1, 3, 2]}])), ?_assertError({invalid_value, "qwe", "observe accepts only numbers"}, prometheus_histogram:observe(request_duration, "qwe")), ?_assertError({invalid_value, "qwe", "observe_duration accepts only functions"}, prometheus_histogram:observe_duration(pool_size, "qwe")) ]. test_buckets(_) -> prometheus_histogram:new([{name, "default_buckets"}, {help, ""}]), DefaultBuckets = prometheus_histogram:buckets("default_buckets"), prometheus_histogram:new([{name, http_request_duration_milliseconds}, {labels, [method]}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Http Request execution time"}, {duration_unit, false}]), prometheus_histogram:new([{name, "explicit_default_buckets"}, {help, ""}, {buckets, default}]), ExplicitDefaultBuckets = prometheus_histogram:buckets("explicit_default_buckets"), prometheus_histogram:new([{name, "linear_buckets"}, {help, ""}, {buckets, {linear, -15, 5, 6}}]), LinearBuckets = prometheus_histogram:buckets("linear_buckets"), prometheus_histogram:declare([{name, "exp_buckets"}, {help, ""}, {buckets, {exponential, 100, 1.2, 3}}]), ExpBuckets = prometheus_histogram:buckets("exp_buckets"), CustomBuckets = prometheus_histogram:buckets(http_request_duration_milliseconds, [method]), [?_assertEqual(prometheus_buckets:default() ++ [infinity], DefaultBuckets), ?_assertEqual(prometheus_buckets:default() ++ [infinity], ExplicitDefaultBuckets), ?_assertEqual([100, 300, 500, 750, 1000, infinity], CustomBuckets), ?_assertEqual([-15, -10, -5, 0, 5, 10, infinity], LinearBuckets), ?_assertEqual([100, 120, 144, infinity], ExpBuckets)]. test_observe(_) -> prometheus_histogram:new([{name, http_request_duration_milliseconds}, {labels, [method]}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Http Request execution time"}, {duration_unit, false}]), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 95), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 100), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 102), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 150), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 250), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 75), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 350), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 550), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 950), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 500.2), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 150.4), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 450.5), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 850.3), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 750.9), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 1650.23), Value = prometheus_histogram:value(http_request_duration_milliseconds, [get]), prometheus_histogram:reset(http_request_duration_milliseconds, [get]), RValue = prometheus_histogram:value(http_request_duration_milliseconds, [get]), [?_assertMatch({[3, 4, 2, 2, 3, 1], Sum} when Sum > 6974.5 andalso Sum < 6974.55, Value), ?_assertEqual({[0, 0, 0, 0, 0, 0], 0}, RValue)]. test_observe_duration_seconds(_) -> prometheus_histogram:new([{name, fun_duration_seconds}, {buckets, [0.5, 1.1]}, {help, ""}]), prometheus_histogram:observe_duration(fun_duration_seconds, fun () -> timer:sleep(1000) end), {Buckets, Sum} = prometheus_histogram:value(fun_duration_seconds), try prometheus_histogram:observe_duration(fun_duration_seconds, fun () -> erlang:error({qwe}) end) catch _:_ -> ok end, {BucketsE, SumE} = prometheus_histogram:value(fun_duration_seconds), [MF] = prometheus_collector:collect_mf_to_list(prometheus_histogram), MBuckets = [#'Bucket'{cumulative_count=1, upper_bound=0.5}, #'Bucket'{cumulative_count=2, upper_bound=1.1}, #'Bucket'{cumulative_count=2, upper_bound=infinity}], #'MetricFamily'{metric= [#'Metric'{histogram= #'Histogram'{sample_sum=MFSum, sample_count=MFCount, bucket=MBuckets}}]} = MF, [?_assertEqual([0, 1, 0], Buckets), ?_assertEqual([1, 1, 0], BucketsE), ?_assertEqual(true, 0.9 < Sum andalso Sum < 1.2), ?_assertEqual(true, 0.9 < SumE andalso SumE < 1.2), ?_assertEqual(2, MFCount), ?_assertEqual(true, 0.9 < MFSum andalso MFSum < 1.2)]. test_observe_duration_milliseconds(_) -> prometheus_histogram:new([{name, fun_duration_histogram}, {buckets, [500, 1100]}, {help, ""}, {duration_unit, milliseconds}]), prometheus_histogram:observe_duration(fun_duration_histogram, fun () -> timer:sleep(1000) end), {Buckets, Sum} = prometheus_histogram:value(fun_duration_histogram), try prometheus_histogram:observe_duration(fun_duration_histogram, fun () -> erlang:error({qwe}) end) catch _:_ -> ok end, {BucketsE, SumE} = prometheus_histogram:value(fun_duration_histogram), [?_assertEqual([0, 1, 0], Buckets), ?_assertEqual([1, 1, 0], BucketsE), ?_assertMatch(true, 900 < Sum andalso Sum < 1200), ?_assertMatch(true, 900 < SumE andalso SumE < 1200)]. test_deregister(_) -> prometheus_histogram:new([{name, histogram}, {buckets, [5, 10]}, {labels, [pool]}, {help, ""}]), prometheus_histogram:new([{name, simple_histogram}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(histogram, [mongodb], 1), prometheus_histogram:observe(simple_histogram, 1), prometheus_histogram:observe(histogram, [mongodb], 6), prometheus_histogram:observe(simple_histogram, 6), [?_assertMatch({true, true}, prometheus_histogram:deregister(histogram)), ?_assertMatch({false, false}, prometheus_histogram:deregister(histogram)), ?_assertEqual(2, length(ets:tab2list(prometheus_histogram_table))), ?_assertEqual({[1, 1, 0], 7}, prometheus_histogram:value(simple_histogram)) ]. test_remove(_) -> prometheus_histogram:new([{name, histogram}, {buckets, [5, 10]}, {labels, [pool]}, {help, ""}]), prometheus_histogram:new([{name, simple_histogram}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(histogram, [mongodb], 1), prometheus_histogram:observe(simple_histogram, 1), prometheus_histogram:observe(histogram, [mongodb], 6), prometheus_histogram:observe(simple_histogram, 6), BRValue1 = prometheus_histogram:value(histogram, [mongodb]), BRValue2 = prometheus_histogram:value(simple_histogram), RResult1 = prometheus_histogram:remove(histogram, [mongodb]), RResult2 = prometheus_histogram:remove(simple_histogram), ARValue1 = prometheus_histogram:value(histogram, [mongodb]), ARValue2 = prometheus_histogram:value(simple_histogram), RResult3 = prometheus_histogram:remove(histogram, [mongodb]), RResult4 = prometheus_histogram:remove(simple_histogram), [?_assertEqual({[1, 1, 0], 7}, BRValue1), ?_assertEqual({[1, 1, 0], 7}, BRValue2), ?_assertEqual(true, RResult1), ?_assertEqual(true, RResult2), ?_assertEqual(undefined, ARValue1), ?_assertEqual(undefined, ARValue2), ?_assertEqual(false, RResult3), ?_assertEqual(false, RResult4)]. test_default_value(_) -> prometheus_histogram:new([{name, duration_histogram}, {labels, [label]}, {help, ""}]), UndefinedValue = prometheus_histogram:value(duration_histogram, [label]), prometheus_histogram:new([{name, something_histogram}, {labels, []}, {help, ""}, {buckets, [5, 10]}]), SomethingValue = prometheus_histogram:value(something_histogram), [?_assertEqual(undefined, UndefinedValue), ?_assertEqual({[0, 0, 0], 0}, SomethingValue)]. test_values(_) -> prometheus_histogram:new([{name, duration_histogram}, {labels, [label]}, {help, ""}]), prometheus_histogram:observe(duration_histogram, [label1], 12), prometheus_histogram:observe(duration_histogram, [label2], 111), [?_assertEqual([{[{"label", label1}], [{0.005, 0}, {0.01, 0}, {0.025, 0}, {0.05, 0}, {0.1, 0}, {0.25, 0}, {0.5, 0}, {1, 0}, {2.5, 0}, {5, 0}, {10, 0}, {infinity, 1}], 12}, {[{"label", label2}], [{0.005, 0}, {0.01, 0}, {0.025, 0}, {0.05, 0}, {0.1, 0}, {0.25, 0}, {0.5, 0}, {1, 0}, {2.5, 0}, {5, 0}, {10, 0}, {infinity, 1}], 111}], lists:sort(prometheus_histogram:values(default, duration_histogram)))]. test_collector1(_) -> prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 4), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=4, bucket=[#'Bucket'{cumulative_count=1, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], prometheus_collector:collect_mf_to_list(prometheus_histogram))]. test_collector2(_) -> prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {constant_labels, #{qwe => qwa}}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 7), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= <<"qwe">>, value= <<"qwa">>}, #'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=7, bucket=[#'Bucket'{cumulative_count=0, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], prometheus_collector:collect_mf_to_list(prometheus_histogram))]. test_collector3(_) -> MFList = try prometheus:start(), application:set_env(prometheus, global_labels, [{node, node()}]), prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 7), prometheus_collector:collect_mf_to_list(prometheus_histogram) after application:unset_env(prometheus, global_labels) end, NodeBin = atom_to_binary(node(), utf8), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= <<"node">>, value= NodeBin}, #'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=7, bucket=[#'Bucket'{cumulative_count=0, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], MFList)].
null
https://raw.githubusercontent.com/deadtrickster/prometheus.erl/b7cdd4fe70127aee738993c649e8c853718ea52a/test/eunit/metric/prometheus_histogram_tests.erl
erlang
basic name/labels/help validations test mf/arity errors histogram specific errors
-module(prometheus_histogram_tests). -include_lib("eunit/include/eunit.hrl"). -include("prometheus_model.hrl"). prometheus_format_test_() -> {foreach, fun prometheus_eunit_common:start/0, fun prometheus_eunit_common:stop/1, [fun test_registration/1, fun test_errors/1, fun test_buckets/1, fun test_observe/1, fun test_observe_duration_seconds/1, fun test_observe_duration_milliseconds/1, fun test_deregister/1, fun test_remove/1, fun test_default_value/1, fun test_values/1, fun test_collector1/1, fun test_collector2/1, fun test_collector3/1]}. test_registration(_)-> Name = request_duration, SpecWithRegistry = [{name, Name}, {buckets, [100, 300, 500, 750, 1000]}, {help, ""}, {registry, qwe}], [?_assertEqual(true, prometheus_histogram:declare(SpecWithRegistry)), ?_assertError({mf_already_exists, {qwe, Name}, "Consider using declare instead."}, prometheus_histogram:new(SpecWithRegistry))]. test_errors(_) -> prometheus_histogram:new([{name, request_duration}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Track requests duration"}]), prometheus_histogram:new([{name, db_query_duration}, {labels, [repo]}, {help, ""}]), ?_assertError({invalid_metric_name, 12, "metric name is not a string"}, prometheus_histogram:new([{name, 12}, {help, ""}])), ?_assertError({invalid_metric_labels, 12, "not list"}, prometheus_histogram:new([{name, "qwe"}, {labels, 12}, {help, ""}])), ?_assertError({invalid_metric_label_name, "le", "histogram cannot have a label named \"le\""}, prometheus_histogram:new([{name, "qwe"}, {labels, ["qwe", "le"]}, {help, ""}])), ?_assertError({invalid_metric_help, 12, "metric help is not a string"}, prometheus_histogram:new([{name, "qwe"}, {help, 12}])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:observe(unknown_metric, 1)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:observe(db_query_duration, [repo, db], 1)), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:observe_duration(unknown_metric, fun() -> 1 end)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:observe_duration(db_query_duration, [repo, db], fun() -> 1 end)), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:reset(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:reset(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:value(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:value(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:buckets(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:buckets(db_query_duration, [repo, db])), ?_assertError({unknown_metric, default, unknown_metric}, prometheus_histogram:remove(unknown_metric)), ?_assertError({invalid_metric_arity, 2, 1}, prometheus_histogram:remove(db_query_duration, [repo, db])), ?_assertError({no_buckets, []}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, []}])), ?_assertError({no_buckets, undefined}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, undefined}])), ?_assertError({invalid_buckets, 1, "not a list"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, 1}])), ?_assertError({invalid_bound, "qwe"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, ["qwe"]}])), ?_assertError({invalid_buckets, [1, 3, 2], "buckets not sorted"}, prometheus_histogram:new([{name, "qwe"}, {help, ""}, {buckets, [1, 3, 2]}])), ?_assertError({invalid_value, "qwe", "observe accepts only numbers"}, prometheus_histogram:observe(request_duration, "qwe")), ?_assertError({invalid_value, "qwe", "observe_duration accepts only functions"}, prometheus_histogram:observe_duration(pool_size, "qwe")) ]. test_buckets(_) -> prometheus_histogram:new([{name, "default_buckets"}, {help, ""}]), DefaultBuckets = prometheus_histogram:buckets("default_buckets"), prometheus_histogram:new([{name, http_request_duration_milliseconds}, {labels, [method]}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Http Request execution time"}, {duration_unit, false}]), prometheus_histogram:new([{name, "explicit_default_buckets"}, {help, ""}, {buckets, default}]), ExplicitDefaultBuckets = prometheus_histogram:buckets("explicit_default_buckets"), prometheus_histogram:new([{name, "linear_buckets"}, {help, ""}, {buckets, {linear, -15, 5, 6}}]), LinearBuckets = prometheus_histogram:buckets("linear_buckets"), prometheus_histogram:declare([{name, "exp_buckets"}, {help, ""}, {buckets, {exponential, 100, 1.2, 3}}]), ExpBuckets = prometheus_histogram:buckets("exp_buckets"), CustomBuckets = prometheus_histogram:buckets(http_request_duration_milliseconds, [method]), [?_assertEqual(prometheus_buckets:default() ++ [infinity], DefaultBuckets), ?_assertEqual(prometheus_buckets:default() ++ [infinity], ExplicitDefaultBuckets), ?_assertEqual([100, 300, 500, 750, 1000, infinity], CustomBuckets), ?_assertEqual([-15, -10, -5, 0, 5, 10, infinity], LinearBuckets), ?_assertEqual([100, 120, 144, infinity], ExpBuckets)]. test_observe(_) -> prometheus_histogram:new([{name, http_request_duration_milliseconds}, {labels, [method]}, {buckets, [100, 300, 500, 750, 1000]}, {help, "Http Request execution time"}, {duration_unit, false}]), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 95), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 100), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 102), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 150), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 250), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 75), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 350), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 550), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 950), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 500.2), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 150.4), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 450.5), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 850.3), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 750.9), prometheus_histogram:observe(http_request_duration_milliseconds, [get], 1650.23), Value = prometheus_histogram:value(http_request_duration_milliseconds, [get]), prometheus_histogram:reset(http_request_duration_milliseconds, [get]), RValue = prometheus_histogram:value(http_request_duration_milliseconds, [get]), [?_assertMatch({[3, 4, 2, 2, 3, 1], Sum} when Sum > 6974.5 andalso Sum < 6974.55, Value), ?_assertEqual({[0, 0, 0, 0, 0, 0], 0}, RValue)]. test_observe_duration_seconds(_) -> prometheus_histogram:new([{name, fun_duration_seconds}, {buckets, [0.5, 1.1]}, {help, ""}]), prometheus_histogram:observe_duration(fun_duration_seconds, fun () -> timer:sleep(1000) end), {Buckets, Sum} = prometheus_histogram:value(fun_duration_seconds), try prometheus_histogram:observe_duration(fun_duration_seconds, fun () -> erlang:error({qwe}) end) catch _:_ -> ok end, {BucketsE, SumE} = prometheus_histogram:value(fun_duration_seconds), [MF] = prometheus_collector:collect_mf_to_list(prometheus_histogram), MBuckets = [#'Bucket'{cumulative_count=1, upper_bound=0.5}, #'Bucket'{cumulative_count=2, upper_bound=1.1}, #'Bucket'{cumulative_count=2, upper_bound=infinity}], #'MetricFamily'{metric= [#'Metric'{histogram= #'Histogram'{sample_sum=MFSum, sample_count=MFCount, bucket=MBuckets}}]} = MF, [?_assertEqual([0, 1, 0], Buckets), ?_assertEqual([1, 1, 0], BucketsE), ?_assertEqual(true, 0.9 < Sum andalso Sum < 1.2), ?_assertEqual(true, 0.9 < SumE andalso SumE < 1.2), ?_assertEqual(2, MFCount), ?_assertEqual(true, 0.9 < MFSum andalso MFSum < 1.2)]. test_observe_duration_milliseconds(_) -> prometheus_histogram:new([{name, fun_duration_histogram}, {buckets, [500, 1100]}, {help, ""}, {duration_unit, milliseconds}]), prometheus_histogram:observe_duration(fun_duration_histogram, fun () -> timer:sleep(1000) end), {Buckets, Sum} = prometheus_histogram:value(fun_duration_histogram), try prometheus_histogram:observe_duration(fun_duration_histogram, fun () -> erlang:error({qwe}) end) catch _:_ -> ok end, {BucketsE, SumE} = prometheus_histogram:value(fun_duration_histogram), [?_assertEqual([0, 1, 0], Buckets), ?_assertEqual([1, 1, 0], BucketsE), ?_assertMatch(true, 900 < Sum andalso Sum < 1200), ?_assertMatch(true, 900 < SumE andalso SumE < 1200)]. test_deregister(_) -> prometheus_histogram:new([{name, histogram}, {buckets, [5, 10]}, {labels, [pool]}, {help, ""}]), prometheus_histogram:new([{name, simple_histogram}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(histogram, [mongodb], 1), prometheus_histogram:observe(simple_histogram, 1), prometheus_histogram:observe(histogram, [mongodb], 6), prometheus_histogram:observe(simple_histogram, 6), [?_assertMatch({true, true}, prometheus_histogram:deregister(histogram)), ?_assertMatch({false, false}, prometheus_histogram:deregister(histogram)), ?_assertEqual(2, length(ets:tab2list(prometheus_histogram_table))), ?_assertEqual({[1, 1, 0], 7}, prometheus_histogram:value(simple_histogram)) ]. test_remove(_) -> prometheus_histogram:new([{name, histogram}, {buckets, [5, 10]}, {labels, [pool]}, {help, ""}]), prometheus_histogram:new([{name, simple_histogram}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(histogram, [mongodb], 1), prometheus_histogram:observe(simple_histogram, 1), prometheus_histogram:observe(histogram, [mongodb], 6), prometheus_histogram:observe(simple_histogram, 6), BRValue1 = prometheus_histogram:value(histogram, [mongodb]), BRValue2 = prometheus_histogram:value(simple_histogram), RResult1 = prometheus_histogram:remove(histogram, [mongodb]), RResult2 = prometheus_histogram:remove(simple_histogram), ARValue1 = prometheus_histogram:value(histogram, [mongodb]), ARValue2 = prometheus_histogram:value(simple_histogram), RResult3 = prometheus_histogram:remove(histogram, [mongodb]), RResult4 = prometheus_histogram:remove(simple_histogram), [?_assertEqual({[1, 1, 0], 7}, BRValue1), ?_assertEqual({[1, 1, 0], 7}, BRValue2), ?_assertEqual(true, RResult1), ?_assertEqual(true, RResult2), ?_assertEqual(undefined, ARValue1), ?_assertEqual(undefined, ARValue2), ?_assertEqual(false, RResult3), ?_assertEqual(false, RResult4)]. test_default_value(_) -> prometheus_histogram:new([{name, duration_histogram}, {labels, [label]}, {help, ""}]), UndefinedValue = prometheus_histogram:value(duration_histogram, [label]), prometheus_histogram:new([{name, something_histogram}, {labels, []}, {help, ""}, {buckets, [5, 10]}]), SomethingValue = prometheus_histogram:value(something_histogram), [?_assertEqual(undefined, UndefinedValue), ?_assertEqual({[0, 0, 0], 0}, SomethingValue)]. test_values(_) -> prometheus_histogram:new([{name, duration_histogram}, {labels, [label]}, {help, ""}]), prometheus_histogram:observe(duration_histogram, [label1], 12), prometheus_histogram:observe(duration_histogram, [label2], 111), [?_assertEqual([{[{"label", label1}], [{0.005, 0}, {0.01, 0}, {0.025, 0}, {0.05, 0}, {0.1, 0}, {0.25, 0}, {0.5, 0}, {1, 0}, {2.5, 0}, {5, 0}, {10, 0}, {infinity, 1}], 12}, {[{"label", label2}], [{0.005, 0}, {0.01, 0}, {0.025, 0}, {0.05, 0}, {0.1, 0}, {0.25, 0}, {0.5, 0}, {1, 0}, {2.5, 0}, {5, 0}, {10, 0}, {infinity, 1}], 111}], lists:sort(prometheus_histogram:values(default, duration_histogram)))]. test_collector1(_) -> prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 4), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=4, bucket=[#'Bucket'{cumulative_count=1, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], prometheus_collector:collect_mf_to_list(prometheus_histogram))]. test_collector2(_) -> prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {constant_labels, #{qwe => qwa}}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 7), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= <<"qwe">>, value= <<"qwa">>}, #'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=7, bucket=[#'Bucket'{cumulative_count=0, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], prometheus_collector:collect_mf_to_list(prometheus_histogram))]. test_collector3(_) -> MFList = try prometheus:start(), application:set_env(prometheus, global_labels, [{node, node()}]), prometheus_histogram:new([{name, simple_histogram}, {labels, ["label"]}, {buckets, [5, 10]}, {help, ""}]), prometheus_histogram:observe(simple_histogram, [label_value], 7), prometheus_collector:collect_mf_to_list(prometheus_histogram) after application:unset_env(prometheus, global_labels) end, NodeBin = atom_to_binary(node(), utf8), [?_assertMatch([#'MetricFamily'{metric= [#'Metric'{label=[#'LabelPair'{name= <<"node">>, value= NodeBin}, #'LabelPair'{name= "label", value= <<"label_value">>}], histogram=#'Histogram'{sample_count=1, sample_sum=7, bucket=[#'Bucket'{cumulative_count=0, upper_bound=5}, #'Bucket'{cumulative_count=1, upper_bound=10}, #'Bucket'{cumulative_count=1, upper_bound=infinity}]}}]}], MFList)].
176b3bff28989c79d196e0c7724d77ad4260728629481c9bc2acc4b31ff9ba5f
pixura/simple-graphql-client
Types.hs
# LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # module Network.GraphQL.Client.Types ( GraphQLQuery(..) , Location(..) , GraphQLError(..) , GraphQLQueryError(..) , GraphQLResponse(..) , GraphQLBody(..) , Nodes(..) ) where import qualified Data.Aeson as J import Control.Monad.Catch ( Exception(..) ) import Data.Char ( toLower ) import Data.Text ( Text ) import Data.String ( IsString ) import GHC.Generics defaultJSONOptions :: String -> J.Options defaultJSONOptions n = J.defaultOptions { J.fieldLabelModifier = lowerFirst . drop (length n) } where lowerFirst [] = [] lowerFirst (x : xs) = (toLower x) : xs ----------------------------------------------------------------------------- -- | GraphQLQuery ----------------------------------------------------------------------------- -- | The graphql query newtype GraphQLQuery = GraphQLQuery { unGraphQLQuery :: Text } deriving (Show, Eq, J.ToJSON, J.FromJSON, IsString, Generic) ----------------------------------------------------------------------------- -- | GraphQLQueryError ----------------------------------------------------------------------------- data GraphQLQueryError = EmptyGraphQLReponse | HttpError Text | ParsingError Text deriving (Show, Eq, Generic) instance Exception GraphQLQueryError ----------------------------------------------------------------------------- -- | GraphQLError ----------------------------------------------------------------------------- -- | GraphQL error response data GraphQLError = GraphQLError { graphQLErrorMessage :: Text , graphQLErrorLocations :: Maybe [Location] , graphQLErrorPath :: Maybe [Text] } deriving (Show, Eq, Generic) instance J.ToJSON GraphQLError where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLError" instance J.FromJSON GraphQLError where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLError" ----------------------------------------------------------------------------- -- | Location ----------------------------------------------------------------------------- | Location of the error in the GraphQL query data Location = Location { locationLine :: Integer , locationColumn :: Integer } deriving (Show, Eq, Generic) instance J.ToJSON Location where toJSON = J.genericToJSON $ defaultJSONOptions "Location" instance J.FromJSON Location where parseJSON = J.genericParseJSON $ defaultJSONOptions "Location" ----------------------------------------------------------------------------- -- | GraphQLResponse ----------------------------------------------------------------------------- -- | The response to the GraphQL query. data GraphQLResponse a = GraphQLResponse { graphQLResponseData :: Maybe a , graphQLResponseErrors :: Maybe [GraphQLError] } deriving (Eq, Show, Generic) instance J.ToJSON a => J.ToJSON (GraphQLResponse a) where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLResponse" instance J.FromJSON a => J.FromJSON (GraphQLResponse a) where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLResponse" ----------------------------------------------------------------------------- -- | Nodes ----------------------------------------------------------------------------- -- | Utility type for common json patterns parsed from graphql repsonse data. -- e.g. `{ allPeople :: Nodes Person }` data Nodes a = Nodes { nodes :: [a] } deriving (Eq, Show, Generic) instance (J.ToJSON a) => J.ToJSON (Nodes a) where toJSON = J.genericToJSON J.defaultOptions instance (J.FromJSON a) => J.FromJSON (Nodes a) ----------------------------------------------------------------------------- -- | GraphQLBody ----------------------------------------------------------------------------- -- | body object expected by GraphQL APIs. data GraphQLBody a = GraphQLBody { graphQLBodyQuery :: GraphQLQuery , graphQLBodyVariables :: Maybe a } deriving (Eq, Show, Generic) instance (J.ToJSON a) => J.ToJSON (GraphQLBody a) where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLBody" instance (J.FromJSON a) => J.FromJSON (GraphQLBody a) where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLBody"
null
https://raw.githubusercontent.com/pixura/simple-graphql-client/ed663325693b85b226bac1bc4204f8af65a1c611/src/Network/GraphQL/Client/Types.hs
haskell
# LANGUAGE DeriveGeneric # # LANGUAGE OverloadedStrings # --------------------------------------------------------------------------- | GraphQLQuery --------------------------------------------------------------------------- | The graphql query --------------------------------------------------------------------------- | GraphQLQueryError --------------------------------------------------------------------------- --------------------------------------------------------------------------- | GraphQLError --------------------------------------------------------------------------- | GraphQL error response --------------------------------------------------------------------------- | Location --------------------------------------------------------------------------- --------------------------------------------------------------------------- | GraphQLResponse --------------------------------------------------------------------------- | The response to the GraphQL query. --------------------------------------------------------------------------- | Nodes --------------------------------------------------------------------------- | Utility type for common json patterns parsed from graphql repsonse data. e.g. `{ allPeople :: Nodes Person }` --------------------------------------------------------------------------- | GraphQLBody --------------------------------------------------------------------------- | body object expected by GraphQL APIs.
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE RecordWildCards # module Network.GraphQL.Client.Types ( GraphQLQuery(..) , Location(..) , GraphQLError(..) , GraphQLQueryError(..) , GraphQLResponse(..) , GraphQLBody(..) , Nodes(..) ) where import qualified Data.Aeson as J import Control.Monad.Catch ( Exception(..) ) import Data.Char ( toLower ) import Data.Text ( Text ) import Data.String ( IsString ) import GHC.Generics defaultJSONOptions :: String -> J.Options defaultJSONOptions n = J.defaultOptions { J.fieldLabelModifier = lowerFirst . drop (length n) } where lowerFirst [] = [] lowerFirst (x : xs) = (toLower x) : xs newtype GraphQLQuery = GraphQLQuery { unGraphQLQuery :: Text } deriving (Show, Eq, J.ToJSON, J.FromJSON, IsString, Generic) data GraphQLQueryError = EmptyGraphQLReponse | HttpError Text | ParsingError Text deriving (Show, Eq, Generic) instance Exception GraphQLQueryError data GraphQLError = GraphQLError { graphQLErrorMessage :: Text , graphQLErrorLocations :: Maybe [Location] , graphQLErrorPath :: Maybe [Text] } deriving (Show, Eq, Generic) instance J.ToJSON GraphQLError where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLError" instance J.FromJSON GraphQLError where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLError" | Location of the error in the GraphQL query data Location = Location { locationLine :: Integer , locationColumn :: Integer } deriving (Show, Eq, Generic) instance J.ToJSON Location where toJSON = J.genericToJSON $ defaultJSONOptions "Location" instance J.FromJSON Location where parseJSON = J.genericParseJSON $ defaultJSONOptions "Location" data GraphQLResponse a = GraphQLResponse { graphQLResponseData :: Maybe a , graphQLResponseErrors :: Maybe [GraphQLError] } deriving (Eq, Show, Generic) instance J.ToJSON a => J.ToJSON (GraphQLResponse a) where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLResponse" instance J.FromJSON a => J.FromJSON (GraphQLResponse a) where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLResponse" data Nodes a = Nodes { nodes :: [a] } deriving (Eq, Show, Generic) instance (J.ToJSON a) => J.ToJSON (Nodes a) where toJSON = J.genericToJSON J.defaultOptions instance (J.FromJSON a) => J.FromJSON (Nodes a) data GraphQLBody a = GraphQLBody { graphQLBodyQuery :: GraphQLQuery , graphQLBodyVariables :: Maybe a } deriving (Eq, Show, Generic) instance (J.ToJSON a) => J.ToJSON (GraphQLBody a) where toJSON = J.genericToJSON $ defaultJSONOptions "GraphQLBody" instance (J.FromJSON a) => J.FromJSON (GraphQLBody a) where parseJSON = J.genericParseJSON $ defaultJSONOptions "GraphQLBody"
941762d0ae21efea31cbafcf3b2b800563a373578ea1d2696e615bc85b9d0372
jscl-project/jscl
extended-loop.lisp
-*- Mode : LISP ; Syntax : Common - lisp ; Package : ANSI - LOOP ; Base : 10 ; Lowercase : T -*- ;;;> > Portions of LOOP are Copyright ( c ) 1986 by the Massachusetts Institute of Technology . ;;;> All Rights Reserved. ;;;> ;;;> Permission to use, copy, modify and distribute this software and its ;;;> documentation for any purpose and without fee is hereby granted, > provided that the M.I.T. copyright notice appear in all copies and that ;;;> both that copyright notice and this permission notice appear in > supporting documentation . The names " M.I.T. " and " Massachusetts > Institute of Technology " may not be used in advertising or publicity ;;;> pertaining to distribution of the software without specific, written ;;;> prior permission. Notice must be given in supporting documentation that > copying distribution is by permission of M.I.T. M.I.T. makes no ;;;> representations about the suitability of this software for any purpose. ;;;> It is provided "as is" without express or implied warranty. ;;;> > Massachusetts Institute of Technology > 77 Massachusetts Avenue > Cambridge , Massachusetts 02139 > United States of America ;;;> +1-617-253-1000 ;;;> > Portions of LOOP are Copyright ( c ) 1989 , 1990 , 1991 , 1992 by Symbolics , Inc. ;;;> All Rights Reserved. ;;;> ;;;> Permission to use, copy, modify and distribute this software and its ;;;> documentation for any purpose and without fee is hereby granted, ;;;> provided that the Symbolics copyright notice appear in all copies and ;;;> that both that copyright notice and this permission notice appear in ;;;> supporting documentation. The name "Symbolics" may not be used in ;;;> advertising or publicity pertaining to distribution of the software ;;;> without specific, written prior permission. Notice must be given in ;;;> supporting documentation that copying distribution is by permission of ;;;> Symbolics. Symbolics makes no representations about the suitability of ;;;> this software for any purpose. It is provided "as is" without express ;;;> or implied warranty. ;;;> > Symbolics , CLOE Runtime , and Minima are trademarks , and CLOE , , > and are registered trademarks of Symbolics , Inc. ;;;> ;;;> Symbolics, Inc. > 8 New England Executive Park , East > Burlington , Massachusetts 01803 > United States of America ;;;> +1-617-221-1000 (in-package :ansi-loop) #+Cloe-Runtime ;Don't ask. (car (push "%Z% %M% %I% %E% %U%" system::*module-identifications*)) The following code could be used to set up the SYMBOLICS - LOOP package as it is expected to be . At Symbolics , in both and CLOE , the ;;; package setup is done elsewhere. #-Symbolics (unless (find-package 'symbolics-loop) (make-package 'symbolics-loop :use nil)) #-Symbolics (import 'ansi-loop::loop-finish (find-package 'symbolics-loop)) #-Symbolics (export '(symbolics-loop::loop symbolics-loop::loop-finish symbolics-loop::define-loop-iteration-path symbolics-loop::define-loop-sequence-path ) (find-package 'symbolics-loop)) ;;;This is our typical "extensible" universe, which should be a proper superset of the ansi universe. (defvar *loop-default-universe* (make-ansi-loop-universe t)) (defmacro symbolics-loop:define-loop-iteration-path (path-name function &key alternate-names preposition-groups inclusive-permitted user-data (loop-universe '*loop-default-universe*)) `(eval-when (eval compile load) (add-loop-path '(,path-name ,@alternate-names) ,function ,loop-universe :preposition-groups ',preposition-groups :inclusive-permitted ',inclusive-permitted :user-data ',user-data))) (defmacro symbolics-loop:define-loop-sequence-path (path-name-or-names fetch-function size-function &optional sequence-type element-type) "Defines a sequence iteration path. PATH-NAME-OR-NAMES is either an atomic path name or a list of path names. FETCHFUN is a function of two arguments, the sequence and the index of the item to be fetched. Indexing is assumed to be zero-origined. SIZEFUN is a function of one argument, the sequence; it should return the number of elements in the sequence. SEQUENCE-TYPE is the name of the data-type of the sequence, and ELEMENT-TYPE is the name of the data-type of the elements of the sequence." `(eval-when (eval compile load) (add-loop-path ',path-name-or-names 'loop-sequence-elements-path *loop-default-universe* :preposition-groups '((:of :in) (:from :downfrom :upfrom) (:to :downto :below :above) (:by)) :inclusive-permitted nil :user-data '(:fetch-function ,fetch-function :size-function ,size-function :sequence-type ,sequence-type :element-type ,element-type)))) (defmacro symbolics-loop:loop (&environment env &rest keywords-and-forms) #+Genera (declare (compiler:do-not-record-macroexpansions) (zwei:indentation . zwei:indent-loop)) (loop-standard-expansion keywords-and-forms env *loop-default-universe*))
null
https://raw.githubusercontent.com/jscl-project/jscl/d38eec2aeb47d04f1caf3d1cda82dc968d67c305/src/ansiloop/extended-loop.lisp
lisp
Syntax : Common - lisp ; Package : ANSI - LOOP ; Base : 10 ; Lowercase : T -*- > > All Rights Reserved. > > Permission to use, copy, modify and distribute this software and its > documentation for any purpose and without fee is hereby granted, > both that copyright notice and this permission notice appear in > pertaining to distribution of the software without specific, written > prior permission. Notice must be given in supporting documentation that > representations about the suitability of this software for any purpose. > It is provided "as is" without express or implied warranty. > > +1-617-253-1000 > > All Rights Reserved. > > Permission to use, copy, modify and distribute this software and its > documentation for any purpose and without fee is hereby granted, > provided that the Symbolics copyright notice appear in all copies and > that both that copyright notice and this permission notice appear in > supporting documentation. The name "Symbolics" may not be used in > advertising or publicity pertaining to distribution of the software > without specific, written prior permission. Notice must be given in > supporting documentation that copying distribution is by permission of > Symbolics. Symbolics makes no representations about the suitability of > this software for any purpose. It is provided "as is" without express > or implied warranty. > > > Symbolics, Inc. > +1-617-221-1000 Don't ask. package setup is done elsewhere. This is our typical "extensible" universe, which should be a proper superset of the ansi universe. it should return the number of elements in
> Portions of LOOP are Copyright ( c ) 1986 by the Massachusetts Institute of Technology . > provided that the M.I.T. copyright notice appear in all copies and that > supporting documentation . The names " M.I.T. " and " Massachusetts > Institute of Technology " may not be used in advertising or publicity > copying distribution is by permission of M.I.T. M.I.T. makes no > Massachusetts Institute of Technology > 77 Massachusetts Avenue > Cambridge , Massachusetts 02139 > United States of America > Portions of LOOP are Copyright ( c ) 1989 , 1990 , 1991 , 1992 by Symbolics , Inc. > Symbolics , CLOE Runtime , and Minima are trademarks , and CLOE , , > and are registered trademarks of Symbolics , Inc. > 8 New England Executive Park , East > Burlington , Massachusetts 01803 > United States of America (in-package :ansi-loop) (car (push "%Z% %M% %I% %E% %U%" system::*module-identifications*)) The following code could be used to set up the SYMBOLICS - LOOP package as it is expected to be . At Symbolics , in both and CLOE , the #-Symbolics (unless (find-package 'symbolics-loop) (make-package 'symbolics-loop :use nil)) #-Symbolics (import 'ansi-loop::loop-finish (find-package 'symbolics-loop)) #-Symbolics (export '(symbolics-loop::loop symbolics-loop::loop-finish symbolics-loop::define-loop-iteration-path symbolics-loop::define-loop-sequence-path ) (find-package 'symbolics-loop)) (defvar *loop-default-universe* (make-ansi-loop-universe t)) (defmacro symbolics-loop:define-loop-iteration-path (path-name function &key alternate-names preposition-groups inclusive-permitted user-data (loop-universe '*loop-default-universe*)) `(eval-when (eval compile load) (add-loop-path '(,path-name ,@alternate-names) ,function ,loop-universe :preposition-groups ',preposition-groups :inclusive-permitted ',inclusive-permitted :user-data ',user-data))) (defmacro symbolics-loop:define-loop-sequence-path (path-name-or-names fetch-function size-function &optional sequence-type element-type) "Defines a sequence iteration path. PATH-NAME-OR-NAMES is either an atomic path name or a list of path names. FETCHFUN is a function of two arguments, the sequence and the index of the item to be fetched. Indexing is assumed to be zero-origined. SIZEFUN is a function of the sequence. SEQUENCE-TYPE is the name of the data-type of the sequence, and ELEMENT-TYPE is the name of the data-type of the elements of the sequence." `(eval-when (eval compile load) (add-loop-path ',path-name-or-names 'loop-sequence-elements-path *loop-default-universe* :preposition-groups '((:of :in) (:from :downfrom :upfrom) (:to :downto :below :above) (:by)) :inclusive-permitted nil :user-data '(:fetch-function ,fetch-function :size-function ,size-function :sequence-type ,sequence-type :element-type ,element-type)))) (defmacro symbolics-loop:loop (&environment env &rest keywords-and-forms) #+Genera (declare (compiler:do-not-record-macroexpansions) (zwei:indentation . zwei:indent-loop)) (loop-standard-expansion keywords-and-forms env *loop-default-universe*))
1a4e262e6903b5334482e7e87451c52b1d08f3975e17f0d14c93f20a2afa849a
inhabitedtype/ocaml-aws
listTagsForResource.ml
open Types open Aws type input = ListTagsForResourceRequest.t type output = ListTagsForResourceResponse.t type error = Errors_internal.t let service = "route53" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2013-04-01" ]; "Action", [ "ListTagsForResource" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (ListTagsForResourceRequest.to_query req))))) in `GET, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "ListTagsForResourceResponse" (snd xml) in try Util.or_error (Util.option_bind resp ListTagsForResourceResponse.parse) (let open Error in BadResponse { body; message = "Could not find well formed ListTagsForResourceResponse." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing ListTagsForResourceResponse - missing field in body or \ children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/route53/lib/listTagsForResource.ml
ocaml
open Types open Aws type input = ListTagsForResourceRequest.t type output = ListTagsForResourceResponse.t type error = Errors_internal.t let service = "route53" let signature_version = Request.V4 let to_http service region req = let uri = Uri.add_query_params (Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region))) (List.append [ "Version", [ "2013-04-01" ]; "Action", [ "ListTagsForResource" ] ] (Util.drop_empty (Uri.query_of_encoded (Query.render (ListTagsForResourceRequest.to_query req))))) in `GET, uri, [] let of_http body = try let xml = Ezxmlm.from_string body in let resp = Xml.member "ListTagsForResourceResponse" (snd xml) in try Util.or_error (Util.option_bind resp ListTagsForResourceResponse.parse) (let open Error in BadResponse { body; message = "Could not find well formed ListTagsForResourceResponse." }) with Xml.RequiredFieldMissing msg -> let open Error in `Error (BadResponse { body ; message = "Error parsing ListTagsForResourceResponse - missing field in body or \ children: " ^ msg }) with Failure msg -> `Error (let open Error in BadResponse { body; message = "Error parsing xml: " ^ msg }) let parse_error code err = let errors = [] @ Errors_internal.common in match Errors_internal.of_string err with | Some var -> if List.mem var errors && match Errors_internal.to_http_code var with | Some var -> var = code | None -> true then Some var else None | None -> None
288ffbd3f608e4ff00a78ad1b3a82ee0deedccc1bf45f0752aa77a9e21922ccd
xtdb/xtdb
prometheus.clj
(ns xtdb.metrics.prometheus (:require [xtdb.metrics :as metrics] [xtdb.system :as sys] [iapetos.collector.jvm :as jvm] [iapetos.core :as prometheus] [iapetos.standalone :as server]) (:import com.codahale.metrics.MetricRegistry io.prometheus.client.dropwizard.DropwizardExports java.time.Duration java.util.concurrent.TimeUnit [org.dhatim.dropwizard.prometheus PrometheusReporter Pushgateway])) (defn ->reporter {::sys/deps {:registry ::metrics/registry :metrics ::metrics/metrics} ::sys/args {:report-frequency {:doc "Frequency of reporting metrics" :default (Duration/ofSeconds 1) :spec ::sys/duration} :prefix {:doc "Prefix all metrics with this string" :required? false :spec ::sys/string} :push-gateway {:doc "Address of the prometheus server" :required? true :spec ::sys/string}}} [{:keys [registry prefix metric-filter push-gateway report-frequency]}] (-> (PrometheusReporter/forRegistry registry) (cond-> prefix (.prefixedWith prefix) metric-filter (.filter metric-filter)) (.build (Pushgateway. push-gateway)) (doto (.start (.toMillis ^Duration report-frequency) (TimeUnit/MILLISECONDS))))) (defn ->http-exporter {::sys/deps {:registry ::metrics/registry :metrics ::metrics/metrics} ::sys/args {:port {:doc "Port for prometheus exporter server" :default 8080 :spec ::sys/int} :jvm-metrics? {:doc "Dictates if JVM metrics are exported" :default false :spec ::sys/boolean}}} [{:keys [^MetricRegistry registry port jvm-metrics?]}] (-> (prometheus/collector-registry) (prometheus/register (DropwizardExports. registry)) (cond-> jvm-metrics? (jvm/initialize)) (server/metrics-server {:port port})))
null
https://raw.githubusercontent.com/xtdb/xtdb/e2f51ed99fc2716faa8ad254c0b18166c937b134/modules/metrics/src/xtdb/metrics/prometheus.clj
clojure
(ns xtdb.metrics.prometheus (:require [xtdb.metrics :as metrics] [xtdb.system :as sys] [iapetos.collector.jvm :as jvm] [iapetos.core :as prometheus] [iapetos.standalone :as server]) (:import com.codahale.metrics.MetricRegistry io.prometheus.client.dropwizard.DropwizardExports java.time.Duration java.util.concurrent.TimeUnit [org.dhatim.dropwizard.prometheus PrometheusReporter Pushgateway])) (defn ->reporter {::sys/deps {:registry ::metrics/registry :metrics ::metrics/metrics} ::sys/args {:report-frequency {:doc "Frequency of reporting metrics" :default (Duration/ofSeconds 1) :spec ::sys/duration} :prefix {:doc "Prefix all metrics with this string" :required? false :spec ::sys/string} :push-gateway {:doc "Address of the prometheus server" :required? true :spec ::sys/string}}} [{:keys [registry prefix metric-filter push-gateway report-frequency]}] (-> (PrometheusReporter/forRegistry registry) (cond-> prefix (.prefixedWith prefix) metric-filter (.filter metric-filter)) (.build (Pushgateway. push-gateway)) (doto (.start (.toMillis ^Duration report-frequency) (TimeUnit/MILLISECONDS))))) (defn ->http-exporter {::sys/deps {:registry ::metrics/registry :metrics ::metrics/metrics} ::sys/args {:port {:doc "Port for prometheus exporter server" :default 8080 :spec ::sys/int} :jvm-metrics? {:doc "Dictates if JVM metrics are exported" :default false :spec ::sys/boolean}}} [{:keys [^MetricRegistry registry port jvm-metrics?]}] (-> (prometheus/collector-registry) (prometheus/register (DropwizardExports. registry)) (cond-> jvm-metrics? (jvm/initialize)) (server/metrics-server {:port port})))
b250473a6789ae29a54ceed71b653fd9efbc86db21d726813623b9b7649e392b
angelhof/flumina
log_mod.erl
-module(log_mod). -export([initialize_message_logger_state/2, initialize_message_logger_state/3, initialize_specialized_message_logger/3, initialize_specialized_message_logger/4, maybe_log_message/3, no_message_logger/1, message_logger/1, init_num_log_state/0, reset_num_log_state/1, incr_num_log_state/2, make_num_log_triple/0, no_log_triple/0, num_logger_process/2, init_debug_log/0, debug_log/2, debug_log_time/2]). -include("type_definitions.hrl"). -include("config.hrl"). %% TODO: If the API grows more, refactor these to have options like the rest (producer, sink) -spec initialize_message_logger_state(string(), sets:set(tag())) -> message_logger_log_fun(). initialize_message_logger_state(Prefix, Tags) -> initialize_message_logger_state(Prefix, Tags, node()). -spec initialize_message_logger_state(string(), sets:set(tag()), node()) -> message_logger_log_fun(). initialize_message_logger_state(Prefix, Tags, Node) -> Filename = io_lib:format("~s/~s_~s_~s_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), Pid = spawn_link(Node, ?MODULE, message_logger, [Filename]), fun(Msg) -> maybe_log_message(Msg, Tags, Pid) end. -spec initialize_specialized_message_logger(string(), sets:set(tag()), impl_tag()) -> message_logger_log_fun(). initialize_specialized_message_logger(Prefix, Tags, ImplTag) -> initialize_specialized_message_logger(Prefix, Tags, ImplTag, node()). -spec initialize_specialized_message_logger(string(), sets:set(tag()), impl_tag(), node()) -> message_logger_log_fun(). initialize_specialized_message_logger(Prefix, Tags, ImplTag, Node) -> Filename = io_lib:format("~s/~s_~s_~s_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), Pid = spawn_link(Node, ?MODULE, message_logger, [Filename]), {Tag, _TagNode} = ImplTag, case sets:is_element(Tag, Tags) of true -> fun(Msg) -> log_message(Msg, Pid) end; false -> fun(_Msg) -> ok end end. the predicate to be anything instead of just a tag set %% WARNING: At the moment this only logs messages, not heartbeats -spec maybe_log_message(gen_impl_message(), sets:set(tag()), pid()) -> 'ok'. maybe_log_message({{Tag, _}, _, _} = Msg, Tags, Pid) -> case sets:is_element(Tag, Tags) of true -> log_message(Msg, Pid); false -> ok end; maybe_log_message(_Msg, _Tags, _Pid) -> ok. -spec log_message(gen_impl_message(), pid()) -> 'ok'. log_message(Msg, Pid) -> CurrentTimestamp = ?GET_SYSTEM_TIME(), PidNode = {self(), node()}, Pid ! {Msg, PidNode, CurrentTimestamp}, ok. %% Obsolete synchronous logging code % % the predicate to be anything instead of just a tag set %% %% WARNING: At the moment this only logs messages, not heartbeats -spec old_maybe_log_message(gen_impl_message ( ) , message_logger_state ( ) ) - > ' ok ' . %% old_maybe_log_message({{Tag, _}, _, _} = Msg, {Tags, _} = LoggerState) -> %% case sets:is_element(Tag, Tags) of %% true -> log_message(Msg , LoggerState ) ; %% false -> %% ok %% end; %% old_maybe_log_message(Msg, LoggerState) -> %% ok. %% -spec log_message(gen_impl_message(), message_logger_state()) -> 'ok'. %% log_message(Msg, {_Tags, File}) -> CurrentTimestamp = ? ( ) , %% %% CurrentTimestamp = erlang:system_time(nanosecond), PidNode = { self ( ) , node ( ) } , Data = io_lib : format("~w ~ n " , [ { Msg , PidNode , CurrentTimestamp } ] ) , %% ok = file:write(File, Data). %% Have a message logger to asynchronously log messages -spec message_logger(file:filename()) -> ok. message_logger(Filename) -> %% Trap exits to empty buffer if the producer exits process_flag(trap_exit, true), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [append, raw]), ok = file:truncate(IoDevice), message_logger_loop(IoDevice, [], 0). -type message_logger_buffer() :: [string()]. -spec message_logger_loop(file:io_device(), message_logger_buffer(), integer()) -> ok. message_logger_loop(IoDevice, Buffer, N) when N >= ?ASYNC_MESSAGE_LOGGER_BUFFER_SIZE-> OrderedBuffer = lists:reverse(Buffer), FlatOutput = lists:flatten(OrderedBuffer), ok = file:write(IoDevice, FlatOutput), message_logger_loop(IoDevice, [], 0); message_logger_loop(IoDevice, Buffer, N) -> receive {'EXIT', _, _} -> %% If some linked process exits, then we have to empty buffer message_logger_loop(IoDevice, Buffer, ?ASYNC_MESSAGE_LOGGER_BUFFER_SIZE); MsgToLog -> Data = io_lib:format("~w~n", [MsgToLog]), message_logger_loop(IoDevice, [Data|Buffer], N+1) end. -spec no_message_logger(maybe_impl_tag()) -> message_logger_log_fun(). no_message_logger(_MaybeImplTag) -> fun(_Msg) -> ok end. %% %% Number of messages loggers %% -spec init_num_log_state() -> integer(). init_num_log_state() -> 0. -spec reset_num_log_state(num_log_state()) -> integer(). reset_num_log_state(_) -> 0. -spec incr_num_log_state(gen_message() | merge_request(), num_log_state()) -> num_log_state(). incr_num_log_state(_Msg, Num) -> Num + 1. -spec make_num_log_triple() -> num_log_triple(). make_num_log_triple() -> {fun log_mod:incr_num_log_state/2, fun log_mod:reset_num_log_state/1, init_num_log_state()}. -spec no_log_triple() -> num_log_triple(). no_log_triple() -> {fun(_,_) -> 0 end, fun(_) -> 0 end, 0}. -spec num_logger_process(string(), configuration()) -> ok. num_logger_process(Prefix, Configuration) -> io:format(" -- !!WARNING!! -- This is an obsolete method of logging throughput.~n" " Instead log total time and total number of messages!~n", []), register('num_messages_logger_process', self()), Filename = io_lib:format("~s/~s_~s_~s_num_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [append]), ok = file:truncate(IoDevice), num_logger_process_loop(IoDevice, Configuration). -spec num_logger_process_loop(file:io_device(), configuration()) -> ok. num_logger_process_loop(IoDevice, Configuration) -> %% It should be messages every 500 ms timer:sleep(500), %% Send the get_log_message to all mailboxes in the configuration PidMboxPairs = configuration:find_node_mailbox_pid_pairs(Configuration), {registered_name, MyName} = erlang:process_info(self(), registered_name), RequestMessage = {get_message_log, {MyName, node()}}, [Mbox ! RequestMessage || {_Node, Mbox} <- PidMboxPairs], %% Receive the answer from all mailboxes in the configuration ReceivedLogs = receive_message_logs(PidMboxPairs, []), %% Log all the answers in the file (with a current timestamp) CurrentTimestamp = ?GET_SYSTEM_TIME(), append_logs_in_file(ReceivedLogs, CurrentTimestamp, IoDevice), num_logger_process_loop(IoDevice, Configuration). -spec receive_message_logs([{pid(), mailbox()}], [{mailbox(), num_log_state()}]) -> [{mailbox(), num_log_state()}]. receive_message_logs([], Received) -> Received; receive_message_logs([{NodePid, {MboxName, Node}}|Rest], Received) -> receive {message_log, {NodePid, Node}, LogState} -> receive_message_logs(Rest, [{{MboxName, Node}, LogState}|Received]) end. -spec append_logs_in_file([{mailbox(), num_log_state()}], integer(), file:io_device()) -> ok. append_logs_in_file(ReceivedLogs, CurrentTimestamp, IoDevice) -> lists:foreach( fun(MboxLog) -> append_log_in_file(MboxLog, CurrentTimestamp, IoDevice) end, ReceivedLogs). -spec append_log_in_file({mailbox(), num_log_state()}, integer(), file:io_device()) -> ok. append_log_in_file({Mbox, Log}, CurrentTimestamp, IoDevice) -> Data = io_lib:format("~w~n", [{Mbox, CurrentTimestamp, Log}]), ok = file:write(IoDevice, Data). %% %% These functions are for debug logging. %% The names of the files are generated from the pid and node %% %% This function creates and truncates the debug log file -spec init_debug_log() -> ok. -if(?DEBUG =:= true). init_debug_log() -> Filename = io_lib:format("~s/debug_~s_~s.log", [?LOG_DIR, pid_to_list(self()), atom_to_list(node())]), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [write]), ok = file:truncate(IoDevice), ok = file:close(IoDevice). -else. init_debug_log() -> ok. -endif. -spec debug_log(string(), [any()]) -> ok. -if(?DEBUG =:= true). debug_log(Format, Args) -> Filename = io_lib:format("~s/debug_~s_~s.log", [?LOG_DIR, pid_to_list(self()), atom_to_list(node())]), Data = io_lib:format(Format, Args), filelib:ensure_dir(Filename), ok = file:write_file(Filename, Data, [append]). -else. debug_log(_Format, _Args) -> ok. -endif. -spec debug_log_time(string(), [any()]) -> ok. -if(?DEBUG =:= true). debug_log_time(Format, Args) -> NewFormat = "Ts: ~s -- " ++ Format, NewArgs = [util:local_timestamp()|Args], debug_log(NewFormat, NewArgs). -else. debug_log_time(_Format, _Args) -> ok. -endif.
null
https://raw.githubusercontent.com/angelhof/flumina/9602454b845cddf8e3dff8c54089c7f970ee08e1/src/log_mod.erl
erlang
TODO: If the API grows more, refactor these to have options like the rest (producer, sink) WARNING: At the moment this only logs messages, not heartbeats Obsolete synchronous logging code % the predicate to be anything instead of just a tag set %% WARNING: At the moment this only logs messages, not heartbeats old_maybe_log_message({{Tag, _}, _, _} = Msg, {Tags, _} = LoggerState) -> case sets:is_element(Tag, Tags) of true -> false -> ok end; old_maybe_log_message(Msg, LoggerState) -> ok. -spec log_message(gen_impl_message(), message_logger_state()) -> 'ok'. log_message(Msg, {_Tags, File}) -> %% CurrentTimestamp = erlang:system_time(nanosecond), ok = file:write(File, Data). Have a message logger to asynchronously log messages Trap exits to empty buffer if the producer exits If some linked process exits, then we have to empty buffer Number of messages loggers It should be messages every 500 ms Send the get_log_message to all mailboxes in the configuration Receive the answer from all mailboxes in the configuration Log all the answers in the file (with a current timestamp) These functions are for debug logging. The names of the files are generated from the pid and node This function creates and truncates the debug log file
-module(log_mod). -export([initialize_message_logger_state/2, initialize_message_logger_state/3, initialize_specialized_message_logger/3, initialize_specialized_message_logger/4, maybe_log_message/3, no_message_logger/1, message_logger/1, init_num_log_state/0, reset_num_log_state/1, incr_num_log_state/2, make_num_log_triple/0, no_log_triple/0, num_logger_process/2, init_debug_log/0, debug_log/2, debug_log_time/2]). -include("type_definitions.hrl"). -include("config.hrl"). -spec initialize_message_logger_state(string(), sets:set(tag())) -> message_logger_log_fun(). initialize_message_logger_state(Prefix, Tags) -> initialize_message_logger_state(Prefix, Tags, node()). -spec initialize_message_logger_state(string(), sets:set(tag()), node()) -> message_logger_log_fun(). initialize_message_logger_state(Prefix, Tags, Node) -> Filename = io_lib:format("~s/~s_~s_~s_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), Pid = spawn_link(Node, ?MODULE, message_logger, [Filename]), fun(Msg) -> maybe_log_message(Msg, Tags, Pid) end. -spec initialize_specialized_message_logger(string(), sets:set(tag()), impl_tag()) -> message_logger_log_fun(). initialize_specialized_message_logger(Prefix, Tags, ImplTag) -> initialize_specialized_message_logger(Prefix, Tags, ImplTag, node()). -spec initialize_specialized_message_logger(string(), sets:set(tag()), impl_tag(), node()) -> message_logger_log_fun(). initialize_specialized_message_logger(Prefix, Tags, ImplTag, Node) -> Filename = io_lib:format("~s/~s_~s_~s_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), Pid = spawn_link(Node, ?MODULE, message_logger, [Filename]), {Tag, _TagNode} = ImplTag, case sets:is_element(Tag, Tags) of true -> fun(Msg) -> log_message(Msg, Pid) end; false -> fun(_Msg) -> ok end end. the predicate to be anything instead of just a tag set -spec maybe_log_message(gen_impl_message(), sets:set(tag()), pid()) -> 'ok'. maybe_log_message({{Tag, _}, _, _} = Msg, Tags, Pid) -> case sets:is_element(Tag, Tags) of true -> log_message(Msg, Pid); false -> ok end; maybe_log_message(_Msg, _Tags, _Pid) -> ok. -spec log_message(gen_impl_message(), pid()) -> 'ok'. log_message(Msg, Pid) -> CurrentTimestamp = ?GET_SYSTEM_TIME(), PidNode = {self(), node()}, Pid ! {Msg, PidNode, CurrentTimestamp}, ok. -spec old_maybe_log_message(gen_impl_message ( ) , message_logger_state ( ) ) - > ' ok ' . log_message(Msg , LoggerState ) ; CurrentTimestamp = ? ( ) , PidNode = { self ( ) , node ( ) } , Data = io_lib : format("~w ~ n " , [ { Msg , PidNode , CurrentTimestamp } ] ) , -spec message_logger(file:filename()) -> ok. message_logger(Filename) -> process_flag(trap_exit, true), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [append, raw]), ok = file:truncate(IoDevice), message_logger_loop(IoDevice, [], 0). -type message_logger_buffer() :: [string()]. -spec message_logger_loop(file:io_device(), message_logger_buffer(), integer()) -> ok. message_logger_loop(IoDevice, Buffer, N) when N >= ?ASYNC_MESSAGE_LOGGER_BUFFER_SIZE-> OrderedBuffer = lists:reverse(Buffer), FlatOutput = lists:flatten(OrderedBuffer), ok = file:write(IoDevice, FlatOutput), message_logger_loop(IoDevice, [], 0); message_logger_loop(IoDevice, Buffer, N) -> receive {'EXIT', _, _} -> message_logger_loop(IoDevice, Buffer, ?ASYNC_MESSAGE_LOGGER_BUFFER_SIZE); MsgToLog -> Data = io_lib:format("~w~n", [MsgToLog]), message_logger_loop(IoDevice, [Data|Buffer], N+1) end. -spec no_message_logger(maybe_impl_tag()) -> message_logger_log_fun(). no_message_logger(_MaybeImplTag) -> fun(_Msg) -> ok end. -spec init_num_log_state() -> integer(). init_num_log_state() -> 0. -spec reset_num_log_state(num_log_state()) -> integer(). reset_num_log_state(_) -> 0. -spec incr_num_log_state(gen_message() | merge_request(), num_log_state()) -> num_log_state(). incr_num_log_state(_Msg, Num) -> Num + 1. -spec make_num_log_triple() -> num_log_triple(). make_num_log_triple() -> {fun log_mod:incr_num_log_state/2, fun log_mod:reset_num_log_state/1, init_num_log_state()}. -spec no_log_triple() -> num_log_triple(). no_log_triple() -> {fun(_,_) -> 0 end, fun(_) -> 0 end, 0}. -spec num_logger_process(string(), configuration()) -> ok. num_logger_process(Prefix, Configuration) -> io:format(" -- !!WARNING!! -- This is an obsolete method of logging throughput.~n" " Instead log total time and total number of messages!~n", []), register('num_messages_logger_process', self()), Filename = io_lib:format("~s/~s_~s_~s_num_messages.log", [?LOG_DIR, Prefix, pid_to_list(self()), atom_to_list(node())]), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [append]), ok = file:truncate(IoDevice), num_logger_process_loop(IoDevice, Configuration). -spec num_logger_process_loop(file:io_device(), configuration()) -> ok. num_logger_process_loop(IoDevice, Configuration) -> timer:sleep(500), PidMboxPairs = configuration:find_node_mailbox_pid_pairs(Configuration), {registered_name, MyName} = erlang:process_info(self(), registered_name), RequestMessage = {get_message_log, {MyName, node()}}, [Mbox ! RequestMessage || {_Node, Mbox} <- PidMboxPairs], ReceivedLogs = receive_message_logs(PidMboxPairs, []), CurrentTimestamp = ?GET_SYSTEM_TIME(), append_logs_in_file(ReceivedLogs, CurrentTimestamp, IoDevice), num_logger_process_loop(IoDevice, Configuration). -spec receive_message_logs([{pid(), mailbox()}], [{mailbox(), num_log_state()}]) -> [{mailbox(), num_log_state()}]. receive_message_logs([], Received) -> Received; receive_message_logs([{NodePid, {MboxName, Node}}|Rest], Received) -> receive {message_log, {NodePid, Node}, LogState} -> receive_message_logs(Rest, [{{MboxName, Node}, LogState}|Received]) end. -spec append_logs_in_file([{mailbox(), num_log_state()}], integer(), file:io_device()) -> ok. append_logs_in_file(ReceivedLogs, CurrentTimestamp, IoDevice) -> lists:foreach( fun(MboxLog) -> append_log_in_file(MboxLog, CurrentTimestamp, IoDevice) end, ReceivedLogs). -spec append_log_in_file({mailbox(), num_log_state()}, integer(), file:io_device()) -> ok. append_log_in_file({Mbox, Log}, CurrentTimestamp, IoDevice) -> Data = io_lib:format("~w~n", [{Mbox, CurrentTimestamp, Log}]), ok = file:write(IoDevice, Data). -spec init_debug_log() -> ok. -if(?DEBUG =:= true). init_debug_log() -> Filename = io_lib:format("~s/debug_~s_~s.log", [?LOG_DIR, pid_to_list(self()), atom_to_list(node())]), filelib:ensure_dir(Filename), {ok, IoDevice} = file:open(Filename, [write]), ok = file:truncate(IoDevice), ok = file:close(IoDevice). -else. init_debug_log() -> ok. -endif. -spec debug_log(string(), [any()]) -> ok. -if(?DEBUG =:= true). debug_log(Format, Args) -> Filename = io_lib:format("~s/debug_~s_~s.log", [?LOG_DIR, pid_to_list(self()), atom_to_list(node())]), Data = io_lib:format(Format, Args), filelib:ensure_dir(Filename), ok = file:write_file(Filename, Data, [append]). -else. debug_log(_Format, _Args) -> ok. -endif. -spec debug_log_time(string(), [any()]) -> ok. -if(?DEBUG =:= true). debug_log_time(Format, Args) -> NewFormat = "Ts: ~s -- " ++ Format, NewArgs = [util:local_timestamp()|Args], debug_log(NewFormat, NewArgs). -else. debug_log_time(_Format, _Args) -> ok. -endif.
c4b1b9062e3bd62809bb5258ac03123cbff6809097e560b0f36238316b9d8fe4
abdulapopoola/SICPBook
5.25.scm
#lang planet neil/sicp ;; Skipping this exercise However Skanev has a solution here ( if you are interested ) ;;
null
https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%205/5.4/5.25.scm
scheme
Skipping this exercise
#lang planet neil/sicp However Skanev has a solution here ( if you are interested )
d623d54372ae8f66b09891f9bc5deec1f6bd05a84045f379560b5329a14632dc
y-taka-23/wasm-game-of-life
UniverseSpec.hs
module Acme.GameOfLife.UniverseSpec (spec) where import Test.Hspec ( Spec, describe, it, shouldBe ) import Test.Hspec.QuickCheck ( prop ) import Acme.GameOfLife.Universe ( fromList , stringify , tick , toggle , unstringify ) spec :: Spec spec = do describe "tick" $ do it "preserves the blank universe" $ do let input = [] expected = [] tick (fromList 4 4 input) `shouldBe` fromList 4 4 expected it "moves a glider" $ do let input = [(1, 2), (2, 3), (3, 1), (3, 2), (3, 3)] expected = [(2, 1), (2, 3), (3, 2), (3, 3), (4, 2)] tick (fromList 6 6 input) `shouldBe` fromList 6 6 expected describe "toggle" $ do prop "toggle is involutive" $ \i j h w ps -> do let univ = fromList h w ps toggle i j (toggle i j univ) `shouldBe` univ describe "unstringify" $ do prop "unstringify is the inverse of stringify" $ \h w ps-> do let univ = fromList h w ps unstringify h w (stringify univ) `shouldBe` univ
null
https://raw.githubusercontent.com/y-taka-23/wasm-game-of-life/69b3269e3fa05c65b7def23fdb7a71a92a22c54f/test/Acme/GameOfLife/UniverseSpec.hs
haskell
module Acme.GameOfLife.UniverseSpec (spec) where import Test.Hspec ( Spec, describe, it, shouldBe ) import Test.Hspec.QuickCheck ( prop ) import Acme.GameOfLife.Universe ( fromList , stringify , tick , toggle , unstringify ) spec :: Spec spec = do describe "tick" $ do it "preserves the blank universe" $ do let input = [] expected = [] tick (fromList 4 4 input) `shouldBe` fromList 4 4 expected it "moves a glider" $ do let input = [(1, 2), (2, 3), (3, 1), (3, 2), (3, 3)] expected = [(2, 1), (2, 3), (3, 2), (3, 3), (4, 2)] tick (fromList 6 6 input) `shouldBe` fromList 6 6 expected describe "toggle" $ do prop "toggle is involutive" $ \i j h w ps -> do let univ = fromList h w ps toggle i j (toggle i j univ) `shouldBe` univ describe "unstringify" $ do prop "unstringify is the inverse of stringify" $ \h w ps-> do let univ = fromList h w ps unstringify h w (stringify univ) `shouldBe` univ
846540881c9e270d9b0854ce11a8c6d2cf99af2c1d01d6fa3a9875a9b72b8cda
rmloveland/scheme48-0.53
low.scm
Copyright ( c ) 1993 - 1999 by and . See file COPYING . ; Portable versions of low-level things that would really like to rely ; on the Scheme 48 VM or on special features provided by the byte code ; compiler. (define (vector-unassigned? v i) #f) (define (flush-the-symbol-table!) #f) (define maybe-open-input-file open-input-file) (define maybe-open-output-file open-output-file) ; Suppress undefined export warnings. (define-syntax %file-name% (syntax-rules () ((%file-name%) ""))) (define-syntax structure-ref (syntax-rules () ((structure-ref ?struct ?name) (error "structure-ref isn't implemented" '?struct '?name))))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/alt/low.scm
scheme
Portable versions of low-level things that would really like to rely on the Scheme 48 VM or on special features provided by the byte code compiler. Suppress undefined export warnings.
Copyright ( c ) 1993 - 1999 by and . See file COPYING . (define (vector-unassigned? v i) #f) (define (flush-the-symbol-table!) #f) (define maybe-open-input-file open-input-file) (define maybe-open-output-file open-output-file) (define-syntax %file-name% (syntax-rules () ((%file-name%) ""))) (define-syntax structure-ref (syntax-rules () ((structure-ref ?struct ?name) (error "structure-ref isn't implemented" '?struct '?name))))
ee329036de929ee5e247e9d34143886d024c450b0daf612aaa6422914409f21f
metabase/metabase
setting_test.clj
(ns ^:mb/once metabase.api.setting-test (:require [clojure.test :refer :all] [metabase.api.common.validation :as validation] [metabase.models.setting :as setting :refer [defsetting]] [metabase.models.setting-test :as models.setting-test] [metabase.public-settings.premium-features-test :as premium-features-test] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.util.i18n :refer [deferred-tru]] [schema.core :as s])) (set! *warn-on-reflection* true) (use-fixtures :once (fixtures/initialize :db)) (defsetting test-api-setting-boolean (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :boolean) (defsetting test-api-setting-double (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :double) (defsetting test-api-setting-integer (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :integer) (defsetting test-settings-manager-visibility (deferred-tru "Setting to test the `:settings-manager` visibility level. This only shows up in dev.") :visibility :settings-manager) # # Helper Fns (defn- fetch-test-settings "Fetch the provided settings using the API. Settings not present in the response are ignored." ([setting-names] (fetch-test-settings :crowberto setting-names)) ([user setting-names] (for [setting (mt/user-http-request user :get 200 "setting") :when (.contains ^clojure.lang.PersistentVector (vec setting-names) (keyword (:key setting)))] setting))) (defn- fetch-setting "Fetch a single setting." ([setting-name status] (fetch-setting :crowberto setting-name status)) ([user setting-name status] (mt/user-http-request user :get status (format "setting/%s" (name setting-name))))) (defn- do-with-mocked-settings-manager-access [f] (with-redefs [setting/has-advanced-setting-access? (constantly true) validation/check-has-application-permission (constantly true)] (f))) (defmacro ^:private with-mocked-settings-manager-access "Runs `body` with the approrpiate functions redefined to give the current user settings manager permissions." [& body] `(do-with-mocked-settings-manager-access (fn [] ~@body))) (deftest fetch-setting-test (testing "GET /api/setting" (testing "Check that we can fetch all Settings as an admin, except `:visiblity :internal` ones" (models.setting-test/test-setting-1! nil) (models.setting-test/test-setting-2! "FANCY") (models.setting-test/test-setting-3! "oh hai") ; internal setting that should not be returned (is (= [{:key "test-setting-1" :value nil :is_env_setting false :env_name "MB_TEST_SETTING_1" :description "Test setting - this only shows up in dev (1)" :default nil} {:key "test-setting-2" :value "FANCY" :is_env_setting false :env_name "MB_TEST_SETTING_2" :description "Test setting - this only shows up in dev (2)" :default "[Default Value]"}] (fetch-test-settings [:test-setting-1 :test-setting-2 :test-setting-3])))) (testing "Check that non-admin setting managers can fetch Settings with `:visibility :settings-manager`" (test-settings-manager-visibility! nil) (with-mocked-settings-manager-access (is (= [{:key "test-settings-manager-visibility", :value nil, :is_env_setting false, :env_name "MB_TEST_SETTINGS_MANAGER_VISIBILITY", :description "Setting to test the `:settings-manager` visibility level. This only shows up in dev.", :default nil}] (fetch-test-settings :rasta [:test-setting-1 :test-settings-manager-visibility]))))) (testing "Check that non-admins are denied access" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 "setting"))))) (testing "GET /api/setting/:key" (testing "Test that admins can fetch a single Setting" (models.setting-test/test-setting-2! "OK!") (is (= "OK!" (fetch-setting :test-setting-2 200)))) (testing "Test that non-admin setting managers can fetch a single Setting if it has `:visibility :settings-manager`." (test-settings-manager-visibility! "OK!") (with-mocked-settings-manager-access (is (= "OK!" (fetch-setting :test-settings-manager-visibility 200))))) (testing "Check that non-superusers cannot fetch a single Setting if it is not user-local" (is (= "You don't have permissions to do that." (fetch-setting :rasta :test-setting-2 403)))) (testing "non-string values work over the api (#20735)" ;; n.b. the api will return nil if a setting is its default value. (test-api-setting-double! 3.14) (is (= 3.14 (fetch-setting :test-api-setting-double 200))) (test-api-setting-boolean! true) (is (= true (fetch-setting :test-api-setting-boolean 200))) (test-api-setting-integer! 42) (is (= 42 (fetch-setting :test-api-setting-integer 200)))))) (deftest fetch-calculated-settings-test (testing "GET /api/setting" (testing "Should return the correct `:value` for Settings with no underlying DB/env var value" (premium-features-test/with-premium-features #{:embedding} (is (schema= {:key (s/eq "hide-embed-branding?") :value (s/eq true) :is_env_setting (s/eq false) :env_name (s/eq "MB_HIDE_EMBED_BRANDING") :default (s/eq nil) s/Keyword s/Any} (some (fn [{setting-name :key, :as setting}] (when (= setting-name "hide-embed-branding?") setting)) (mt/user-http-request :crowberto :get 200 "setting")))))))) (deftest fetch-internal-settings-test (testing "Test that we can't fetch internal settings" (models.setting-test/test-setting-3! "NOPE!") (is (= "Setting :test-setting-3 is internal" (:message (fetch-setting :test-setting-3 500)))))) (deftest update-settings-test (testing "PUT /api/setting/:key" (mt/user-http-request :crowberto :put 204 "setting/test-setting-1" {:value "NICE!"}) (is (= "NICE!" (models.setting-test/test-setting-1)) "Updated setting should be visible from setting getter") (is (= "NICE!" (fetch-setting :test-setting-1 200)) "Updated setting should be visible from API endpoint") (testing "Check that non-admin setting managers can only update Settings with `:visibility :settings-manager`." (with-mocked-settings-manager-access (mt/user-http-request :rasta :put 204 "setting/test-settings-manager-visibility" {:value "NICE!"}) (is (= "NICE!" (fetch-setting :test-settings-manager-visibility 200))) (mt/user-http-request :rasta :put 403 "setting/test-setting-1" {:value "Not nice :("}))) (testing "Check non-superuser can't set a Setting that is not user-local" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting/test-setting-1" {:value "NICE!"})))) (testing "Check that a generic 403 error is returned if a non-superuser tries to set a Setting that doesn't exist" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting/bad-setting" {:value "NICE!"})))))) (deftest fetch-sensitive-setting-test (testing "Sensitive settings should always come back obfuscated" (testing "GET /api/setting/:name" (models.setting-test/test-sensitive-setting! "ABCDEF") (is (= "**********EF" (fetch-setting :test-sensitive-setting 200)))) (testing "GET /api/setting" (models.setting-test/test-sensitive-setting! "GHIJKLM") (is (= {:key "test-sensitive-setting" :value "**********LM" :is_env_setting false :env_name "MB_TEST_SENSITIVE_SETTING" :description "This is a sample sensitive Setting." :default nil} (some (fn [{setting-name :key, :as setting}] (when (= setting-name "test-sensitive-setting") setting)) (mt/user-http-request :crowberto :get 200 "setting"))))))) (deftest set-sensitive-setting-test (testing (str "Setting the Setting via an endpoint should still work as expected; the normal getter functions " "should *not* obfuscate sensitive Setting values -- that should be done by the API") (mt/user-http-request :crowberto :put 204 "setting/test-sensitive-setting" {:value "123456"}) (is (= "123456" (models.setting-test/test-sensitive-setting)))) (testing "Attempts to set the Setting to an obfuscated value should be ignored" (testing "PUT /api/setting/:name" (models.setting-test/test-sensitive-setting! "123456") (is (= nil (mt/user-http-request :crowberto :put 204 "setting/test-sensitive-setting" {:value "**********56"}))) (is (= "123456" (models.setting-test/test-sensitive-setting)))) (testing "PUT /api/setting" (models.setting-test/test-sensitive-setting! "123456") (is (= nil (mt/user-http-request :crowberto :put 204 "setting" {:test-sensitive-setting "**********56"}))) (is (= "123456" (models.setting-test/test-sensitive-setting)))))) ;; there are additional tests for this functionality in [[metabase.models.models.setting-test/set-many!-test]], since ;; this API endpoint is just a thin wrapper around that function (deftest update-multiple-settings-test (testing "PUT /api/setting/" (testing "admin should be able to update multiple settings at once" (is (= nil (mt/user-http-request :crowberto :put 204 "setting" {:test-setting-1 "ABC", :test-setting-2 "DEF"}))) (is (= "ABC" (models.setting-test/test-setting-1))) (is (= "DEF" (models.setting-test/test-setting-2)))) (testing "non-admin setting managers should only be able to update multiple settings at once if they have `:visibility :settings-manager`" (with-mocked-settings-manager-access (is (= nil (mt/user-http-request :rasta :put 204 "setting" {:test-settings-manager-visibility "ABC"}))) (is (= "ABC" (test-settings-manager-visibility))) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-settings-manager-visibility "GHI", :test-setting-1 "JKL"}))) (is (= "ABC" (test-settings-manager-visibility))) (is (= "ABC" (models.setting-test/test-setting-1))))) (testing "non-admin should not be able to update multiple settings at once if any of them are not user-local" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-setting-1 "GHI", :test-setting-2 "JKL"}))) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-setting-1 "GHI", :test-user-local-allowed-setting "JKL"})))))) (defn- fetch-user-local-test-settings [user] (for [setting (mt/user-http-request user :get 200 "setting") :when (re-find #"^test-user-local.*setting$" (name (:key setting)))] setting)) (defn- set-initial-user-local-values [] (mt/with-current-user (mt/user->id :crowberto) (models.setting-test/test-user-local-only-setting! "ABC") (models.setting-test/test-user-local-allowed-setting! "ABC")) (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting! "DEF") (models.setting-test/test-user-local-allowed-setting! "DEF"))) (defn- clear-user-local-values [] (mt/with-current-user (mt/user->id :crowberto) (models.setting-test/test-user-local-only-setting! nil) (models.setting-test/test-user-local-allowed-setting! nil)) (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting! nil) (models.setting-test/test-user-local-allowed-setting! nil))) (deftest user-local-settings-test (testing "GET /api/setting/" (testing "admins can list all settings and see user-local values included" (set-initial-user-local-values) (is (= [{:key "test-user-local-allowed-setting" :value "ABC" , :is_env_setting false, :env_name "MB_TEST_USER_LOCAL_ALLOWED_SETTING", :description "test Setting", :default nil} {:key "test-user-local-only-setting", :value "ABC" , :is_env_setting false, :env_name "MB_TEST_USER_LOCAL_ONLY_SETTING", :description "test Setting", :default nil}] (fetch-user-local-test-settings :crowberto))) (clear-user-local-values))) (testing "GET /api/setting/:key" (testing "should return the user-local value of a user-local setting" (set-initial-user-local-values) (is (= "ABC" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (is (= "ABC" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (is (= "DEF" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (is (= "DEF" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values))) (testing "PUT /api/setting/:key" (testing "should update the user-local value of a user-local setting" (set-initial-user-local-values) (mt/user-http-request :crowberto :put 204 "setting/test-user-local-only-setting" {:value "GHI"}) (is (= "GHI" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (mt/user-http-request :crowberto :put 204 "setting/test-user-local-allowed-setting" {:value "JKL"}) (is (= "JKL" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (mt/user-http-request :rasta :put 204 "setting/test-user-local-only-setting" {:value "MNO"}) (is (= "MNO" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (mt/user-http-request :rasta :put 204 "setting/test-user-local-allowed-setting" {:value "PQR"}) (is (= "PQR" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values))) (testing "PUT /api/setting" (testing "can updated multiple user-local settings at once" (set-initial-user-local-values) (mt/user-http-request :crowberto :put 204 "setting" {:test-user-local-only-setting "GHI" :test-user-local-allowed-setting "JKL"}) (is (= "GHI" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (is (= "JKL" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (mt/user-http-request :rasta :put 204 "setting" {:test-user-local-only-setting "MNO" :test-user-local-allowed-setting "PQR"}) (is (= "MNO" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (is (= "PQR" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values)) (testing "if a non-admin tries to set multiple settings and any aren't user-local, none are updated" (set-initial-user-local-values) (models.setting-test/test-setting-1! "ABC") (mt/user-http-request :rasta :put 403 "setting" {:test-user-local-only-setting "MNO" :test-setting-1 "PQR"}) (is (= "DEF" (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting)))) (is (= "ABC" (models.setting-test/test-setting-1))))))
null
https://raw.githubusercontent.com/metabase/metabase/56b28e5b07e73002d5c507f583e3d64439ba8b8c/test/metabase/api/setting_test.clj
clojure
internal setting that should not be returned n.b. the api will return nil if a setting is its default value. there are additional tests for this functionality in [[metabase.models.models.setting-test/set-many!-test]], since this API endpoint is just a thin wrapper around that function
(ns ^:mb/once metabase.api.setting-test (:require [clojure.test :refer :all] [metabase.api.common.validation :as validation] [metabase.models.setting :as setting :refer [defsetting]] [metabase.models.setting-test :as models.setting-test] [metabase.public-settings.premium-features-test :as premium-features-test] [metabase.test :as mt] [metabase.test.fixtures :as fixtures] [metabase.util.i18n :refer [deferred-tru]] [schema.core :as s])) (set! *warn-on-reflection* true) (use-fixtures :once (fixtures/initialize :db)) (defsetting test-api-setting-boolean (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :boolean) (defsetting test-api-setting-double (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :double) (defsetting test-api-setting-integer (deferred-tru "Test setting - this only shows up in dev (3)") :visibility :public :type :integer) (defsetting test-settings-manager-visibility (deferred-tru "Setting to test the `:settings-manager` visibility level. This only shows up in dev.") :visibility :settings-manager) # # Helper Fns (defn- fetch-test-settings "Fetch the provided settings using the API. Settings not present in the response are ignored." ([setting-names] (fetch-test-settings :crowberto setting-names)) ([user setting-names] (for [setting (mt/user-http-request user :get 200 "setting") :when (.contains ^clojure.lang.PersistentVector (vec setting-names) (keyword (:key setting)))] setting))) (defn- fetch-setting "Fetch a single setting." ([setting-name status] (fetch-setting :crowberto setting-name status)) ([user setting-name status] (mt/user-http-request user :get status (format "setting/%s" (name setting-name))))) (defn- do-with-mocked-settings-manager-access [f] (with-redefs [setting/has-advanced-setting-access? (constantly true) validation/check-has-application-permission (constantly true)] (f))) (defmacro ^:private with-mocked-settings-manager-access "Runs `body` with the approrpiate functions redefined to give the current user settings manager permissions." [& body] `(do-with-mocked-settings-manager-access (fn [] ~@body))) (deftest fetch-setting-test (testing "GET /api/setting" (testing "Check that we can fetch all Settings as an admin, except `:visiblity :internal` ones" (models.setting-test/test-setting-1! nil) (models.setting-test/test-setting-2! "FANCY") (is (= [{:key "test-setting-1" :value nil :is_env_setting false :env_name "MB_TEST_SETTING_1" :description "Test setting - this only shows up in dev (1)" :default nil} {:key "test-setting-2" :value "FANCY" :is_env_setting false :env_name "MB_TEST_SETTING_2" :description "Test setting - this only shows up in dev (2)" :default "[Default Value]"}] (fetch-test-settings [:test-setting-1 :test-setting-2 :test-setting-3])))) (testing "Check that non-admin setting managers can fetch Settings with `:visibility :settings-manager`" (test-settings-manager-visibility! nil) (with-mocked-settings-manager-access (is (= [{:key "test-settings-manager-visibility", :value nil, :is_env_setting false, :env_name "MB_TEST_SETTINGS_MANAGER_VISIBILITY", :description "Setting to test the `:settings-manager` visibility level. This only shows up in dev.", :default nil}] (fetch-test-settings :rasta [:test-setting-1 :test-settings-manager-visibility]))))) (testing "Check that non-admins are denied access" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :get 403 "setting"))))) (testing "GET /api/setting/:key" (testing "Test that admins can fetch a single Setting" (models.setting-test/test-setting-2! "OK!") (is (= "OK!" (fetch-setting :test-setting-2 200)))) (testing "Test that non-admin setting managers can fetch a single Setting if it has `:visibility :settings-manager`." (test-settings-manager-visibility! "OK!") (with-mocked-settings-manager-access (is (= "OK!" (fetch-setting :test-settings-manager-visibility 200))))) (testing "Check that non-superusers cannot fetch a single Setting if it is not user-local" (is (= "You don't have permissions to do that." (fetch-setting :rasta :test-setting-2 403)))) (testing "non-string values work over the api (#20735)" (test-api-setting-double! 3.14) (is (= 3.14 (fetch-setting :test-api-setting-double 200))) (test-api-setting-boolean! true) (is (= true (fetch-setting :test-api-setting-boolean 200))) (test-api-setting-integer! 42) (is (= 42 (fetch-setting :test-api-setting-integer 200)))))) (deftest fetch-calculated-settings-test (testing "GET /api/setting" (testing "Should return the correct `:value` for Settings with no underlying DB/env var value" (premium-features-test/with-premium-features #{:embedding} (is (schema= {:key (s/eq "hide-embed-branding?") :value (s/eq true) :is_env_setting (s/eq false) :env_name (s/eq "MB_HIDE_EMBED_BRANDING") :default (s/eq nil) s/Keyword s/Any} (some (fn [{setting-name :key, :as setting}] (when (= setting-name "hide-embed-branding?") setting)) (mt/user-http-request :crowberto :get 200 "setting")))))))) (deftest fetch-internal-settings-test (testing "Test that we can't fetch internal settings" (models.setting-test/test-setting-3! "NOPE!") (is (= "Setting :test-setting-3 is internal" (:message (fetch-setting :test-setting-3 500)))))) (deftest update-settings-test (testing "PUT /api/setting/:key" (mt/user-http-request :crowberto :put 204 "setting/test-setting-1" {:value "NICE!"}) (is (= "NICE!" (models.setting-test/test-setting-1)) "Updated setting should be visible from setting getter") (is (= "NICE!" (fetch-setting :test-setting-1 200)) "Updated setting should be visible from API endpoint") (testing "Check that non-admin setting managers can only update Settings with `:visibility :settings-manager`." (with-mocked-settings-manager-access (mt/user-http-request :rasta :put 204 "setting/test-settings-manager-visibility" {:value "NICE!"}) (is (= "NICE!" (fetch-setting :test-settings-manager-visibility 200))) (mt/user-http-request :rasta :put 403 "setting/test-setting-1" {:value "Not nice :("}))) (testing "Check non-superuser can't set a Setting that is not user-local" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting/test-setting-1" {:value "NICE!"})))) (testing "Check that a generic 403 error is returned if a non-superuser tries to set a Setting that doesn't exist" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting/bad-setting" {:value "NICE!"})))))) (deftest fetch-sensitive-setting-test (testing "Sensitive settings should always come back obfuscated" (testing "GET /api/setting/:name" (models.setting-test/test-sensitive-setting! "ABCDEF") (is (= "**********EF" (fetch-setting :test-sensitive-setting 200)))) (testing "GET /api/setting" (models.setting-test/test-sensitive-setting! "GHIJKLM") (is (= {:key "test-sensitive-setting" :value "**********LM" :is_env_setting false :env_name "MB_TEST_SENSITIVE_SETTING" :description "This is a sample sensitive Setting." :default nil} (some (fn [{setting-name :key, :as setting}] (when (= setting-name "test-sensitive-setting") setting)) (mt/user-http-request :crowberto :get 200 "setting"))))))) (deftest set-sensitive-setting-test (testing (str "Setting the Setting via an endpoint should still work as expected; the normal getter functions " "should *not* obfuscate sensitive Setting values -- that should be done by the API") (mt/user-http-request :crowberto :put 204 "setting/test-sensitive-setting" {:value "123456"}) (is (= "123456" (models.setting-test/test-sensitive-setting)))) (testing "Attempts to set the Setting to an obfuscated value should be ignored" (testing "PUT /api/setting/:name" (models.setting-test/test-sensitive-setting! "123456") (is (= nil (mt/user-http-request :crowberto :put 204 "setting/test-sensitive-setting" {:value "**********56"}))) (is (= "123456" (models.setting-test/test-sensitive-setting)))) (testing "PUT /api/setting" (models.setting-test/test-sensitive-setting! "123456") (is (= nil (mt/user-http-request :crowberto :put 204 "setting" {:test-sensitive-setting "**********56"}))) (is (= "123456" (models.setting-test/test-sensitive-setting)))))) (deftest update-multiple-settings-test (testing "PUT /api/setting/" (testing "admin should be able to update multiple settings at once" (is (= nil (mt/user-http-request :crowberto :put 204 "setting" {:test-setting-1 "ABC", :test-setting-2 "DEF"}))) (is (= "ABC" (models.setting-test/test-setting-1))) (is (= "DEF" (models.setting-test/test-setting-2)))) (testing "non-admin setting managers should only be able to update multiple settings at once if they have `:visibility :settings-manager`" (with-mocked-settings-manager-access (is (= nil (mt/user-http-request :rasta :put 204 "setting" {:test-settings-manager-visibility "ABC"}))) (is (= "ABC" (test-settings-manager-visibility))) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-settings-manager-visibility "GHI", :test-setting-1 "JKL"}))) (is (= "ABC" (test-settings-manager-visibility))) (is (= "ABC" (models.setting-test/test-setting-1))))) (testing "non-admin should not be able to update multiple settings at once if any of them are not user-local" (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-setting-1 "GHI", :test-setting-2 "JKL"}))) (is (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 "setting" {:test-setting-1 "GHI", :test-user-local-allowed-setting "JKL"})))))) (defn- fetch-user-local-test-settings [user] (for [setting (mt/user-http-request user :get 200 "setting") :when (re-find #"^test-user-local.*setting$" (name (:key setting)))] setting)) (defn- set-initial-user-local-values [] (mt/with-current-user (mt/user->id :crowberto) (models.setting-test/test-user-local-only-setting! "ABC") (models.setting-test/test-user-local-allowed-setting! "ABC")) (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting! "DEF") (models.setting-test/test-user-local-allowed-setting! "DEF"))) (defn- clear-user-local-values [] (mt/with-current-user (mt/user->id :crowberto) (models.setting-test/test-user-local-only-setting! nil) (models.setting-test/test-user-local-allowed-setting! nil)) (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting! nil) (models.setting-test/test-user-local-allowed-setting! nil))) (deftest user-local-settings-test (testing "GET /api/setting/" (testing "admins can list all settings and see user-local values included" (set-initial-user-local-values) (is (= [{:key "test-user-local-allowed-setting" :value "ABC" , :is_env_setting false, :env_name "MB_TEST_USER_LOCAL_ALLOWED_SETTING", :description "test Setting", :default nil} {:key "test-user-local-only-setting", :value "ABC" , :is_env_setting false, :env_name "MB_TEST_USER_LOCAL_ONLY_SETTING", :description "test Setting", :default nil}] (fetch-user-local-test-settings :crowberto))) (clear-user-local-values))) (testing "GET /api/setting/:key" (testing "should return the user-local value of a user-local setting" (set-initial-user-local-values) (is (= "ABC" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (is (= "ABC" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (is (= "DEF" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (is (= "DEF" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values))) (testing "PUT /api/setting/:key" (testing "should update the user-local value of a user-local setting" (set-initial-user-local-values) (mt/user-http-request :crowberto :put 204 "setting/test-user-local-only-setting" {:value "GHI"}) (is (= "GHI" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (mt/user-http-request :crowberto :put 204 "setting/test-user-local-allowed-setting" {:value "JKL"}) (is (= "JKL" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (mt/user-http-request :rasta :put 204 "setting/test-user-local-only-setting" {:value "MNO"}) (is (= "MNO" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (mt/user-http-request :rasta :put 204 "setting/test-user-local-allowed-setting" {:value "PQR"}) (is (= "PQR" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values))) (testing "PUT /api/setting" (testing "can updated multiple user-local settings at once" (set-initial-user-local-values) (mt/user-http-request :crowberto :put 204 "setting" {:test-user-local-only-setting "GHI" :test-user-local-allowed-setting "JKL"}) (is (= "GHI" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-only-setting"))) (is (= "JKL" (mt/user-http-request :crowberto :get 200 "setting/test-user-local-allowed-setting"))) (mt/user-http-request :rasta :put 204 "setting" {:test-user-local-only-setting "MNO" :test-user-local-allowed-setting "PQR"}) (is (= "MNO" (mt/user-http-request :rasta :get 200 "setting/test-user-local-only-setting"))) (is (= "PQR" (mt/user-http-request :rasta :get 200 "setting/test-user-local-allowed-setting"))) (clear-user-local-values)) (testing "if a non-admin tries to set multiple settings and any aren't user-local, none are updated" (set-initial-user-local-values) (models.setting-test/test-setting-1! "ABC") (mt/user-http-request :rasta :put 403 "setting" {:test-user-local-only-setting "MNO" :test-setting-1 "PQR"}) (is (= "DEF" (mt/with-current-user (mt/user->id :rasta) (models.setting-test/test-user-local-only-setting)))) (is (= "ABC" (models.setting-test/test-setting-1))))))
7a5a46daceb6a034de94c29f430ce5a7ec9cc3d4b04b7e4abfef8686ffdf60c5
polymeris/cljs-aws
cloudhsm.cljs
(ns cljs-aws.cloudhsm (:require [cljs-aws.base.requests]) (:require-macros [cljs-aws.base.service :refer [defservice]])) (defservice "CloudHSM" "cloudhsm-2014-05-30.min.json")
null
https://raw.githubusercontent.com/polymeris/cljs-aws/3326e7c4db4dfc36dcb80770610c14c8a7fd0d66/src/cljs_aws/cloudhsm.cljs
clojure
(ns cljs-aws.cloudhsm (:require [cljs-aws.base.requests]) (:require-macros [cljs-aws.base.service :refer [defservice]])) (defservice "CloudHSM" "cloudhsm-2014-05-30.min.json")
3633b6b508be3bf7c081aebcad626ec08d3239038582a43b57eb0b1d8fb963f3
leon-gondelman/ocaml2lang
translate.ml
open Location open Longident module P = Parsetree open Lang type info = { (* auxiliary information needed for translation, such as free variables, local variables, paths, etc. *) info_lvars: (ident, unit) Hashtbl.t; } let create_info () = { info_lvars = Hashtbl.create 16 } let mk_gvar s = Evar (Vgvar (Gvar s)) let rec name_of_pat pat = match pat.P.ppat_desc with | Ppat_any -> "_" | Ppat_var s -> s.txt | Ppat_constraint (p, _) -> name_of_pat p TODO let rec structure info str = List.flatten (List.map (structure_item info) str) and structure_item info str_item = match str_item.P.pstr_desc with | Pstr_value (rec_flag, [val_bind]) -> TODO let id, expr = value_binding info val_bind in [DDefinition (id, TyVal, expr)] | Pstr_type _ -> [] TODO and value_binding info {pvb_pat; pvb_expr; _} = name_of_pat pvb_pat, expression info [] pvb_expr and longident info params = function TODO | Lident s -> if List.mem s params || Hashtbl.mem info.info_lvars s then Vlvar s else Vgvar (Gvar s) | Ldot (t, s) -> let v = longident info [] t in match v with | Vgvar x -> Vgvar (Gdot (x, s)) | Vlvar _ -> assert false and expression info params expr = let is_fst P.{pexp_desc; _} = match pexp_desc with | Pexp_ident {txt = Lident "fst"; _} -> true | _ -> false in let is_snd P.{pexp_desc; _} = match pexp_desc with | Pexp_ident {txt = Lident "snd"; _} -> true | _ -> false in let rec loop (P.{pexp_desc; _} as e) = match pexp_desc with | Pexp_fun (_, _, pat, e) -> let args, expr = loop e in let id = name_of_pat pat in id :: args, expr | _ -> [], e in let add_info id = Hashtbl.add info.info_lvars id () in let add_local_args args = List.iter add_info args in let remove_info id = Hashtbl.remove info.info_lvars id in let remove_local_args args = List.iter remove_info args in match expr.pexp_desc with | Pexp_constant c -> Evalue (LitV (constant c)) | Pexp_construct (c,o) -> construct info params (c,o) | Pexp_ident t -> Evar (longident info params t.txt) | Pexp_fun (Nolabel, None, pat, expr) -> let id = name_of_pat pat in let expr = expression info (id :: params) expr in begin match expr with | Efun (il, e) -> Efun (id :: il, e) | _ -> Efun ([id], expr) end | Pexp_apply (f, [(_, e)]) when is_fst f -> EFst (expression info params e) | Pexp_apply (f, [(_, e)]) when is_snd f -> ESnd (expression info params e) | Pexp_apply (e1, el) -> let expr1 = expression info params e1 in let (_, args) = List.split el in let exprl = List.map (expression info params) args in Eapp (expr1, exprl) | Pexp_tuple expr_list when List.length expr_list = 2 -> Etuple (List.map (expression info params) expr_list) | Pexp_tuple _ -> TODO | Pexp_match (e, [c1; c2]) -> let expr = expression info params e in Ecase (expr, pattern info params c1, pattern info params c2) | Pexp_match _ -> TODO | Pexp_constraint (e, _) -> expression info params e | Pexp_let (Recursive, [{pvb_pat; pvb_expr; _}], e2) -> let fun_name = name_of_pat pvb_pat in let args, e1 = loop pvb_expr in add_info fun_name; add_local_args args; let e1 = expression info params e1 in let e2 = expression info params e2 in remove_info fun_name; remove_local_args args; Erec (fun_name, args, e1, e2) TODO and pattern info params P.{pc_lhs; pc_rhs; _} = let add_info id = Hashtbl.add info.info_lvars id () in let rec pat_desc P.{ppat_desc; _} = match ppat_desc with | P.Ppat_any -> Ppat_any | Ppat_var {txt; _} -> add_info txt; Ppat_var txt | Ppat_construct ({txt; _}, p) -> Ppat_apply (longident info params txt, Option.map pat_desc p) TODO let pc_lhs = pat_desc pc_lhs in let pc_rhs = expression info params pc_rhs in { pc_lhs; pc_rhs } and constant = function Pconst_integer (t, _) -> LitInt (int_of_string t) | Pconst_string (s, _, _) -> LitString s not implemented in AnerisLang not implemented in AnerisLang and construct info params = function | ({txt = Lident "()"; loc = _}, None) -> Evalue (LitV LitUnit) | ({txt = Lident "true"; loc = _}, None) -> Evalue (LitV (LitBool true)) | ({txt = Lident "false"; loc = _}, None) -> Evalue (LitV (LitBool false)) | ({txt = Lident "None"; loc = _}, None) -> Evalue NONEV | ({txt = Lident "Some"; loc = _}, Some expr) -> let e = expression info params expr in begin match e with | Evalue v -> Evalue (SOMEV v) | _ -> Esome e end | ({txt = Lident "::"; loc = _}, Some e) -> begin match e.pexp_desc with | Pexp_tuple [e1;e2] -> Eapp (mk_gvar "::", [expression info params e1; expression info params e2]) | _ -> assert false end | ({txt = Lident "[]"; loc = _}, None) -> Evalue NONEV TODO type un_op = * | NegOp | MinusUnOp | StringOfInt | IntOfString | StringLength * * type bin_op = * | PlusOp | MinusOp | MultOp | QuotOp | RemOp ( \ * Arithmetic * \ ) * | AndOp | OrOp | XorOp ( \ * Bitwise * \ ) * | ShiftLOp | ShiftROp ( \ * Shifts * \ ) * | LeOp | LtOp | EqOp ( \ * Relations * \ ) * | StringApp * | NegOp | MinusUnOp | StringOfInt | IntOfString | StringLength * * type bin_op = * | PlusOp | MinusOp | MultOp | QuotOp | RemOp (\* Arithmetic *\) * | AndOp | OrOp | XorOp (\* Bitwise *\) * | ShiftLOp | ShiftROp (\* Shifts *\) * | LeOp | LtOp | EqOp (\* Relations *\) * | StringApp *) let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let f x = y " ) ) ; * [ % expect { | Definition f : base_lang.val : = λ : " x " , y. | } ] * * let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let x = [ 1;2;3 ] " ) ) ; * [ % expect{| * Definition x : base_lang.val : = * list_cons # 1 ( list_cons # 2 ( list_cons # 3 NONEV ) ) . | } ] * * let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let f x = List.fold_left ( fun x y - > x y z ) [ 1;2;3 ] " ) ) ; * [ % expect{| * Definition f : base_lang.val : = * λ : " x " , * list_fold ( λ : " x " " y " , " x " " y " z ) * ( list_cons # 1 ( list_cons # 2 ( list_cons # 3 NONE ) ) ) . | } ] * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let f x = y")); * [%expect {| Definition f : base_lang.val := λ: "x", y. |}] * * let%expect_test _ = * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let x = [1;2;3]")); * [%expect{| * Definition x : base_lang.val := * list_cons #1 (list_cons #2 (list_cons #3 NONEV)). |}] * * let%expect_test _ = * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let f x = List.fold_left (fun x y -> x y z) [1;2;3]")); * [%expect{| * Definition f : base_lang.val := * λ: "x", * list_fold (λ: "x" "y", "x" "y" z) * (list_cons #1 (list_cons #2 (list_cons #3 NONE))). |}] *)
null
https://raw.githubusercontent.com/leon-gondelman/ocaml2lang/f94f02d35b537623b7e4da812d33eb6c29cc9214/tmp/translate.ml
ocaml
auxiliary information needed for translation, such as free variables, local variables, paths, etc.
open Location open Longident module P = Parsetree open Lang info_lvars: (ident, unit) Hashtbl.t; } let create_info () = { info_lvars = Hashtbl.create 16 } let mk_gvar s = Evar (Vgvar (Gvar s)) let rec name_of_pat pat = match pat.P.ppat_desc with | Ppat_any -> "_" | Ppat_var s -> s.txt | Ppat_constraint (p, _) -> name_of_pat p TODO let rec structure info str = List.flatten (List.map (structure_item info) str) and structure_item info str_item = match str_item.P.pstr_desc with | Pstr_value (rec_flag, [val_bind]) -> TODO let id, expr = value_binding info val_bind in [DDefinition (id, TyVal, expr)] | Pstr_type _ -> [] TODO and value_binding info {pvb_pat; pvb_expr; _} = name_of_pat pvb_pat, expression info [] pvb_expr and longident info params = function TODO | Lident s -> if List.mem s params || Hashtbl.mem info.info_lvars s then Vlvar s else Vgvar (Gvar s) | Ldot (t, s) -> let v = longident info [] t in match v with | Vgvar x -> Vgvar (Gdot (x, s)) | Vlvar _ -> assert false and expression info params expr = let is_fst P.{pexp_desc; _} = match pexp_desc with | Pexp_ident {txt = Lident "fst"; _} -> true | _ -> false in let is_snd P.{pexp_desc; _} = match pexp_desc with | Pexp_ident {txt = Lident "snd"; _} -> true | _ -> false in let rec loop (P.{pexp_desc; _} as e) = match pexp_desc with | Pexp_fun (_, _, pat, e) -> let args, expr = loop e in let id = name_of_pat pat in id :: args, expr | _ -> [], e in let add_info id = Hashtbl.add info.info_lvars id () in let add_local_args args = List.iter add_info args in let remove_info id = Hashtbl.remove info.info_lvars id in let remove_local_args args = List.iter remove_info args in match expr.pexp_desc with | Pexp_constant c -> Evalue (LitV (constant c)) | Pexp_construct (c,o) -> construct info params (c,o) | Pexp_ident t -> Evar (longident info params t.txt) | Pexp_fun (Nolabel, None, pat, expr) -> let id = name_of_pat pat in let expr = expression info (id :: params) expr in begin match expr with | Efun (il, e) -> Efun (id :: il, e) | _ -> Efun ([id], expr) end | Pexp_apply (f, [(_, e)]) when is_fst f -> EFst (expression info params e) | Pexp_apply (f, [(_, e)]) when is_snd f -> ESnd (expression info params e) | Pexp_apply (e1, el) -> let expr1 = expression info params e1 in let (_, args) = List.split el in let exprl = List.map (expression info params) args in Eapp (expr1, exprl) | Pexp_tuple expr_list when List.length expr_list = 2 -> Etuple (List.map (expression info params) expr_list) | Pexp_tuple _ -> TODO | Pexp_match (e, [c1; c2]) -> let expr = expression info params e in Ecase (expr, pattern info params c1, pattern info params c2) | Pexp_match _ -> TODO | Pexp_constraint (e, _) -> expression info params e | Pexp_let (Recursive, [{pvb_pat; pvb_expr; _}], e2) -> let fun_name = name_of_pat pvb_pat in let args, e1 = loop pvb_expr in add_info fun_name; add_local_args args; let e1 = expression info params e1 in let e2 = expression info params e2 in remove_info fun_name; remove_local_args args; Erec (fun_name, args, e1, e2) TODO and pattern info params P.{pc_lhs; pc_rhs; _} = let add_info id = Hashtbl.add info.info_lvars id () in let rec pat_desc P.{ppat_desc; _} = match ppat_desc with | P.Ppat_any -> Ppat_any | Ppat_var {txt; _} -> add_info txt; Ppat_var txt | Ppat_construct ({txt; _}, p) -> Ppat_apply (longident info params txt, Option.map pat_desc p) TODO let pc_lhs = pat_desc pc_lhs in let pc_rhs = expression info params pc_rhs in { pc_lhs; pc_rhs } and constant = function Pconst_integer (t, _) -> LitInt (int_of_string t) | Pconst_string (s, _, _) -> LitString s not implemented in AnerisLang not implemented in AnerisLang and construct info params = function | ({txt = Lident "()"; loc = _}, None) -> Evalue (LitV LitUnit) | ({txt = Lident "true"; loc = _}, None) -> Evalue (LitV (LitBool true)) | ({txt = Lident "false"; loc = _}, None) -> Evalue (LitV (LitBool false)) | ({txt = Lident "None"; loc = _}, None) -> Evalue NONEV | ({txt = Lident "Some"; loc = _}, Some expr) -> let e = expression info params expr in begin match e with | Evalue v -> Evalue (SOMEV v) | _ -> Esome e end | ({txt = Lident "::"; loc = _}, Some e) -> begin match e.pexp_desc with | Pexp_tuple [e1;e2] -> Eapp (mk_gvar "::", [expression info params e1; expression info params e2]) | _ -> assert false end | ({txt = Lident "[]"; loc = _}, None) -> Evalue NONEV TODO type un_op = * | NegOp | MinusUnOp | StringOfInt | IntOfString | StringLength * * type bin_op = * | PlusOp | MinusOp | MultOp | QuotOp | RemOp ( \ * Arithmetic * \ ) * | AndOp | OrOp | XorOp ( \ * Bitwise * \ ) * | ShiftLOp | ShiftROp ( \ * Shifts * \ ) * | LeOp | LtOp | EqOp ( \ * Relations * \ ) * | StringApp * | NegOp | MinusUnOp | StringOfInt | IntOfString | StringLength * * type bin_op = * | PlusOp | MinusOp | MultOp | QuotOp | RemOp (\* Arithmetic *\) * | AndOp | OrOp | XorOp (\* Bitwise *\) * | ShiftLOp | ShiftROp (\* Shifts *\) * | LeOp | LtOp | EqOp (\* Relations *\) * | StringApp *) let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let f x = y " ) ) ; * [ % expect { | Definition f : base_lang.val : = λ : " x " , y. | } ] * * let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let x = [ 1;2;3 ] " ) ) ; * [ % expect{| * Definition x : base_lang.val : = * list_cons # 1 ( list_cons # 2 ( list_cons # 3 NONEV ) ) . | } ] * * let%expect_test _ = * Format.std_formatter * ( structure ( create_info ( ) ) ( ptree_of_string " let f x = List.fold_left ( fun x y - > x y z ) [ 1;2;3 ] " ) ) ; * [ % expect{| * Definition f : base_lang.val : = * λ : " x " , * list_fold ( λ : " x " " y " , " x " " y " z ) * ( list_cons # 1 ( list_cons # 2 ( list_cons # 3 NONE ) ) ) . | } ] * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let f x = y")); * [%expect {| Definition f : base_lang.val := λ: "x", y. |}] * * let%expect_test _ = * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let x = [1;2;3]")); * [%expect{| * Definition x : base_lang.val := * list_cons #1 (list_cons #2 (list_cons #3 NONEV)). |}] * * let%expect_test _ = * Lang.pp_decls Format.std_formatter * (structure (create_info ()) (ptree_of_string "let f x = List.fold_left (fun x y -> x y z) [1;2;3]")); * [%expect{| * Definition f : base_lang.val := * λ: "x", * list_fold (λ: "x" "y", "x" "y" z) * (list_cons #1 (list_cons #2 (list_cons #3 NONE))). |}] *)
67d19586f78e4804fa6100bcceadf60ac5926a613ffe287805da2fa2af7b8f82
sbtourist/clamq
activemq_test.clj
(ns clamq.test.activemq-test (:use [clojure.test] [clamq.test.base-jms-test] [clamq.jms] [clamq.activemq])) (defn setup-connection-and-test [test-fn] (with-open [connection (activemq-connection "tcp:61616")] (test-fn connection))) (deftest activemq-test-suite [] (setup-connection-and-test producer-consumer-test) (setup-connection-and-test producer-consumer-topic-test) (setup-connection-and-test producer-consumer-limit-test) (setup-connection-and-test on-failure-test) (setup-connection-and-test transacted-test) (setup-connection-and-test seqable-consumer-test) (setup-connection-and-test seqable-consumer-close-test) (setup-connection-and-test pipe-test) (setup-connection-and-test pipe-topic-test) (setup-connection-and-test pipe-limit-test) (setup-connection-and-test multi-pipe-test) (setup-connection-and-test multi-pipe-topic-test) (setup-connection-and-test multi-pipe-limit-test) (setup-connection-and-test router-pipe-test) (setup-connection-and-test router-pipe-topic-test) (setup-connection-and-test router-pipe-limit-test))
null
https://raw.githubusercontent.com/sbtourist/clamq/34a6bbcb7a2a431ea629aa5cfbc687ef31f860f2/clamq-activemq/test/clamq/test/activemq_test.clj
clojure
(ns clamq.test.activemq-test (:use [clojure.test] [clamq.test.base-jms-test] [clamq.jms] [clamq.activemq])) (defn setup-connection-and-test [test-fn] (with-open [connection (activemq-connection "tcp:61616")] (test-fn connection))) (deftest activemq-test-suite [] (setup-connection-and-test producer-consumer-test) (setup-connection-and-test producer-consumer-topic-test) (setup-connection-and-test producer-consumer-limit-test) (setup-connection-and-test on-failure-test) (setup-connection-and-test transacted-test) (setup-connection-and-test seqable-consumer-test) (setup-connection-and-test seqable-consumer-close-test) (setup-connection-and-test pipe-test) (setup-connection-and-test pipe-topic-test) (setup-connection-and-test pipe-limit-test) (setup-connection-and-test multi-pipe-test) (setup-connection-and-test multi-pipe-topic-test) (setup-connection-and-test multi-pipe-limit-test) (setup-connection-and-test router-pipe-test) (setup-connection-and-test router-pipe-topic-test) (setup-connection-and-test router-pipe-limit-test))
8e65716c65e6502b3fe0296727664c9cf5b55a977e7904929139281b86346182
a-nikolaev/wanderers
win.ml
* Copyright ( C ) 2007 , 2008 * * Redistribution and use in source and binary forms , with or without modification , are permitted provided * that the following conditions are met : * - Redistributions of source code must retain the above copyright notice , this list of conditions * and the following disclaimer . * - Redistributions in binary form must reproduce the above copyright notice , this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution . * - The name may not be used to endorse or promote products derived from this software * without specific prior written permission . * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ' AS IS ' AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT * LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , * EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR * PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING * NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . * Copyright (C) 2007, 2008 Elliott OTI * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * - The name Elliott Oti may not be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) (*********************** Windowing ****************************************) * To prepare an Ocaml graphics window for use with OpenGL the following hack is used . * The method is similar , but not identical , on both Windows and X11 . * After opening the window with Graphics.open_graph ( ) , the function init_opengl ( ) * has to be called . This function gives the window a ( hopefully ) unique name . Then * some C code is called which searches through all available windows for a window * with that particular name , gets pointers to its internal structure ( both Win32 and * Xlib allow this ) and sets it up for use as an OpenGL surface . * * Compiling : * You need the files win_stub.c , win.ml and win.mli * Link the resultant executable with libGL.a on X11 , opengl32.lib and gdi32.lib on Windows * * Usage : * First set up your caml window with Graphics.open_graph ( ) * Next , call the function init_gl ( ) defined here below . * After this you can ( re)set the window title ( if you set it previously it will be empty ) * Feel free to call any OpenGL calls you wish . lablgl , and camlgl may all be used . * You may mix the Ocaml graphics functions with OpenGL . * Call swap_buffers ( ) any time you need to flip the contents of your back buffer to the screen . * To prepare an Ocaml graphics window for use with OpenGL the following hack is used. * The method is similar, but not identical, on both Windows and X11. * After opening the window with Graphics.open_graph (), the function init_opengl () * has to be called. This function gives the window a (hopefully) unique name. Then * some C code is called which searches through all available windows for a window * with that particular name, gets pointers to its internal structure (both Win32 and * Xlib allow this) and sets it up for use as an OpenGL surface. * * Compiling: * You need the files win_stub.c, win.ml and win.mli * Link the resultant executable with libGL.a on X11, opengl32.lib and gdi32.lib on Windows * * Usage: * First set up your caml window with Graphics.open_graph () * Next, call the function init_gl () defined here below. * After this you can (re)set the window title (if you set it previously it will be empty) * Feel free to call any OpenGL calls you wish. lablgl, glcaml and camlgl may all be used. * You may mix the Ocaml graphics functions with OpenGL. * Call swap_buffers () any time you need to flip the contents of your back buffer to the screen. *) external init_gl' : string -> unit = "stub_init_gl" "stub_init_gl" external swap_buffers : unit -> unit = "stub_swap_buffers" "stub_swap_buffers" let init_opengl () = let _ = Random.self_init () in let title = Printf.sprintf "%d.%d" (Random.int 1000000) (Random.int 1000000) in Graphics.set_window_title title; init_gl' title; Graphics.set_window_title "";; (* Sleep for n microseconds *) external usleep: int -> unit = "stub_usleep"
null
https://raw.githubusercontent.com/a-nikolaev/wanderers/054c1cdc6dd833d8938357e6d898def510531d67/lib/win.ml
ocaml
********************** Windowing *************************************** Sleep for n microseconds
* Copyright ( C ) 2007 , 2008 * * Redistribution and use in source and binary forms , with or without modification , are permitted provided * that the following conditions are met : * - Redistributions of source code must retain the above copyright notice , this list of conditions * and the following disclaimer . * - Redistributions in binary form must reproduce the above copyright notice , this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution . * - The name may not be used to endorse or promote products derived from this software * without specific prior written permission . * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ' AS IS ' AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT * LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , * EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR * PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING * NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . * Copyright (C) 2007, 2008 Elliott OTI * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * - The name Elliott Oti may not be used to endorse or promote products derived from this software * without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) * To prepare an Ocaml graphics window for use with OpenGL the following hack is used . * The method is similar , but not identical , on both Windows and X11 . * After opening the window with Graphics.open_graph ( ) , the function init_opengl ( ) * has to be called . This function gives the window a ( hopefully ) unique name . Then * some C code is called which searches through all available windows for a window * with that particular name , gets pointers to its internal structure ( both Win32 and * Xlib allow this ) and sets it up for use as an OpenGL surface . * * Compiling : * You need the files win_stub.c , win.ml and win.mli * Link the resultant executable with libGL.a on X11 , opengl32.lib and gdi32.lib on Windows * * Usage : * First set up your caml window with Graphics.open_graph ( ) * Next , call the function init_gl ( ) defined here below . * After this you can ( re)set the window title ( if you set it previously it will be empty ) * Feel free to call any OpenGL calls you wish . lablgl , and camlgl may all be used . * You may mix the Ocaml graphics functions with OpenGL . * Call swap_buffers ( ) any time you need to flip the contents of your back buffer to the screen . * To prepare an Ocaml graphics window for use with OpenGL the following hack is used. * The method is similar, but not identical, on both Windows and X11. * After opening the window with Graphics.open_graph (), the function init_opengl () * has to be called. This function gives the window a (hopefully) unique name. Then * some C code is called which searches through all available windows for a window * with that particular name, gets pointers to its internal structure (both Win32 and * Xlib allow this) and sets it up for use as an OpenGL surface. * * Compiling: * You need the files win_stub.c, win.ml and win.mli * Link the resultant executable with libGL.a on X11, opengl32.lib and gdi32.lib on Windows * * Usage: * First set up your caml window with Graphics.open_graph () * Next, call the function init_gl () defined here below. * After this you can (re)set the window title (if you set it previously it will be empty) * Feel free to call any OpenGL calls you wish. lablgl, glcaml and camlgl may all be used. * You may mix the Ocaml graphics functions with OpenGL. * Call swap_buffers () any time you need to flip the contents of your back buffer to the screen. *) external init_gl' : string -> unit = "stub_init_gl" "stub_init_gl" external swap_buffers : unit -> unit = "stub_swap_buffers" "stub_swap_buffers" let init_opengl () = let _ = Random.self_init () in let title = Printf.sprintf "%d.%d" (Random.int 1000000) (Random.int 1000000) in Graphics.set_window_title title; init_gl' title; Graphics.set_window_title "";; external usleep: int -> unit = "stub_usleep"
f877975acdf07091f5bc26c16d29bedd86e190bd164f59061c66ea36e08857d6
aiya000/hs-character-cases
Cases.hs
# LANGUAGE QuasiQuotes # -- | Exposes subspecies types of . -- e.g. `[a-z]`, `[A-Z]`, and `[0-9]`. module Data.Char.Cases ( AlphaNumChar (..) , alphaNumToChar , alphaNumChar , charToAlphaNum , alphaNumCharQ , AlphaChar (..) , alphaToChar , charToAlpha , alphaChar , alphaCharQ , UpperChar (..) , upperToChar , upperChar , charToUpper , upperCharQ , LowerChar (..) , lowerToChar , lowerChar , charToLower , lowerCharQ , DigitChar (..) , digitToChar , digitChar , charToDigit , digitCharQ , SnakeChar (..) , snakeToChar , snakeChar , charToSnake , snakeCharQ , SnakeHeadChar (..) , snakeHeadToChar , snakeHeadChar , charToSnakeHead , snakeHeadCharQ , UpperSnakeHeadChar (..) , upperSnakeHeadToChar , upperSnakeHeadChar , charToUpperSnakeHead , upperSnakeHeadCharQ , UpperSnakeChar (..) , upperSnakeToChar , upperSnakeChar , charToUpperSnake , upperSnakeCharQ ) where import Cases.Megaparsec import Control.Applicative import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust) import Data.Tuple (swap) import Language.Haskell.TH import Language.Haskell.TH.Quote (QuasiQuoter(..)) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P -- $setup -- >>> :set -XQuasiQuotes dual :: Ord a => Map k a -> Map a k dual (Map.toList -> x) = Map.fromList $ map swap x -- | '[A-Za-z0-9]' data AlphaNumChar = AlphaNumAlpha AlphaChar | AlphaNumDigit DigitChar deriving (Show, Eq, Ord) alphaNumToChar :: AlphaNumChar -> Char alphaNumToChar (AlphaNumAlpha x) = alphaToChar x alphaNumToChar (AlphaNumDigit x) = digitToChar x alphaNumChar :: CodeParsing m => m AlphaNumChar alphaNumChar = AlphaNumAlpha <$> alphaChar <|> AlphaNumDigit <$> digitChar charToAlphaNum :: Char -> Maybe AlphaNumChar charToAlphaNum x = P.parseMaybe alphaNumChar [x] -- | to ' alphaCharQ ' and ' digitCharQ ' . -- -- >>> [alphaNumCharQ|x|] -- AlphaNumAlpha (AlphaLower X_) -- -- >>> [alphaNumCharQ|X|] -- AlphaNumAlpha (AlphaUpper X) -- -- >>> [alphaNumCharQ|1|] -- AlphaNumDigit D1 alphaNumCharQ :: QuasiQuoter alphaNumCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "alphaNumCharQ required a Char, but nothign is specified." expQ (x : []) = case charToAlphaNum x of Nothing -> fail $ show x <> " is not an AlphaNumChar." Just (AlphaNumAlpha _) -> (ConE (mkName "AlphaNumAlpha") `AppE`) <$> (quoteExp alphaCharQ) [x] Just (AlphaNumDigit _) -> (ConE (mkName "AlphaNumDigit") `AppE`) <$> (quoteExp digitCharQ) [x] expQ xs@(_ : _) = fail $ "alphaNumCharQ required a Char, but a String is specified: " <> xs -- | '[A-Za-z]' data AlphaChar = AlphaLower LowerChar | AlphaUpper UpperChar deriving (Show, Eq, Ord) alphaToChar :: AlphaChar -> Char alphaToChar (AlphaLower x) = lowerToChar x alphaToChar (AlphaUpper x) = upperToChar x charToAlpha :: Char -> Maybe AlphaChar charToAlpha x = P.parseMaybe alphaChar [x] alphaChar :: CodeParsing m => m AlphaChar alphaChar = AlphaLower <$> lowerChar <|> AlphaUpper <$> upperChar | to ' lowerCharQ ' and ' upperCharQ ' . alphaCharQ :: QuasiQuoter alphaCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "alphaCharQ required a Char, but nothign is specified." expQ (x : []) = case charToAlpha x of Nothing -> fail $ show x <> " is not an AlphaChar." Just (AlphaLower _) -> (ConE (mkName "AlphaLower") `AppE`) <$> (quoteExp lowerCharQ) [x] Just (AlphaUpper _) -> (ConE (mkName "AlphaUpper") `AppE`) <$> (quoteExp upperCharQ) [x] expQ xs@(_ : _) = fail $ "alphaCharQ required a Char, but a String is specified: " <> xs -- | '[A-Z]' data UpperChar = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z deriving (Show, Eq, Ord) upperToChar :: UpperChar -> Char upperToChar = fromJust . flip Map.lookup uppers uppers :: Map UpperChar Char uppers = Map.fromList [ (A, 'A'), (B, 'B'), (C, 'C') , (D, 'D'), (E, 'E'), (F, 'F') , (G, 'G'), (H, 'H'), (I, 'I') , (J, 'J'), (K, 'K'), (L, 'L') , (M, 'M'), (N, 'N'), (O, 'O') , (P, 'P'), (Q, 'Q'), (R, 'R') , (S, 'S'), (T, 'T'), (U, 'U') , (V, 'V'), (W, 'W'), (X, 'X') , (Y, 'Y'), (Z, 'Z') ] upperChar :: CodeParsing m => m UpperChar upperChar = do char <- P.upperChar let maybeUpper = Map.lookup char $ dual uppers case maybeUpper of Nothing -> fail "non upper char" Just x -> pure x charToUpper :: Char -> Maybe UpperChar charToUpper x = P.parseMaybe upperChar [x] -- | -- Extracts a Char of [A-Z]. -- Also throws compile error if non [A-Z] is passed. -- -- >>> [upperCharQ|X|] -- X -- -- >>> [upperCharQ|Y|] -- Y upperCharQ :: QuasiQuoter upperCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpper x of Nothing -> fail $ show x <> " is not an UpperChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "upperCharQ required a Char, but a String is specified: " <> xs -- | '[a-z]' data LowerChar = A_ | B_ | C_ | D_ | E_ | F_ | G_ | H_ | I_ | J_ | K_ | L_ | M_ | N_ | O_ | P_ | Q_ | R_ | S_ | T_ | U_ | V_ | W_ | X_ | Y_ | Z_ deriving (Show, Eq, Ord) lowerToChar :: LowerChar -> Char lowerToChar = fromJust . flip Map.lookup lowers lowers :: Map LowerChar Char lowers = Map.fromList [ (A_, 'a'), (B_, 'b'), (C_, 'c') , (D_, 'd'), (E_, 'e'), (F_, 'f') , (G_, 'g'), (H_, 'h'), (I_, 'i') , (J_, 'j'), (K_, 'k'), (L_, 'l') , (M_, 'm'), (N_, 'n'), (O_, 'o') , (P_, 'p'), (Q_, 'q'), (R_, 'r') , (S_, 's'), (T_, 't'), (U_, 'u') , (V_, 'v'), (W_, 'w'), (X_, 'x') , (Y_, 'y'), (Z_, 'z') ] lowerChar :: CodeParsing m => m LowerChar lowerChar = do char <- P.lowerChar let maybeLower = Map.lookup char $ dual lowers case maybeLower of Nothing -> fail "non lower char" Just x -> pure x charToLower :: Char -> Maybe LowerChar charToLower x = P.parseMaybe lowerChar [x] -- | -- Extracts a Char of [a-z]. -- Also throws compile error if non [a-z] is passed. -- -- >>> [lowerCharQ|x|] -- X_ -- -- >>> [lowerCharQ|y|] -- Y_ lowerCharQ :: QuasiQuoter lowerCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "lowerCharQ required a Char, but nothign is specified." expQ (x : []) = case charToLower x of Nothing -> fail $ show x <> " is not a LowerChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "lowerCharQ required a Char, but a String is specified: " <> xs -- | '[0-9]' data DigitChar = D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9 deriving (Show, Eq, Ord) digitToChar :: DigitChar -> Char digitToChar = fromJust . flip Map.lookup digits digits :: Map DigitChar Char digits = Map.fromList [ (D0, '0') , (D1, '1'), (D2, '2'), (D3, '3') , (D4, '4'), (D5, '5'), (D6, '6') , (D4, '7'), (D8, '8'), (D9, '9') ] digitChar :: CodeParsing m => m DigitChar digitChar = do char <- P.digitChar let maybeNum = Map.lookup char $ dual digits case maybeNum of Nothing -> fail "non numeric char" Just x -> pure x charToDigit :: Char -> Maybe DigitChar charToDigit x = P.parseMaybe digitChar [x] -- | -- Extracts a Char of [0-9]. -- Also throws compile error if non [a-z] is passed. -- -- >>> [digitCharQ|0|] -- D0 -- -- >>> [digitCharQ|9|] D9 digitCharQ :: QuasiQuoter digitCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "digitCharQ required a Char, but nothign is specified." expQ (x : []) = case charToDigit x of Nothing -> fail $ show x <> " is not a DigitChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "digitCharQ required a Char, but a String is specified: " <> xs -- | -- '[a-zA-Z0-9_]' -- -- Please see 'Data.String.Cases.Snake'. data SnakeChar = SnakeUnderscore -- ^ _ | SnakeAlphaNum AlphaNumChar -- ^ [a-zA-Z0-9] deriving (Show, Eq) snakeToChar :: SnakeChar -> Char snakeToChar SnakeUnderscore = '_' snakeToChar (SnakeAlphaNum x) = alphaNumToChar x snakeChar :: CodeParsing m => m SnakeChar snakeChar = SnakeUnderscore <$ P.char '_' <|> SnakeAlphaNum <$> alphaNumChar charToSnake :: Char -> Maybe SnakeChar charToSnake x = P.parseMaybe snakeChar [x] -- | -- Extracts a Char of [a-zA-Z0-9_]. -- Also throws compile error if non [a-zA-Z0-9_] is passed. -- -- >>> [snakeCharQ|x|] -- SnakeAlphaNum (AlphaNumAlpha (AlphaLower X_)) -- -- >>> [snakeCharQ|X|] -- SnakeAlphaNum (AlphaNumAlpha (AlphaUpper X)) -- -- >>> [snakeCharQ|_|] -- SnakeUnderscore -- > > > [ ] SnakeAlphaNum ( ) snakeCharQ :: QuasiQuoter snakeCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "snakeCharQ required a Char, but nothign is specified." expQ (x : []) = case charToSnake x of Nothing -> fail $ show x <> " is not a SnakeChar." Just SnakeUnderscore -> conE $ mkName "SnakeUnderscore" Just (SnakeAlphaNum _) -> (ConE (mkName "SnakeAlphaNum") `AppE`) <$> (quoteExp alphaNumCharQ) [x] expQ xs@(_ : _) = fail $ "snakeCharQ required a Char, but a String is specified: " <> xs -- | -- '[a-zA-Z_]' -- -- Please see 'Data.String.Cases.Snake'. data SnakeHeadChar = SnakeHeadUnderscore | SnakeHeadAlpha AlphaChar deriving (Show, Eq) snakeHeadToChar :: SnakeHeadChar -> Char snakeHeadToChar SnakeHeadUnderscore = '_' snakeHeadToChar (SnakeHeadAlpha x) = alphaToChar x snakeHeadChar :: CodeParsing m => m SnakeHeadChar snakeHeadChar = SnakeHeadUnderscore <$ P.char '_' <|> SnakeHeadAlpha <$> alphaChar charToSnakeHead :: Char -> Maybe SnakeHeadChar charToSnakeHead x = P.parseMaybe snakeHeadChar [x] -- | -- Extracts a Char of [a-zA-Z_]. -- Also throws compile error if non [a-zA-Z_] is passed. -- > > > [ snakeHeadCharQ|x| ] -- SnakeHeadAlpha (AlphaLower X_) -- > > > [ snakeHeadCharQ|X| ] -- SnakeHeadAlpha (AlphaUpper X) -- -- >>> [snakeHeadCharQ|_|] -- SnakeHeadUnderscore snakeHeadCharQ :: QuasiQuoter snakeHeadCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "snakeHeadCharQ required a Char, but nothign is specified." expQ (x : []) = case charToSnakeHead x of Nothing -> fail $ show x <> " is not a SnakeHeadChar." Just SnakeHeadUnderscore -> conE $ mkName "SnakeHeadUnderscore" Just (SnakeHeadAlpha _) -> (ConE (mkName "SnakeHeadAlpha") `AppE`) <$> (quoteExp alphaCharQ) [x] expQ xs@(_ : _) = fail $ "snakeHeadCharQ required a Char, but a String is specified: " <> xs -- | -- '[A-Z_]' -- -- Please sese 'Data.String.Cases.UpperSnake'. data UpperSnakeHeadChar = UpperSnakeHeadUnderscore -- ^ _ | UpperSnakeHeadUpper UpperChar -- ^ [A-Z] deriving (Show, Eq) upperSnakeHeadToChar :: UpperSnakeHeadChar -> Char upperSnakeHeadToChar UpperSnakeHeadUnderscore = '_' upperSnakeHeadToChar (UpperSnakeHeadUpper x) = upperToChar x upperSnakeHeadChar :: CodeParsing m => m UpperSnakeHeadChar upperSnakeHeadChar = UpperSnakeHeadUnderscore <$ P.char '_' <|> UpperSnakeHeadUpper <$> upperChar charToUpperSnakeHead :: Char -> Maybe UpperSnakeHeadChar charToUpperSnakeHead x = P.parseMaybe upperSnakeHeadChar [x] -- | -- >>> [upperSnakeHeadCharQ|_|] -- UpperSnakeHeadUnderscore -- > > > [ upperSnakeHeadCharQ|A| ] -- UpperSnakeHeadUpper A upperSnakeHeadCharQ :: QuasiQuoter upperSnakeHeadCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperSnakeHeadCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpperSnakeHead x of Nothing -> fail $ show x <> " is not a UpperSnakeHeadChar." Just UpperSnakeHeadUnderscore -> conE $ mkName "UpperSnakeHeadUnderscore" Just (UpperSnakeHeadUpper _) -> (ConE (mkName "UpperSnakeHeadUpper") `AppE`) <$> (quoteExp upperCharQ) [x] expQ xs@(_ : _) = fail $ "upperSnakeHeadCharQ required a Char, but a String is specified: " <> xs -- | -- '[A-Z0-9_]' -- -- Please see 'Data.String.Cases.UpperSnake'. data UpperSnakeChar = UpperSnakeUnderscore -- ^ _ | UpperSnakeUpper UpperChar -- ^ [A-Z] | UpperSnakeDigit DigitChar -- ^ [0-9] deriving (Show, Eq) upperSnakeToChar :: UpperSnakeChar -> Char upperSnakeToChar UpperSnakeUnderscore = '_' upperSnakeToChar (UpperSnakeUpper x) = upperToChar x upperSnakeToChar (UpperSnakeDigit x) = digitToChar x upperSnakeChar :: CodeParsing m => m UpperSnakeChar upperSnakeChar = UpperSnakeUnderscore <$ P.char '_' <|> UpperSnakeUpper <$> upperChar <|> UpperSnakeDigit <$> digitChar charToUpperSnake :: Char -> Maybe UpperSnakeChar charToUpperSnake x = P.parseMaybe upperSnakeChar [x] -- | -- >>> [upperSnakeCharQ|_|] -- UpperSnakeUnderscore -- > > > [ upperSnakeCharQ|A| ] -- UpperSnakeUpper A -- -- >>> [upperSnakeCharQ|0|] -- UpperSnakeDigit D0 upperSnakeCharQ :: QuasiQuoter upperSnakeCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperSnakeCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpperSnake x of Nothing -> fail $ show x <> " is not a UpperSnakeChar." Just UpperSnakeUnderscore -> conE $ mkName "UpperSnakeUnderscore" Just (UpperSnakeUpper _) -> (ConE (mkName "UpperSnakeUpper") `AppE`) <$> (quoteExp upperCharQ) [x] Just (UpperSnakeDigit _) -> (ConE (mkName "UpperSnakeDigit") `AppE`) <$> (quoteExp digitCharQ) [x] expQ xs@(_ : _) = fail $ "upperSnakeCharQ required a Char, but a String is specified: " <> xs
null
https://raw.githubusercontent.com/aiya000/hs-character-cases/3b6156310e7a68ee1ad514f8bc6f590c3c1000a3/src/Data/Char/Cases.hs
haskell
| e.g. `[a-z]`, `[A-Z]`, and `[0-9]`. $setup >>> :set -XQuasiQuotes | '[A-Za-z0-9]' | >>> [alphaNumCharQ|x|] AlphaNumAlpha (AlphaLower X_) >>> [alphaNumCharQ|X|] AlphaNumAlpha (AlphaUpper X) >>> [alphaNumCharQ|1|] AlphaNumDigit D1 | '[A-Za-z]' | '[A-Z]' | Extracts a Char of [A-Z]. Also throws compile error if non [A-Z] is passed. >>> [upperCharQ|X|] X >>> [upperCharQ|Y|] Y | '[a-z]' | Extracts a Char of [a-z]. Also throws compile error if non [a-z] is passed. >>> [lowerCharQ|x|] X_ >>> [lowerCharQ|y|] Y_ | '[0-9]' | Extracts a Char of [0-9]. Also throws compile error if non [a-z] is passed. >>> [digitCharQ|0|] D0 >>> [digitCharQ|9|] | '[a-zA-Z0-9_]' Please see 'Data.String.Cases.Snake'. ^ _ ^ [a-zA-Z0-9] | Extracts a Char of [a-zA-Z0-9_]. Also throws compile error if non [a-zA-Z0-9_] is passed. >>> [snakeCharQ|x|] SnakeAlphaNum (AlphaNumAlpha (AlphaLower X_)) >>> [snakeCharQ|X|] SnakeAlphaNum (AlphaNumAlpha (AlphaUpper X)) >>> [snakeCharQ|_|] SnakeUnderscore | '[a-zA-Z_]' Please see 'Data.String.Cases.Snake'. | Extracts a Char of [a-zA-Z_]. Also throws compile error if non [a-zA-Z_] is passed. SnakeHeadAlpha (AlphaLower X_) SnakeHeadAlpha (AlphaUpper X) >>> [snakeHeadCharQ|_|] SnakeHeadUnderscore | '[A-Z_]' Please sese 'Data.String.Cases.UpperSnake'. ^ _ ^ [A-Z] | >>> [upperSnakeHeadCharQ|_|] UpperSnakeHeadUnderscore UpperSnakeHeadUpper A | '[A-Z0-9_]' Please see 'Data.String.Cases.UpperSnake'. ^ _ ^ [A-Z] ^ [0-9] | >>> [upperSnakeCharQ|_|] UpperSnakeUnderscore UpperSnakeUpper A >>> [upperSnakeCharQ|0|] UpperSnakeDigit D0
# LANGUAGE QuasiQuotes # Exposes subspecies types of . module Data.Char.Cases ( AlphaNumChar (..) , alphaNumToChar , alphaNumChar , charToAlphaNum , alphaNumCharQ , AlphaChar (..) , alphaToChar , charToAlpha , alphaChar , alphaCharQ , UpperChar (..) , upperToChar , upperChar , charToUpper , upperCharQ , LowerChar (..) , lowerToChar , lowerChar , charToLower , lowerCharQ , DigitChar (..) , digitToChar , digitChar , charToDigit , digitCharQ , SnakeChar (..) , snakeToChar , snakeChar , charToSnake , snakeCharQ , SnakeHeadChar (..) , snakeHeadToChar , snakeHeadChar , charToSnakeHead , snakeHeadCharQ , UpperSnakeHeadChar (..) , upperSnakeHeadToChar , upperSnakeHeadChar , charToUpperSnakeHead , upperSnakeHeadCharQ , UpperSnakeChar (..) , upperSnakeToChar , upperSnakeChar , charToUpperSnake , upperSnakeCharQ ) where import Cases.Megaparsec import Control.Applicative import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust) import Data.Tuple (swap) import Language.Haskell.TH import Language.Haskell.TH.Quote (QuasiQuoter(..)) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P dual :: Ord a => Map k a -> Map a k dual (Map.toList -> x) = Map.fromList $ map swap x data AlphaNumChar = AlphaNumAlpha AlphaChar | AlphaNumDigit DigitChar deriving (Show, Eq, Ord) alphaNumToChar :: AlphaNumChar -> Char alphaNumToChar (AlphaNumAlpha x) = alphaToChar x alphaNumToChar (AlphaNumDigit x) = digitToChar x alphaNumChar :: CodeParsing m => m AlphaNumChar alphaNumChar = AlphaNumAlpha <$> alphaChar <|> AlphaNumDigit <$> digitChar charToAlphaNum :: Char -> Maybe AlphaNumChar charToAlphaNum x = P.parseMaybe alphaNumChar [x] to ' alphaCharQ ' and ' digitCharQ ' . alphaNumCharQ :: QuasiQuoter alphaNumCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "alphaNumCharQ required a Char, but nothign is specified." expQ (x : []) = case charToAlphaNum x of Nothing -> fail $ show x <> " is not an AlphaNumChar." Just (AlphaNumAlpha _) -> (ConE (mkName "AlphaNumAlpha") `AppE`) <$> (quoteExp alphaCharQ) [x] Just (AlphaNumDigit _) -> (ConE (mkName "AlphaNumDigit") `AppE`) <$> (quoteExp digitCharQ) [x] expQ xs@(_ : _) = fail $ "alphaNumCharQ required a Char, but a String is specified: " <> xs data AlphaChar = AlphaLower LowerChar | AlphaUpper UpperChar deriving (Show, Eq, Ord) alphaToChar :: AlphaChar -> Char alphaToChar (AlphaLower x) = lowerToChar x alphaToChar (AlphaUpper x) = upperToChar x charToAlpha :: Char -> Maybe AlphaChar charToAlpha x = P.parseMaybe alphaChar [x] alphaChar :: CodeParsing m => m AlphaChar alphaChar = AlphaLower <$> lowerChar <|> AlphaUpper <$> upperChar | to ' lowerCharQ ' and ' upperCharQ ' . alphaCharQ :: QuasiQuoter alphaCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "alphaCharQ required a Char, but nothign is specified." expQ (x : []) = case charToAlpha x of Nothing -> fail $ show x <> " is not an AlphaChar." Just (AlphaLower _) -> (ConE (mkName "AlphaLower") `AppE`) <$> (quoteExp lowerCharQ) [x] Just (AlphaUpper _) -> (ConE (mkName "AlphaUpper") `AppE`) <$> (quoteExp upperCharQ) [x] expQ xs@(_ : _) = fail $ "alphaCharQ required a Char, but a String is specified: " <> xs data UpperChar = A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z deriving (Show, Eq, Ord) upperToChar :: UpperChar -> Char upperToChar = fromJust . flip Map.lookup uppers uppers :: Map UpperChar Char uppers = Map.fromList [ (A, 'A'), (B, 'B'), (C, 'C') , (D, 'D'), (E, 'E'), (F, 'F') , (G, 'G'), (H, 'H'), (I, 'I') , (J, 'J'), (K, 'K'), (L, 'L') , (M, 'M'), (N, 'N'), (O, 'O') , (P, 'P'), (Q, 'Q'), (R, 'R') , (S, 'S'), (T, 'T'), (U, 'U') , (V, 'V'), (W, 'W'), (X, 'X') , (Y, 'Y'), (Z, 'Z') ] upperChar :: CodeParsing m => m UpperChar upperChar = do char <- P.upperChar let maybeUpper = Map.lookup char $ dual uppers case maybeUpper of Nothing -> fail "non upper char" Just x -> pure x charToUpper :: Char -> Maybe UpperChar charToUpper x = P.parseMaybe upperChar [x] upperCharQ :: QuasiQuoter upperCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpper x of Nothing -> fail $ show x <> " is not an UpperChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "upperCharQ required a Char, but a String is specified: " <> xs data LowerChar = A_ | B_ | C_ | D_ | E_ | F_ | G_ | H_ | I_ | J_ | K_ | L_ | M_ | N_ | O_ | P_ | Q_ | R_ | S_ | T_ | U_ | V_ | W_ | X_ | Y_ | Z_ deriving (Show, Eq, Ord) lowerToChar :: LowerChar -> Char lowerToChar = fromJust . flip Map.lookup lowers lowers :: Map LowerChar Char lowers = Map.fromList [ (A_, 'a'), (B_, 'b'), (C_, 'c') , (D_, 'd'), (E_, 'e'), (F_, 'f') , (G_, 'g'), (H_, 'h'), (I_, 'i') , (J_, 'j'), (K_, 'k'), (L_, 'l') , (M_, 'm'), (N_, 'n'), (O_, 'o') , (P_, 'p'), (Q_, 'q'), (R_, 'r') , (S_, 's'), (T_, 't'), (U_, 'u') , (V_, 'v'), (W_, 'w'), (X_, 'x') , (Y_, 'y'), (Z_, 'z') ] lowerChar :: CodeParsing m => m LowerChar lowerChar = do char <- P.lowerChar let maybeLower = Map.lookup char $ dual lowers case maybeLower of Nothing -> fail "non lower char" Just x -> pure x charToLower :: Char -> Maybe LowerChar charToLower x = P.parseMaybe lowerChar [x] lowerCharQ :: QuasiQuoter lowerCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "lowerCharQ required a Char, but nothign is specified." expQ (x : []) = case charToLower x of Nothing -> fail $ show x <> " is not a LowerChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "lowerCharQ required a Char, but a String is specified: " <> xs data DigitChar = D0 | D1 | D2 | D3 | D4 | D5 | D6 | D7 | D8 | D9 deriving (Show, Eq, Ord) digitToChar :: DigitChar -> Char digitToChar = fromJust . flip Map.lookup digits digits :: Map DigitChar Char digits = Map.fromList [ (D0, '0') , (D1, '1'), (D2, '2'), (D3, '3') , (D4, '4'), (D5, '5'), (D6, '6') , (D4, '7'), (D8, '8'), (D9, '9') ] digitChar :: CodeParsing m => m DigitChar digitChar = do char <- P.digitChar let maybeNum = Map.lookup char $ dual digits case maybeNum of Nothing -> fail "non numeric char" Just x -> pure x charToDigit :: Char -> Maybe DigitChar charToDigit x = P.parseMaybe digitChar [x] D9 digitCharQ :: QuasiQuoter digitCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "digitCharQ required a Char, but nothign is specified." expQ (x : []) = case charToDigit x of Nothing -> fail $ show x <> " is not a DigitChar." Just z -> conE . mkName $ show z expQ xs@(_ : _) = fail $ "digitCharQ required a Char, but a String is specified: " <> xs deriving (Show, Eq) snakeToChar :: SnakeChar -> Char snakeToChar SnakeUnderscore = '_' snakeToChar (SnakeAlphaNum x) = alphaNumToChar x snakeChar :: CodeParsing m => m SnakeChar snakeChar = SnakeUnderscore <$ P.char '_' <|> SnakeAlphaNum <$> alphaNumChar charToSnake :: Char -> Maybe SnakeChar charToSnake x = P.parseMaybe snakeChar [x] > > > [ ] SnakeAlphaNum ( ) snakeCharQ :: QuasiQuoter snakeCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "snakeCharQ required a Char, but nothign is specified." expQ (x : []) = case charToSnake x of Nothing -> fail $ show x <> " is not a SnakeChar." Just SnakeUnderscore -> conE $ mkName "SnakeUnderscore" Just (SnakeAlphaNum _) -> (ConE (mkName "SnakeAlphaNum") `AppE`) <$> (quoteExp alphaNumCharQ) [x] expQ xs@(_ : _) = fail $ "snakeCharQ required a Char, but a String is specified: " <> xs data SnakeHeadChar = SnakeHeadUnderscore | SnakeHeadAlpha AlphaChar deriving (Show, Eq) snakeHeadToChar :: SnakeHeadChar -> Char snakeHeadToChar SnakeHeadUnderscore = '_' snakeHeadToChar (SnakeHeadAlpha x) = alphaToChar x snakeHeadChar :: CodeParsing m => m SnakeHeadChar snakeHeadChar = SnakeHeadUnderscore <$ P.char '_' <|> SnakeHeadAlpha <$> alphaChar charToSnakeHead :: Char -> Maybe SnakeHeadChar charToSnakeHead x = P.parseMaybe snakeHeadChar [x] > > > [ snakeHeadCharQ|x| ] > > > [ snakeHeadCharQ|X| ] snakeHeadCharQ :: QuasiQuoter snakeHeadCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "snakeHeadCharQ required a Char, but nothign is specified." expQ (x : []) = case charToSnakeHead x of Nothing -> fail $ show x <> " is not a SnakeHeadChar." Just SnakeHeadUnderscore -> conE $ mkName "SnakeHeadUnderscore" Just (SnakeHeadAlpha _) -> (ConE (mkName "SnakeHeadAlpha") `AppE`) <$> (quoteExp alphaCharQ) [x] expQ xs@(_ : _) = fail $ "snakeHeadCharQ required a Char, but a String is specified: " <> xs deriving (Show, Eq) upperSnakeHeadToChar :: UpperSnakeHeadChar -> Char upperSnakeHeadToChar UpperSnakeHeadUnderscore = '_' upperSnakeHeadToChar (UpperSnakeHeadUpper x) = upperToChar x upperSnakeHeadChar :: CodeParsing m => m UpperSnakeHeadChar upperSnakeHeadChar = UpperSnakeHeadUnderscore <$ P.char '_' <|> UpperSnakeHeadUpper <$> upperChar charToUpperSnakeHead :: Char -> Maybe UpperSnakeHeadChar charToUpperSnakeHead x = P.parseMaybe upperSnakeHeadChar [x] > > > [ upperSnakeHeadCharQ|A| ] upperSnakeHeadCharQ :: QuasiQuoter upperSnakeHeadCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperSnakeHeadCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpperSnakeHead x of Nothing -> fail $ show x <> " is not a UpperSnakeHeadChar." Just UpperSnakeHeadUnderscore -> conE $ mkName "UpperSnakeHeadUnderscore" Just (UpperSnakeHeadUpper _) -> (ConE (mkName "UpperSnakeHeadUpper") `AppE`) <$> (quoteExp upperCharQ) [x] expQ xs@(_ : _) = fail $ "upperSnakeHeadCharQ required a Char, but a String is specified: " <> xs deriving (Show, Eq) upperSnakeToChar :: UpperSnakeChar -> Char upperSnakeToChar UpperSnakeUnderscore = '_' upperSnakeToChar (UpperSnakeUpper x) = upperToChar x upperSnakeToChar (UpperSnakeDigit x) = digitToChar x upperSnakeChar :: CodeParsing m => m UpperSnakeChar upperSnakeChar = UpperSnakeUnderscore <$ P.char '_' <|> UpperSnakeUpper <$> upperChar <|> UpperSnakeDigit <$> digitChar charToUpperSnake :: Char -> Maybe UpperSnakeChar charToUpperSnake x = P.parseMaybe upperSnakeChar [x] > > > [ upperSnakeCharQ|A| ] upperSnakeCharQ :: QuasiQuoter upperSnakeCharQ = QuasiQuoter { quoteExp = expQ , quotePat = error "not supported" , quoteType = error "not supported" , quoteDec = error "not supported" } where expQ :: String -> Q Exp expQ [] = fail "upperSnakeCharQ required a Char, but nothign is specified." expQ (x : []) = case charToUpperSnake x of Nothing -> fail $ show x <> " is not a UpperSnakeChar." Just UpperSnakeUnderscore -> conE $ mkName "UpperSnakeUnderscore" Just (UpperSnakeUpper _) -> (ConE (mkName "UpperSnakeUpper") `AppE`) <$> (quoteExp upperCharQ) [x] Just (UpperSnakeDigit _) -> (ConE (mkName "UpperSnakeDigit") `AppE`) <$> (quoteExp digitCharQ) [x] expQ xs@(_ : _) = fail $ "upperSnakeCharQ required a Char, but a String is specified: " <> xs
b509c04909851c1b62a3f1ef08a0f6e7ddf3b49fc8d9654c59964aa54235514b
tonyrog/dbus
dbus_app.erl
%%%---- BEGIN COPYRIGHT ------------------------------------------------------- %%% Copyright ( C ) 2007 - 2013 , Rogvall Invest AB , < > %%% %%% This software is licensed as described in the file COPYRIGHT, which %%% you should have received as part of this distribution. The terms %%% are also available at . %%% %%% You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software , and permit persons to whom the Software is %%% furnished to do so, under the terms of the COPYRIGHT file. %%% This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY %%% KIND, either express or implied. %%% %%%---- END COPYRIGHT --------------------------------------------------------- -module(dbus_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> dbus_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/tonyrog/dbus/0705e9bee81ace1b5ad2d3af07ae5c156046c47a/src/dbus_app.erl
erlang
---- BEGIN COPYRIGHT ------------------------------------------------------- This software is licensed as described in the file COPYRIGHT, which you should have received as part of this distribution. The terms are also available at . You may opt to use, copy, modify, merge, publish, distribute and/or sell furnished to do so, under the terms of the COPYRIGHT file. KIND, either express or implied. ---- END COPYRIGHT --------------------------------------------------------- Application callbacks =================================================================== Application callbacks ===================================================================
Copyright ( C ) 2007 - 2013 , Rogvall Invest AB , < > copies of the Software , and permit persons to whom the Software is This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY -module(dbus_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> dbus_sup:start_link(). stop(_State) -> ok.
2587c7d8de19eea30c1797be4d92dc94fe5eda9fe88591eac09e9294426487e1
xh4/web-toolkit
stream.lisp
(in-package :http-test) (in-suite :http-test) (test stream (it (babel-streams:with-input-from-sequence (stream #(1 2 3 4 5)) (setf stream (make-instance 'http::stream :upstream stream :length 5)) (is (= 1 (read-byte stream))) (is (= 4 (http::stream-remaining-length stream))) (read-sequence (make-array 2) stream) (is (= 2 (http::stream-remaining-length stream))) (http::stream-read-remain stream) (is (= 0 (http::stream-remaining-length stream))))))
null
https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/test/http/stream.lisp
lisp
(in-package :http-test) (in-suite :http-test) (test stream (it (babel-streams:with-input-from-sequence (stream #(1 2 3 4 5)) (setf stream (make-instance 'http::stream :upstream stream :length 5)) (is (= 1 (read-byte stream))) (is (= 4 (http::stream-remaining-length stream))) (read-sequence (make-array 2) stream) (is (= 2 (http::stream-remaining-length stream))) (http::stream-read-remain stream) (is (= 0 (http::stream-remaining-length stream))))))
2c5ea2a20ede02c6fb715ec47d8c70b6833f20e75325a792804ef0c8722f834d
ghc/testsuite
T3177.hs
{- LANGUAGE TemplateHaskell #-} Template Haskell type splices module T3177 where f :: $(id [t| Int |]) f = 3 class C a where op :: a -> a instance C a => C ($([t| Maybe |]) a) where op x = fmap op x
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/th/T3177.hs
haskell
LANGUAGE TemplateHaskell #
Template Haskell type splices module T3177 where f :: $(id [t| Int |]) f = 3 class C a where op :: a -> a instance C a => C ($([t| Maybe |]) a) where op x = fmap op x
d0143fd97764ffd5672478361dd4371f441b9c6ba094b33a27d0d135d957ffe6
cenary-lang/cenary
Language.hs
module Cenary.Lexer.Language where -------------------------------------------------------------------------------- import Text.Parsec.Language (emptyDef) import Text.Parsec.Token -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- style :: LanguageDef state style = emptyDef { commentLine = "--" , reservedOpNames = ops , reservedNames = names } ops :: [String] ops = [ "+", "*", "-", "/", ";" , "'", "{", "}", "[", "]" ] names :: [String] names = [ "if", "then", "else", "while", "times", "endtimes", "end" , "do", "debug", "true", "false", "int", "char", "bool", "pure" ]
null
https://raw.githubusercontent.com/cenary-lang/cenary/bf5ab4ac6bbc2353b072d32de2f3bc86cbc88266/src/Cenary/Lexer/Language.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
module Cenary.Lexer.Language where import Text.Parsec.Language (emptyDef) import Text.Parsec.Token style :: LanguageDef state style = emptyDef { commentLine = "--" , reservedOpNames = ops , reservedNames = names } ops :: [String] ops = [ "+", "*", "-", "/", ";" , "'", "{", "}", "[", "]" ] names :: [String] names = [ "if", "then", "else", "while", "times", "endtimes", "end" , "do", "debug", "true", "false", "int", "char", "bool", "pure" ]
977ee52df12ec5123c8170bb0fc2081a9a64ee269f26ba796bb7812155c508c2
w3ntao/sicp-solution
3-61.rkt
#lang racket (provide (all-defined-out)) (require (only-in "../ToolBox/AbstractionOfData/stream.rkt" cons-stream stream-cdr scale-stream mul-series display-stream-until exp-series)) (define (invert-unit-series series) (cons-stream 1 (scale-stream (mul-series (stream-cdr series) (invert-unit-series series)) -1))) (display-stream-until exp-series 10) (newline) (display-stream-until (invert-unit-series exp-series) 10) (newline) (display-stream-until (mul-series exp-series (invert-unit-series exp-series)) 10)
null
https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-3/3-61.rkt
racket
#lang racket (provide (all-defined-out)) (require (only-in "../ToolBox/AbstractionOfData/stream.rkt" cons-stream stream-cdr scale-stream mul-series display-stream-until exp-series)) (define (invert-unit-series series) (cons-stream 1 (scale-stream (mul-series (stream-cdr series) (invert-unit-series series)) -1))) (display-stream-until exp-series 10) (newline) (display-stream-until (invert-unit-series exp-series) 10) (newline) (display-stream-until (mul-series exp-series (invert-unit-series exp-series)) 10)
9b8d04c96ae0fbd9e1ceb5d0b3f04f2bf57361b2ab57479351c88574f9fbf299
scarvalhojr/haskellbook
section18.6.hs
import Control.Monad ((>=>)) sayHi :: String -> IO String sayHi greeting = do putStrLn greeting getLine readM :: Read a => String -> IO a readM = return . read getAge :: String -> IO Int getAge = sayHi >=> readM askForAge :: IO Int askForAge = getAge "How old are you?"
null
https://raw.githubusercontent.com/scarvalhojr/haskellbook/6016a5a78da3fc4a29f5ea68b239563895c448d5/chapter18/section18.6.hs
haskell
import Control.Monad ((>=>)) sayHi :: String -> IO String sayHi greeting = do putStrLn greeting getLine readM :: Read a => String -> IO a readM = return . read getAge :: String -> IO Int getAge = sayHi >=> readM askForAge :: IO Int askForAge = getAge "How old are you?"
bde251f3235fc9584b6258c6aeb57c0099cb112ade3850cd3982b53548ee6fca
rcherrueau/APE
ast.rkt
#lang typed/racket/base (require "utils.rkt") (provide (all-defined-out)) (define-datatype Primitive1 Add1 Sub1) (define-datatype Exp [Num Number] [Id Symbol] [Prim1 Primitive1 Exp] [Let (Listof (Pairof Symbol Exp)) Exp] )
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/pan/core/ast.rkt
racket
#lang typed/racket/base (require "utils.rkt") (provide (all-defined-out)) (define-datatype Primitive1 Add1 Sub1) (define-datatype Exp [Num Number] [Id Symbol] [Prim1 Primitive1 Exp] [Let (Listof (Pairof Symbol Exp)) Exp] )
45e3d95feca36be3e7c6159a258aa1de411e979935530dd8865756da0b0cd159
melange-re/melange
lam_analysis.mli
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) (** A module which provides some basic analysis over lambda expression *) val no_side_effects : Lam.t -> bool (** No side effect, but it might depend on data store *) val size : Lam.t -> int val ok_to_inline_fun_when_app : Lam.lfunction -> Lam.t list -> bool val small_inline_size : int val exit_inline_size : int val safe_to_inline : Lam.t -> bool
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/core/lam_analysis.mli
ocaml
* A module which provides some basic analysis over lambda expression * No side effect, but it might depend on data store
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) val no_side_effects : Lam.t -> bool val size : Lam.t -> int val ok_to_inline_fun_when_app : Lam.lfunction -> Lam.t list -> bool val small_inline_size : int val exit_inline_size : int val safe_to_inline : Lam.t -> bool
b5002fe82e3caa6cbef4b14d02c3269880482606539196cead95a3fcba600ddc
input-output-hk/ouroboros-network
Run.hs
{-# LANGUAGE FlexibleContexts #-} # LANGUAGE NamedFieldPuns # {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # module Cardano.Tools.DBAnalyser.Run (analyse) where import Codec.CBOR.Decoding (Decoder) import Codec.Serialise (Serialise (decode)) import Control.Monad.Except (runExceptT) import qualified Debug.Trace as Debug import System.IO import Control.Tracer (Tracer (..), nullTracer) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config import qualified Ouroboros.Consensus.Fragment.InFuture as InFuture import Ouroboros.Consensus.Ledger.Extended import qualified Ouroboros.Consensus.Ledger.SupportsMempool as LedgerSupportsMempool (HasTxs) import qualified Ouroboros.Consensus.Node as Node import qualified Ouroboros.Consensus.Node.InitStorage as Node import Ouroboros.Consensus.Node.ProtocolInfo (ProtocolInfo (..)) import Ouroboros.Consensus.Storage.Serialisation (DecodeDisk (..)) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Util.Orphans () import Ouroboros.Consensus.Util.ResourceRegistry import qualified Ouroboros.Consensus.Storage.ChainDB as ChainDB import Ouroboros.Consensus.Storage.ChainDB.Impl.Args (fromChainDbArgs) import qualified Ouroboros.Consensus.Storage.ImmutableDB as ImmutableDB import Ouroboros.Consensus.Storage.LedgerDB (SnapshotInterval (..), defaultDiskPolicy, readSnapshot) import qualified Ouroboros.Consensus.Storage.VolatileDB as VolatileDB import Cardano.Tools.DBAnalyser.Analysis import Cardano.Tools.DBAnalyser.HasAnalysis import Cardano.Tools.DBAnalyser.Types {------------------------------------------------------------------------------- Analyse -------------------------------------------------------------------------------} analyse :: forall blk . ( Node.RunNode blk , Show (Header blk) , HasAnalysis blk , HasProtocolInfo blk , LedgerSupportsMempool.HasTxs blk ) => DBAnalyserConfig -> Args blk -> IO (Maybe AnalysisResult) analyse DBAnalyserConfig{analysis, confLimit, dbDir, selectDB, validation, verbose} args = withRegistry $ \registry -> do chainDBTracer <- mkTracer verbose analysisTracer <- mkTracer True ProtocolInfo { pInfoInitLedger = genesisLedger, pInfoConfig = cfg } <- mkProtocolInfo args let chunkInfo = Node.nodeImmutableDbChunkInfo (configStorage cfg) k = configSecurityParam cfg diskPolicy = defaultDiskPolicy k DefaultSnapshotInterval args' = Node.mkChainDbArgs registry InFuture.dontCheck cfg genesisLedger chunkInfo $ ChainDB.defaultArgs (Node.stdMkChainDbHasFS dbDir) diskPolicy chainDbArgs = args' { ChainDB.cdbImmutableDbValidation = immValidationPolicy , ChainDB.cdbVolatileDbValidation = volValidationPolicy , ChainDB.cdbTracer = chainDBTracer } (immutableDbArgs, _, _, _) = fromChainDbArgs chainDbArgs ledgerDbFS = ChainDB.cdbHasFSLgrDB chainDbArgs case selectDB of SelectImmutableDB initializeFrom -> do -- TODO we need to check if the snapshot exists. If not, print an error and ask the user if she wanted to create a snapshot first and -- how to do it. initLedgerErr <- runExceptT $ case initializeFrom of Nothing -> pure genesisLedger Just snapshot -> readSnapshot ledgerDbFS (decodeExtLedgerState' cfg) decode snapshot TODO @readSnapshot@ has type @ExceptT ReadIncrementalErr m -- (ExtLedgerState blk)@ but it also throws exceptions! This makes -- error handling more challenging than it ought to be. Maybe we -- can enrich the error that @readSnapthot@ return, so that it can -- contain the @HasFS@ errors as well. initLedger <- either (error . show) pure initLedgerErr -- This marker divides the "loading" phase of the program, where the -- system is principally occupied with reading snapshot data from -- disk, from the "processing" phase, where we are streaming blocks -- and running the ledger processing on them. Debug.traceMarkerIO "SNAPSHOT_LOADED" ImmutableDB.withDB (ImmutableDB.openDB immutableDbArgs runWithTempRegistry) $ \immutableDB -> do result <- runAnalysis analysis $ AnalysisEnv { cfg , initLedger , db = Left immutableDB , registry , ledgerDbFS = ledgerDbFS , limit = confLimit , tracer = analysisTracer } tipPoint <- atomically $ ImmutableDB.getTipPoint immutableDB putStrLn $ "ImmutableDB tip: " ++ show tipPoint pure result SelectChainDB -> ChainDB.withDB chainDbArgs $ \chainDB -> do result <- runAnalysis analysis $ AnalysisEnv { cfg , initLedger = genesisLedger , db = Right chainDB , registry , ledgerDbFS = ledgerDbFS , limit = confLimit , tracer = analysisTracer } tipPoint <- atomically $ ChainDB.getTipPoint chainDB putStrLn $ "ChainDB tip: " ++ show tipPoint pure result where mkTracer False = return nullTracer mkTracer True = do startTime <- getMonotonicTime return $ Tracer $ \ev -> do traceTime <- getMonotonicTime let diff = diffTime traceTime startTime hPutStrLn stderr $ concat ["[", show diff, "] ", show ev] hFlush stderr immValidationPolicy = case (analysis, validation) of (_, Just ValidateAllBlocks) -> ImmutableDB.ValidateAllChunks (_, Just MinimumBlockValidation) -> ImmutableDB.ValidateMostRecentChunk (OnlyValidation, _ ) -> ImmutableDB.ValidateAllChunks _ -> ImmutableDB.ValidateMostRecentChunk volValidationPolicy = case (analysis, validation) of (_, Just ValidateAllBlocks) -> VolatileDB.ValidateAll (_, Just MinimumBlockValidation) -> VolatileDB.NoValidation (OnlyValidation, _ ) -> VolatileDB.ValidateAll _ -> VolatileDB.NoValidation decodeExtLedgerState' :: forall s . TopLevelConfig blk -> Decoder s (ExtLedgerState blk) decodeExtLedgerState' cfg = let ccfg = configCodec cfg in decodeExtLedgerState (decodeDisk ccfg) (decodeDisk ccfg) (decodeDisk ccfg)
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/358880057f1d6d86cc385e8475813ace3b9ebef6/ouroboros-consensus-cardano-tools/src/Cardano/Tools/DBAnalyser/Run.hs
haskell
# LANGUAGE FlexibleContexts # # LANGUAGE RankNTypes # ------------------------------------------------------------------------------ Analyse ------------------------------------------------------------------------------ TODO we need to check if the snapshot exists. If not, print an how to do it. (ExtLedgerState blk)@ but it also throws exceptions! This makes error handling more challenging than it ought to be. Maybe we can enrich the error that @readSnapthot@ return, so that it can contain the @HasFS@ errors as well. This marker divides the "loading" phase of the program, where the system is principally occupied with reading snapshot data from disk, from the "processing" phase, where we are streaming blocks and running the ledger processing on them.
# LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # module Cardano.Tools.DBAnalyser.Run (analyse) where import Codec.CBOR.Decoding (Decoder) import Codec.Serialise (Serialise (decode)) import Control.Monad.Except (runExceptT) import qualified Debug.Trace as Debug import System.IO import Control.Tracer (Tracer (..), nullTracer) import Ouroboros.Consensus.Block import Ouroboros.Consensus.Config import qualified Ouroboros.Consensus.Fragment.InFuture as InFuture import Ouroboros.Consensus.Ledger.Extended import qualified Ouroboros.Consensus.Ledger.SupportsMempool as LedgerSupportsMempool (HasTxs) import qualified Ouroboros.Consensus.Node as Node import qualified Ouroboros.Consensus.Node.InitStorage as Node import Ouroboros.Consensus.Node.ProtocolInfo (ProtocolInfo (..)) import Ouroboros.Consensus.Storage.Serialisation (DecodeDisk (..)) import Ouroboros.Consensus.Util.IOLike import Ouroboros.Consensus.Util.Orphans () import Ouroboros.Consensus.Util.ResourceRegistry import qualified Ouroboros.Consensus.Storage.ChainDB as ChainDB import Ouroboros.Consensus.Storage.ChainDB.Impl.Args (fromChainDbArgs) import qualified Ouroboros.Consensus.Storage.ImmutableDB as ImmutableDB import Ouroboros.Consensus.Storage.LedgerDB (SnapshotInterval (..), defaultDiskPolicy, readSnapshot) import qualified Ouroboros.Consensus.Storage.VolatileDB as VolatileDB import Cardano.Tools.DBAnalyser.Analysis import Cardano.Tools.DBAnalyser.HasAnalysis import Cardano.Tools.DBAnalyser.Types analyse :: forall blk . ( Node.RunNode blk , Show (Header blk) , HasAnalysis blk , HasProtocolInfo blk , LedgerSupportsMempool.HasTxs blk ) => DBAnalyserConfig -> Args blk -> IO (Maybe AnalysisResult) analyse DBAnalyserConfig{analysis, confLimit, dbDir, selectDB, validation, verbose} args = withRegistry $ \registry -> do chainDBTracer <- mkTracer verbose analysisTracer <- mkTracer True ProtocolInfo { pInfoInitLedger = genesisLedger, pInfoConfig = cfg } <- mkProtocolInfo args let chunkInfo = Node.nodeImmutableDbChunkInfo (configStorage cfg) k = configSecurityParam cfg diskPolicy = defaultDiskPolicy k DefaultSnapshotInterval args' = Node.mkChainDbArgs registry InFuture.dontCheck cfg genesisLedger chunkInfo $ ChainDB.defaultArgs (Node.stdMkChainDbHasFS dbDir) diskPolicy chainDbArgs = args' { ChainDB.cdbImmutableDbValidation = immValidationPolicy , ChainDB.cdbVolatileDbValidation = volValidationPolicy , ChainDB.cdbTracer = chainDBTracer } (immutableDbArgs, _, _, _) = fromChainDbArgs chainDbArgs ledgerDbFS = ChainDB.cdbHasFSLgrDB chainDbArgs case selectDB of SelectImmutableDB initializeFrom -> do error and ask the user if she wanted to create a snapshot first and initLedgerErr <- runExceptT $ case initializeFrom of Nothing -> pure genesisLedger Just snapshot -> readSnapshot ledgerDbFS (decodeExtLedgerState' cfg) decode snapshot TODO @readSnapshot@ has type @ExceptT ReadIncrementalErr m initLedger <- either (error . show) pure initLedgerErr Debug.traceMarkerIO "SNAPSHOT_LOADED" ImmutableDB.withDB (ImmutableDB.openDB immutableDbArgs runWithTempRegistry) $ \immutableDB -> do result <- runAnalysis analysis $ AnalysisEnv { cfg , initLedger , db = Left immutableDB , registry , ledgerDbFS = ledgerDbFS , limit = confLimit , tracer = analysisTracer } tipPoint <- atomically $ ImmutableDB.getTipPoint immutableDB putStrLn $ "ImmutableDB tip: " ++ show tipPoint pure result SelectChainDB -> ChainDB.withDB chainDbArgs $ \chainDB -> do result <- runAnalysis analysis $ AnalysisEnv { cfg , initLedger = genesisLedger , db = Right chainDB , registry , ledgerDbFS = ledgerDbFS , limit = confLimit , tracer = analysisTracer } tipPoint <- atomically $ ChainDB.getTipPoint chainDB putStrLn $ "ChainDB tip: " ++ show tipPoint pure result where mkTracer False = return nullTracer mkTracer True = do startTime <- getMonotonicTime return $ Tracer $ \ev -> do traceTime <- getMonotonicTime let diff = diffTime traceTime startTime hPutStrLn stderr $ concat ["[", show diff, "] ", show ev] hFlush stderr immValidationPolicy = case (analysis, validation) of (_, Just ValidateAllBlocks) -> ImmutableDB.ValidateAllChunks (_, Just MinimumBlockValidation) -> ImmutableDB.ValidateMostRecentChunk (OnlyValidation, _ ) -> ImmutableDB.ValidateAllChunks _ -> ImmutableDB.ValidateMostRecentChunk volValidationPolicy = case (analysis, validation) of (_, Just ValidateAllBlocks) -> VolatileDB.ValidateAll (_, Just MinimumBlockValidation) -> VolatileDB.NoValidation (OnlyValidation, _ ) -> VolatileDB.ValidateAll _ -> VolatileDB.NoValidation decodeExtLedgerState' :: forall s . TopLevelConfig blk -> Decoder s (ExtLedgerState blk) decodeExtLedgerState' cfg = let ccfg = configCodec cfg in decodeExtLedgerState (decodeDisk ccfg) (decodeDisk ccfg) (decodeDisk ccfg)
d3a5f580c455e69e6f6725e0ce2fad8b8e53ab5eb5174baf1cef99e59768d317
yrashk/erlang
snmpa_svbl.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(snmpa_svbl). -include("snmp_types.hrl"). -define(VMODULE,"SVBL"). -include("snmp_verbosity.hrl"). -export([sort_varbindlist/2, sort_varbinds_rows/1, sa_split/1, delete_org_index/1, col_to_orgindex/2]). %%----------------------------------------------------------------- Func : sort_varbindlist/2 Args : Varbinds is a list of # varbind Purpose : Group all variablebindings that corresponds to logically %% the same entity, i.e. group all plain variables, all %% table operations for each table, all varbinds to each %% subagent. Returns : { VarbindsForThisAgent %% VarbindsForSubAgents} where VarbindsForThisAgent = List of { TableOid , List of # ivarbinds } | %% #ivarbinds = List of { SubAgentPid , List of { SAOid , # varbinds } } %%----------------------------------------------------------------- sort_varbindlist(Mib, Varbinds) -> {Vars, Tabs, Subagents} = partition(Mib, Varbinds), {lists:append(Tabs, Vars), Subagents}. partition(Mib, Vbs) -> partition(Mib, Vbs, [], [], []). partition(Mib, [Varbind | Vbs], Vars, Tabs, Subs) -> #varbind{oid = Oid} = Varbind, ?vtrace("partition -> Oid: ~p", [Oid]), case snmpa_mib:lookup(Mib, Oid) of {table_column, MibEntry, TableOid} -> IVarbind = #ivarbind{varbind = fix_bits(Varbind, MibEntry), mibentry = MibEntry}, NewTabs = insert_key(TableOid, IVarbind, Tabs), partition(Mib, Vbs, Vars, NewTabs, Subs); {subagent, SubagentPid, SAOid} -> NewSubs = insert_key(SubagentPid, {SAOid, Varbind}, Subs), partition(Mib, Vbs, Vars, Tabs, NewSubs); {variable, MibEntry} -> IVarbind = #ivarbind{varbind = fix_bits(Varbind, MibEntry), mibentry = MibEntry}, partition(Mib, Vbs, [IVarbind | Vars], Tabs, Subs); ErrorCode = noSuchObject | noSuchInstance IVarbind = #ivarbind{status = ErrorCode, varbind = Varbind}, partition(Mib, Vbs, [IVarbind | Vars], Tabs, Subs) end; partition(_Mib, [], Vars, Subs, Tabs) -> {Vars, Subs, Tabs}. % fix_bits(#varbind{bertype = 'BITS', % variabletype = 'OCTET STRING', % value = V} = VarBind, #me{asn1_type = A}) -> VarBind#varbind{variabletype = ' BITS ' , value = snmp_pdus : ) } ; fix_bits(VarBind, #me{asn1_type=A}) when A#asn1_type.bertype == 'BITS', VarBind#varbind.variabletype == 'OCTET STRING', list(VarBind#varbind.value) -> VarBind#varbind{variabletype = 'BITS', value = snmp_pdus:octet_str_to_bits(VarBind#varbind.value)}; fix_bits(Vb,_me) -> Vb. insert_key(Key, Value, [{Key, Values} | Rest]) -> [{Key, [Value | Values]} | Rest]; insert_key(Key, Value, [{KeyX, Values} | Rest]) -> [{KeyX, Values} | insert_key(Key, Value, Rest)]; insert_key(Key, Value, []) -> [{Key, [Value]}]. %%----------------------------------------------------------------- Tranforms a list of { Oid , Vb } to a 2 - tuple with all Oids and all . These lists will be reversed . %%----------------------------------------------------------------- sa_split(Vbs) -> sa_split(Vbs, [], []). sa_split([{SAOid, Vb} | T], Oids, Vbs) -> sa_split(T, [SAOid | Oids], [Vb | Vbs]); sa_split([], Oids, Vbs) -> {Oids, Vbs}. %%----------------------------------------------------------------- %% Func: sort_varbinds_rows/1 Args : Varbinds is a list of { Oid , Value } . Pre : Varbinds is for one table . Purpose : Sorts all varbinds in Oid order , and in row order . %% Returns: list of Row where %% Row = {Indexes, List of Col} and Col = { ColNo , Value , OrgIndex } and OrgIndex is index in original varbind list . %%----------------------------------------------------------------- sort_varbinds_rows(Varbinds) -> P = pack(Varbinds), S = lists:keysort(1, P), unpack(S). In : list of { Oid , Value } Out : list of { { Indexes_for_row , Col } , , Index } pack(V) -> pack(1, V). pack(Index, [{[Col | Rest], Val} | T]) -> [{{Rest, Col}, Val, Index} | pack(Index+1, T)]; pack(_, []) -> []. unpack([{{Rest, Col}, Val, Index} | T]) -> unpack(Rest, [[{Col, Val, Index}]], T); unpack([]) -> []. unpack(Rest, [Row | Rows], [{{Rest, Col}, Val, Index} | T]) -> unpack(Rest, [[{Col, Val, Index} | Row] | Rows], T); unpack(Rest, [Row | Rows], [{{Rest2, Col}, Val, Index} | T]) -> unpack(Rest2, [[{Col, Val, Index}], {Rest, lists:reverse(Row)} | Rows], T); unpack(Rest, [Row | Rows], []) -> NewRow = {Rest, lists:reverse(Row)}, lists:reverse([NewRow | Rows]). OrgIndex should not be present when we call the is_set_ok / set / undo %% table functions. They just see the list of cols, and if an error occurs , they return the column . %% Also, delete duplicate columns. If a SET is performed with duplicate %% columns, it is undefined which column to use. We just pick one. delete_org_index([{RowIndex, Cols} | Rows]) -> [{RowIndex, doi(Cols)} | delete_org_index(Rows)]; delete_org_index([]) -> []. doi([{Col, Val, OrgIndex}, {Col, _Val, _OrgIndex} | T]) -> doi([{Col, Val, OrgIndex} | T]); doi([{Col, Val, _OrgIndex} | T]) -> [{Col, Val} | doi(T)]; doi([]) -> []. Maps the column number to OrgIndex . col_to_orgindex(0, _) -> 0; col_to_orgindex(Col, [{Col, _Val, OrgIndex}|_]) -> OrgIndex; col_to_orgindex(Col, [_|Cols]) -> col_to_orgindex(Col, Cols); col_to_orgindex(BadCol, _) -> {false, BadCol}.
null
https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/snmp/src/agent/snmpa_svbl.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% ----------------------------------------------------------------- the same entity, i.e. group all plain variables, all table operations for each table, all varbinds to each subagent. VarbindsForSubAgents} where #ivarbinds ----------------------------------------------------------------- fix_bits(#varbind{bertype = 'BITS', variabletype = 'OCTET STRING', value = V} = VarBind, #me{asn1_type = A}) -> ----------------------------------------------------------------- ----------------------------------------------------------------- ----------------------------------------------------------------- Func: sort_varbinds_rows/1 Returns: list of Row where Row = {Indexes, List of Col} and ----------------------------------------------------------------- table functions. They just see the list of cols, and if an error Also, delete duplicate columns. If a SET is performed with duplicate columns, it is undefined which column to use. We just pick one.
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(snmpa_svbl). -include("snmp_types.hrl"). -define(VMODULE,"SVBL"). -include("snmp_verbosity.hrl"). -export([sort_varbindlist/2, sort_varbinds_rows/1, sa_split/1, delete_org_index/1, col_to_orgindex/2]). Func : sort_varbindlist/2 Args : Varbinds is a list of # varbind Purpose : Group all variablebindings that corresponds to logically Returns : { VarbindsForThisAgent VarbindsForThisAgent = List of { TableOid , List of # ivarbinds } | = List of { SubAgentPid , List of { SAOid , # varbinds } } sort_varbindlist(Mib, Varbinds) -> {Vars, Tabs, Subagents} = partition(Mib, Varbinds), {lists:append(Tabs, Vars), Subagents}. partition(Mib, Vbs) -> partition(Mib, Vbs, [], [], []). partition(Mib, [Varbind | Vbs], Vars, Tabs, Subs) -> #varbind{oid = Oid} = Varbind, ?vtrace("partition -> Oid: ~p", [Oid]), case snmpa_mib:lookup(Mib, Oid) of {table_column, MibEntry, TableOid} -> IVarbind = #ivarbind{varbind = fix_bits(Varbind, MibEntry), mibentry = MibEntry}, NewTabs = insert_key(TableOid, IVarbind, Tabs), partition(Mib, Vbs, Vars, NewTabs, Subs); {subagent, SubagentPid, SAOid} -> NewSubs = insert_key(SubagentPid, {SAOid, Varbind}, Subs), partition(Mib, Vbs, Vars, Tabs, NewSubs); {variable, MibEntry} -> IVarbind = #ivarbind{varbind = fix_bits(Varbind, MibEntry), mibentry = MibEntry}, partition(Mib, Vbs, [IVarbind | Vars], Tabs, Subs); ErrorCode = noSuchObject | noSuchInstance IVarbind = #ivarbind{status = ErrorCode, varbind = Varbind}, partition(Mib, Vbs, [IVarbind | Vars], Tabs, Subs) end; partition(_Mib, [], Vars, Subs, Tabs) -> {Vars, Subs, Tabs}. VarBind#varbind{variabletype = ' BITS ' , value = snmp_pdus : ) } ; fix_bits(VarBind, #me{asn1_type=A}) when A#asn1_type.bertype == 'BITS', VarBind#varbind.variabletype == 'OCTET STRING', list(VarBind#varbind.value) -> VarBind#varbind{variabletype = 'BITS', value = snmp_pdus:octet_str_to_bits(VarBind#varbind.value)}; fix_bits(Vb,_me) -> Vb. insert_key(Key, Value, [{Key, Values} | Rest]) -> [{Key, [Value | Values]} | Rest]; insert_key(Key, Value, [{KeyX, Values} | Rest]) -> [{KeyX, Values} | insert_key(Key, Value, Rest)]; insert_key(Key, Value, []) -> [{Key, [Value]}]. Tranforms a list of { Oid , Vb } to a 2 - tuple with all Oids and all . These lists will be reversed . sa_split(Vbs) -> sa_split(Vbs, [], []). sa_split([{SAOid, Vb} | T], Oids, Vbs) -> sa_split(T, [SAOid | Oids], [Vb | Vbs]); sa_split([], Oids, Vbs) -> {Oids, Vbs}. Args : Varbinds is a list of { Oid , Value } . Pre : Varbinds is for one table . Purpose : Sorts all varbinds in Oid order , and in row order . Col = { ColNo , Value , OrgIndex } and OrgIndex is index in original varbind list . sort_varbinds_rows(Varbinds) -> P = pack(Varbinds), S = lists:keysort(1, P), unpack(S). In : list of { Oid , Value } Out : list of { { Indexes_for_row , Col } , , Index } pack(V) -> pack(1, V). pack(Index, [{[Col | Rest], Val} | T]) -> [{{Rest, Col}, Val, Index} | pack(Index+1, T)]; pack(_, []) -> []. unpack([{{Rest, Col}, Val, Index} | T]) -> unpack(Rest, [[{Col, Val, Index}]], T); unpack([]) -> []. unpack(Rest, [Row | Rows], [{{Rest, Col}, Val, Index} | T]) -> unpack(Rest, [[{Col, Val, Index} | Row] | Rows], T); unpack(Rest, [Row | Rows], [{{Rest2, Col}, Val, Index} | T]) -> unpack(Rest2, [[{Col, Val, Index}], {Rest, lists:reverse(Row)} | Rows], T); unpack(Rest, [Row | Rows], []) -> NewRow = {Rest, lists:reverse(Row)}, lists:reverse([NewRow | Rows]). OrgIndex should not be present when we call the is_set_ok / set / undo occurs , they return the column . delete_org_index([{RowIndex, Cols} | Rows]) -> [{RowIndex, doi(Cols)} | delete_org_index(Rows)]; delete_org_index([]) -> []. doi([{Col, Val, OrgIndex}, {Col, _Val, _OrgIndex} | T]) -> doi([{Col, Val, OrgIndex} | T]); doi([{Col, Val, _OrgIndex} | T]) -> [{Col, Val} | doi(T)]; doi([]) -> []. Maps the column number to OrgIndex . col_to_orgindex(0, _) -> 0; col_to_orgindex(Col, [{Col, _Val, OrgIndex}|_]) -> OrgIndex; col_to_orgindex(Col, [_|Cols]) -> col_to_orgindex(Col, Cols); col_to_orgindex(BadCol, _) -> {false, BadCol}.
383feb88f68720ed173487f6f8b2735421112bcfa0c0710d7726c80d2921ac01
openmusic-project/openmusic
om-osc.lisp
;;=========================================================================== OM API Multiplatform API for OpenMusic ; Copyright ( C ) 2004 IRCAM - Centre , Paris , France . ; ;This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 ;of the License, or (at your option) any later version. ; ;See file LICENSE for further informations on licensing terms. ; ;This program is distributed in the hope that it will be useful, ;but WITHOUT ANY WARRANTY; without even the implied warranty of ;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;GNU General Public License for more details. ; You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . ; Authors : and ;;=========================================================================== ;;=========================================================================== ;loads the OSC API ;;=========================================================================== (in-package :cl-user) (setf *stdout* #.*standard-output*) (load (make-pathname :directory (append (pathname-directory *load-pathname*) (list "cl-osc")) :name "osc.asd")) (asdf:operate 'asdf:load-op 'osc) (push :osc *features*) (in-package :om-api) (export '( om-send-osc-bundle om-send-osc-message om-start-osc-server om-stop-osc-server om-decode-msg-or-bundle ) :om-api) ;; the representation of an osc msg is a list of string or fixnum objects a bundle is a list of such . Upon reception , decode - bundle gives a list with a time - tag as its first element does not handle floats and int are limited to 2 ^ 31 as udpsend and udpreceive tend to replace OpenSoundControl in , there is a simplewrite - osc - msg ;; in addition to write-osc-bundle ;;; OLD WAY ;(defun write-osc-msg (message osc-stream) ; (write-sequence (apply #'osc:encode-message message) osc-stream) ; (force-output osc-stream)) ; ;(defun write-osc-bundle (bundle osc-stream &optional (time-tag :now)) ; (write-sequence (osc:encode-bundle bundle time-tag) osc-stream) ; (force-output osc-stream)) ; ;(defun open-osc-out-stream (host port) ; (comm+:open-udp-stream host port :direction :output :element-type '(unsigned-byte 8))) ; ;(defun close-osc-stream (osc-stream) ; (close osc-stream)) ;;; OSC OVER UDP (COMM+) (defun write-osc-msg (message datagram) (comm+:send-message datagram (apply #'osc:encode-message message))) (defun write-osc-bundle (bundle datagram &optional (time-tag :now)) (comm+:send-message datagram (osc:encode-bundle bundle time-tag))) (defun open-osc-out-stream (host port) (comm+:connect-to-udp-server host port)) (defun close-osc-stream (datagram) (comm+:close-datagram datagram)) ;;;================ OM API ;;;================ ;;; SEND (defun om-send-osc-message (port host message) (let ((outs (open-osc-out-stream host port))) (write-osc-msg message outs) (close-osc-stream outs))) (defun om-send-osc-bundle (port host bundle) (let ((outs (open-osc-out-stream host port))) (write-osc-bundle bundle outs) (close-osc-stream outs))) ;;; RECEIVE (defun om-decode-msg-or-bundle (msg) (osc::decode-message-or-bundle msg)) (defun om-start-osc-server (port host function &optional name) (comm+:start-udp-server :address host :service port :function function :process-name (or name (format nil "OSC receiver on ~S ~S" host port)))) (defun om-stop-osc-server (server) (when server (comm+:stop-udp-server server :wait t)))
null
https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/api/externals/OSC/om-osc.lisp
lisp
=========================================================================== This program is free software; you can redistribute it and/or either version 2 of the License, or (at your option) any later version. See file LICENSE for further informations on licensing terms. 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. if not , write to the Free Software =========================================================================== =========================================================================== loads the OSC API =========================================================================== the representation of an osc msg is a list of string or fixnum objects in addition to write-osc-bundle OLD WAY (defun write-osc-msg (message osc-stream) (write-sequence (apply #'osc:encode-message message) osc-stream) (force-output osc-stream)) (defun write-osc-bundle (bundle osc-stream &optional (time-tag :now)) (write-sequence (osc:encode-bundle bundle time-tag) osc-stream) (force-output osc-stream)) (defun open-osc-out-stream (host port) (comm+:open-udp-stream host port :direction :output :element-type '(unsigned-byte 8))) (defun close-osc-stream (osc-stream) (close osc-stream)) OSC OVER UDP (COMM+) ================ ================ SEND RECEIVE
OM API Multiplatform API for OpenMusic Copyright ( C ) 2004 IRCAM - Centre , Paris , France . modify it under the terms of the GNU General Public License You should have received a copy of the GNU General Public License Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . Authors : and (in-package :cl-user) (setf *stdout* #.*standard-output*) (load (make-pathname :directory (append (pathname-directory *load-pathname*) (list "cl-osc")) :name "osc.asd")) (asdf:operate 'asdf:load-op 'osc) (push :osc *features*) (in-package :om-api) (export '( om-send-osc-bundle om-send-osc-message om-start-osc-server om-stop-osc-server om-decode-msg-or-bundle ) :om-api) a bundle is a list of such . Upon reception , decode - bundle gives a list with a time - tag as its first element does not handle floats and int are limited to 2 ^ 31 as udpsend and udpreceive tend to replace OpenSoundControl in , there is a simplewrite - osc - msg (defun write-osc-msg (message datagram) (comm+:send-message datagram (apply #'osc:encode-message message))) (defun write-osc-bundle (bundle datagram &optional (time-tag :now)) (comm+:send-message datagram (osc:encode-bundle bundle time-tag))) (defun open-osc-out-stream (host port) (comm+:connect-to-udp-server host port)) (defun close-osc-stream (datagram) (comm+:close-datagram datagram)) OM API (defun om-send-osc-message (port host message) (let ((outs (open-osc-out-stream host port))) (write-osc-msg message outs) (close-osc-stream outs))) (defun om-send-osc-bundle (port host bundle) (let ((outs (open-osc-out-stream host port))) (write-osc-bundle bundle outs) (close-osc-stream outs))) (defun om-decode-msg-or-bundle (msg) (osc::decode-message-or-bundle msg)) (defun om-start-osc-server (port host function &optional name) (comm+:start-udp-server :address host :service port :function function :process-name (or name (format nil "OSC receiver on ~S ~S" host port)))) (defun om-stop-osc-server (server) (when server (comm+:stop-udp-server server :wait t)))
7cd9766aca85673b422162b07f84ed09d08d172de596d7893c6c3479fb0705a1
nunchaku-inria/nunchaku
Bit_set.ml
(* This file is free software, part of containers. See file "license" for more details. *) (** {1 Bit Field} *) exception TooManyFields exception Frozen let max_width = Sys.word_size - 2 module type S = sig type t = private int * Generative type of bitfields . Each instantiation of the functor should create a new , incompatible type should create a new, incompatible type *) val empty : t * Empty bitfields ( all bits 0 ) type field val get : field -> t -> bool (** Get the value of this field *) val set : field -> bool -> t -> t (** Set the value of this field *) val mk_field : unit -> field (** Make a new field *) val freeze : unit -> unit * Prevent new fields from being added . From now on , creating a field will raise a field will raise Frozen *) val total_width : unit -> int * Current width of the bitfield end let rec all_bits_ acc w = if w=0 then acc else let acc = acc lor (1 lsl w-1) in all_bits_ acc (w-1) $ T all_bits _ 0 1 = 1 all_bits _ 0 2 = 3 all_bits _ 0 3 = 7 all_bits _ 0 4 = 15 all_bits_ 0 1 = 1 all_bits_ 0 2 = 3 all_bits_ 0 3 = 7 all_bits_ 0 4 = 15 *) (* increment and return previous value *) let get_then_incr n = let x = !n in incr n; x let get_then_add n offset = let x = !n in n := !n + offset; x module Make(X : sig end) : S = struct type t = int let empty = 0 let width_ = ref 0 let frozen_ = ref false type field = int (* a mask *) let get field x = (x land field) <> 0 let set field b x = if b then x lor field else x land (lnot field) let mk_field () = if !frozen_ then raise Frozen; let n = get_then_incr width_ in if n > max_width then raise TooManyFields; let mask = 1 lsl n in mask let freeze () = frozen_ := true let total_width () = !width_ end
null
https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/core/Bit_set.ml
ocaml
This file is free software, part of containers. See file "license" for more details. * {1 Bit Field} * Get the value of this field * Set the value of this field * Make a new field increment and return previous value a mask
exception TooManyFields exception Frozen let max_width = Sys.word_size - 2 module type S = sig type t = private int * Generative type of bitfields . Each instantiation of the functor should create a new , incompatible type should create a new, incompatible type *) val empty : t * Empty bitfields ( all bits 0 ) type field val get : field -> t -> bool val set : field -> bool -> t -> t val mk_field : unit -> field val freeze : unit -> unit * Prevent new fields from being added . From now on , creating a field will raise a field will raise Frozen *) val total_width : unit -> int * Current width of the bitfield end let rec all_bits_ acc w = if w=0 then acc else let acc = acc lor (1 lsl w-1) in all_bits_ acc (w-1) $ T all_bits _ 0 1 = 1 all_bits _ 0 2 = 3 all_bits _ 0 3 = 7 all_bits _ 0 4 = 15 all_bits_ 0 1 = 1 all_bits_ 0 2 = 3 all_bits_ 0 3 = 7 all_bits_ 0 4 = 15 *) let get_then_incr n = let x = !n in incr n; x let get_then_add n offset = let x = !n in n := !n + offset; x module Make(X : sig end) : S = struct type t = int let empty = 0 let width_ = ref 0 let frozen_ = ref false let get field x = (x land field) <> 0 let set field b x = if b then x lor field else x land (lnot field) let mk_field () = if !frozen_ then raise Frozen; let n = get_then_incr width_ in if n > max_width then raise TooManyFields; let mask = 1 lsl n in mask let freeze () = frozen_ := true let total_width () = !width_ end
0e6822ce4d492d6692ec29d8ed047d337a44bd01518f70320e3d58bef956973f
zilch-lang/nstar
REX.hs
module Language.NStar.CodeGen.Machine.Internal.X64.REX where import Language.NStar.CodeGen.Machine.Internal.Intermediate (InterOpcode(..)) | REX with only the W bit set , so it indicates 64 - bit operand size , but no high registers . rexW :: InterOpcode rexW = Byte 0x48
null
https://raw.githubusercontent.com/zilch-lang/nstar/8a9d1d5aa19fe6493c556ae3606c758829683762/lib/nsc-codegen/src/Language/NStar/CodeGen/Machine/Internal/X64/REX.hs
haskell
module Language.NStar.CodeGen.Machine.Internal.X64.REX where import Language.NStar.CodeGen.Machine.Internal.Intermediate (InterOpcode(..)) | REX with only the W bit set , so it indicates 64 - bit operand size , but no high registers . rexW :: InterOpcode rexW = Byte 0x48
93e495bbe846dd72088e6f6a0a0d2e2d5382b0dcada59ad106bd804d1db7bed7
logseq/mldoc
block0.ml
open! Prelude open Angstrom open Parsers open Type open Conf open Helper open Pos module MakeBlock (Lists : sig val parse : Conf.t -> (Type.t * Pos.pos_meta) list Angstrom.t -> Type.t Angstrom.t end) = struct There are 2 kinds of blocks . 1 . ` begin ... end ` # + BEGIN_X line1 line 2 # + END_x 2 . Verbatim , each line starts with ` : ` . 1. `begin ... end` #+BEGIN_X line1 line 2 #+END_x 2. Verbatim, each line starts with `:`. *) let results = spaces *> string "#+RESULTS:" >>= fun _ -> return Results let verbatim = lines_starts_with (char ':') <?> "verbatim" let md_blockquote = char '>' *> lines_while (spaces *> char '>' *> spaces *> eol *> return "" <|> ( spaces *> optional (char '>') *> spaces *> line >>= fun line -> if not (starts_with line "- " || starts_with line "# " || starts_with line "id:: " || line = "-" || line = "#") then return line else fail "new block" )) <?> "markdown blockquote" let displayed_math = string "$$" *> end_string "$$" (fun s -> Displayed_Math s) let separate_name_options = function | None -> (None, None) | Some s -> ( match String.split_on_char ' ' s with | [] -> (None, None) | [ name ] -> (Some name, None) | name :: options -> (Some name, Some options)) ` ` ` json * { * " firstName " : " " , * " lastName " : " " , * " age " : 25 * } * ` ` ` * { * "firstName": "John", * "lastName": "Smith", * "age": 25 * } * ``` *) let fenced_language = (string "```" <|> string "~~~") *> spaces *> optional line <* optional eol let fenced_code_block = fenced_language >>= fun language_and_options -> let p = between_lines ~trim:false (fun line -> starts_with (String.trim line) "```" || starts_with (String.trim line) "~~~") "fenced_code_block" in let p' = with_pos_meta p in p' >>| fun (lines, { start_pos; end_pos }) -> let pos_meta = { start_pos; end_pos = end_pos - 3 } in let language, options = separate_name_options language_and_options in Src { language; options; lines; pos_meta } let block_name_options_parser = lift2 (fun name options -> match options with | None | Some "" -> (name, None) | _ -> (name, options)) (string_ci "#+begin_" *> non_spaces) (spaces *> optional line) <* optional eol let list_content_parsers config block_parse = let p = choice [ Table.parse config ; block_parse ; Directive.parse ; Latex_env.parse config ; Hr.parse config ; results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p let block_content_parsers config block_parse = let list_content_parser = list_content_parsers config block_parse in let p = choice [ Directive.parse ; Table.parse config ; Lists.parse config list_content_parser ; block_parse ; Latex_env.parse config ; Hr.parse config ; results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p let block_parse config = fix (fun parse -> let p = peek_char_fail >>= function | '#' -> ( block_name_options_parser >>= fun (name, options) -> let p = between_lines ~trim:false (fun line -> let prefix = "#+end_" ^ name in starts_with (String.trim line) prefix) "block" in let p' = with_pos_meta p in p' >>| fun (lines, { start_pos; end_pos }) -> (* clear indents *) let lines = if lines = [] then [] else let indent = get_indent (List.hd lines) in if indent = 0 then lines else List.map (fun line -> let line_ltrim = String.ltrim line in if String.length line - String.length line_ltrim >= indent then safe_sub line indent (String.length line - indent) else if line_ltrim = "" then line else line_ltrim) lines in let name = String.lowercase_ascii name in match name with | "src" -> let language, options = separate_name_options options in let pos_meta = { start_pos; end_pos = end_pos - 9 } in Src { language; options; lines; pos_meta } | "example" -> Example lines | "quote" -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Quote result | "export" -> (* export html, etc *) let name, options = separate_name_options options in let name = match name with | None -> "" | Some s -> s in let content = String.concat "" lines in Export (name, options, content) | "comment" -> CommentBlock lines | _ -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Custom (name, options, result, content)) | ':' -> ( (* verbatim block *) match config.format with | Org -> verbatim >>| fun lines -> Example lines | Markdown -> fail "block") | '>' -> md_blockquote >>| fun lines -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Quote result | '`' | '~' -> fenced_code_block | '$' -> displayed_math | '<' -> Raw_html.parse >>| fun s -> Raw_Html s | '[' -> if config.hiccup_in_block then Hiccup.parse >>| fun s -> Hiccup s else fail "block" | _ -> fail "block" in between_eols p) let parse config = match config.format with | Org -> block_parse config | Markdown -> block_parse config end
null
https://raw.githubusercontent.com/logseq/mldoc/1404fdf6e9b7b044f55292706541b50d559aa693/lib/syntax/block0.ml
ocaml
clear indents export html, etc verbatim block
open! Prelude open Angstrom open Parsers open Type open Conf open Helper open Pos module MakeBlock (Lists : sig val parse : Conf.t -> (Type.t * Pos.pos_meta) list Angstrom.t -> Type.t Angstrom.t end) = struct There are 2 kinds of blocks . 1 . ` begin ... end ` # + BEGIN_X line1 line 2 # + END_x 2 . Verbatim , each line starts with ` : ` . 1. `begin ... end` #+BEGIN_X line1 line 2 #+END_x 2. Verbatim, each line starts with `:`. *) let results = spaces *> string "#+RESULTS:" >>= fun _ -> return Results let verbatim = lines_starts_with (char ':') <?> "verbatim" let md_blockquote = char '>' *> lines_while (spaces *> char '>' *> spaces *> eol *> return "" <|> ( spaces *> optional (char '>') *> spaces *> line >>= fun line -> if not (starts_with line "- " || starts_with line "# " || starts_with line "id:: " || line = "-" || line = "#") then return line else fail "new block" )) <?> "markdown blockquote" let displayed_math = string "$$" *> end_string "$$" (fun s -> Displayed_Math s) let separate_name_options = function | None -> (None, None) | Some s -> ( match String.split_on_char ' ' s with | [] -> (None, None) | [ name ] -> (Some name, None) | name :: options -> (Some name, Some options)) ` ` ` json * { * " firstName " : " " , * " lastName " : " " , * " age " : 25 * } * ` ` ` * { * "firstName": "John", * "lastName": "Smith", * "age": 25 * } * ``` *) let fenced_language = (string "```" <|> string "~~~") *> spaces *> optional line <* optional eol let fenced_code_block = fenced_language >>= fun language_and_options -> let p = between_lines ~trim:false (fun line -> starts_with (String.trim line) "```" || starts_with (String.trim line) "~~~") "fenced_code_block" in let p' = with_pos_meta p in p' >>| fun (lines, { start_pos; end_pos }) -> let pos_meta = { start_pos; end_pos = end_pos - 3 } in let language, options = separate_name_options language_and_options in Src { language; options; lines; pos_meta } let block_name_options_parser = lift2 (fun name options -> match options with | None | Some "" -> (name, None) | _ -> (name, options)) (string_ci "#+begin_" *> non_spaces) (spaces *> optional line) <* optional eol let list_content_parsers config block_parse = let p = choice [ Table.parse config ; block_parse ; Directive.parse ; Latex_env.parse config ; Hr.parse config ; results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p let block_content_parsers config block_parse = let list_content_parser = list_content_parsers config block_parse in let p = choice [ Directive.parse ; Table.parse config ; Lists.parse config list_content_parser ; block_parse ; Latex_env.parse config ; Hr.parse config ; results ; Comment.parse config ; Paragraph.parse ; Paragraph.sep ] in let p = Helper.with_pos_meta p in many1 p let block_parse config = fix (fun parse -> let p = peek_char_fail >>= function | '#' -> ( block_name_options_parser >>= fun (name, options) -> let p = between_lines ~trim:false (fun line -> let prefix = "#+end_" ^ name in starts_with (String.trim line) prefix) "block" in let p' = with_pos_meta p in p' >>| fun (lines, { start_pos; end_pos }) -> let lines = if lines = [] then [] else let indent = get_indent (List.hd lines) in if indent = 0 then lines else List.map (fun line -> let line_ltrim = String.ltrim line in if String.length line - String.length line_ltrim >= indent then safe_sub line indent (String.length line - indent) else if line_ltrim = "" then line else line_ltrim) lines in let name = String.lowercase_ascii name in match name with | "src" -> let language, options = separate_name_options options in let pos_meta = { start_pos; end_pos = end_pos - 9 } in Src { language; options; lines; pos_meta } | "example" -> Example lines | "quote" -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Quote result | "export" -> let name, options = separate_name_options options in let name = match name with | None -> "" | Some s -> s in let content = String.concat "" lines in Export (name, options, content) | "comment" -> CommentBlock lines | _ -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Custom (name, options, result, content)) | ':' -> ( match config.format with | Org -> verbatim >>| fun lines -> Example lines | Markdown -> fail "block") | '>' -> md_blockquote >>| fun lines -> let content = String.concat "" lines in let result = match parse_string ~consume:All (block_content_parsers config parse) content with | Ok result -> let result = Paragraph.concat_paragraph_lines config result in List.map fst result | Error _e -> [] in Quote result | '`' | '~' -> fenced_code_block | '$' -> displayed_math | '<' -> Raw_html.parse >>| fun s -> Raw_Html s | '[' -> if config.hiccup_in_block then Hiccup.parse >>| fun s -> Hiccup s else fail "block" | _ -> fail "block" in between_eols p) let parse config = match config.format with | Org -> block_parse config | Markdown -> block_parse config end
783d522eaf0a3ec74ea397084eb9ad8ed6d3329cdcd96c98a824a8248809435c
swarm-game/swarm
MkLogo.hs
#!/usr/bin/env stack -- stack --resolver lts-19.3 script import System.Random main = do txt <- lines <$> readFile "title.txt" txt' <- (traverse . traverse) replace txt writeFile "logo.txt" (unlines txt') chars = "<^>vT~@▒ " replace :: Char -> IO Char replace ' ' = pick $ zip (replicate 8 0.005 ++ [1]) chars replace _ = pick $ zip (replicate 4 0.2 ++ replicate 4 0.04 ++ [1]) chars pick :: [(Double, a)] -> IO a pick es = do r <- randomRIO (0 :: Double, 1) return $ go r es where go _ [(_, a)] = a go r ((p, a) : es) | r < p = a | otherwise = go (r - p) es
null
https://raw.githubusercontent.com/swarm-game/swarm/8b8c16a71bd7a666bd2302975ce38078484a26d4/images/logo/MkLogo.hs
haskell
stack --resolver lts-19.3 script
#!/usr/bin/env stack import System.Random main = do txt <- lines <$> readFile "title.txt" txt' <- (traverse . traverse) replace txt writeFile "logo.txt" (unlines txt') chars = "<^>vT~@▒ " replace :: Char -> IO Char replace ' ' = pick $ zip (replicate 8 0.005 ++ [1]) chars replace _ = pick $ zip (replicate 4 0.2 ++ replicate 4 0.04 ++ [1]) chars pick :: [(Double, a)] -> IO a pick es = do r <- randomRIO (0 :: Double, 1) return $ go r es where go _ [(_, a)] = a go r ((p, a) : es) | r < p = a | otherwise = go (r - p) es
e99bbf6b2cf33df4036ed09a315db5dcef8c1eeafcc804e789b933d05b281a85
larcenists/larceny
bv2string.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2007 . ; ; Permission to copy this software, in whole or in part, to use this ; software for any lawful purpose, and to redistribute this software ; is granted subject to the restriction that all copies made of this ; software must include this copyright notice in full. ; ; I also request that you send me a copy of any improvements that you ; make to this software so that they may be incorporated within it to ; the benefit of the Scheme community. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Tests of string <-> bytevector conversions. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (import (scheme base) (scheme read) (scheme write) (scheme time)) ; Crude test rig, just for benchmarking. (define failed-tests '()) (define (test name actual expected) (if (not (equal? actual expected)) (begin (display "******** FAILED TEST ******** ") (display name) (newline) (set! failed-tests (cons name failed-tests))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; We 're limited to Ascii strings here because the R7RS does n't actually require anything beyond Ascii . ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Basic sanity tests, followed by stress tests on random inputs. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (string-bytevector-tests *random-stress-tests* *random-stress-test-max-size*) (define (test-roundtrip bvec tostring tobvec) (let* ((s1 (tostring bvec)) (b2 (tobvec s1)) (s2 (tostring b2))) (test "round trip of string conversion" (string=? s1 s2) #t))) ; This random number generator doesn't have to be good. ; It just has to be fast. (define random (letrec ((random14 (lambda (n) (set! x (remainder (+ (* a x) c) (+ m 1))) (remainder (quotient x 8) n))) (a 701) (x 1) (c 743483) (m 524287) (loop (lambda (q r n) (if (zero? q) (remainder r n) (loop (quotient q 16384) (+ (* 16384 r) (random14 16384)) n))))) (lambda (n) (if (< n 16384) (random14 n) (loop (quotient n 16384) (random14 16384) n))))) ; Returns a random bytevector of length up to n, with all elements less than 128 . (define (random-bytevector n) (let* ((n (random n)) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) ; Returns a random bytevector of even length up to n. (define (random-bytevector2 n) (let* ((n (random n)) (n (if (odd? n) (+ n 1) n)) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) ; Returns a random bytevector of multiple-of-4 length up to n. (define (random-bytevector4 n) (let* ((n (random n)) (n (* 4 (round (/ n 4)))) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) (test-roundtrip (random-bytevector 10) utf8->string string->utf8) (do ((i 0 (+ i 1))) ((= i *random-stress-tests*)) (test-roundtrip (random-bytevector *random-stress-test-max-size*) utf8->string string->utf8)) ) (define (main) (let* ((count (read)) (input1 (read)) (input2 (read)) (output (read)) (s3 (number->string count)) (s2 (number->string input2)) (s1 (number->string input1)) (name "bv2string")) (run-r7rs-benchmark (string-append name ":" s1 ":" s2 ":" s3) count (lambda () (string-bytevector-tests (hide count input1) (hide count input2)) (length failed-tests)) (lambda (result) (equal? result output)))))
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/test/Benchmarking/R7RS/src/bv2string.scm
scheme
Permission to copy this software, in whole or in part, to use this software for any lawful purpose, and to redistribute this software is granted subject to the restriction that all copies made of this software must include this copyright notice in full. I also request that you send me a copy of any improvements that you make to this software so that they may be incorporated within it to the benefit of the Scheme community. Tests of string <-> bytevector conversions. Crude test rig, just for benchmarking. Basic sanity tests, followed by stress tests on random inputs. This random number generator doesn't have to be good. It just has to be fast. Returns a random bytevector of length up to n, Returns a random bytevector of even length up to n. Returns a random bytevector of multiple-of-4 length up to n.
Copyright 2007 . (import (scheme base) (scheme read) (scheme write) (scheme time)) (define failed-tests '()) (define (test name actual expected) (if (not (equal? actual expected)) (begin (display "******** FAILED TEST ******** ") (display name) (newline) (set! failed-tests (cons name failed-tests))))) We 're limited to Ascii strings here because the R7RS does n't actually require anything beyond Ascii . (define (string-bytevector-tests *random-stress-tests* *random-stress-test-max-size*) (define (test-roundtrip bvec tostring tobvec) (let* ((s1 (tostring bvec)) (b2 (tobvec s1)) (s2 (tostring b2))) (test "round trip of string conversion" (string=? s1 s2) #t))) (define random (letrec ((random14 (lambda (n) (set! x (remainder (+ (* a x) c) (+ m 1))) (remainder (quotient x 8) n))) (a 701) (x 1) (c 743483) (m 524287) (loop (lambda (q r n) (if (zero? q) (remainder r n) (loop (quotient q 16384) (+ (* 16384 r) (random14 16384)) n))))) (lambda (n) (if (< n 16384) (random14 n) (loop (quotient n 16384) (random14 16384) n))))) with all elements less than 128 . (define (random-bytevector n) (let* ((n (random n)) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) (define (random-bytevector2 n) (let* ((n (random n)) (n (if (odd? n) (+ n 1) n)) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) (define (random-bytevector4 n) (let* ((n (random n)) (n (* 4 (round (/ n 4)))) (bv (make-bytevector n))) (do ((i 0 (+ i 1))) ((= i n) bv) (bytevector-u8-set! bv i (random 128))))) (test-roundtrip (random-bytevector 10) utf8->string string->utf8) (do ((i 0 (+ i 1))) ((= i *random-stress-tests*)) (test-roundtrip (random-bytevector *random-stress-test-max-size*) utf8->string string->utf8)) ) (define (main) (let* ((count (read)) (input1 (read)) (input2 (read)) (output (read)) (s3 (number->string count)) (s2 (number->string input2)) (s1 (number->string input1)) (name "bv2string")) (run-r7rs-benchmark (string-append name ":" s1 ":" s2 ":" s3) count (lambda () (string-bytevector-tests (hide count input1) (hide count input2)) (length failed-tests)) (lambda (result) (equal? result output)))))
d179c2f16b2c67ff7e0d46c2e3d7da35fc7c62e44370287acf2806b6136f484f
benzap/fif
utils.cljc
(ns fif-test.utils (:require [clojure.test :refer [deftest testing is are]] [fif.stack-machine :as stack] [fif.core :as fif :include-macros true])) (def ^:dynamic *test-step-max* 10000) (def max-step-exceeded-keyword ::max-step-exceeded) (defn teval-fn "Used to test fif evaluation, while ensuring the stackmachine is in good health after evaluation. Notes: - teval assumes full evaluation back to the global environment scope, otherwise it will error out with an appropriate error message." ([args] (let [test-sm (-> fif/*default-stack* (stack/set-step-max *test-step-max*)) sm-result (fif/with-stack test-sm (fif/eval-fn args)) step-num (stack/get-step-num sm-result)] (cond Infinite Loop Protection . Ensure that there is no infinite loop (>= step-num *test-step-max*) max-step-exceeded-keyword ;; A healthy stack machine has no flags active. (not (empty? (stack/get-flags sm-result))) ::unmanaged-flags ;; There are no return values on the return stack when the ;; stack machine is healthy. (not (empty? (stack/get-ret sm-result))) ::return-stack-populated ;; The global scope is all that is left when the stack machine ;; is healthy. (not (= 1 (count (stack/get-scope sm-result)))) ::scope-out-of-bounds :else (-> sm-result stack/get-stack reverse))))) (deftest test-teval-fn (is (= '(4) (teval-fn '(2 2 +))))) (defmacro teval [& body] `(teval-fn (quote ~body))) (deftest test-teval (is (= '(4) (teval 2 2 +)))) (defmacro are-eq* [& body] `(are [x# _sep# y#] (= y# x#) ~@body)) (deftest test-are-eq* (testing "Simple Addition" (are-eq* (teval 2 2 +) => '(4))))
null
https://raw.githubusercontent.com/benzap/fif/972adab8b86c016b04babea49d52198585172fe3/test/fif_test/utils.cljc
clojure
A healthy stack machine has no flags active. There are no return values on the return stack when the stack machine is healthy. The global scope is all that is left when the stack machine is healthy.
(ns fif-test.utils (:require [clojure.test :refer [deftest testing is are]] [fif.stack-machine :as stack] [fif.core :as fif :include-macros true])) (def ^:dynamic *test-step-max* 10000) (def max-step-exceeded-keyword ::max-step-exceeded) (defn teval-fn "Used to test fif evaluation, while ensuring the stackmachine is in good health after evaluation. Notes: - teval assumes full evaluation back to the global environment scope, otherwise it will error out with an appropriate error message." ([args] (let [test-sm (-> fif/*default-stack* (stack/set-step-max *test-step-max*)) sm-result (fif/with-stack test-sm (fif/eval-fn args)) step-num (stack/get-step-num sm-result)] (cond Infinite Loop Protection . Ensure that there is no infinite loop (>= step-num *test-step-max*) max-step-exceeded-keyword (not (empty? (stack/get-flags sm-result))) ::unmanaged-flags (not (empty? (stack/get-ret sm-result))) ::return-stack-populated (not (= 1 (count (stack/get-scope sm-result)))) ::scope-out-of-bounds :else (-> sm-result stack/get-stack reverse))))) (deftest test-teval-fn (is (= '(4) (teval-fn '(2 2 +))))) (defmacro teval [& body] `(teval-fn (quote ~body))) (deftest test-teval (is (= '(4) (teval 2 2 +)))) (defmacro are-eq* [& body] `(are [x# _sep# y#] (= y# x#) ~@body)) (deftest test-are-eq* (testing "Simple Addition" (are-eq* (teval 2 2 +) => '(4))))
ba6061d178d78f7a9bd3c1ca8752f3f47503325e3254044ae47f6cac9d73708e
carlohamalainen/ghc-imported-from
ImportedFromSpec.hs
{-# LANGUAGE RankNTypes #-} module ImportedFromSpec where import Language.Haskell.GhcImportedFrom import System.FilePath() import Test.Hspec import Control.Exception as E import Data.List (isPrefixOf) import System.Directory import System.FilePath (addTrailingPathSeparator) ------------------------------------------------------------------------------- withDirectory _ , withDirectory , and toRelativeDir are copied from ghc - mod . withDirectory_ :: FilePath -> IO a -> IO a withDirectory_ dir action = bracket getCurrentDirectory setCurrentDirectory (\_ -> setCurrentDirectory dir >> action) withDirectory :: FilePath -> (FilePath -> IO a) -> IO a withDirectory dir action = bracket getCurrentDirectory setCurrentDirectory (\d -> setCurrentDirectory dir >> action d) toRelativeDir :: FilePath -> FilePath -> FilePath toRelativeDir dir file | dir' `isPrefixOf` file = drop len file | otherwise = file where dir' = addTrailingPathSeparator dir len = length dir' isRight :: forall a b. Either a b -> Bool isRight = either (const False) (const True) ------------------------------------------------------------------------------- -- Instead of shouldSatisfy isRight, these should check for the right module/package -- name turning up in the results. spec :: Spec spec = do describe "checkImportedFrom" $ do it "can look up Maybe" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Maybe" 11 11 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Just" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Just" 12 7 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Just" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Just" 16 10 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up String" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "String" 20 14 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Int" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Int" 22 23 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up DL.length" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "DL.length" 23 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up print" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "print" 25 8 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up DM.fromList" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "DM.fromList" 27 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Safe.headMay" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Safe.headMay" 29 6 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up map" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Hiding.hs" "Hiding" "map" 14 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up head" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Hiding.hs" "Hiding" "head" 16 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up when" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "When.hs" "When" "when" 15 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight
null
https://raw.githubusercontent.com/carlohamalainen/ghc-imported-from/ac28f1c26644791abd698c55b00ce663ccbd861d/test/ImportedFromSpec.hs
haskell
# LANGUAGE RankNTypes # ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Instead of shouldSatisfy isRight, these should check for the right module/package name turning up in the results.
module ImportedFromSpec where import Language.Haskell.GhcImportedFrom import System.FilePath() import Test.Hspec import Control.Exception as E import Data.List (isPrefixOf) import System.Directory import System.FilePath (addTrailingPathSeparator) withDirectory _ , withDirectory , and toRelativeDir are copied from ghc - mod . withDirectory_ :: FilePath -> IO a -> IO a withDirectory_ dir action = bracket getCurrentDirectory setCurrentDirectory (\_ -> setCurrentDirectory dir >> action) withDirectory :: FilePath -> (FilePath -> IO a) -> IO a withDirectory dir action = bracket getCurrentDirectory setCurrentDirectory (\d -> setCurrentDirectory dir >> action d) toRelativeDir :: FilePath -> FilePath -> FilePath toRelativeDir dir file | dir' `isPrefixOf` file = drop len file | otherwise = file where dir' = addTrailingPathSeparator dir len = length dir' isRight :: forall a b. Either a b -> Bool isRight = either (const False) (const True) spec :: Spec spec = do describe "checkImportedFrom" $ do it "can look up Maybe" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Maybe" 11 11 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Just" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Just" 12 7 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Just" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Just" 16 10 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up String" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "String" 20 14 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Int" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Int" 22 23 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up DL.length" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "DL.length" 23 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up print" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "print" 25 8 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up DM.fromList" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "DM.fromList" 27 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up Safe.headMay" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Muddle.hs" "Muddle" "Safe.headMay" 29 6 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up map" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Hiding.hs" "Hiding" "map" 14 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up head" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "Hiding.hs" "Hiding" "head" 16 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight it "can look up when" $ do withDirectory_ "test/data" $ do res <- guessHaddockUrl "When.hs" "When" "when" 15 5 (GhcOptions []) (GhcPkgOptions []) res `shouldSatisfy` isRight
5153a9e42dfbc71ccb5e6d5696581680abefdcfc9066020f6574bfcedec68c29
ocaml-ppx/ppx_tools_versioned
ast_mapper_class_410.mli
open Migrate_parsetree.Ast_410 (* This file is part of the ppx_tools package. It is released *) under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi (** Class-based customizable mapper *) open Parsetree class mapper: object method attribute: attribute -> attribute method attributes: attribute list -> attribute list method binding_op: binding_op -> binding_op method case: case -> case method cases: case list -> case list method class_declaration: class_declaration -> class_declaration method class_description: class_description -> class_description method class_expr: class_expr -> class_expr method class_field: class_field -> class_field method class_signature: class_signature -> class_signature method class_structure: class_structure -> class_structure method class_type: class_type -> class_type method class_type_declaration: class_type_declaration -> class_type_declaration method class_type_field: class_type_field -> class_type_field method constructor_arguments: constructor_arguments -> constructor_arguments method constructor_declaration: constructor_declaration -> constructor_declaration method expr: expression -> expression method extension: extension -> extension method extension_constructor: extension_constructor -> extension_constructor method include_declaration: include_declaration -> include_declaration method include_description: include_description -> include_description method label_declaration: label_declaration -> label_declaration method location: Location.t -> Location.t method module_binding: module_binding -> module_binding method module_declaration: module_declaration -> module_declaration method module_substitution: module_substitution -> module_substitution method module_expr: module_expr -> module_expr method module_type: module_type -> module_type method module_type_declaration: module_type_declaration -> module_type_declaration method open_declaration: open_declaration -> open_declaration method open_description: open_description -> open_description method pat: pattern -> pattern method payload: payload -> payload method signature: signature -> signature method signature_item: signature_item -> signature_item method structure: structure -> structure method structure_item: structure_item -> structure_item method typ: core_type -> core_type method type_declaration: type_declaration -> type_declaration method type_exception: type_exception -> type_exception method type_extension: type_extension -> type_extension method type_kind: type_kind -> type_kind method value_binding: value_binding -> value_binding method value_description: value_description -> value_description method with_constraint: with_constraint -> with_constraint end val to_mapper: #mapper -> Ast_mapper.mapper * The resulting mapper is " closed " , i.e. methods ignore their first argument . their first argument. *)
null
https://raw.githubusercontent.com/ocaml-ppx/ppx_tools_versioned/00a0150cdabfa7f0dad2c5e0e6b32230d22295ca/ast_mapper_class_410.mli
ocaml
This file is part of the ppx_tools package. It is released * Class-based customizable mapper
open Migrate_parsetree.Ast_410 under the terms of the MIT license ( see LICENSE file ) . Copyright 2013 and LexiFi open Parsetree class mapper: object method attribute: attribute -> attribute method attributes: attribute list -> attribute list method binding_op: binding_op -> binding_op method case: case -> case method cases: case list -> case list method class_declaration: class_declaration -> class_declaration method class_description: class_description -> class_description method class_expr: class_expr -> class_expr method class_field: class_field -> class_field method class_signature: class_signature -> class_signature method class_structure: class_structure -> class_structure method class_type: class_type -> class_type method class_type_declaration: class_type_declaration -> class_type_declaration method class_type_field: class_type_field -> class_type_field method constructor_arguments: constructor_arguments -> constructor_arguments method constructor_declaration: constructor_declaration -> constructor_declaration method expr: expression -> expression method extension: extension -> extension method extension_constructor: extension_constructor -> extension_constructor method include_declaration: include_declaration -> include_declaration method include_description: include_description -> include_description method label_declaration: label_declaration -> label_declaration method location: Location.t -> Location.t method module_binding: module_binding -> module_binding method module_declaration: module_declaration -> module_declaration method module_substitution: module_substitution -> module_substitution method module_expr: module_expr -> module_expr method module_type: module_type -> module_type method module_type_declaration: module_type_declaration -> module_type_declaration method open_declaration: open_declaration -> open_declaration method open_description: open_description -> open_description method pat: pattern -> pattern method payload: payload -> payload method signature: signature -> signature method signature_item: signature_item -> signature_item method structure: structure -> structure method structure_item: structure_item -> structure_item method typ: core_type -> core_type method type_declaration: type_declaration -> type_declaration method type_exception: type_exception -> type_exception method type_extension: type_extension -> type_extension method type_kind: type_kind -> type_kind method value_binding: value_binding -> value_binding method value_description: value_description -> value_description method with_constraint: with_constraint -> with_constraint end val to_mapper: #mapper -> Ast_mapper.mapper * The resulting mapper is " closed " , i.e. methods ignore their first argument . their first argument. *)
6070b7e4cecc682547cb2528b77a82278e4974ce5c6b4bf36a36781cacfefd04
input-output-hk/cardano-wallet
LayerSpec.hs
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE NumericUnderscores # # LANGUAGE OverloadedLabels # # LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - warn - orphans # {-# OPTIONS_GHC -Wno-unused-imports #-} -- | Copyright : © 2018 - 2020 IOHK -- License: Apache-2.0 -- DBLayer tests for SQLite implementation . -- -- To test individual properties in GHCi, use the shorthand type aliases. For -- example: -- -- >>> db <- newMemoryDBLayer :: IO TestDBSeq -- >>> quickCheck $ prop_sequential db module Cardano.Wallet.DB.LayerSpec ( spec ) where import Prelude import Cardano.BM.Configuration.Static ( defaultConfigTesting ) import Cardano.BM.Data.Tracer ( nullTracer ) import Cardano.BM.Setup ( setupTrace ) import Cardano.BM.Trace ( traceInTVarIO ) import Cardano.Chain.ValidationMode ( whenTxValidation ) import Cardano.Crypto.Wallet ( XPrv ) import Cardano.DB.Sqlite ( DBField, DBLog (..), SqliteContext, fieldName, newInMemorySqliteContext ) import Cardano.Mnemonic ( SomeMnemonic (..) ) import Cardano.Wallet.DB ( DBFactory (..), DBLayer (..), cleanDB ) import Cardano.Wallet.DB.Arbitrary ( GenState, KeyValPairs (..) ) import Cardano.Wallet.DB.Layer ( DefaultFieldValues (..) , PersistAddressBook , WalletDBLog (..) , newDBFactory , newDBLayerInMemory , withDBLayer , withDBLayerInMemory ) import Cardano.Wallet.DB.Properties ( properties ) import Cardano.Wallet.DB.Sqlite.Migration ( InvalidDatabaseSchemaVersion (..) , SchemaVersion (..) , currentSchemaVersion ) import Cardano.Wallet.DB.StateMachine ( TestConstraints, prop_parallel, prop_sequential, validateGenerators ) import Cardano.Wallet.DB.WalletState ( ErrNoSuchWallet (..) ) import Cardano.Wallet.DummyTarget.Primitive.Types ( block0, dummyGenesisParameters, dummyTimeInterpreter ) import Cardano.Wallet.Gen ( genMnemonic ) import Cardano.Wallet.Logging ( trMessageText ) import Cardano.Wallet.Primitive.AddressDerivation ( Depth (..) , DerivationType (..) , Index , NetworkDiscriminant (..) , PaymentAddress (..) , PersistPrivateKey , WalletKey ) import Cardano.Wallet.Primitive.AddressDerivation.Byron ( ByronKey (..) ) import Cardano.Wallet.Primitive.AddressDerivation.Icarus ( IcarusKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shared () import Cardano.Wallet.Primitive.AddressDerivation.SharedKey ( SharedKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey (..), generateKeyFromSeed ) import Cardano.Wallet.Primitive.AddressDiscovery ( GetPurpose, KnownAddresses (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Random ( RndState (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( DerivationPrefix (..) , SeqState (..) , coinTypeAda , defaultAddressPoolGap , mkSeqStateFromRootXPrv , purposeBIP44 , purposeCIP1852 ) import Cardano.Wallet.Primitive.AddressDiscovery.Shared ( SharedState ) import Cardano.Wallet.Primitive.Model ( FilteredBlock (..) , Wallet , applyBlock , availableBalance , currentTip , getState , initWallet , utxo ) import Cardano.Wallet.Primitive.Passphrase ( encryptPassphrase, preparePassphrase ) import Cardano.Wallet.Primitive.Passphrase.Types ( Passphrase (..) , PassphraseHash (..) , PassphraseScheme (..) , WalletPassphraseInfo (..) ) import Cardano.Wallet.Primitive.Types ( ActiveSlotCoefficient (..) , Block (..) , BlockHeader (..) , GenesisParameters (..) , Range , SlotNo (..) , SortOrder (..) , StartTime (..) , WalletDelegation (..) , WalletDelegationStatus (..) , WalletId (..) , WalletMetadata (..) , WalletName (..) , WithOrigin (At) , wholeRange ) import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..) ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..), mockHash ) import Cardano.Wallet.Primitive.Types.TokenBundle ( TokenBundle ) import Cardano.Wallet.Primitive.Types.Tx ( Direction (..) , TransactionInfo (..) , Tx (..) , TxMeta (..) , TxScriptValidity (..) , TxStatus (..) , toTxHistory ) import Cardano.Wallet.Primitive.Types.Tx.TxIn ( TxIn (..) ) import Cardano.Wallet.Primitive.Types.Tx.TxOut ( TxOut (..) ) import Cardano.Wallet.Unsafe ( unsafeFromHex, unsafeRunExceptT ) import Control.Monad ( forM_, forever, replicateM_, unless, void ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Except ( ExceptT, mapExceptT ) import Control.Tracer ( Tracer ) import Crypto.Hash ( hash ) import Data.ByteString ( ByteString ) import Data.Coerce ( coerce ) import Data.Generics.Internal.VL.Lens ( over, view, (^.) ) import Data.Generics.Labels () import Data.Maybe ( fromMaybe, isJust, isNothing, mapMaybe ) import Data.Quantity ( Quantity (..) ) import Data.String.Interpolate ( i ) import Data.Text ( Text ) import Data.Text.Class ( fromText, toText ) import Data.Time.Clock ( getCurrentTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import Data.Typeable ( Typeable, typeOf ) import Data.Word ( Word64 ) import Database.Persist.EntityDef ( getEntityDBName, getEntityFields ) import Database.Persist.Names ( EntityNameDB (..), unFieldNameDB ) import Database.Persist.Sql ( EntityNameDB (..), FieldNameDB (..), PersistEntity (..), fieldDB ) import Database.Persist.Sqlite ( Single (..) ) import Numeric.Natural ( Natural ) import Safe ( headMay ) import System.Directory ( copyFile, doesFileExist, listDirectory, removeFile ) import System.FilePath ( (</>) ) import System.IO ( IOMode (..), hClose, withFile ) import System.IO.Error ( isUserError ) import System.IO.Temp ( emptySystemTempFile ) import System.IO.Unsafe ( unsafePerformIO ) import System.Random ( randomRIO ) import Test.Hspec ( Expectation , Spec , SpecWith , anyIOException , around , before , beforeWith , describe , it , shouldBe , shouldNotBe , shouldNotContain , shouldReturn , shouldSatisfy , shouldThrow , xit ) import Test.Hspec.Extra ( parallel ) import Test.QuickCheck ( Arbitrary (..) , Property , choose , generate , noShrinking , property , (==>) ) import Test.QuickCheck.Monadic ( assert, monadicIO, run ) import Test.Utils.Paths ( getTestData ) import Test.Utils.Trace ( captureLogging ) import UnliftIO.Async ( concurrently, concurrently_ ) import UnliftIO.Concurrent ( forkIO, killThread, threadDelay ) import UnliftIO.Exception ( SomeException, handle, throwIO ) import UnliftIO.MVar ( isEmptyMVar, newEmptyMVar, putMVar, takeMVar ) import UnliftIO.STM ( TVar, newTVarIO, readTVarIO, writeTVar ) import UnliftIO.Temporary ( withSystemTempDirectory, withSystemTempFile ) import qualified Cardano.Wallet.DB.Sqlite.Schema as DB import qualified Cardano.Wallet.DB.Sqlite.Types as DB import qualified Cardano.Wallet.Primitive.AddressDerivation.Shelley as Seq import qualified Cardano.Wallet.Primitive.Types.Coin as Coin import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle import qualified Cardano.Wallet.Primitive.Types.Tx.TxMeta as W import qualified Data.ByteArray as BA import qualified Data.ByteString as BS import qualified Data.List as L import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Database.Persist.Sql as Sql import qualified Database.Persist.Sqlite as Sqlite import qualified UnliftIO.STM as STM spec :: Spec spec = parallel $ do stateMachineSpecSeq stateMachineSpecRnd stateMachineSpecShared propertiesSpecSeq loggingSpec fileModeSpec manualMigrationsSpec stateMachineSpec :: forall k s ktype. ( WalletKey k , PersistPrivateKey (k 'RootK) , PaymentAddress 'Mainnet k ktype , PersistAddressBook s , TestConstraints s k , Typeable s ) => Spec stateMachineSpec = describe ("State machine test (" ++ showState @s ++ ")") $ do validateGenerators @s let newDB = newDBLayerInMemory @s @k nullTracer dummyTimeInterpreter it "Sequential" $ prop_sequential newDB xit "Parallel" $ prop_parallel newDB stateMachineSpecSeq, stateMachineSpecRnd, stateMachineSpecShared :: Spec stateMachineSpecSeq = stateMachineSpec @ShelleyKey @(SeqState 'Mainnet ShelleyKey) @'CredFromKeyK stateMachineSpecRnd = stateMachineSpec @ByronKey @(RndState 'Mainnet) @'CredFromKeyK stateMachineSpecShared = stateMachineSpec @SharedKey @(SharedState 'Mainnet SharedKey) @'CredFromScriptK instance PaymentAddress 'Mainnet SharedKey 'CredFromScriptK where paymentAddress _ = error "does not make sense for SharedKey but want to use stateMachineSpec" liftPaymentAddress _ = error "does not make sense for SharedKey but want to use stateMachineSpec" showState :: forall s. Typeable s => String showState = show (typeOf @s undefined) propertiesSpecSeq :: Spec propertiesSpecSeq = around withShelleyDBLayer $ describe "Properties" (properties :: SpecWith TestDBSeq) {------------------------------------------------------------------------------- Logging Spec -------------------------------------------------------------------------------} loggingSpec :: Spec loggingSpec = withLoggingDB @(SeqState 'Mainnet ShelleyKey) $ do describe "Sqlite query logging" $ do it "should log queries at DEBUG level" $ \(getLogs, DBLayer{..}) -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp logs <- getLogs logs `shouldHaveMsgQuery` "INSERT" it "should not log query parameters" $ \(getLogs, DBLayer{..}) -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp let walletName = T.unpack $ coerce $ name testMetadata msgs <- T.unlines . mapMaybe getMsgQuery <$> getLogs T.unpack msgs `shouldNotContain` walletName describe "Sqlite observables" $ do it "should measure query timings" $ \(getLogs, DBLayer{..}) -> do let count = 5 replicateM_ count (atomically listWallets) msgs <- findObserveDiffs <$> getLogs length msgs `shouldBe` count * 2 withLoggingDB :: (Show s, PersistAddressBook s) => SpecWith (IO [DBLog], DBLayer IO s ShelleyKey) -> Spec withLoggingDB = around f . beforeWith clean where f act = do logVar <- newTVarIO [] withDBLayerInMemory (traceInTVarIO logVar) dummyTimeInterpreter (\db -> act (logVar, db)) clean (logs, db) = do cleanDB db STM.atomically $ writeTVar logs [] pure (mapMaybe getMsgDB <$> readTVarIO logs, db) getMsgDB :: WalletDBLog -> Maybe DBLog getMsgDB (MsgDB msg) = Just msg shouldHaveMsgQuery :: [DBLog] -> Text -> Expectation shouldHaveMsgQuery msgs str = unless (any match msgs) $ fail $ "Did not find DB query " ++ T.unpack str ++ " within " ++ show msgs where match = maybe False (str `T.isInfixOf`) . getMsgQuery getMsgQuery :: DBLog -> Maybe Text getMsgQuery (MsgQuery msg _) = Just msg getMsgQuery _ = Nothing findObserveDiffs :: [DBLog] -> [DBLog] findObserveDiffs = filter isObserveDiff where isObserveDiff (MsgRun _) = True isObserveDiff _ = False ------------------------------------------------------------------------------ File Mode Spec ------------------------------------------------------------------------------ File Mode Spec -------------------------------------------------------------------------------} type TestDBSeq = DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey fileModeSpec :: Spec fileModeSpec = do describe "Check db opening/closing" $ do it "Opening and closing of db works" $ do replicateM_ 25 $ do db <- temporaryDBFile withShelleyFileDBLayer @(SeqState 'Mainnet ShelleyKey) db (\_ -> pure ()) describe "DBFactory" $ do let ti = dummyTimeInterpreter let withDBFactory action = withSystemTempDirectory "DBFactory" $ \dir -> do dbf <- newDBFactory nullTracer defaultFieldValues ti (Just dir) action dir dbf let whileFileOpened delay f action = do opened <- newEmptyMVar concurrently_ (withFile f ReadMode (\_ -> putMVar opened () >> threadDelay delay)) (takeMVar opened >> action) it "withDatabase *> removeDatabase works and remove files" $ do withDBFactory $ \dir DBFactory{..} -> do -- NOTE -- Start a concurrent worker which makes action on the DB in -- parallel to simulate activity. pid <- forkIO $ withDatabase testWid $ \(DBLayer{..} :: TestDBSeq) -> do handle @IO @SomeException (const (pure ())) $ forever $ do atomically $ do liftIO $ threadDelay 10_000 void $ readCheckpoint testWid killThread pid *> removeDatabase testWid listDirectory dir `shouldReturn` mempty it "removeDatabase still works if file is opened" $ do withDBFactory $ \dir DBFactory{..} -> do -- set up a database file withDatabase testWid $ \(_ :: TestDBSeq) -> pure () files <- listDirectory dir files `shouldNotBe` mempty -- Try removing the database when it's already opened for reading for . -- This simulates an antivirus program on windows which may -- interfere with file deletion. whileFileOpened 100_000 (dir </> head files) (removeDatabase testWid) listDirectory dir `shouldReturn` mempty it "removeDatabase waits for connections to close" $ do withDBFactory $ \_ DBFactory{..} -> do closed <- newEmptyMVar let conn = withDatabase testWid $ \(_ :: TestDBSeq) -> do threadDelay 500_000 putMVar closed () let rm = do removeDatabase testWid isEmptyMVar closed concurrently conn (threadDelay 50_000 >> rm) `shouldReturn` ((), False) describe "Sqlite database file" $ do let writeSomething DBLayer{..} = do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp atomically listWallets `shouldReturn` [testWid] tempFilesAbsent fp = do doesFileExist fp `shouldReturn` True doesFileExist (fp <> "-wal") `shouldReturn` False doesFileExist (fp <> "-shm") `shouldReturn` False bomb = throwIO (userError "bomb") it "is properly closed after withDBLayer" $ withTestDBFile writeSomething tempFilesAbsent it "is properly closed after an exception in withDBLayer" $ withTestDBFile (\db -> writeSomething db >> bomb) tempFilesAbsent `shouldThrow` isUserError before temporaryDBFile $ describe "Check db reading/writing from/to file and cleaning" $ do it "create and list wallet works" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp testOpeningCleaning f listWallets' [testWid] [] it "create and get meta works" $ \f -> do meta <- withShelleyFileDBLayer f $ \DBLayer{..} -> do now <- getCurrentTime let meta = testMetadata { passphraseInfo = Just $ WalletPassphraseInfo now EncryptWithPBKDF2 } atomically $ unsafeRunExceptT $ initializeWallet testWid testCp meta mempty gp return (meta, WalletDelegation NotDelegating []) testOpeningCleaning f (`readWalletMeta'` testWid) (Just meta) Nothing it "create and get private key" $ \f -> do (k, h) <- withShelleyFileDBLayer f $ \db@DBLayer{..} -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ attachPrivateKey db testWid testOpeningCleaning f (`readPrivateKey'` testWid) (Just (k, h)) Nothing it "put and read tx history (Ascending)" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putTxHistory testWid testTxs testOpeningCleaning f (\db' -> readTransactions' db' testWid Ascending wholeRange Nothing ) testTxs -- expected after opening db mempty -- expected after cleaning db it "put and read tx history (Descending)" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putTxHistory testWid testTxs testOpeningCleaning f (\db' -> readTransactions' db' testWid Descending wholeRange Nothing ) (reverse testTxs) -- expected after opening db mempty -- expected after cleaning db it "put and read checkpoint" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putCheckpoint testWid testCp testOpeningCleaning f (`readCheckpoint'` testWid) (Just testCp) Nothing describe "Golden rollback scenarios" $ do let dummyHash x = Hash $ x <> BS.pack (replicate (32 - (BS.length x)) 0) let dummyAddr x = Address $ x <> BS.pack (replicate (32 - (BS.length x)) 0) let mockApply DBLayer{..} h mockTxs = do Just cpA <- atomically $ readCheckpoint testWid let slotA = view #slotNo $ currentTip cpA let Quantity bhA = view #blockHeight $ currentTip cpA let hashA = headerHash $ currentTip cpA let fakeBlock = Block (BlockHeader { slotNo = slotA + 100 Increment blockHeight by steps greater than k -- Such that old checkpoints are always pruned. , blockHeight = Quantity $ bhA + 5_000 , headerHash = h , parentHeaderHash = Just hashA }) mockTxs mempty let (FilteredBlock{transactions=txs}, (_,cpB)) = applyBlock fakeBlock cpA atomically $ do unsafeRunExceptT $ putCheckpoint testWid cpB unsafeRunExceptT $ putTxHistory testWid txs unsafeRunExceptT $ prune testWid (Quantity 2_160) $ 2_160 * 3 * 20 it "Should spend collateral inputs and create spendable collateral \ \outputs if validation fails" $ \f -> withShelleyFileDBLayer f $ \db@DBLayer{..} -> do let ourAddrs = map (\(a,s,_) -> (a,s)) $ knownAddresses (getState testCp) atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp ------------------------------------------------------------ -- Transaction 1 -- -- This transaction provides initial funding for the wallet. ------------------------------------------------------------ mockApply db (dummyHash "block1") [ Tx { txId = dummyHash "tx1" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "faucet") 0 , Just $ TxOut (dummyAddr "faucetOut1") (coinToBundle 4) ) , ( TxIn (dummyHash "faucet") 1 , Just $ TxOut (dummyAddr "faucetOut2") (coinToBundle 8) ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (fst $ head ourAddrs) (coinToBundle 4) , TxOut (fst $ head $ tail ourAddrs) (coinToBundle 8) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptValid } ] = = ( 4 + 8) ------------------------------------------------------------ -- Transaction 2 -- -- This transaction has a script that fails validation. -- Therefore, we should forfeit value from the collateral -- inputs, but recover value from the collateral outputs. ------------------------------------------------------------ mockApply db (dummyHash "block2") [ Tx { txId = dummyHash "tx2" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "tx1") 0 , Just $ TxOut (dummyAddr "faucetOut1") (coinToBundle 4) ) ] , resolvedCollateralInputs = [(TxIn (dummyHash "tx1") 1, Nothing)] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 2) , TxOut (fst $ ourAddrs !! 1) (coinToBundle 2) ] , collateralOutput = Just $ TxOut (fst $ ourAddrs !! 1) (coinToBundle 7) , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptInvalid } ] mockApply db (dummyHash "block2a") [] getTxsInLedger db `shouldReturn` -- We: - forfeited 8 from collateral inputs ; - recovered 7 from collateral ouputs . Therefore we lost a net collateral value of ( 8 - 7 ): [ (Outgoing, 1) We got 12 from the faucet , (Incoming, 12) ] = 12 - 1 ------------------------------------------------------------ -- Transaction 3 -- -- This transaction uses a collateral output created in the -- previous transaction to make a payment. ------------------------------------------------------------ mockApply db (dummyHash "block3") [ Tx { txId = dummyHash "tx3" , txCBOR = Nothing , fee = Nothing , resolvedInputs = -- Here we refer to a collateral output from -- the previous transaction. -- -- Note that we refer to the sole collateral -- output by using a special index value that -- is equal to the number of ordinary outputs -- in that transaction: -- [ ( TxIn (dummyHash "tx2") 2 , Just $ TxOut (fst $ ourAddrs !! 1) (coinToBundle 7) ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 8) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptValid } ] mockApply db (dummyHash "block3a") [] = 11 - 7 it "(Regression test #1575) - TxMetas and checkpoints should \ \rollback to the same place" $ \f -> do withShelleyFileDBLayer f $ \db@DBLayer{..} -> do let ourAddrs = map (\(a,s,_) -> (a,s)) $ knownAddresses (getState testCp) atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp let mockApplyBlock1 = mockApply db (dummyHash "block1") [ Tx { txId = dummyHash "tx1" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "faucet") 0 , Just $ TxOut (dummyAddr "out_for_in") (coinToBundle 4) ) ] -- TODO: (ADP-957) , resolvedCollateralInputs = [] , outputs = [TxOut (fst $ head ourAddrs) (coinToBundle 4)] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } ] -- Slot 1 0 mockApplyBlock1 getAvailableBalance db `shouldReturn` 4 Slot 200 mockApply db (dummyHash "block2a") [ Tx { txId = dummyHash "tx2a" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "tx1") 0 , Just $ TxOut (dummyAddr "out_for_in") (coinToBundle 4) ) ] -- TODO: (ADP-957) , resolvedCollateralInputs = [] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 2) , TxOut (fst $ ourAddrs !! 1) (coinToBundle 2) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } ] Slot 300 mockApply db (dummyHash "block3a") [] getAvailableBalance db `shouldReturn` 2 getTxsInLedger db `shouldReturn` [(Outgoing, 2), (Incoming, 4)] atomically . void . unsafeRunExceptT $ rollbackTo testWid (At $ SlotNo 200) Just cp <- atomically $ readCheckpoint testWid view #slotNo (currentTip cp) `shouldBe` (SlotNo 0) getTxsInLedger db `shouldReturn` [] describe "random operation chunks property" $ do it "realize a random batch of operations upon one db open" (property $ prop_randomOpChunks @(SeqState 'Mainnet ShelleyKey)) -- This property checks that executing series of wallet operations in a single SQLite session has the same effect as executing the same operations over -- multiple sessions. prop_randomOpChunks :: (Eq s, PersistAddressBook s, Show s) => KeyValPairs WalletId (Wallet s, WalletMetadata) -> Property prop_randomOpChunks (KeyValPairs pairs) = not (null pairs) ==> monadicIO (liftIO prop) where prop = do filepath <- temporaryDBFile withShelleyFileDBLayer filepath $ \dbF -> do cleanDB dbF withShelleyDBLayer $ \dbM -> do cleanDB dbM forM_ pairs (insertPair dbM) cutRandomly pairs >>= mapM_ (mapM (insertPair dbF)) dbF `shouldBeConsistentWith` dbM insertPair :: DBLayer IO s k -> (WalletId, (Wallet s, WalletMetadata)) -> IO () insertPair DBLayer{..} (k, (cp, meta)) = do keys <- atomically listWallets if k `elem` keys then atomically $ do unsafeRunExceptT $ putCheckpoint k cp unsafeRunExceptT $ putWalletMeta k meta else do let cp0 = imposeGenesisState cp atomically $ unsafeRunExceptT $ initializeWallet k cp0 meta mempty gp Set.fromList <$> atomically listWallets `shouldReturn` Set.fromList (k:keys) imposeGenesisState :: Wallet s -> Wallet s imposeGenesisState = over #currentTip $ \(BlockHeader _ _ h _) -> BlockHeader (SlotNo 0) (Quantity 0) h Nothing shouldBeConsistentWith :: (Eq s, Show s) => DBLayer IO s k -> DBLayer IO s k -> IO () shouldBeConsistentWith db1 db2 = do wids1 <- Set.fromList <$> listWallets' db1 wids2 <- Set.fromList <$> listWallets' db2 wids1 `shouldBe` wids2 forM_ wids1 $ \walId -> do cps1 <- readCheckpoint' db1 walId cps2 <- readCheckpoint' db2 walId cps1 `shouldBe` cps2 forM_ wids1 $ \walId -> do meta1 <- readWalletMeta' db1 walId meta2 <- readWalletMeta' db2 walId meta1 `shouldBe` meta2 -- | Test that data is preserved between open / close of the same database and -- that cleaning up happens as expected. testOpeningCleaning :: (Show s, Eq s) => FilePath -> (DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey -> IO s) -> s -> s -> Expectation testOpeningCleaning filepath call expectedAfterOpen expectedAfterClean = do withShelleyFileDBLayer filepath $ \db -> do call db `shouldReturn` expectedAfterOpen _ <- cleanDB db call db `shouldReturn` expectedAfterClean withShelleyFileDBLayer filepath $ \db -> do call db `shouldReturn` expectedAfterClean -- | Run a test action inside withDBLayer, then check assertions. withTestDBFile :: (DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey -> IO ()) -> (FilePath -> IO a) -> IO a withTestDBFile action expectations = do logConfig <- defaultConfigTesting trace <- setupTrace (Right logConfig) "connectionSpec" withSystemTempFile "spec.db" $ \fp h -> do hClose h removeFile fp withDBLayer (trMessageText trace) defaultFieldValues fp ti action expectations fp where ti = dummyTimeInterpreter temporaryDBFile :: IO FilePath temporaryDBFile = emptySystemTempFile "cardano-wallet-SqliteFileMode" defaultFieldValues :: DefaultFieldValues defaultFieldValues = DefaultFieldValues { defaultActiveSlotCoefficient = ActiveSlotCoefficient 1.0 , defaultDesiredNumberOfPool = 0 , defaultMinimumUTxOValue = Coin 1_000_000 , defaultHardforkEpoch = Nothing , defaultKeyDeposit = Coin 2_000_000 } -- Note: Having helper with concrete key types reduces the need -- for type-application everywhere. withShelleyDBLayer :: PersistAddressBook s => (DBLayer IO s ShelleyKey -> IO a) -> IO a withShelleyDBLayer = withDBLayerInMemory nullTracer dummyTimeInterpreter withShelleyFileDBLayer :: PersistAddressBook s => FilePath -> (DBLayer IO s ShelleyKey -> IO a) -> IO a withShelleyFileDBLayer fp = withDBLayer nullTracer -- fixme: capture logging defaultFieldValues fp dummyTimeInterpreter listWallets' :: DBLayer m s k -> m [WalletId] listWallets' DBLayer{..} = atomically listWallets readCheckpoint' :: DBLayer m s k -> WalletId -> m (Maybe (Wallet s)) readCheckpoint' DBLayer{..} = atomically . readCheckpoint readWalletMeta' :: DBLayer m s k -> WalletId -> m (Maybe (WalletMetadata, WalletDelegation)) readWalletMeta' DBLayer{..} = atomically . readWalletMeta readTransactions' :: DBLayer m s k -> WalletId -> SortOrder -> Range SlotNo -> Maybe TxStatus -> m [(Tx, TxMeta)] readTransactions' DBLayer{..} a0 a1 a2 = atomically . fmap (fmap toTxHistory) . readTransactions a0 Nothing a1 a2 readPrivateKey' :: DBLayer m s k -> WalletId -> m (Maybe (k 'RootK XPrv, PassphraseHash)) readPrivateKey' DBLayer{..} = atomically . readPrivateKey -- | Attach an arbitrary private key to a wallet attachPrivateKey :: DBLayer IO s ShelleyKey -> WalletId -> ExceptT ErrNoSuchWallet IO (ShelleyKey 'RootK XPrv, PassphraseHash) attachPrivateKey DBLayer{..} wid = do let pwd = Passphrase $ BA.convert $ T.encodeUtf8 "simplevalidphrase" seed <- liftIO $ generate $ SomeMnemonic <$> genMnemonic @15 (scheme, h) <- liftIO $ encryptPassphrase pwd let k = generateKeyFromSeed (seed, Nothing) (preparePassphrase scheme pwd) mapExceptT atomically $ putPrivateKey wid (k, h) return (k, h) cutRandomly :: [a] -> IO [[a]] cutRandomly = iter [] where iter acc rest | L.length rest <= 1 = pure $ L.reverse (rest:acc) | otherwise = do chunksNum <- randomRIO (1, L.length rest) let chunk = L.take chunksNum rest iter (chunk:acc) (L.drop chunksNum rest) {------------------------------------------------------------------------------- Manual migrations tests -------------------------------------------------------------------------------} manualMigrationsSpec :: Spec manualMigrationsSpec = describe "Manual migrations" $ do it "'migrate' db with no passphrase scheme set." $ testMigrationPassphraseScheme "passphraseScheme-v2020-03-16.sqlite" it "'migrate' db with no 'derivation_prefix' for seq state (Icarus)" $ testMigrationSeqStateDerivationPrefix @IcarusKey "icarusDerivationPrefix-v2020-10-07.sqlite" ( purposeBIP44 , coinTypeAda , minBound ) it "'migrate' db with no 'derivation_prefix' for seq state (Shelley)" $ testMigrationSeqStateDerivationPrefix @ShelleyKey "shelleyDerivationPrefix-v2020-10-07.sqlite" ( purposeCIP1852 , coinTypeAda , minBound ) it "'migrate' db with old text serialization for 'Role'" $ testMigrationRole "shelleyRole-v2020-10-13.sqlite" it "'migrate' db with partially applied checkpoint migration" $ testMigrationRole "shelleyRole-corrupted-v2020-10-13.sqlite" it "'migrate' db with unused protocol parameters in checkpoints" $ testMigrationCleanupCheckpoints "shelleyDerivationPrefix-v2020-10-07.sqlite" (GenesisParameters { getGenesisBlockHash = Hash $ unsafeFromHex "5f20df933584822601f9e3f8c024eb5eb252fe8cefb24d1317dc3d432e940ebb" , getGenesisBlockDate = StartTime $ posixSecondsToUTCTime 1_506_203_091 } ) (BlockHeader { slotNo = SlotNo 1_125_119 , blockHeight = Quantity 1_124_949 , headerHash = Hash $ unsafeFromHex "3b309f1ca388459f0ce2c4ccca20ea646b75e6fc1447be032a41d43f209ecb50" , parentHeaderHash = Just $ Hash $ unsafeFromHex "e9414e08d8c5ca177dd0cb6a9e4bf868e1ea03389c31f5f7a6b099a3bcdfdedf" } ) it "'migrate' db to add fees to transactions" $ testMigrationTxMetaFee "metaFee-v2020-11-26.sqlite" 129 -- number of transactions -- This one (chosen for its stake key registration) has: -- - one input of 1000000000 - one output of 997825743 . -- which gives a delta of 2174257 , which means -- - 2000000 of key deposit - 174257 of fee -- [ ( Hash $ unsafeFromHex "00058d433a73574a64d0b4a3c37f1e460697fa8f1e3265a51e95eb9e9573b5ab" , Coin 174_257 ) -- This one (chosen because of its very round fee) has: -- - two inputs of 1000000 each - one output of 1000000 -- which gives a delta ( and fee ) of 1000000 , ( Hash $ unsafeFromHex "8f79e7f79ddeb7a7494121259832c0180c1b6bb746d8b2337cd1f4fb5b0d8216" , Coin 1_000_000 ) -- This one (chosen for its withdrawal) has: -- - one input of 909199523 - one withdrawal of 863644 - two outputs of 1000000 and 908888778 -- which gives a delta ( and fee ) of 174389 , ( Hash $ unsafeFromHex "eefa06dfa8ce91237117f9b4bdc4f6970c31de54906313b545dafb7ca6235171" , Coin 174_389 ) -- This one (chosen for its high fee) has: -- - one input of 997825743 - two outputs of 1000000 and 995950742 -- which gives a delta ( and fee ) of 875001 , ( Hash $ unsafeFromHex "8943f9fa4b56b32cd44ab9c22d46693882f0bbca1bc3f0705124e75c2e40b9c2" , Coin 875_001 ) -- This one (chosen for having many inputs and many outputs) has: -- -- - 10 inputs: -- - 1654330 -- - 2111100 -- - 2234456 -- - 9543345 -- - 1826766 -- - 8871831 -- - 3823766 -- - 6887025 -- - 1958037 -- - 3575522 -- -- - 10 outputs: -- - 4000000 -- - 7574304 -- - 9000000 -- - 1000000 -- - 1164635 -- - 6752132 -- - 1000000 -- - 8596880 - 2000000 -- - 1707865 -- -- - 1 withdrawal: - 565251 -- which gives a delta ( and fee ) of 255613 , ( Hash $ unsafeFromHex "99907bf6ac73f6fe6fe25bd6b68bae6776425b9d15a7c46c7a49b85b8b03f291" , Coin 255_613 ) -- This one (chosen for its high ratio input:output) has: -- - 1 input of 1000000000 -- - 33 relatively small outputs - 1 withdrawal of 561120 -- which gives a delta ( and fee ) of 267537 , ( Hash $ unsafeFromHex "15940a7c1df8696279282046ebdb1ee890d4e9ac3c5d7213f360921648b36666" , Coin 267_537 ) ] it "'migrate' db to create metadata table when it doesn't exist" testCreateMetadataTable it "'migrate' db never modifies database with newer version" testNewerDatabaseIsNeverModified it "'migrate' db submissions encoding" $ testMigrationSubmissionsEncoding "before_submission-v2022-12-14.sqlite" | Copy a given @.sqlite@ file , load it into a ` DBLayer ` -- (possibly triggering migrations), and run an action on it. -- -- Useful for testing the logs and results of migrations. withDBLayerFromCopiedFile :: forall k s a. ( PersistAddressBook s , PersistPrivateKey (k 'RootK) , WalletKey k , s ~ SeqState 'Mainnet k ) => FilePath ^ Filename of the @.sqlite@ file to load . -> (DBLayer IO s k -> IO a) -- ^ Action to run. -> IO ([WalletDBLog], a) -- ^ (logs, result of the action) withDBLayerFromCopiedFile dbName action = withinCopiedFile dbName $ \path tr-> withDBLayer tr defaultFieldValues path dummyTimeInterpreter action withinCopiedFile :: FilePath -> (FilePath -> Tracer IO msg -> IO a) -> IO ([msg], a) withinCopiedFile dbName action = do let orig = $(getTestData) </> dbName withSystemTempDirectory "migration-db" $ \dir -> do let path = dir </> "db.sqlite" copyFile orig path captureLogging $ action path testMigrationTxMetaFee :: String -> Int -> [(Hash "Tx", Coin)] -> IO () testMigrationTxMetaFee dbName expectedLength caseByCase = do (logs, result) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readTransactions wid Nothing Descending wholeRange Nothing -- Check that we've indeed logged a needed migration for 'fee' length (filter isMsgManualMigration logs) `shouldBe` 1 -- Check that the migrated history has the correct length. length result `shouldBe` expectedLength -- Verify that all incoming transactions have no fees set, and that all -- outgoing ones do. forM_ result $ \TransactionInfo{txInfoFee,txInfoMeta} -> do case txInfoMeta ^. #direction of Incoming -> txInfoFee `shouldSatisfy` isNothing Outgoing -> txInfoFee `shouldSatisfy` isJust -- Also verify a few hand-picked transactions forM_ caseByCase $ \(txid, expectedFee) -> do case L.find ((== txid) . txInfoId) result of Nothing -> fail $ "tx not found: " <> T.unpack (toText txid) Just TransactionInfo{txInfoFee} -> txInfoFee `shouldBe` Just expectedFee where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.TxMetaFee in fieldName field == unFieldNameDB fieldInDB matchMsgManualMigration :: (DBField -> Bool) -> WalletDBLog -> Bool matchMsgManualMigration p = \case MsgDB (MsgManualMigrationNeeded field _) -> p field MsgDB (MsgExpectedMigration (MsgManualMigrationNeeded field _)) -> p field _ -> False testMigrationCleanupCheckpoints :: FilePath -> GenesisParameters -> BlockHeader -> IO () testMigrationCleanupCheckpoints dbName genesisParameters tip = do (logs, result) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets (,) <$> readGenesisParameters wid <*> readCheckpoint wid length (filter (isMsgManualMigration fieldGenesisHash) logs) `shouldBe` 1 length (filter (isMsgManualMigration fieldGenesisStart) logs) `shouldBe` 1 (fst result) `shouldBe` Just genesisParameters (currentTip <$> snd result) `shouldBe` Just tip where fieldGenesisHash = fieldDB $ persistFieldDef DB.WalGenesisHash fieldGenesisStart = fieldDB $ persistFieldDef DB.WalGenesisStart isMsgManualMigration :: FieldNameDB -> WalletDBLog -> Bool isMsgManualMigration fieldInDB = matchMsgManualMigration $ \field -> fieldName field == unFieldNameDB fieldInDB testMigrationRole :: String -> IO () testMigrationRole dbName = do (logs, Just cp) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readCheckpoint wid let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 3 length (knownAddresses $ getState cp) `shouldBe` 71 where isMsgManualMigration :: WalletDBLog -> Bool isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.SeqStateAddressRole in fieldName field == unFieldNameDB fieldInDB testMigrationSeqStateDerivationPrefix :: forall k s. ( s ~ SeqState 'Mainnet k , WalletKey k , PersistAddressBook s , PersistPrivateKey (k 'RootK) , Show s ) => String -> ( Index 'Hardened 'PurposeK , Index 'Hardened 'CoinTypeK , Index 'Hardened 'AccountK ) -> IO () testMigrationSeqStateDerivationPrefix dbName prefix = do (logs, Just cp) <- withDBLayerFromCopiedFile @k @s dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readCheckpoint wid let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 1 derivationPrefix (getState cp) `shouldBe` DerivationPrefix prefix where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.SeqStateDerivationPrefix in fieldName field == unFieldNameDB fieldInDB testMigrationPassphraseScheme :: FilePath -> IO () testMigrationPassphraseScheme dbName = do (logs, (a,b,c,d)) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do Just a <- readWalletMeta walNeedMigration Just b <- readWalletMeta walNewScheme Just c <- readWalletMeta walOldScheme Just d <- readWalletMeta walNoPassphrase pure (fst a, fst b, fst c, fst d) -- Migration is visible from the logs let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 1 The first wallet is stored in the database with only a -- 'passphraseLastUpdatedAt' field, but no 'passphraseScheme'. So, -- after the migration, both should now be `Just`. (passphraseScheme <$> passphraseInfo a) `shouldBe` Just EncryptWithPBKDF2 The second wallet was just fine and already has a passphrase -- scheme set to use PBKDF2. Nothing should have changed. (passphraseScheme <$> passphraseInfo b) `shouldBe` Just EncryptWithPBKDF2 The third wallet had a scheme too , but was using the legacy -- scheme. Nothing should have changed. (passphraseScheme <$> passphraseInfo c) `shouldBe` Just EncryptWithScrypt -- The last wallet had no passphrase whatsoever (restored from -- account public key), so it should still have NO scheme. (passphraseScheme <$> passphraseInfo d) `shouldBe` Nothing where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.WalPassphraseScheme in fieldName field == unFieldNameDB fieldInDB -- Coming from __test/data/passphraseScheme-v2020-03-16.sqlite__: -- sqlite3 > SELECT wallet_id , passphrase_last_updated_at , passphrase_scheme FROM wallet ; -- -- wallet_id | passphrase_last_updated_at | passphrase_scheme -- =========================================+===============================+================== 64581f7393190aed462fc3180ce52c3c1fe580a9 | 2020 - 06 - 02T14:22:17.48678659 | 5e481f55084afda69fc9cd3863ced80fa83734aa | 2020 - 06 - 02T14:22:03.234087113 | EncryptWithPBKDF2 4a6279cd71d5993a288b2c5879daa7c42cebb73d | 2020 - 06 - 02T14:21:45.418841818 | EncryptWithScrypt -- ba74a7d2c1157ea7f32a93f255dac30e9ebca62b | | -- Right walNeedMigration = fromText "64581f7393190aed462fc3180ce52c3c1fe580a9" Right walNewScheme = fromText "5e481f55084afda69fc9cd3863ced80fa83734aa" Right walOldScheme = fromText "4a6279cd71d5993a288b2c5879daa7c42cebb73d" Right walNoPassphrase = fromText "ba74a7d2c1157ea7f32a93f255dac30e9ebca62b" testCreateMetadataTable :: forall s k. (k ~ ShelleyKey, s ~ SeqState 'Mainnet k) => IO () testCreateMetadataTable = withSystemTempFile "db.sql" $ \path _ -> do let noop _ = pure () tr = nullTracer withDBLayer @s @k tr defaultFieldValues path dummyTimeInterpreter noop actualVersion <- Sqlite.runSqlite (T.pack path) $ do [Sqlite.Single (version :: Int)] <- Sqlite.rawSql "SELECT version FROM database_schema_version \ \WHERE name = 'schema'" [] pure $ SchemaVersion $ fromIntegral version actualVersion `shouldBe` currentSchemaVersion testNewerDatabaseIsNeverModified :: forall s k. (k ~ ShelleyKey, s ~ SeqState 'Mainnet k) => IO () testNewerDatabaseIsNeverModified = withSystemTempFile "db.sql" $ \path _ -> do let newerVersion = SchemaVersion 100 _ <- Sqlite.runSqlite (T.pack path) $ do Sqlite.rawExecute "CREATE TABLE database_schema_version (name, version)" [] Sqlite.rawExecute ( "INSERT INTO database_schema_version \ \VALUES ('schema', " <> T.pack (show newerVersion) <> ")" ) [] let noop _ = pure () tr = nullTracer withDBLayer @s @k tr defaultFieldValues path dummyTimeInterpreter noop `shouldThrow` \case InvalidDatabaseSchemaVersion {..} | expectedVersion == currentSchemaVersion && actualVersion == newerVersion -> True _ -> False localTxSubmissionTableExists :: Text localTxSubmissionTableExists = [i| SELECT EXISTS ( SELECT name FROM sqlite_schema WHERE type='table' AND name='local_tx_submission' ); |] testMigrationSubmissionsEncoding :: FilePath -> IO () testMigrationSubmissionsEncoding dbName = do let performMigrations path = withDBLayer @(SeqState 'Mainnet ShelleyKey) @ShelleyKey nullTracer defaultFieldValues path dummyTimeInterpreter $ \_ -> pure () testOnCopiedAndMigrated test = fmap snd $ withinCopiedFile dbName $ \path _ -> do performMigrations path test path testOnCopiedAndMigrated testAllPresentTxIdsAreInLedger testOnCopiedAndMigrated allTransactionDataIsRepresentedInTxMeta testOnCopiedAndMigrated testLocalTxSubmissionIsMissing where testLocalTxSubmissionIsMissing path = do [Single (count :: Int)] <- Sqlite.runSqlite (T.pack path) $ Sqlite.rawSql localTxSubmissionTableExists [] count `shouldBe` 0 pure () allTransactionDataIsRepresentedInTxMeta path = do let idOf = unSingle @DB.TxId selectIds t = fmap idOf <$> Sqlite.rawSql ("SELECT tx_id FROM " <> t) [] runQuery = Sqlite.runSqlite (T.pack path) shouldBe' mtxs t = do txs <- runQuery $ selectIds t liftIO $ Set.fromList txs `shouldSatisfy` \x -> x `Set.isSubsetOf` (Set.fromList mtxs) metaIds <- runQuery $ selectIds "tx_meta" mapM_ (shouldBe' metaIds) [ "tx_in" , "tx_collateral" , "tx_out" , "tx_out_token" , "tx_collateral_out" , "tx_collateral_out_token" , "tx_withdrawal" , "c_b_o_r" ] testAllPresentTxIdsAreInLedger path = do metas <- Sqlite.runSqlite (T.pack path) $ Sqlite.rawSql "SELECT status FROM tx_meta" [] forM_ metas $ \(Single status) -> status `shouldBe` ("in_ledger" :: Text) {------------------------------------------------------------------------------- Test data -------------------------------------------------------------------------------} coinToBundle :: Word64 -> TokenBundle coinToBundle = TokenBundle.fromCoin . Coin.fromWord64 testCp :: Wallet (SeqState 'Mainnet ShelleyKey) testCp = snd $ initWallet block0 initDummyState where initDummyState :: SeqState 'Mainnet ShelleyKey initDummyState = mkSeqStateFromRootXPrv (xprv, mempty) purposeCIP1852 defaultAddressPoolGap where mw = SomeMnemonic . unsafePerformIO . generate $ genMnemonic @15 xprv = generateKeyFromSeed (mw, Nothing) mempty testMetadata :: WalletMetadata testMetadata = WalletMetadata { name = WalletName "test wallet" , creationTime = unsafePerformIO getCurrentTime , passphraseInfo = Nothing } testWid :: WalletId testWid = WalletId (hash ("test" :: ByteString)) testTxs :: [(Tx, TxMeta)] testTxs = [ (tx1, meta1), (tx2, meta2) ] where tx1 = Tx { txId = mockHash @String "tx2" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (mockHash @String "tx1") 0 , Nothing ) ] , resolvedCollateralInputs = [] , outputs = [TxOut (Address "addr1") (coinToBundle 10)] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } meta1 = TxMeta { status = InLedger , direction = Incoming , slotNo = SlotNo 140 , blockHeight = Quantity 0 , amount = Coin 1_337_144 , expiry = Nothing } tx2 = Tx { txId = mockHash @String "tx3" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (mockHash @String "tx2") 0 , headMay $ tx1 ^. #outputs ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (Address "addr2") (coinToBundle 5) , TxOut (Address "addr3") (coinToBundle 5) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } meta2 = TxMeta { status = InLedger , direction = Incoming , slotNo = SlotNo 150 , blockHeight = Quantity 0 , amount = Coin 10 , expiry = Nothing } gp :: GenesisParameters gp = dummyGenesisParameters {------------------------------------------------------------------------------- Helpers for golden rollback tests -------------------------------------------------------------------------------} getAvailableBalance :: DBLayer IO s k -> IO Natural getAvailableBalance DBLayer{..} = do cp <- fmap (fromMaybe (error "nothing")) <$> atomically $ readCheckpoint testWid pend <- atomically $ fmap toTxHistory <$> readTransactions testWid Nothing Descending wholeRange (Just Pending) return $ fromIntegral $ unCoin $ TokenBundle.getCoin $ availableBalance (Set.fromList $ map fst pend) cp getTxsInLedger :: DBLayer IO s k -> IO ([(Direction, Natural)]) getTxsInLedger DBLayer {..} = do pend <- atomically $ fmap toTxHistory <$> readTransactions testWid Nothing Descending wholeRange (Just InLedger) pure $ map (\(_, m) -> (direction m, fromIntegral $ unCoin $ amount m)) pend {------------------------------------------------------------------------------- Test data - Sequential AD -------------------------------------------------------------------------------} testCpSeq :: Wallet (SeqState 'Mainnet ShelleyKey) testCpSeq = snd $ initWallet block0 initDummyStateSeq initDummyStateSeq :: SeqState 'Mainnet ShelleyKey initDummyStateSeq = mkSeqStateFromRootXPrv (xprv, mempty) purposeCIP1852 defaultAddressPoolGap where mw = SomeMnemonic $ unsafePerformIO (generate $ genMnemonic @15) xprv = Seq.generateKeyFromSeed (mw, Nothing) mempty
null
https://raw.githubusercontent.com/input-output-hk/cardano-wallet/053771567b5dc2c9d0670d739cf5f7364ac636e3/lib/wallet/test/unit/Cardano/Wallet/DB/LayerSpec.hs
haskell
# LANGUAGE GADTs # # LANGUAGE RankNTypes # # OPTIONS_GHC -Wno-unused-imports # | License: Apache-2.0 To test individual properties in GHCi, use the shorthand type aliases. For example: >>> db <- newMemoryDBLayer :: IO TestDBSeq >>> quickCheck $ prop_sequential db ------------------------------------------------------------------------------ Logging Spec ------------------------------------------------------------------------------ ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} NOTE Start a concurrent worker which makes action on the DB in parallel to simulate activity. set up a database file Try removing the database when it's already opened for This simulates an antivirus program on windows which may interfere with file deletion. expected after opening db expected after cleaning db expected after opening db expected after cleaning db Such that old checkpoints are always pruned. ---------------------------------------------------------- Transaction 1 This transaction provides initial funding for the wallet. ---------------------------------------------------------- ---------------------------------------------------------- Transaction 2 This transaction has a script that fails validation. Therefore, we should forfeit value from the collateral inputs, but recover value from the collateral outputs. ---------------------------------------------------------- We: ---------------------------------------------------------- Transaction 3 This transaction uses a collateral output created in the previous transaction to make a payment. ---------------------------------------------------------- Here we refer to a collateral output from the previous transaction. Note that we refer to the sole collateral output by using a special index value that is equal to the number of ordinary outputs in that transaction: TODO: (ADP-957) Slot 1 0 TODO: (ADP-957) This property checks that executing series of wallet operations in a single multiple sessions. | Test that data is preserved between open / close of the same database and that cleaning up happens as expected. | Run a test action inside withDBLayer, then check assertions. Note: Having helper with concrete key types reduces the need for type-application everywhere. fixme: capture logging | Attach an arbitrary private key to a wallet ------------------------------------------------------------------------------ Manual migrations tests ------------------------------------------------------------------------------ number of transactions This one (chosen for its stake key registration) has: This one (chosen because of its very round fee) has: This one (chosen for its withdrawal) has: This one (chosen for its high fee) has: This one (chosen for having many inputs and many outputs) has: - 10 inputs: - 1654330 - 2111100 - 2234456 - 9543345 - 1826766 - 8871831 - 3823766 - 6887025 - 1958037 - 3575522 - 10 outputs: - 4000000 - 7574304 - 9000000 - 1000000 - 1164635 - 6752132 - 1000000 - 8596880 - 1707865 - 1 withdrawal: This one (chosen for its high ratio input:output) has: - 33 relatively small outputs (possibly triggering migrations), and run an action on it. Useful for testing the logs and results of migrations. ^ Action to run. ^ (logs, result of the action) Check that we've indeed logged a needed migration for 'fee' Check that the migrated history has the correct length. Verify that all incoming transactions have no fees set, and that all outgoing ones do. Also verify a few hand-picked transactions Migration is visible from the logs 'passphraseLastUpdatedAt' field, but no 'passphraseScheme'. So, after the migration, both should now be `Just`. scheme set to use PBKDF2. Nothing should have changed. scheme. Nothing should have changed. The last wallet had no passphrase whatsoever (restored from account public key), so it should still have NO scheme. Coming from __test/data/passphraseScheme-v2020-03-16.sqlite__: wallet_id | passphrase_last_updated_at | passphrase_scheme =========================================+===============================+================== ba74a7d2c1157ea7f32a93f255dac30e9ebca62b | | ------------------------------------------------------------------------------ Test data ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Helpers for golden rollback tests ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Test data - Sequential AD ------------------------------------------------------------------------------
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DerivingStrategies # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE NumericUnderscores # # LANGUAGE OverloadedLabels # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - warn - orphans # Copyright : © 2018 - 2020 IOHK DBLayer tests for SQLite implementation . module Cardano.Wallet.DB.LayerSpec ( spec ) where import Prelude import Cardano.BM.Configuration.Static ( defaultConfigTesting ) import Cardano.BM.Data.Tracer ( nullTracer ) import Cardano.BM.Setup ( setupTrace ) import Cardano.BM.Trace ( traceInTVarIO ) import Cardano.Chain.ValidationMode ( whenTxValidation ) import Cardano.Crypto.Wallet ( XPrv ) import Cardano.DB.Sqlite ( DBField, DBLog (..), SqliteContext, fieldName, newInMemorySqliteContext ) import Cardano.Mnemonic ( SomeMnemonic (..) ) import Cardano.Wallet.DB ( DBFactory (..), DBLayer (..), cleanDB ) import Cardano.Wallet.DB.Arbitrary ( GenState, KeyValPairs (..) ) import Cardano.Wallet.DB.Layer ( DefaultFieldValues (..) , PersistAddressBook , WalletDBLog (..) , newDBFactory , newDBLayerInMemory , withDBLayer , withDBLayerInMemory ) import Cardano.Wallet.DB.Properties ( properties ) import Cardano.Wallet.DB.Sqlite.Migration ( InvalidDatabaseSchemaVersion (..) , SchemaVersion (..) , currentSchemaVersion ) import Cardano.Wallet.DB.StateMachine ( TestConstraints, prop_parallel, prop_sequential, validateGenerators ) import Cardano.Wallet.DB.WalletState ( ErrNoSuchWallet (..) ) import Cardano.Wallet.DummyTarget.Primitive.Types ( block0, dummyGenesisParameters, dummyTimeInterpreter ) import Cardano.Wallet.Gen ( genMnemonic ) import Cardano.Wallet.Logging ( trMessageText ) import Cardano.Wallet.Primitive.AddressDerivation ( Depth (..) , DerivationType (..) , Index , NetworkDiscriminant (..) , PaymentAddress (..) , PersistPrivateKey , WalletKey ) import Cardano.Wallet.Primitive.AddressDerivation.Byron ( ByronKey (..) ) import Cardano.Wallet.Primitive.AddressDerivation.Icarus ( IcarusKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shared () import Cardano.Wallet.Primitive.AddressDerivation.SharedKey ( SharedKey ) import Cardano.Wallet.Primitive.AddressDerivation.Shelley ( ShelleyKey (..), generateKeyFromSeed ) import Cardano.Wallet.Primitive.AddressDiscovery ( GetPurpose, KnownAddresses (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Random ( RndState (..) ) import Cardano.Wallet.Primitive.AddressDiscovery.Sequential ( DerivationPrefix (..) , SeqState (..) , coinTypeAda , defaultAddressPoolGap , mkSeqStateFromRootXPrv , purposeBIP44 , purposeCIP1852 ) import Cardano.Wallet.Primitive.AddressDiscovery.Shared ( SharedState ) import Cardano.Wallet.Primitive.Model ( FilteredBlock (..) , Wallet , applyBlock , availableBalance , currentTip , getState , initWallet , utxo ) import Cardano.Wallet.Primitive.Passphrase ( encryptPassphrase, preparePassphrase ) import Cardano.Wallet.Primitive.Passphrase.Types ( Passphrase (..) , PassphraseHash (..) , PassphraseScheme (..) , WalletPassphraseInfo (..) ) import Cardano.Wallet.Primitive.Types ( ActiveSlotCoefficient (..) , Block (..) , BlockHeader (..) , GenesisParameters (..) , Range , SlotNo (..) , SortOrder (..) , StartTime (..) , WalletDelegation (..) , WalletDelegationStatus (..) , WalletId (..) , WalletMetadata (..) , WalletName (..) , WithOrigin (At) , wholeRange ) import Cardano.Wallet.Primitive.Types.Address ( Address (..) ) import Cardano.Wallet.Primitive.Types.Coin ( Coin (..) ) import Cardano.Wallet.Primitive.Types.Hash ( Hash (..), mockHash ) import Cardano.Wallet.Primitive.Types.TokenBundle ( TokenBundle ) import Cardano.Wallet.Primitive.Types.Tx ( Direction (..) , TransactionInfo (..) , Tx (..) , TxMeta (..) , TxScriptValidity (..) , TxStatus (..) , toTxHistory ) import Cardano.Wallet.Primitive.Types.Tx.TxIn ( TxIn (..) ) import Cardano.Wallet.Primitive.Types.Tx.TxOut ( TxOut (..) ) import Cardano.Wallet.Unsafe ( unsafeFromHex, unsafeRunExceptT ) import Control.Monad ( forM_, forever, replicateM_, unless, void ) import Control.Monad.IO.Class ( liftIO ) import Control.Monad.Trans.Except ( ExceptT, mapExceptT ) import Control.Tracer ( Tracer ) import Crypto.Hash ( hash ) import Data.ByteString ( ByteString ) import Data.Coerce ( coerce ) import Data.Generics.Internal.VL.Lens ( over, view, (^.) ) import Data.Generics.Labels () import Data.Maybe ( fromMaybe, isJust, isNothing, mapMaybe ) import Data.Quantity ( Quantity (..) ) import Data.String.Interpolate ( i ) import Data.Text ( Text ) import Data.Text.Class ( fromText, toText ) import Data.Time.Clock ( getCurrentTime ) import Data.Time.Clock.POSIX ( posixSecondsToUTCTime ) import Data.Typeable ( Typeable, typeOf ) import Data.Word ( Word64 ) import Database.Persist.EntityDef ( getEntityDBName, getEntityFields ) import Database.Persist.Names ( EntityNameDB (..), unFieldNameDB ) import Database.Persist.Sql ( EntityNameDB (..), FieldNameDB (..), PersistEntity (..), fieldDB ) import Database.Persist.Sqlite ( Single (..) ) import Numeric.Natural ( Natural ) import Safe ( headMay ) import System.Directory ( copyFile, doesFileExist, listDirectory, removeFile ) import System.FilePath ( (</>) ) import System.IO ( IOMode (..), hClose, withFile ) import System.IO.Error ( isUserError ) import System.IO.Temp ( emptySystemTempFile ) import System.IO.Unsafe ( unsafePerformIO ) import System.Random ( randomRIO ) import Test.Hspec ( Expectation , Spec , SpecWith , anyIOException , around , before , beforeWith , describe , it , shouldBe , shouldNotBe , shouldNotContain , shouldReturn , shouldSatisfy , shouldThrow , xit ) import Test.Hspec.Extra ( parallel ) import Test.QuickCheck ( Arbitrary (..) , Property , choose , generate , noShrinking , property , (==>) ) import Test.QuickCheck.Monadic ( assert, monadicIO, run ) import Test.Utils.Paths ( getTestData ) import Test.Utils.Trace ( captureLogging ) import UnliftIO.Async ( concurrently, concurrently_ ) import UnliftIO.Concurrent ( forkIO, killThread, threadDelay ) import UnliftIO.Exception ( SomeException, handle, throwIO ) import UnliftIO.MVar ( isEmptyMVar, newEmptyMVar, putMVar, takeMVar ) import UnliftIO.STM ( TVar, newTVarIO, readTVarIO, writeTVar ) import UnliftIO.Temporary ( withSystemTempDirectory, withSystemTempFile ) import qualified Cardano.Wallet.DB.Sqlite.Schema as DB import qualified Cardano.Wallet.DB.Sqlite.Types as DB import qualified Cardano.Wallet.Primitive.AddressDerivation.Shelley as Seq import qualified Cardano.Wallet.Primitive.Types.Coin as Coin import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle import qualified Cardano.Wallet.Primitive.Types.Tx.TxMeta as W import qualified Data.ByteArray as BA import qualified Data.ByteString as BS import qualified Data.List as L import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Database.Persist.Sql as Sql import qualified Database.Persist.Sqlite as Sqlite import qualified UnliftIO.STM as STM spec :: Spec spec = parallel $ do stateMachineSpecSeq stateMachineSpecRnd stateMachineSpecShared propertiesSpecSeq loggingSpec fileModeSpec manualMigrationsSpec stateMachineSpec :: forall k s ktype. ( WalletKey k , PersistPrivateKey (k 'RootK) , PaymentAddress 'Mainnet k ktype , PersistAddressBook s , TestConstraints s k , Typeable s ) => Spec stateMachineSpec = describe ("State machine test (" ++ showState @s ++ ")") $ do validateGenerators @s let newDB = newDBLayerInMemory @s @k nullTracer dummyTimeInterpreter it "Sequential" $ prop_sequential newDB xit "Parallel" $ prop_parallel newDB stateMachineSpecSeq, stateMachineSpecRnd, stateMachineSpecShared :: Spec stateMachineSpecSeq = stateMachineSpec @ShelleyKey @(SeqState 'Mainnet ShelleyKey) @'CredFromKeyK stateMachineSpecRnd = stateMachineSpec @ByronKey @(RndState 'Mainnet) @'CredFromKeyK stateMachineSpecShared = stateMachineSpec @SharedKey @(SharedState 'Mainnet SharedKey) @'CredFromScriptK instance PaymentAddress 'Mainnet SharedKey 'CredFromScriptK where paymentAddress _ = error "does not make sense for SharedKey but want to use stateMachineSpec" liftPaymentAddress _ = error "does not make sense for SharedKey but want to use stateMachineSpec" showState :: forall s. Typeable s => String showState = show (typeOf @s undefined) propertiesSpecSeq :: Spec propertiesSpecSeq = around withShelleyDBLayer $ describe "Properties" (properties :: SpecWith TestDBSeq) loggingSpec :: Spec loggingSpec = withLoggingDB @(SeqState 'Mainnet ShelleyKey) $ do describe "Sqlite query logging" $ do it "should log queries at DEBUG level" $ \(getLogs, DBLayer{..}) -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp logs <- getLogs logs `shouldHaveMsgQuery` "INSERT" it "should not log query parameters" $ \(getLogs, DBLayer{..}) -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp let walletName = T.unpack $ coerce $ name testMetadata msgs <- T.unlines . mapMaybe getMsgQuery <$> getLogs T.unpack msgs `shouldNotContain` walletName describe "Sqlite observables" $ do it "should measure query timings" $ \(getLogs, DBLayer{..}) -> do let count = 5 replicateM_ count (atomically listWallets) msgs <- findObserveDiffs <$> getLogs length msgs `shouldBe` count * 2 withLoggingDB :: (Show s, PersistAddressBook s) => SpecWith (IO [DBLog], DBLayer IO s ShelleyKey) -> Spec withLoggingDB = around f . beforeWith clean where f act = do logVar <- newTVarIO [] withDBLayerInMemory (traceInTVarIO logVar) dummyTimeInterpreter (\db -> act (logVar, db)) clean (logs, db) = do cleanDB db STM.atomically $ writeTVar logs [] pure (mapMaybe getMsgDB <$> readTVarIO logs, db) getMsgDB :: WalletDBLog -> Maybe DBLog getMsgDB (MsgDB msg) = Just msg shouldHaveMsgQuery :: [DBLog] -> Text -> Expectation shouldHaveMsgQuery msgs str = unless (any match msgs) $ fail $ "Did not find DB query " ++ T.unpack str ++ " within " ++ show msgs where match = maybe False (str `T.isInfixOf`) . getMsgQuery getMsgQuery :: DBLog -> Maybe Text getMsgQuery (MsgQuery msg _) = Just msg getMsgQuery _ = Nothing findObserveDiffs :: [DBLog] -> [DBLog] findObserveDiffs = filter isObserveDiff where isObserveDiff (MsgRun _) = True isObserveDiff _ = False File Mode Spec File Mode Spec type TestDBSeq = DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey fileModeSpec :: Spec fileModeSpec = do describe "Check db opening/closing" $ do it "Opening and closing of db works" $ do replicateM_ 25 $ do db <- temporaryDBFile withShelleyFileDBLayer @(SeqState 'Mainnet ShelleyKey) db (\_ -> pure ()) describe "DBFactory" $ do let ti = dummyTimeInterpreter let withDBFactory action = withSystemTempDirectory "DBFactory" $ \dir -> do dbf <- newDBFactory nullTracer defaultFieldValues ti (Just dir) action dir dbf let whileFileOpened delay f action = do opened <- newEmptyMVar concurrently_ (withFile f ReadMode (\_ -> putMVar opened () >> threadDelay delay)) (takeMVar opened >> action) it "withDatabase *> removeDatabase works and remove files" $ do withDBFactory $ \dir DBFactory{..} -> do pid <- forkIO $ withDatabase testWid $ \(DBLayer{..} :: TestDBSeq) -> do handle @IO @SomeException (const (pure ())) $ forever $ do atomically $ do liftIO $ threadDelay 10_000 void $ readCheckpoint testWid killThread pid *> removeDatabase testWid listDirectory dir `shouldReturn` mempty it "removeDatabase still works if file is opened" $ do withDBFactory $ \dir DBFactory{..} -> do withDatabase testWid $ \(_ :: TestDBSeq) -> pure () files <- listDirectory dir files `shouldNotBe` mempty reading for . whileFileOpened 100_000 (dir </> head files) (removeDatabase testWid) listDirectory dir `shouldReturn` mempty it "removeDatabase waits for connections to close" $ do withDBFactory $ \_ DBFactory{..} -> do closed <- newEmptyMVar let conn = withDatabase testWid $ \(_ :: TestDBSeq) -> do threadDelay 500_000 putMVar closed () let rm = do removeDatabase testWid isEmptyMVar closed concurrently conn (threadDelay 50_000 >> rm) `shouldReturn` ((), False) describe "Sqlite database file" $ do let writeSomething DBLayer{..} = do atomically $ unsafeRunExceptT $ initializeWallet testWid testCpSeq testMetadata mempty gp atomically listWallets `shouldReturn` [testWid] tempFilesAbsent fp = do doesFileExist fp `shouldReturn` True doesFileExist (fp <> "-wal") `shouldReturn` False doesFileExist (fp <> "-shm") `shouldReturn` False bomb = throwIO (userError "bomb") it "is properly closed after withDBLayer" $ withTestDBFile writeSomething tempFilesAbsent it "is properly closed after an exception in withDBLayer" $ withTestDBFile (\db -> writeSomething db >> bomb) tempFilesAbsent `shouldThrow` isUserError before temporaryDBFile $ describe "Check db reading/writing from/to file and cleaning" $ do it "create and list wallet works" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp testOpeningCleaning f listWallets' [testWid] [] it "create and get meta works" $ \f -> do meta <- withShelleyFileDBLayer f $ \DBLayer{..} -> do now <- getCurrentTime let meta = testMetadata { passphraseInfo = Just $ WalletPassphraseInfo now EncryptWithPBKDF2 } atomically $ unsafeRunExceptT $ initializeWallet testWid testCp meta mempty gp return (meta, WalletDelegation NotDelegating []) testOpeningCleaning f (`readWalletMeta'` testWid) (Just meta) Nothing it "create and get private key" $ \f -> do (k, h) <- withShelleyFileDBLayer f $ \db@DBLayer{..} -> do atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ attachPrivateKey db testWid testOpeningCleaning f (`readPrivateKey'` testWid) (Just (k, h)) Nothing it "put and read tx history (Ascending)" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putTxHistory testWid testTxs testOpeningCleaning f (\db' -> readTransactions' db' testWid Ascending wholeRange Nothing ) it "put and read tx history (Descending)" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putTxHistory testWid testTxs testOpeningCleaning f (\db' -> readTransactions' db' testWid Descending wholeRange Nothing ) it "put and read checkpoint" $ \f -> do withShelleyFileDBLayer f $ \DBLayer{..} -> do atomically $ do unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp unsafeRunExceptT $ putCheckpoint testWid testCp testOpeningCleaning f (`readCheckpoint'` testWid) (Just testCp) Nothing describe "Golden rollback scenarios" $ do let dummyHash x = Hash $ x <> BS.pack (replicate (32 - (BS.length x)) 0) let dummyAddr x = Address $ x <> BS.pack (replicate (32 - (BS.length x)) 0) let mockApply DBLayer{..} h mockTxs = do Just cpA <- atomically $ readCheckpoint testWid let slotA = view #slotNo $ currentTip cpA let Quantity bhA = view #blockHeight $ currentTip cpA let hashA = headerHash $ currentTip cpA let fakeBlock = Block (BlockHeader { slotNo = slotA + 100 Increment blockHeight by steps greater than k , blockHeight = Quantity $ bhA + 5_000 , headerHash = h , parentHeaderHash = Just hashA }) mockTxs mempty let (FilteredBlock{transactions=txs}, (_,cpB)) = applyBlock fakeBlock cpA atomically $ do unsafeRunExceptT $ putCheckpoint testWid cpB unsafeRunExceptT $ putTxHistory testWid txs unsafeRunExceptT $ prune testWid (Quantity 2_160) $ 2_160 * 3 * 20 it "Should spend collateral inputs and create spendable collateral \ \outputs if validation fails" $ \f -> withShelleyFileDBLayer f $ \db@DBLayer{..} -> do let ourAddrs = map (\(a,s,_) -> (a,s)) $ knownAddresses (getState testCp) atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp mockApply db (dummyHash "block1") [ Tx { txId = dummyHash "tx1" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "faucet") 0 , Just $ TxOut (dummyAddr "faucetOut1") (coinToBundle 4) ) , ( TxIn (dummyHash "faucet") 1 , Just $ TxOut (dummyAddr "faucetOut2") (coinToBundle 8) ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (fst $ head ourAddrs) (coinToBundle 4) , TxOut (fst $ head $ tail ourAddrs) (coinToBundle 8) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptValid } ] = = ( 4 + 8) mockApply db (dummyHash "block2") [ Tx { txId = dummyHash "tx2" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "tx1") 0 , Just $ TxOut (dummyAddr "faucetOut1") (coinToBundle 4) ) ] , resolvedCollateralInputs = [(TxIn (dummyHash "tx1") 1, Nothing)] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 2) , TxOut (fst $ ourAddrs !! 1) (coinToBundle 2) ] , collateralOutput = Just $ TxOut (fst $ ourAddrs !! 1) (coinToBundle 7) , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptInvalid } ] mockApply db (dummyHash "block2a") [] getTxsInLedger db `shouldReturn` - forfeited 8 from collateral inputs ; - recovered 7 from collateral ouputs . Therefore we lost a net collateral value of ( 8 - 7 ): [ (Outgoing, 1) We got 12 from the faucet , (Incoming, 12) ] = 12 - 1 mockApply db (dummyHash "block3") [ Tx { txId = dummyHash "tx3" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "tx2") 2 , Just $ TxOut (fst $ ourAddrs !! 1) (coinToBundle 7) ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 8) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Just TxScriptValid } ] mockApply db (dummyHash "block3a") [] = 11 - 7 it "(Regression test #1575) - TxMetas and checkpoints should \ \rollback to the same place" $ \f -> do withShelleyFileDBLayer f $ \db@DBLayer{..} -> do let ourAddrs = map (\(a,s,_) -> (a,s)) $ knownAddresses (getState testCp) atomically $ unsafeRunExceptT $ initializeWallet testWid testCp testMetadata mempty gp let mockApplyBlock1 = mockApply db (dummyHash "block1") [ Tx { txId = dummyHash "tx1" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "faucet") 0 , Just $ TxOut (dummyAddr "out_for_in") (coinToBundle 4) ) ] , resolvedCollateralInputs = [] , outputs = [TxOut (fst $ head ourAddrs) (coinToBundle 4)] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } ] mockApplyBlock1 getAvailableBalance db `shouldReturn` 4 Slot 200 mockApply db (dummyHash "block2a") [ Tx { txId = dummyHash "tx2a" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (dummyHash "tx1") 0 , Just $ TxOut (dummyAddr "out_for_in") (coinToBundle 4) ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (dummyAddr "faucetAddr2") (coinToBundle 2) , TxOut (fst $ ourAddrs !! 1) (coinToBundle 2) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } ] Slot 300 mockApply db (dummyHash "block3a") [] getAvailableBalance db `shouldReturn` 2 getTxsInLedger db `shouldReturn` [(Outgoing, 2), (Incoming, 4)] atomically . void . unsafeRunExceptT $ rollbackTo testWid (At $ SlotNo 200) Just cp <- atomically $ readCheckpoint testWid view #slotNo (currentTip cp) `shouldBe` (SlotNo 0) getTxsInLedger db `shouldReturn` [] describe "random operation chunks property" $ do it "realize a random batch of operations upon one db open" (property $ prop_randomOpChunks @(SeqState 'Mainnet ShelleyKey)) SQLite session has the same effect as executing the same operations over prop_randomOpChunks :: (Eq s, PersistAddressBook s, Show s) => KeyValPairs WalletId (Wallet s, WalletMetadata) -> Property prop_randomOpChunks (KeyValPairs pairs) = not (null pairs) ==> monadicIO (liftIO prop) where prop = do filepath <- temporaryDBFile withShelleyFileDBLayer filepath $ \dbF -> do cleanDB dbF withShelleyDBLayer $ \dbM -> do cleanDB dbM forM_ pairs (insertPair dbM) cutRandomly pairs >>= mapM_ (mapM (insertPair dbF)) dbF `shouldBeConsistentWith` dbM insertPair :: DBLayer IO s k -> (WalletId, (Wallet s, WalletMetadata)) -> IO () insertPair DBLayer{..} (k, (cp, meta)) = do keys <- atomically listWallets if k `elem` keys then atomically $ do unsafeRunExceptT $ putCheckpoint k cp unsafeRunExceptT $ putWalletMeta k meta else do let cp0 = imposeGenesisState cp atomically $ unsafeRunExceptT $ initializeWallet k cp0 meta mempty gp Set.fromList <$> atomically listWallets `shouldReturn` Set.fromList (k:keys) imposeGenesisState :: Wallet s -> Wallet s imposeGenesisState = over #currentTip $ \(BlockHeader _ _ h _) -> BlockHeader (SlotNo 0) (Quantity 0) h Nothing shouldBeConsistentWith :: (Eq s, Show s) => DBLayer IO s k -> DBLayer IO s k -> IO () shouldBeConsistentWith db1 db2 = do wids1 <- Set.fromList <$> listWallets' db1 wids2 <- Set.fromList <$> listWallets' db2 wids1 `shouldBe` wids2 forM_ wids1 $ \walId -> do cps1 <- readCheckpoint' db1 walId cps2 <- readCheckpoint' db2 walId cps1 `shouldBe` cps2 forM_ wids1 $ \walId -> do meta1 <- readWalletMeta' db1 walId meta2 <- readWalletMeta' db2 walId meta1 `shouldBe` meta2 testOpeningCleaning :: (Show s, Eq s) => FilePath -> (DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey -> IO s) -> s -> s -> Expectation testOpeningCleaning filepath call expectedAfterOpen expectedAfterClean = do withShelleyFileDBLayer filepath $ \db -> do call db `shouldReturn` expectedAfterOpen _ <- cleanDB db call db `shouldReturn` expectedAfterClean withShelleyFileDBLayer filepath $ \db -> do call db `shouldReturn` expectedAfterClean withTestDBFile :: (DBLayer IO (SeqState 'Mainnet ShelleyKey) ShelleyKey -> IO ()) -> (FilePath -> IO a) -> IO a withTestDBFile action expectations = do logConfig <- defaultConfigTesting trace <- setupTrace (Right logConfig) "connectionSpec" withSystemTempFile "spec.db" $ \fp h -> do hClose h removeFile fp withDBLayer (trMessageText trace) defaultFieldValues fp ti action expectations fp where ti = dummyTimeInterpreter temporaryDBFile :: IO FilePath temporaryDBFile = emptySystemTempFile "cardano-wallet-SqliteFileMode" defaultFieldValues :: DefaultFieldValues defaultFieldValues = DefaultFieldValues { defaultActiveSlotCoefficient = ActiveSlotCoefficient 1.0 , defaultDesiredNumberOfPool = 0 , defaultMinimumUTxOValue = Coin 1_000_000 , defaultHardforkEpoch = Nothing , defaultKeyDeposit = Coin 2_000_000 } withShelleyDBLayer :: PersistAddressBook s => (DBLayer IO s ShelleyKey -> IO a) -> IO a withShelleyDBLayer = withDBLayerInMemory nullTracer dummyTimeInterpreter withShelleyFileDBLayer :: PersistAddressBook s => FilePath -> (DBLayer IO s ShelleyKey -> IO a) -> IO a withShelleyFileDBLayer fp = withDBLayer defaultFieldValues fp dummyTimeInterpreter listWallets' :: DBLayer m s k -> m [WalletId] listWallets' DBLayer{..} = atomically listWallets readCheckpoint' :: DBLayer m s k -> WalletId -> m (Maybe (Wallet s)) readCheckpoint' DBLayer{..} = atomically . readCheckpoint readWalletMeta' :: DBLayer m s k -> WalletId -> m (Maybe (WalletMetadata, WalletDelegation)) readWalletMeta' DBLayer{..} = atomically . readWalletMeta readTransactions' :: DBLayer m s k -> WalletId -> SortOrder -> Range SlotNo -> Maybe TxStatus -> m [(Tx, TxMeta)] readTransactions' DBLayer{..} a0 a1 a2 = atomically . fmap (fmap toTxHistory) . readTransactions a0 Nothing a1 a2 readPrivateKey' :: DBLayer m s k -> WalletId -> m (Maybe (k 'RootK XPrv, PassphraseHash)) readPrivateKey' DBLayer{..} = atomically . readPrivateKey attachPrivateKey :: DBLayer IO s ShelleyKey -> WalletId -> ExceptT ErrNoSuchWallet IO (ShelleyKey 'RootK XPrv, PassphraseHash) attachPrivateKey DBLayer{..} wid = do let pwd = Passphrase $ BA.convert $ T.encodeUtf8 "simplevalidphrase" seed <- liftIO $ generate $ SomeMnemonic <$> genMnemonic @15 (scheme, h) <- liftIO $ encryptPassphrase pwd let k = generateKeyFromSeed (seed, Nothing) (preparePassphrase scheme pwd) mapExceptT atomically $ putPrivateKey wid (k, h) return (k, h) cutRandomly :: [a] -> IO [[a]] cutRandomly = iter [] where iter acc rest | L.length rest <= 1 = pure $ L.reverse (rest:acc) | otherwise = do chunksNum <- randomRIO (1, L.length rest) let chunk = L.take chunksNum rest iter (chunk:acc) (L.drop chunksNum rest) manualMigrationsSpec :: Spec manualMigrationsSpec = describe "Manual migrations" $ do it "'migrate' db with no passphrase scheme set." $ testMigrationPassphraseScheme "passphraseScheme-v2020-03-16.sqlite" it "'migrate' db with no 'derivation_prefix' for seq state (Icarus)" $ testMigrationSeqStateDerivationPrefix @IcarusKey "icarusDerivationPrefix-v2020-10-07.sqlite" ( purposeBIP44 , coinTypeAda , minBound ) it "'migrate' db with no 'derivation_prefix' for seq state (Shelley)" $ testMigrationSeqStateDerivationPrefix @ShelleyKey "shelleyDerivationPrefix-v2020-10-07.sqlite" ( purposeCIP1852 , coinTypeAda , minBound ) it "'migrate' db with old text serialization for 'Role'" $ testMigrationRole "shelleyRole-v2020-10-13.sqlite" it "'migrate' db with partially applied checkpoint migration" $ testMigrationRole "shelleyRole-corrupted-v2020-10-13.sqlite" it "'migrate' db with unused protocol parameters in checkpoints" $ testMigrationCleanupCheckpoints "shelleyDerivationPrefix-v2020-10-07.sqlite" (GenesisParameters { getGenesisBlockHash = Hash $ unsafeFromHex "5f20df933584822601f9e3f8c024eb5eb252fe8cefb24d1317dc3d432e940ebb" , getGenesisBlockDate = StartTime $ posixSecondsToUTCTime 1_506_203_091 } ) (BlockHeader { slotNo = SlotNo 1_125_119 , blockHeight = Quantity 1_124_949 , headerHash = Hash $ unsafeFromHex "3b309f1ca388459f0ce2c4ccca20ea646b75e6fc1447be032a41d43f209ecb50" , parentHeaderHash = Just $ Hash $ unsafeFromHex "e9414e08d8c5ca177dd0cb6a9e4bf868e1ea03389c31f5f7a6b099a3bcdfdedf" } ) it "'migrate' db to add fees to transactions" $ testMigrationTxMetaFee "metaFee-v2020-11-26.sqlite" - one input of 1000000000 - one output of 997825743 . which gives a delta of 2174257 , which means - 2000000 of key deposit - 174257 of fee [ ( Hash $ unsafeFromHex "00058d433a73574a64d0b4a3c37f1e460697fa8f1e3265a51e95eb9e9573b5ab" , Coin 174_257 ) - two inputs of 1000000 each - one output of 1000000 which gives a delta ( and fee ) of 1000000 , ( Hash $ unsafeFromHex "8f79e7f79ddeb7a7494121259832c0180c1b6bb746d8b2337cd1f4fb5b0d8216" , Coin 1_000_000 ) - one input of 909199523 - one withdrawal of 863644 - two outputs of 1000000 and 908888778 which gives a delta ( and fee ) of 174389 , ( Hash $ unsafeFromHex "eefa06dfa8ce91237117f9b4bdc4f6970c31de54906313b545dafb7ca6235171" , Coin 174_389 ) - one input of 997825743 - two outputs of 1000000 and 995950742 which gives a delta ( and fee ) of 875001 , ( Hash $ unsafeFromHex "8943f9fa4b56b32cd44ab9c22d46693882f0bbca1bc3f0705124e75c2e40b9c2" , Coin 875_001 ) - 2000000 - 565251 which gives a delta ( and fee ) of 255613 , ( Hash $ unsafeFromHex "99907bf6ac73f6fe6fe25bd6b68bae6776425b9d15a7c46c7a49b85b8b03f291" , Coin 255_613 ) - 1 input of 1000000000 - 1 withdrawal of 561120 which gives a delta ( and fee ) of 267537 , ( Hash $ unsafeFromHex "15940a7c1df8696279282046ebdb1ee890d4e9ac3c5d7213f360921648b36666" , Coin 267_537 ) ] it "'migrate' db to create metadata table when it doesn't exist" testCreateMetadataTable it "'migrate' db never modifies database with newer version" testNewerDatabaseIsNeverModified it "'migrate' db submissions encoding" $ testMigrationSubmissionsEncoding "before_submission-v2022-12-14.sqlite" | Copy a given @.sqlite@ file , load it into a ` DBLayer ` withDBLayerFromCopiedFile :: forall k s a. ( PersistAddressBook s , PersistPrivateKey (k 'RootK) , WalletKey k , s ~ SeqState 'Mainnet k ) => FilePath ^ Filename of the @.sqlite@ file to load . -> (DBLayer IO s k -> IO a) -> IO ([WalletDBLog], a) withDBLayerFromCopiedFile dbName action = withinCopiedFile dbName $ \path tr-> withDBLayer tr defaultFieldValues path dummyTimeInterpreter action withinCopiedFile :: FilePath -> (FilePath -> Tracer IO msg -> IO a) -> IO ([msg], a) withinCopiedFile dbName action = do let orig = $(getTestData) </> dbName withSystemTempDirectory "migration-db" $ \dir -> do let path = dir </> "db.sqlite" copyFile orig path captureLogging $ action path testMigrationTxMetaFee :: String -> Int -> [(Hash "Tx", Coin)] -> IO () testMigrationTxMetaFee dbName expectedLength caseByCase = do (logs, result) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readTransactions wid Nothing Descending wholeRange Nothing length (filter isMsgManualMigration logs) `shouldBe` 1 length result `shouldBe` expectedLength forM_ result $ \TransactionInfo{txInfoFee,txInfoMeta} -> do case txInfoMeta ^. #direction of Incoming -> txInfoFee `shouldSatisfy` isNothing Outgoing -> txInfoFee `shouldSatisfy` isJust forM_ caseByCase $ \(txid, expectedFee) -> do case L.find ((== txid) . txInfoId) result of Nothing -> fail $ "tx not found: " <> T.unpack (toText txid) Just TransactionInfo{txInfoFee} -> txInfoFee `shouldBe` Just expectedFee where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.TxMetaFee in fieldName field == unFieldNameDB fieldInDB matchMsgManualMigration :: (DBField -> Bool) -> WalletDBLog -> Bool matchMsgManualMigration p = \case MsgDB (MsgManualMigrationNeeded field _) -> p field MsgDB (MsgExpectedMigration (MsgManualMigrationNeeded field _)) -> p field _ -> False testMigrationCleanupCheckpoints :: FilePath -> GenesisParameters -> BlockHeader -> IO () testMigrationCleanupCheckpoints dbName genesisParameters tip = do (logs, result) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets (,) <$> readGenesisParameters wid <*> readCheckpoint wid length (filter (isMsgManualMigration fieldGenesisHash) logs) `shouldBe` 1 length (filter (isMsgManualMigration fieldGenesisStart) logs) `shouldBe` 1 (fst result) `shouldBe` Just genesisParameters (currentTip <$> snd result) `shouldBe` Just tip where fieldGenesisHash = fieldDB $ persistFieldDef DB.WalGenesisHash fieldGenesisStart = fieldDB $ persistFieldDef DB.WalGenesisStart isMsgManualMigration :: FieldNameDB -> WalletDBLog -> Bool isMsgManualMigration fieldInDB = matchMsgManualMigration $ \field -> fieldName field == unFieldNameDB fieldInDB testMigrationRole :: String -> IO () testMigrationRole dbName = do (logs, Just cp) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readCheckpoint wid let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 3 length (knownAddresses $ getState cp) `shouldBe` 71 where isMsgManualMigration :: WalletDBLog -> Bool isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.SeqStateAddressRole in fieldName field == unFieldNameDB fieldInDB testMigrationSeqStateDerivationPrefix :: forall k s. ( s ~ SeqState 'Mainnet k , WalletKey k , PersistAddressBook s , PersistPrivateKey (k 'RootK) , Show s ) => String -> ( Index 'Hardened 'PurposeK , Index 'Hardened 'CoinTypeK , Index 'Hardened 'AccountK ) -> IO () testMigrationSeqStateDerivationPrefix dbName prefix = do (logs, Just cp) <- withDBLayerFromCopiedFile @k @s dbName $ \DBLayer{..} -> atomically $ do [wid] <- listWallets readCheckpoint wid let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 1 derivationPrefix (getState cp) `shouldBe` DerivationPrefix prefix where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.SeqStateDerivationPrefix in fieldName field == unFieldNameDB fieldInDB testMigrationPassphraseScheme :: FilePath -> IO () testMigrationPassphraseScheme dbName = do (logs, (a,b,c,d)) <- withDBLayerFromCopiedFile @ShelleyKey dbName $ \DBLayer{..} -> atomically $ do Just a <- readWalletMeta walNeedMigration Just b <- readWalletMeta walNewScheme Just c <- readWalletMeta walOldScheme Just d <- readWalletMeta walNoPassphrase pure (fst a, fst b, fst c, fst d) let migrationMsg = filter isMsgManualMigration logs length migrationMsg `shouldBe` 1 The first wallet is stored in the database with only a (passphraseScheme <$> passphraseInfo a) `shouldBe` Just EncryptWithPBKDF2 The second wallet was just fine and already has a passphrase (passphraseScheme <$> passphraseInfo b) `shouldBe` Just EncryptWithPBKDF2 The third wallet had a scheme too , but was using the legacy (passphraseScheme <$> passphraseInfo c) `shouldBe` Just EncryptWithScrypt (passphraseScheme <$> passphraseInfo d) `shouldBe` Nothing where isMsgManualMigration = matchMsgManualMigration $ \field -> let fieldInDB = fieldDB $ persistFieldDef DB.WalPassphraseScheme in fieldName field == unFieldNameDB fieldInDB sqlite3 > SELECT wallet_id , passphrase_last_updated_at , passphrase_scheme FROM wallet ; 64581f7393190aed462fc3180ce52c3c1fe580a9 | 2020 - 06 - 02T14:22:17.48678659 | 5e481f55084afda69fc9cd3863ced80fa83734aa | 2020 - 06 - 02T14:22:03.234087113 | EncryptWithPBKDF2 4a6279cd71d5993a288b2c5879daa7c42cebb73d | 2020 - 06 - 02T14:21:45.418841818 | EncryptWithScrypt Right walNeedMigration = fromText "64581f7393190aed462fc3180ce52c3c1fe580a9" Right walNewScheme = fromText "5e481f55084afda69fc9cd3863ced80fa83734aa" Right walOldScheme = fromText "4a6279cd71d5993a288b2c5879daa7c42cebb73d" Right walNoPassphrase = fromText "ba74a7d2c1157ea7f32a93f255dac30e9ebca62b" testCreateMetadataTable :: forall s k. (k ~ ShelleyKey, s ~ SeqState 'Mainnet k) => IO () testCreateMetadataTable = withSystemTempFile "db.sql" $ \path _ -> do let noop _ = pure () tr = nullTracer withDBLayer @s @k tr defaultFieldValues path dummyTimeInterpreter noop actualVersion <- Sqlite.runSqlite (T.pack path) $ do [Sqlite.Single (version :: Int)] <- Sqlite.rawSql "SELECT version FROM database_schema_version \ \WHERE name = 'schema'" [] pure $ SchemaVersion $ fromIntegral version actualVersion `shouldBe` currentSchemaVersion testNewerDatabaseIsNeverModified :: forall s k. (k ~ ShelleyKey, s ~ SeqState 'Mainnet k) => IO () testNewerDatabaseIsNeverModified = withSystemTempFile "db.sql" $ \path _ -> do let newerVersion = SchemaVersion 100 _ <- Sqlite.runSqlite (T.pack path) $ do Sqlite.rawExecute "CREATE TABLE database_schema_version (name, version)" [] Sqlite.rawExecute ( "INSERT INTO database_schema_version \ \VALUES ('schema', " <> T.pack (show newerVersion) <> ")" ) [] let noop _ = pure () tr = nullTracer withDBLayer @s @k tr defaultFieldValues path dummyTimeInterpreter noop `shouldThrow` \case InvalidDatabaseSchemaVersion {..} | expectedVersion == currentSchemaVersion && actualVersion == newerVersion -> True _ -> False localTxSubmissionTableExists :: Text localTxSubmissionTableExists = [i| SELECT EXISTS ( SELECT name FROM sqlite_schema WHERE type='table' AND name='local_tx_submission' ); |] testMigrationSubmissionsEncoding :: FilePath -> IO () testMigrationSubmissionsEncoding dbName = do let performMigrations path = withDBLayer @(SeqState 'Mainnet ShelleyKey) @ShelleyKey nullTracer defaultFieldValues path dummyTimeInterpreter $ \_ -> pure () testOnCopiedAndMigrated test = fmap snd $ withinCopiedFile dbName $ \path _ -> do performMigrations path test path testOnCopiedAndMigrated testAllPresentTxIdsAreInLedger testOnCopiedAndMigrated allTransactionDataIsRepresentedInTxMeta testOnCopiedAndMigrated testLocalTxSubmissionIsMissing where testLocalTxSubmissionIsMissing path = do [Single (count :: Int)] <- Sqlite.runSqlite (T.pack path) $ Sqlite.rawSql localTxSubmissionTableExists [] count `shouldBe` 0 pure () allTransactionDataIsRepresentedInTxMeta path = do let idOf = unSingle @DB.TxId selectIds t = fmap idOf <$> Sqlite.rawSql ("SELECT tx_id FROM " <> t) [] runQuery = Sqlite.runSqlite (T.pack path) shouldBe' mtxs t = do txs <- runQuery $ selectIds t liftIO $ Set.fromList txs `shouldSatisfy` \x -> x `Set.isSubsetOf` (Set.fromList mtxs) metaIds <- runQuery $ selectIds "tx_meta" mapM_ (shouldBe' metaIds) [ "tx_in" , "tx_collateral" , "tx_out" , "tx_out_token" , "tx_collateral_out" , "tx_collateral_out_token" , "tx_withdrawal" , "c_b_o_r" ] testAllPresentTxIdsAreInLedger path = do metas <- Sqlite.runSqlite (T.pack path) $ Sqlite.rawSql "SELECT status FROM tx_meta" [] forM_ metas $ \(Single status) -> status `shouldBe` ("in_ledger" :: Text) coinToBundle :: Word64 -> TokenBundle coinToBundle = TokenBundle.fromCoin . Coin.fromWord64 testCp :: Wallet (SeqState 'Mainnet ShelleyKey) testCp = snd $ initWallet block0 initDummyState where initDummyState :: SeqState 'Mainnet ShelleyKey initDummyState = mkSeqStateFromRootXPrv (xprv, mempty) purposeCIP1852 defaultAddressPoolGap where mw = SomeMnemonic . unsafePerformIO . generate $ genMnemonic @15 xprv = generateKeyFromSeed (mw, Nothing) mempty testMetadata :: WalletMetadata testMetadata = WalletMetadata { name = WalletName "test wallet" , creationTime = unsafePerformIO getCurrentTime , passphraseInfo = Nothing } testWid :: WalletId testWid = WalletId (hash ("test" :: ByteString)) testTxs :: [(Tx, TxMeta)] testTxs = [ (tx1, meta1), (tx2, meta2) ] where tx1 = Tx { txId = mockHash @String "tx2" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (mockHash @String "tx1") 0 , Nothing ) ] , resolvedCollateralInputs = [] , outputs = [TxOut (Address "addr1") (coinToBundle 10)] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } meta1 = TxMeta { status = InLedger , direction = Incoming , slotNo = SlotNo 140 , blockHeight = Quantity 0 , amount = Coin 1_337_144 , expiry = Nothing } tx2 = Tx { txId = mockHash @String "tx3" , txCBOR = Nothing , fee = Nothing , resolvedInputs = [ ( TxIn (mockHash @String "tx2") 0 , headMay $ tx1 ^. #outputs ) ] , resolvedCollateralInputs = [] , outputs = [ TxOut (Address "addr2") (coinToBundle 5) , TxOut (Address "addr3") (coinToBundle 5) ] , collateralOutput = Nothing , withdrawals = mempty , metadata = Nothing , scriptValidity = Nothing } meta2 = TxMeta { status = InLedger , direction = Incoming , slotNo = SlotNo 150 , blockHeight = Quantity 0 , amount = Coin 10 , expiry = Nothing } gp :: GenesisParameters gp = dummyGenesisParameters getAvailableBalance :: DBLayer IO s k -> IO Natural getAvailableBalance DBLayer{..} = do cp <- fmap (fromMaybe (error "nothing")) <$> atomically $ readCheckpoint testWid pend <- atomically $ fmap toTxHistory <$> readTransactions testWid Nothing Descending wholeRange (Just Pending) return $ fromIntegral $ unCoin $ TokenBundle.getCoin $ availableBalance (Set.fromList $ map fst pend) cp getTxsInLedger :: DBLayer IO s k -> IO ([(Direction, Natural)]) getTxsInLedger DBLayer {..} = do pend <- atomically $ fmap toTxHistory <$> readTransactions testWid Nothing Descending wholeRange (Just InLedger) pure $ map (\(_, m) -> (direction m, fromIntegral $ unCoin $ amount m)) pend testCpSeq :: Wallet (SeqState 'Mainnet ShelleyKey) testCpSeq = snd $ initWallet block0 initDummyStateSeq initDummyStateSeq :: SeqState 'Mainnet ShelleyKey initDummyStateSeq = mkSeqStateFromRootXPrv (xprv, mempty) purposeCIP1852 defaultAddressPoolGap where mw = SomeMnemonic $ unsafePerformIO (generate $ genMnemonic @15) xprv = Seq.generateKeyFromSeed (mw, Nothing) mempty
19a7df2246a378b5fa3a85f351f58853a39ae64a24ada061b623c338383d72e0
mokus0/junkbox
Quine2a.hs
quine s = do putStr s print s main = quine "quine s = do\n putStr s\n print s\nmain = quine "
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/quine/Quine2a.hs
haskell
quine s = do putStr s print s main = quine "quine s = do\n putStr s\n print s\nmain = quine "
3dc503998bdfc53fec1be3bb1849de47a813b87b9ce0db8fe68652958db152fb
thi-ng/geom
colored_cube.cljs
(ns thi.ng.geom.examples.gl.colored-cube (:require-macros [thi.ng.math.macros :as mm]) (:require [thi.ng.math.core :as m :refer [PI HALF_PI TWO_PI]] [thi.ng.color.core :as col] [thi.ng.typedarrays.core :as arrays] [thi.ng.geom.gl.core :as gl] [thi.ng.geom.gl.webgl.constants :as glc] [thi.ng.geom.gl.webgl.animator :as anim] [thi.ng.geom.gl.buffers :as buf] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.utils :as glu] [thi.ng.geom.gl.glmesh :as glm] [thi.ng.geom.gl.camera :as cam] [thi.ng.geom.core :as g] [thi.ng.geom.vector :as v :refer [vec2 vec3]] [thi.ng.geom.matrix :as mat :refer [M44]] [thi.ng.geom.aabb :as a] [thi.ng.geom.attribs :as attr] [thi.ng.glsl.core :as glsl :include-macros true] [thi.ng.geom.gl.shaders.basic :as basic])) (defn ^:export demo [] (let [gl (gl/gl-context "main") view-rect (gl/get-viewport-rect gl) model (-> (a/aabb 0.8) (g/center) (g/as-mesh {:mesh (glm/indexed-gl-mesh 12 #{:col}) :attribs {:col (->> [[1 0 0] [0 1 0] [0 0 1] [0 1 1] [1 0 1] [1 1 0]] (map col/rgba) (attr/const-face-attribs))}}) (gl/as-gl-buffer-spec {}) (cam/apply (cam/perspective-camera {:aspect view-rect})) (assoc :shader (sh/make-shader-from-spec gl (basic/make-shader-spec-3d true))) (gl/make-buffers-in-spec gl glc/static-draw))] (anim/animate (fn [t frame] (doto gl (gl/set-viewport view-rect) (gl/clear-color-and-depth-buffer col/WHITE 1) (gl/enable glc/depth-test) (gl/draw-with-shader (assoc-in model [:uniforms :model] (-> M44 (g/rotate-x t) (g/rotate-y (* t 2)))))) true))))
null
https://raw.githubusercontent.com/thi-ng/geom/85783a1f87670c5821473298fa0b491bd40c3028/examples/gl/colored_cube.cljs
clojure
(ns thi.ng.geom.examples.gl.colored-cube (:require-macros [thi.ng.math.macros :as mm]) (:require [thi.ng.math.core :as m :refer [PI HALF_PI TWO_PI]] [thi.ng.color.core :as col] [thi.ng.typedarrays.core :as arrays] [thi.ng.geom.gl.core :as gl] [thi.ng.geom.gl.webgl.constants :as glc] [thi.ng.geom.gl.webgl.animator :as anim] [thi.ng.geom.gl.buffers :as buf] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.utils :as glu] [thi.ng.geom.gl.glmesh :as glm] [thi.ng.geom.gl.camera :as cam] [thi.ng.geom.core :as g] [thi.ng.geom.vector :as v :refer [vec2 vec3]] [thi.ng.geom.matrix :as mat :refer [M44]] [thi.ng.geom.aabb :as a] [thi.ng.geom.attribs :as attr] [thi.ng.glsl.core :as glsl :include-macros true] [thi.ng.geom.gl.shaders.basic :as basic])) (defn ^:export demo [] (let [gl (gl/gl-context "main") view-rect (gl/get-viewport-rect gl) model (-> (a/aabb 0.8) (g/center) (g/as-mesh {:mesh (glm/indexed-gl-mesh 12 #{:col}) :attribs {:col (->> [[1 0 0] [0 1 0] [0 0 1] [0 1 1] [1 0 1] [1 1 0]] (map col/rgba) (attr/const-face-attribs))}}) (gl/as-gl-buffer-spec {}) (cam/apply (cam/perspective-camera {:aspect view-rect})) (assoc :shader (sh/make-shader-from-spec gl (basic/make-shader-spec-3d true))) (gl/make-buffers-in-spec gl glc/static-draw))] (anim/animate (fn [t frame] (doto gl (gl/set-viewport view-rect) (gl/clear-color-and-depth-buffer col/WHITE 1) (gl/enable glc/depth-test) (gl/draw-with-shader (assoc-in model [:uniforms :model] (-> M44 (g/rotate-x t) (g/rotate-y (* t 2)))))) true))))
05d0a1367f5ab29330321552876993bd9b4d75724e874a8b34e4bbb8a6223acb
iskandr/parakeet-retired
HostMemspace.ml
open Ptr external c_malloc_impl : int -> Int64.t = "ocaml_malloc" exception HostOutOfMemory let malloc nbytes = let ptr = c_malloc_impl nbytes in if ptr = Int64.zero then raise HostOutOfMemory else ptr external free : Int64.t -> unit = "ocaml_free" external memcpy : Int64.t -> Int64.t -> int -> unit = "ocaml_memcpy" external get_array1_ptr : ('a,'b,'c) Bigarray.Array1.t -> Int64.t = "get_bigarray_ptr" external get_array2_ptr : ('a,'b,'c) Bigarray.Array2.t -> Int64.t = "get_bigarray_ptr" external get_array3_ptr : ('a,'b,'c) Bigarray.Array3.t -> Int64.t = "get_bigarray_ptr" external get_int32 : Int64.t -> int -> Int32.t = "ocaml_get_int32" external set_int32 : Int64.t -> int -> Int32.t -> unit = "ocaml_set_int32" external get_int64 : Int64.t -> int -> Int64.t = "ocaml_get_int64" external set_int64 : Int64.t -> int -> Int64.t -> unit = "ocaml_set_int64" external get_float32 : Int64.t -> int -> float = "ocaml_get_float" external set_float32 : Int64.t -> int -> float -> unit = "ocaml_set_float" external get_float64 : Int64.t -> int -> float = "ocaml_get_double" external set_float64 : Int64.t -> int -> float -> unit = "ocaml_set_double" external get_char : Int64.t -> int -> char = "ocaml_get_char" external set_char : Int64.t -> int -> char -> unit = "ocaml_set_char" let get_bool p offset = Char.code (get_char p offset) > 0 let set_bool p offset b = set_char p offset (Char.chr (if b then 1 else 0)) let get_ptr_to_index (addr:Int64.t) (eltT:Type.elt_t) (index:int) : Int64.t = let elt_size = Type.sizeof eltT in let offset = Int64.of_int(elt_size * index) in Int64.add addr offset let deref_scalar (addr:Int64.t) (eltT:Type.elt_t) : ParNum.t = match eltT with | Type.BoolT -> ParNum.Bool (get_bool addr 0) | Type.CharT -> ParNum.Char (get_char addr 0) | Type.Int16T -> assert false | Type.Int32T -> ParNum.Int32 (get_int32 addr 0) | Type.Int64T -> ParNum.Int64 (get_int64 addr 0) | Type.Float32T -> ParNum.Float32 (get_float32 addr 0) | Type.Float64T -> ParNum.Float64 (get_float64 addr 0) let set_scalar (addr:Int64.t) = function | ParNum.Bool b -> set_bool addr 0 b | ParNum.Char c -> set_char addr 0 c | ParNum.Int16 _ -> assert false | ParNum.Int32 i32 -> set_int32 addr 0 i32 | ParNum.Int64 i64 -> set_int64 addr 0 i64 | ParNum.Float32 f -> set_float32 addr 0 f | ParNum.Float64 f -> set_float64 addr 0 f let fns : Ptr.raw_fns = { Ptr.alloc = malloc; delete = free; get_bool = get_bool; get_char = get_char; get_int32 = get_int32; get_int64 = get_int64; get_float32 = get_float32; get_float64 = get_float64; } let id = Mem.register "host" fns let mk_host_ptr ptr size = {addr=ptr; size=size; memspace=id; fns=fns}
null
https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/Runtime/Memory/HostMemspace.ml
ocaml
open Ptr external c_malloc_impl : int -> Int64.t = "ocaml_malloc" exception HostOutOfMemory let malloc nbytes = let ptr = c_malloc_impl nbytes in if ptr = Int64.zero then raise HostOutOfMemory else ptr external free : Int64.t -> unit = "ocaml_free" external memcpy : Int64.t -> Int64.t -> int -> unit = "ocaml_memcpy" external get_array1_ptr : ('a,'b,'c) Bigarray.Array1.t -> Int64.t = "get_bigarray_ptr" external get_array2_ptr : ('a,'b,'c) Bigarray.Array2.t -> Int64.t = "get_bigarray_ptr" external get_array3_ptr : ('a,'b,'c) Bigarray.Array3.t -> Int64.t = "get_bigarray_ptr" external get_int32 : Int64.t -> int -> Int32.t = "ocaml_get_int32" external set_int32 : Int64.t -> int -> Int32.t -> unit = "ocaml_set_int32" external get_int64 : Int64.t -> int -> Int64.t = "ocaml_get_int64" external set_int64 : Int64.t -> int -> Int64.t -> unit = "ocaml_set_int64" external get_float32 : Int64.t -> int -> float = "ocaml_get_float" external set_float32 : Int64.t -> int -> float -> unit = "ocaml_set_float" external get_float64 : Int64.t -> int -> float = "ocaml_get_double" external set_float64 : Int64.t -> int -> float -> unit = "ocaml_set_double" external get_char : Int64.t -> int -> char = "ocaml_get_char" external set_char : Int64.t -> int -> char -> unit = "ocaml_set_char" let get_bool p offset = Char.code (get_char p offset) > 0 let set_bool p offset b = set_char p offset (Char.chr (if b then 1 else 0)) let get_ptr_to_index (addr:Int64.t) (eltT:Type.elt_t) (index:int) : Int64.t = let elt_size = Type.sizeof eltT in let offset = Int64.of_int(elt_size * index) in Int64.add addr offset let deref_scalar (addr:Int64.t) (eltT:Type.elt_t) : ParNum.t = match eltT with | Type.BoolT -> ParNum.Bool (get_bool addr 0) | Type.CharT -> ParNum.Char (get_char addr 0) | Type.Int16T -> assert false | Type.Int32T -> ParNum.Int32 (get_int32 addr 0) | Type.Int64T -> ParNum.Int64 (get_int64 addr 0) | Type.Float32T -> ParNum.Float32 (get_float32 addr 0) | Type.Float64T -> ParNum.Float64 (get_float64 addr 0) let set_scalar (addr:Int64.t) = function | ParNum.Bool b -> set_bool addr 0 b | ParNum.Char c -> set_char addr 0 c | ParNum.Int16 _ -> assert false | ParNum.Int32 i32 -> set_int32 addr 0 i32 | ParNum.Int64 i64 -> set_int64 addr 0 i64 | ParNum.Float32 f -> set_float32 addr 0 f | ParNum.Float64 f -> set_float64 addr 0 f let fns : Ptr.raw_fns = { Ptr.alloc = malloc; delete = free; get_bool = get_bool; get_char = get_char; get_int32 = get_int32; get_int64 = get_int64; get_float32 = get_float32; get_float64 = get_float64; } let id = Mem.register "host" fns let mk_host_ptr ptr size = {addr=ptr; size=size; memspace=id; fns=fns}
67cb60d3319bf510b9fe50a8eafa332c1e17ba741b8a29b9b6b24b9ebf2160f4
fujita-y/ypsilon
lists.scm
#!nobacktrace (library (rnrs lists (6)) (export find for-all exists filter partition fold-left fold-right remp remove remv remq memp member memv memq assp assoc assv assq cons*) (import (core lists)))
null
https://raw.githubusercontent.com/fujita-y/ypsilon/f742470e2810aabb7a7c898fd6c07227c14a725f/sitelib/rnrs/lists.scm
scheme
#!nobacktrace (library (rnrs lists (6)) (export find for-all exists filter partition fold-left fold-right remp remove remv remq memp member memv memq assp assoc assv assq cons*) (import (core lists)))
72ca59848b8cb5cf8ed828de4112e64a7454548c9ec1c0c4c4e0cb02308521ac
hjcapple/reading-sicp
exercise_3_26.scm
#lang sicp P187 - [ 练习 3.26 ] 树的递归查找和插入,跟 [ 练习 2.66 ] 相似。但有几个地方不同 1 . 将 key value left right 放在一起,省去中间的 entry 。 2 . make - table 中 添加了 compare - key 过程作为参数,可以定制比较函数 。 3 . insert - tree ! 4 . make - table 。 (define (make-tree key value left right) (cons (cons key value) (cons left right))) (define (tree-key t) (car (car t))) (define (tree-value t) (cdr (car t))) (define (tree-left-branch t) (car (cdr t))) (define (tree-right-branch t) (cdr (cdr t))) (define (set-tree-value! t value) (set-cdr! (car t) value)) (define (set-tree-left-branch! t left) (set-car! (cdr t) left)) (define (set-tree-right-branch! t right) (set-cdr! (cdr t) right)) (define (make-table compare-key) (let ((local-tree '())) (define (lookup-tree key tree) (if (null? tree) false (let ((compare-result (compare-key key (tree-key tree)))) (cond ((eq? '= compare-result) (tree-value tree)) ((eq? '< compare-result) (lookup-tree key (tree-left-branch tree))) ((eq? '> compare-result) (lookup-tree key (tree-right-branch tree))))))) (define (insert-tree! key value tree) (if (null? tree) (make-tree key value '() '()) (let ((compare-result (compare-key key (tree-key tree)))) (cond ((eq? '= compare-result) (set-tree-value! tree value)) ((eq? '< compare-result) (set-tree-left-branch! tree (insert-tree! key value (tree-left-branch tree)))) ((eq? '> compare-result) (set-tree-right-branch! tree (insert-tree! key value (tree-right-branch tree))))) tree))) (define (lookup key) (lookup-tree key local-tree)) (define (insert! key value) (set! local-tree (insert-tree! key value local-tree))) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define (insert! key value t) ((t 'insert-proc!) key value)) (define (lookup key t) ((t 'lookup-proc) key)) ;;;;;;;;;;;;;;;;;;;;; (define (compare-number x y) (cond ((= x y) '=) ((> x y) '>) ((< x y) '<))) (define t (make-table compare-number)) (for-each (lambda (pair) (insert! (car pair) (cdr pair) t)) '((1 "Yellow") (3 "Red") (9 "Green") (4 "White") (2 "Blue"))) (lookup 9 t) (lookup 10 t) (lookup 4 t) (insert! 4 "Black" t) (lookup 4 t)
null
https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_3/exercise_3_26.scm
scheme
#lang sicp P187 - [ 练习 3.26 ] 树的递归查找和插入,跟 [ 练习 2.66 ] 相似。但有几个地方不同 1 . 将 key value left right 放在一起,省去中间的 entry 。 2 . make - table 中 添加了 compare - key 过程作为参数,可以定制比较函数 。 3 . insert - tree ! 4 . make - table 。 (define (make-tree key value left right) (cons (cons key value) (cons left right))) (define (tree-key t) (car (car t))) (define (tree-value t) (cdr (car t))) (define (tree-left-branch t) (car (cdr t))) (define (tree-right-branch t) (cdr (cdr t))) (define (set-tree-value! t value) (set-cdr! (car t) value)) (define (set-tree-left-branch! t left) (set-car! (cdr t) left)) (define (set-tree-right-branch! t right) (set-cdr! (cdr t) right)) (define (make-table compare-key) (let ((local-tree '())) (define (lookup-tree key tree) (if (null? tree) false (let ((compare-result (compare-key key (tree-key tree)))) (cond ((eq? '= compare-result) (tree-value tree)) ((eq? '< compare-result) (lookup-tree key (tree-left-branch tree))) ((eq? '> compare-result) (lookup-tree key (tree-right-branch tree))))))) (define (insert-tree! key value tree) (if (null? tree) (make-tree key value '() '()) (let ((compare-result (compare-key key (tree-key tree)))) (cond ((eq? '= compare-result) (set-tree-value! tree value)) ((eq? '< compare-result) (set-tree-left-branch! tree (insert-tree! key value (tree-left-branch tree)))) ((eq? '> compare-result) (set-tree-right-branch! tree (insert-tree! key value (tree-right-branch tree))))) tree))) (define (lookup key) (lookup-tree key local-tree)) (define (insert! key value) (set! local-tree (insert-tree! key value local-tree))) (define (dispatch m) (cond ((eq? m 'lookup-proc) lookup) ((eq? m 'insert-proc!) insert!) (else (error "Unknown operation -- TABLE" m)))) dispatch)) (define (insert! key value t) ((t 'insert-proc!) key value)) (define (lookup key t) ((t 'lookup-proc) key)) (define (compare-number x y) (cond ((= x y) '=) ((> x y) '>) ((< x y) '<))) (define t (make-table compare-number)) (for-each (lambda (pair) (insert! (car pair) (cdr pair) t)) '((1 "Yellow") (3 "Red") (9 "Green") (4 "White") (2 "Blue"))) (lookup 9 t) (lookup 10 t) (lookup 4 t) (insert! 4 "Black" t) (lookup 4 t)
ecc13a190519289214dea07782e9717c90aaf1a2ac45d25c830dd855138d0c92
hsyl20/haskus-system
SymLink.hs
# LANGUAGE DataKinds # # LANGUAGE LambdaCase # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE TypeApplications # # LANGUAGE FlexibleContexts # -- | Symbolic links module Haskus.System.Linux.FileSystem.SymLink ( sysSymlink , ReadSymLinkErrors , readSymbolicLink ) where import Haskus.System.Linux.Error import Haskus.System.Linux.ErrorCode import Haskus.System.Linux.Handle import Haskus.System.Linux.Syscalls import Haskus.Format.String import Haskus.Format.Binary.Storable import Haskus.Utils.Flow type ReadSymLinkErrors = '[ NotAllowed , NotSymbolicLink , FileSystemIOError , SymbolicLinkLoop , TooLongPathName , FileNotFound , OutOfKernelMemory , InvalidPathComponent ] -- | Read the path in a symbolic link readSymbolicLink :: MonadInIO m => Maybe Handle -> FilePath -> Excepts ReadSymLinkErrors m String readSymbolicLink hdl path = do sysReadLinkAt hdl path `catchLiftLeft` \case EACCES -> throwE NotAllowed EINVAL -> throwE NotSymbolicLink EIO -> throwE FileSystemIOError ELOOP -> throwE SymbolicLinkLoop ENAMETOOLONG -> throwE TooLongPathName ENOENT -> throwE FileNotFound ENOMEM -> throwE OutOfKernelMemory ENOTDIR -> throwE InvalidPathComponent EBADF -> error "readSymbolicLink: invalid handle" : should n't happen ( or is a haskus - system bug ) e -> unhdlErr "readSymbolicLink" e -- | Wrapper for readlinkat syscall sysReadLinkAt :: MonadInIO m => Maybe Handle -> FilePath -> Excepts '[ErrorCode] m String sysReadLinkAt hdl path = tryReadLinkAt 2048 where -- if no handle is passed, we assume the path is absolute and we give a -- (-1) file descriptor which should be ignored. If the path is relative, hopefully we will get a EBADF error fd = case hdl of Just (Handle x) -> x Nothing -> maxBound -- allocate a buffer and try to readlinkat. tryReadLinkAt size = do mv <- allocaBytes size $ \ptr -> withCString path $ \path' -> do n <- checkErrorCode =<< liftIO (syscall_readlinkat fd path' ptr (fromIntegral size)) if fromIntegral n == size then return Nothing else Just <$> peekCStringLen (fromIntegral n) ptr case mv of Nothing -> tryReadLinkAt (2*size) -- retry with double buffer size Just v -> return v -- | Create a symbolic link sysSymlink :: MonadInIO m => FilePath -> FilePath -> Excepts '[ErrorCode] m () sysSymlink src dest = withCString src $ \src' -> withCString dest $ \dest' -> checkErrorCode_ =<< liftIO (syscall_symlink src' dest')
null
https://raw.githubusercontent.com/hsyl20/haskus-system/2f389c6ecae5b0180b464ddef51e36f6e567d690/haskus-system/src/lib/Haskus/System/Linux/FileSystem/SymLink.hs
haskell
| Symbolic links | Read the path in a symbolic link | Wrapper for readlinkat syscall if no handle is passed, we assume the path is absolute and we give a (-1) file descriptor which should be ignored. If the path is relative, allocate a buffer and try to readlinkat. retry with double buffer size | Create a symbolic link
# LANGUAGE DataKinds # # LANGUAGE LambdaCase # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE TypeApplications # # LANGUAGE FlexibleContexts # module Haskus.System.Linux.FileSystem.SymLink ( sysSymlink , ReadSymLinkErrors , readSymbolicLink ) where import Haskus.System.Linux.Error import Haskus.System.Linux.ErrorCode import Haskus.System.Linux.Handle import Haskus.System.Linux.Syscalls import Haskus.Format.String import Haskus.Format.Binary.Storable import Haskus.Utils.Flow type ReadSymLinkErrors = '[ NotAllowed , NotSymbolicLink , FileSystemIOError , SymbolicLinkLoop , TooLongPathName , FileNotFound , OutOfKernelMemory , InvalidPathComponent ] readSymbolicLink :: MonadInIO m => Maybe Handle -> FilePath -> Excepts ReadSymLinkErrors m String readSymbolicLink hdl path = do sysReadLinkAt hdl path `catchLiftLeft` \case EACCES -> throwE NotAllowed EINVAL -> throwE NotSymbolicLink EIO -> throwE FileSystemIOError ELOOP -> throwE SymbolicLinkLoop ENAMETOOLONG -> throwE TooLongPathName ENOENT -> throwE FileNotFound ENOMEM -> throwE OutOfKernelMemory ENOTDIR -> throwE InvalidPathComponent EBADF -> error "readSymbolicLink: invalid handle" : should n't happen ( or is a haskus - system bug ) e -> unhdlErr "readSymbolicLink" e sysReadLinkAt :: MonadInIO m => Maybe Handle -> FilePath -> Excepts '[ErrorCode] m String sysReadLinkAt hdl path = tryReadLinkAt 2048 where hopefully we will get a EBADF error fd = case hdl of Just (Handle x) -> x Nothing -> maxBound tryReadLinkAt size = do mv <- allocaBytes size $ \ptr -> withCString path $ \path' -> do n <- checkErrorCode =<< liftIO (syscall_readlinkat fd path' ptr (fromIntegral size)) if fromIntegral n == size then return Nothing else Just <$> peekCStringLen (fromIntegral n) ptr case mv of Just v -> return v sysSymlink :: MonadInIO m => FilePath -> FilePath -> Excepts '[ErrorCode] m () sysSymlink src dest = withCString src $ \src' -> withCString dest $ \dest' -> checkErrorCode_ =<< liftIO (syscall_symlink src' dest')
dc29f233dac68a95016dcd9aba81f037d34f428a8208321bfe93a303b7ec6336
lpw25/prof_spacetime
serve.mli
val serve : address:string -> port:int -> title:string -> Series.t -> unit
null
https://raw.githubusercontent.com/lpw25/prof_spacetime/bb17f61a54b530eaed30dab5759d6d0c2a9d083c/src/serve.mli
ocaml
val serve : address:string -> port:int -> title:string -> Series.t -> unit
6a13751f12d7bd53d43bdb1165e444effe85f5480453f65b96cc3034e69e07de
haskell-numerics/hmatrix
LAPACK.hs
# LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - missing - signatures # ----------------------------------------------------------------------------- -- | Module : Numeric . LinearAlgebra . LAPACK Copyright : ( c ) 2006 - 14 -- License : BSD3 Maintainer : -- Stability : provisional -- Functional interface to selected LAPACK functions ( < > ) . -- ----------------------------------------------------------------------------- module Internal.LAPACK where import Data.Bifunctor (first) import Internal.Devel import Internal.Vector import Internal.Matrix hiding ((#), (#!)) import Internal.Conversion import Internal.Element import Foreign.Ptr(nullPtr) import Foreign.C.Types import Control.Monad(when) import System.IO.Unsafe(unsafePerformIO) ----------------------------------------------------------------------------------- infixr 1 # a # b = apply a b # INLINE ( # ) # a #! b = a # b # id # INLINE ( # ! ) # ----------------------------------------------------------------------------------- type TMMM t = t ::> t ::> t ::> Ok type F = Float type Q = Complex Float foreign import ccall unsafe "multiplyR" dgemmc :: CInt -> CInt -> TMMM R foreign import ccall unsafe "multiplyC" zgemmc :: CInt -> CInt -> TMMM C foreign import ccall unsafe "multiplyF" sgemmc :: CInt -> CInt -> TMMM F foreign import ccall unsafe "multiplyQ" cgemmc :: CInt -> CInt -> TMMM Q foreign import ccall unsafe "multiplyI" c_multiplyI :: I -> TMMM I foreign import ccall unsafe "multiplyL" c_multiplyL :: Z -> TMMM Z isT (rowOrder -> False) = 0 isT _ = 1 tt x@(rowOrder -> False) = x tt x = trans x multiplyAux f st a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ show (rows a,cols a) ++ " x " ++ show (rows b, cols b) s <- createMatrix ColumnMajor (rows a) (cols b) ((tt a) # (tt b) #! s) (f (isT a) (isT b)) #| st return s | Matrix product based on BLAS 's /dgemm/. multiplyR :: Matrix Double -> Matrix Double -> Matrix Double multiplyR a b = {-# SCC "multiplyR" #-} multiplyAux dgemmc "dgemmc" a b | Matrix product based on BLAS 's /zgemm/. multiplyC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) multiplyC a b = multiplyAux zgemmc "zgemmc" a b | Matrix product based on BLAS 's /sgemm/. multiplyF :: Matrix Float -> Matrix Float -> Matrix Float multiplyF a b = multiplyAux sgemmc "sgemmc" a b | Matrix product based on BLAS 's /cgemm/. multiplyQ :: Matrix (Complex Float) -> Matrix (Complex Float) -> Matrix (Complex Float) multiplyQ a b = multiplyAux cgemmc "cgemmc" a b multiplyI :: I -> Matrix CInt -> Matrix CInt -> Matrix CInt multiplyI m a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ shSize a ++ " x " ++ shSize b s <- createMatrix ColumnMajor (rows a) (cols b) (a # b #! s) (c_multiplyI m) #|"c_multiplyI" return s multiplyL :: Z -> Matrix Z -> Matrix Z -> Matrix Z multiplyL m a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ shSize a ++ " x " ++ shSize b s <- createMatrix ColumnMajor (rows a) (cols b) (a # b #! s) (c_multiplyL m) #|"c_multiplyL" return s ----------------------------------------------------------------------------- type TSVD t = t ::> t ::> R :> t ::> Ok foreign import ccall unsafe "svd_l_R" dgesvd :: TSVD R foreign import ccall unsafe "svd_l_C" zgesvd :: TSVD C foreign import ccall unsafe "svd_l_Rdd" dgesdd :: TSVD R foreign import ccall unsafe "svd_l_Cdd" zgesdd :: TSVD C | Full SVD of a real matrix using LAPACK 's /dgesvd/. svdR :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) svdR = svdAux dgesvd "svdR" | Full SVD of a real matrix using LAPACK 's /dgesdd/. svdRd :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) svdRd = svdAux dgesdd "svdRdd" | Full SVD of a complex matrix using LAPACK 's /zgesvd/. svdC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) svdC = svdAux zgesvd "svdC" | Full SVD of a complex matrix using LAPACK 's /zgesdd/. svdCd :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) svdCd = svdAux zgesdd "svdCdd" svdAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r r s <- createVector (min r c) v <- createMatrix ColumnMajor c c (a # u # s #! v) f #| st return (u,s,v) where r = rows x c = cols x | Thin SVD of a real matrix , using LAPACK 's /dgesvd/ with = = jobvt = = \'S\ ' . thinSVDR :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) thinSVDR = thinSVDAux dgesvd "thinSVDR" | Thin SVD of a complex matrix , using LAPACK 's /zgesvd/ with = = jobvt = = \'S\ ' . thinSVDC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) thinSVDC = thinSVDAux zgesvd "thinSVDC" | Thin SVD of a real matrix , using LAPACK 's /dgesdd/ with jobz = = \'S\ ' . thinSVDRd :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) thinSVDRd = thinSVDAux dgesdd "thinSVDRdd" | Thin SVD of a complex matrix , using LAPACK 's /zgesdd/ with jobz = = \'S\ ' . thinSVDCd :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) thinSVDCd = thinSVDAux zgesdd "thinSVDCdd" thinSVDAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r q s <- createVector q v <- createMatrix ColumnMajor q c (a # u # s #! v) f #| st return (u,s,v) where r = rows x c = cols x q = min r c | Singular values of a real matrix , using LAPACK 's /dgesvd/ with = = jobvt = = \'N\ ' . svR :: Matrix Double -> Vector Double svR = svAux dgesvd "svR" | Singular values of a complex matrix , using LAPACK 's /zgesvd/ with = = jobvt = = \'N\ ' . svC :: Matrix (Complex Double) -> Vector Double svC = svAux zgesvd "svC" | Singular values of a real matrix , using LAPACK 's /dgesdd/ with jobz = = \'N\ ' . svRd :: Matrix Double -> Vector Double svRd = svAux dgesdd "svRd" | Singular values of a complex matrix , using LAPACK 's /zgesdd/ with jobz = = \'N\ ' . svCd :: Matrix (Complex Double) -> Vector Double svCd = svAux zgesdd "svCd" svAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x s <- createVector q (a #! s) g #| st return s where r = rows x c = cols x q = min r c g ra ca xra xca pa nb pb = f ra ca xra xca pa 0 0 0 0 nullPtr nb pb 0 0 0 0 nullPtr | Singular values and all right singular vectors of a real matrix , using LAPACK 's /dgesvd/ with = = \'N\ ' and jobvt = = \'A\ ' . rightSVR :: Matrix Double -> (Vector Double, Matrix Double) rightSVR = rightSVAux dgesvd "rightSVR" | Singular values and all right singular vectors of a complex matrix , using LAPACK 's /zgesvd/ with = = \'N\ ' and jobvt = = \'A\ ' . rightSVC :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) rightSVC = rightSVAux zgesvd "rightSVC" rightSVAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x s <- createVector q v <- createMatrix ColumnMajor c c (a # s #! v) g #| st return (s,v) where r = rows x c = cols x q = min r c g ra ca xra xca pa = f ra ca xra xca pa 0 0 0 0 nullPtr | Singular values and all left singular vectors of a real matrix , using LAPACK 's /dgesvd/ with = = \'A\ ' and jobvt = = \'N\ ' . leftSVR :: Matrix Double -> (Matrix Double, Vector Double) leftSVR = leftSVAux dgesvd "leftSVR" | Singular values and all left singular vectors of a complex matrix , using LAPACK 's /zgesvd/ with = = \'A\ ' and jobvt = = \'N\ ' . leftSVC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double) leftSVC = leftSVAux zgesvd "leftSVC" leftSVAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r r s <- createVector q (a # u #! s) g #| st return (u,s) where r = rows x c = cols x q = min r c g ra ca xra xca pa ru cu xru xcu pu nb pb = f ra ca xra xca pa ru cu xru xcu pu nb pb 0 0 0 0 nullPtr ----------------------------------------------------------------------------- foreign import ccall unsafe "eig_l_R" dgeev :: R ::> R ::> C :> R ::> Ok foreign import ccall unsafe "eig_l_G" dggev :: R ::> R ::> C :> R :> R ::> R ::> Ok foreign import ccall unsafe "eig_l_C" zgeev :: C ::> C ::> C :> C ::> Ok foreign import ccall unsafe "eig_l_GC" zggev :: C ::> C ::> C :> C :> C ::> C ::> Ok foreign import ccall unsafe "eig_l_S" dsyev :: CInt -> R :> R ::> Ok foreign import ccall unsafe "eig_l_H" zheev :: CInt -> R :> C ::> Ok eigAux f st m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r v <- createMatrix ColumnMajor r r (a # l #! v) g #| st return (l,v) where r = rows m g ra ca xra xca pa = f ra ca xra xca pa 0 0 0 0 nullPtr | Eigenvalues and right eigenvectors of a general complex matrix , using LAPACK 's /zgeev/. -- The eigenvectors are the columns of v. The eigenvalues are not sorted. eigC :: Matrix (Complex Double) -> (Vector (Complex Double), Matrix (Complex Double)) eigC = eigAux zgeev "eigC" eigOnlyAux f st m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r (a #! l) g #| st return l where r = rows m g ra ca xra xca pa nl pl = f ra ca xra xca pa 0 0 0 0 nullPtr nl pl 0 0 0 0 nullPtr | Eigenvalues of a general complex matrix , using LAPACK 's with jobz = = \'N\ ' . -- The eigenvalues are not sorted. eigOnlyC :: Matrix (Complex Double) -> Vector (Complex Double) eigOnlyC = eigOnlyAux zgeev "eigOnlyC" | Eigenvalues and right eigenvectors of a general real matrix , using LAPACK 's /dgeev/. -- The eigenvectors are the columns of v. The eigenvalues are not sorted. eigR :: Matrix Double -> (Vector (Complex Double), Matrix (Complex Double)) eigR m = (s', v'') where (s,v) = eigRaux m s' = fixeig1 s v' = toRows $ trans v v'' = fromColumns $ fixeig (toList s') v' eigRaux :: Matrix Double -> (Vector (Complex Double), Matrix Double) eigRaux m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r v <- createMatrix ColumnMajor r r (a # l #! v) g #| "eigR" return (l,v) where r = rows m g ra ca xra xca pa = dgeev ra ca xra xca pa 0 0 0 0 nullPtr fixeig1 s = toComplex' (subVector 0 r (asReal s), subVector r r (asReal s)) where r = dim s fixeig [] _ = [] fixeig [_] [v] = [comp' v] fixeig ((r1:+i1):(r2:+i2):r) (v1:v2:vs) | r1 == r2 && i1 == (-i2) = toComplex' (v1,v2) : toComplex' (v1, mapVector negate v2) : fixeig r vs | otherwise = comp' v1 : fixeig ((r2:+i2):r) (v2:vs) fixeig _ _ = error "fixeig with impossible inputs" For dggev alpha(i ) / beta(i ) , alpha(i+1 ) / beta(i+1 ) form a complex conjugate pair when I m alpha(i ) ! = 0 . -- However, this does not lead to Re alpha(i) == Re alpha(i+1), since beta(i) and beta(i+1) -- can be different. Therefore old 'fixeig' would fail for 'eigG'. fixeigG [] _ = [] fixeigG [_] [v] = [comp' v] fixeigG ((_:+ai1) : an : as) (v1:v2:vs) | abs ai1 > 1e-13 = toComplex' (v1, v2) : toComplex' (v1, mapVector negate v2) : fixeigG as vs | otherwise = comp' v1 : fixeigG (an:as) (v2:vs) fixeigG _ _ = error "fixeigG with impossible inputs" | Eigenvalues of a general real matrix , using LAPACK 's /dgeev/ with jobz = = \'N\ ' . -- The eigenvalues are not sorted. eigOnlyR :: Matrix Double -> Vector (Complex Double) eigOnlyR = fixeig1 . eigOnlyAux dgeev "eigOnlyR" | Generalized eigenvalues and right eigenvectors of a pair of real matrices , using LAPACK 's /dggev/. -- The eigenvectors are the columns of v. The eigenvalues are represented as alphas / betas and not sorted. eigG :: Matrix Double -> Matrix Double -> (Vector (Complex Double), Vector Double, Matrix (Complex Double)) eigG a b = (alpha', beta, v'') where (alpha, beta, v) = eigGaux dggev a b "eigG" alpha' = fixeig1 alpha v' = toRows $ trans v v'' = fromColumns $ fixeigG (toList alpha') v' eigGaux f ma mb st = unsafePerformIO $ do a <- copy ColumnMajor ma b <- copy ColumnMajor mb alpha <- createVector r beta <- createVector r vr <- createMatrix ColumnMajor r r (a # b # alpha # beta #! vr) g #| st return (alpha, beta, vr) where r = rows ma g ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta = f ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta 0 0 0 0 nullPtr eigGOnlyAux f ma mb st = unsafePerformIO $ do a <- copy ColumnMajor ma b <- copy ColumnMajor mb alpha <- createVector r beta <- createVector r (a # b # alpha #! beta) g #| st return (alpha, beta) where r = rows ma g ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta = f ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta 0 0 0 0 nullPtr 0 0 0 0 nullPtr | Generalized eigenvalues and right eigenvectors of a pair of complex matrices , using LAPACK 's /zggev/. -- The eigenvectors are the columns of v. The eigenvalues are represented as alphas / betas and not sorted. eigGC :: Matrix (Complex Double) -> Matrix (Complex Double) -> (Vector (Complex Double), Vector (Complex Double), Matrix (Complex Double)) eigGC a b = eigGaux zggev a b "eigGC" eigOnlyG :: Matrix Double -> Matrix Double -> (Vector (Complex Double), Vector Double) eigOnlyG a b = first fixeig1 $ eigGOnlyAux dggev a b "eigOnlyG" eigOnlyGC :: Matrix (Complex Double) -> Matrix (Complex Double) -> (Vector (Complex Double), Vector (Complex Double)) eigOnlyGC a b = eigGOnlyAux zggev a b "eigOnlyGC" ----------------------------------------------------------------------------- eigSHAux f st m = unsafePerformIO $ do l <- createVector r v <- copy ColumnMajor m (l #! v) f #| st return (l,v) where r = rows m | Eigenvalues and right eigenvectors of a symmetric real matrix , using LAPACK 's /dsyev/. -- The eigenvectors are the columns of v. -- The eigenvalues are sorted in descending order (use 'eigS'' for ascending order). eigS :: Matrix Double -> (Vector Double, Matrix Double) eigS m = (s', fliprl v) where (s,v) = eigS' m s' = fromList . reverse . toList $ s -- | 'eigS' in ascending order eigS' :: Matrix Double -> (Vector Double, Matrix Double) eigS' = eigSHAux (dsyev 1) "eigS'" | Eigenvalues and right eigenvectors of a hermitian complex matrix , using LAPACK 's /zheev/. -- The eigenvectors are the columns of v. -- The eigenvalues are sorted in descending order (use 'eigH'' for ascending order). eigH :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) eigH m = (s', fliprl v) where (s,v) = eigH' m s' = fromList . reverse . toList $ s -- | 'eigH' in ascending order eigH' :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) eigH' = eigSHAux (zheev 1) "eigH'" | Eigenvalues of a symmetric real matrix , using LAPACK 's /dsyev/ with jobz = = \'N\ ' . -- The eigenvalues are sorted in descending order. eigOnlyS :: Matrix Double -> Vector Double eigOnlyS = vrev . fst. eigSHAux (dsyev 0) "eigS'" | Eigenvalues of a hermitian complex matrix , using LAPACK 's /zheev/ with jobz = = \'N\ ' . -- The eigenvalues are sorted in descending order. eigOnlyH :: Matrix (Complex Double) -> Vector Double eigOnlyH = vrev . fst. eigSHAux (zheev 0) "eigH'" vrev = flatten . flipud . reshape 1 ----------------------------------------------------------------------------- foreign import ccall unsafe "linearSolveR_l" dgesv :: R ::> R ::> Ok foreign import ccall unsafe "linearSolveC_l" zgesv :: C ::> C ::> Ok linearSolveSQAux g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do a' <- copy ColumnMajor a s <- copy ColumnMajor b (a' #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b | Solve a real linear system ( for square coefficient matrix and several right - hand sides ) using the LU decomposition , based on LAPACK 's /dgesv/. For underconstrained or overconstrained systems use ' linearSolveLSR ' or ' linearSolveSVDR ' . See also ' lusR ' . linearSolveR :: Matrix Double -> Matrix Double -> Matrix Double linearSolveR a b = linearSolveSQAux id dgesv "linearSolveR" a b mbLinearSolveR :: Matrix Double -> Matrix Double -> Maybe (Matrix Double) mbLinearSolveR a b = linearSolveSQAux mbCatch dgesv "linearSolveR" a b | Solve a complex linear system ( for square coefficient matrix and several right - hand sides ) using the LU decomposition , based on LAPACK 's /zgesv/. For underconstrained or overconstrained systems use ' linearSolveLSC ' or ' linearSolveSVDC ' . See also ' lusC ' . linearSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) linearSolveC a b = linearSolveSQAux id zgesv "linearSolveC" a b mbLinearSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Maybe (Matrix (Complex Double)) mbLinearSolveC a b = linearSolveSQAux mbCatch zgesv "linearSolveC" a b -------------------------------------------------------------------------------- foreign import ccall unsafe "cholSolveR_l" dpotrs :: R ::> R ::> Ok foreign import ccall unsafe "cholSolveC_l" zpotrs :: C ::> C ::> Ok linearSolveSQAux2 g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do s <- copy ColumnMajor b (a #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b -- | Solves a symmetric positive definite system of linear equations using a precomputed Cholesky factorization obtained by 'cholS'. cholSolveR :: Matrix Double -> Matrix Double -> Matrix Double cholSolveR a b = linearSolveSQAux2 id dpotrs "cholSolveR" (fmat a) b | Solves a Hermitian positive definite system of linear equations using a precomputed Cholesky factorization obtained by ' cholH ' . cholSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) cholSolveC a b = linearSolveSQAux2 id zpotrs "cholSolveC" (fmat a) b -------------------------------------------------------------------------------- foreign import ccall unsafe "triSolveR_l_u" dtrtrs_u :: R ::> R ::> Ok foreign import ccall unsafe "triSolveC_l_u" ztrtrs_u :: C ::> C ::> Ok foreign import ccall unsafe "triSolveR_l_l" dtrtrs_l :: R ::> R ::> Ok foreign import ccall unsafe "triSolveC_l_l" ztrtrs_l :: C ::> C ::> Ok linearSolveTRAux2 g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do s <- copy ColumnMajor b (a #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b data UpLo = Lower | Upper -- | Solves a triangular system of linear equations. triSolveR :: UpLo -> Matrix Double -> Matrix Double -> Matrix Double triSolveR Lower a b = linearSolveTRAux2 id dtrtrs_l "triSolveR" (fmat a) b triSolveR Upper a b = linearSolveTRAux2 id dtrtrs_u "triSolveR" (fmat a) b -- | Solves a triangular system of linear equations. triSolveC :: UpLo -> Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) triSolveC Lower a b = linearSolveTRAux2 id ztrtrs_l "triSolveC" (fmat a) b triSolveC Upper a b = linearSolveTRAux2 id ztrtrs_u "triSolveC" (fmat a) b -------------------------------------------------------------------------------- foreign import ccall unsafe "triDiagSolveR_l" dgttrs :: R :> R :> R :> R ::> Ok foreign import ccall unsafe "triDiagSolveC_l" zgttrs :: C :> C :> C :> C ::> Ok linearSolveGTAux2 g f st dl d du b | ndl == nd - 1 && ndu == nd - 1 && nd == r = unsafePerformIO . g $ do dl' <- head . toRows <$> copy ColumnMajor (fromRows [dl]) du' <- head . toRows <$> copy ColumnMajor (fromRows [du]) s <- copy ColumnMajor b (dl' # d # du' #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where ndl = dim dl nd = dim d ndu = dim du r = rows b -- | Solves a tridiagonal system of linear equations. triDiagSolveR dl d du b = linearSolveGTAux2 id dgttrs "triDiagSolveR" dl d du b triDiagSolveC dl d du b = linearSolveGTAux2 id zgttrs "triDiagSolveC" dl d du b ----------------------------------------------------------------------------------- foreign import ccall unsafe "linearSolveLSR_l" dgels :: R ::> R ::> Ok foreign import ccall unsafe "linearSolveLSC_l" zgels :: C ::> C ::> Ok foreign import ccall unsafe "linearSolveSVDR_l" dgelss :: Double -> R ::> R ::> Ok foreign import ccall unsafe "linearSolveSVDC_l" zgelss :: Double -> C ::> C ::> Ok linearSolveAux f st a b | m == rows b = unsafePerformIO $ do a' <- copy ColumnMajor a r <- createMatrix ColumnMajor (max m n) nrhs setRect 0 0 b r (a' #! r) f #| st return r | otherwise = error $ "different number of rows in linearSolve ("++st++")" where m = rows a n = cols a nrhs = cols b | Least squared error solution of an overconstrained real linear system , or the minimum norm solution of an underconstrained system , using LAPACK 's /dgels/. For rank - deficient systems use ' linearSolveSVDR ' . linearSolveLSR :: Matrix Double -> Matrix Double -> Matrix Double linearSolveLSR a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux dgels "linearSolverLSR" a b | Least squared error solution of an overconstrained complex linear system , or the minimum norm solution of an underconstrained system , using LAPACK 's /zgels/. For rank - deficient systems use ' linearSolveSVDC ' . linearSolveLSC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) linearSolveLSC a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux zgels "linearSolveLSC" a b | Minimum norm solution of a general real linear least squares problem Ax = B using the SVD , based on LAPACK 's /dgelss/. Admits rank - deficient systems but it is slower than ' linearSolveLSR ' . The effective rank of A is determined by treating as zero those singular valures which are less than rcond times the largest singular value . If rcond = = Nothing machine precision is used . linearSolveSVDR :: Maybe Double -- ^ rcond -> Matrix Double -- ^ coefficient matrix -> Matrix Double -- ^ right hand sides (as columns) -> Matrix Double -- ^ solution vectors (as columns) linearSolveSVDR (Just rcond) a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux (dgelss rcond) "linearSolveSVDR" a b linearSolveSVDR Nothing a b = linearSolveSVDR (Just (-1)) a b | Minimum norm solution of a general complex linear least squares problem Ax = B using the SVD , based on LAPACK 's /zgelss/. Admits rank - deficient systems but it is slower than ' linearSolveLSC ' . The effective rank of A is determined by treating as zero those singular valures which are less than rcond times the largest singular value . If rcond = = Nothing machine precision is used . linearSolveSVDC :: Maybe Double -- ^ rcond -> Matrix (Complex Double) -- ^ coefficient matrix -> Matrix (Complex Double) -- ^ right hand sides (as columns) -> Matrix (Complex Double) -- ^ solution vectors (as columns) linearSolveSVDC (Just rcond) a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux (zgelss rcond) "linearSolveSVDC" a b linearSolveSVDC Nothing a b = linearSolveSVDC (Just (-1)) a b ----------------------------------------------------------------------------------- foreign import ccall unsafe "chol_l_H" zpotrf :: C ::> Ok foreign import ccall unsafe "chol_l_S" dpotrf :: R ::> Ok cholAux f st a = do r <- copy ColumnMajor a (r # id) f #| st return r | Cholesky factorization of a complex Hermitian positive definite matrix , using LAPACK 's /zpotrf/. cholH :: Matrix (Complex Double) -> Matrix (Complex Double) cholH = unsafePerformIO . cholAux zpotrf "cholH" | Cholesky factorization of a real symmetric positive definite matrix , using LAPACK 's /dpotrf/. cholS :: Matrix Double -> Matrix Double cholS = unsafePerformIO . cholAux dpotrf "cholS" | Cholesky factorization of a complex Hermitian positive definite matrix , using LAPACK 's /zpotrf/ ( ' Maybe ' version ) . mbCholH :: Matrix (Complex Double) -> Maybe (Matrix (Complex Double)) mbCholH = unsafePerformIO . mbCatch . cholAux zpotrf "cholH" | Cholesky factorization of a real symmetric positive definite matrix , using LAPACK 's /dpotrf/ ( ' Maybe ' version ) . mbCholS :: Matrix Double -> Maybe (Matrix Double) mbCholS = unsafePerformIO . mbCatch . cholAux dpotrf "cholS" ----------------------------------------------------------------------------------- type TMVM t = t ::> t :> t ::> Ok foreign import ccall unsafe "qr_l_R" dgeqr2 :: R :> R ::> Ok foreign import ccall unsafe "qr_l_C" zgeqr2 :: C :> C ::> Ok | QR factorization of a real matrix , using LAPACK 's /dgeqr2/. qrR :: Matrix Double -> (Matrix Double, Vector Double) qrR = qrAux dgeqr2 "qrR" | QR factorization of a complex matrix , using LAPACK 's /zgeqr2/. qrC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector (Complex Double)) qrC = qrAux zgeqr2 "qrC" qrAux f st a = unsafePerformIO $ do r <- copy ColumnMajor a tau <- createVector mn (tau #! r) f #| st return (r,tau) where m = rows a n = cols a mn = min m n foreign import ccall unsafe "c_dorgqr" dorgqr :: R :> R ::> Ok foreign import ccall unsafe "c_zungqr" zungqr :: C :> C ::> Ok -- | build rotation from reflectors qrgrR :: Int -> (Matrix Double, Vector Double) -> Matrix Double qrgrR = qrgrAux dorgqr "qrgrR" -- | build rotation from reflectors qrgrC :: Int -> (Matrix (Complex Double), Vector (Complex Double)) -> Matrix (Complex Double) qrgrC = qrgrAux zungqr "qrgrC" qrgrAux f st n (a, tau) = unsafePerformIO $ do res <- copy ColumnMajor (subMatrix (0,0) (rows a,n) a) ((subVector 0 n tau') #! res) f #| st return res where tau' = vjoin [tau, constantD 0 n] ----------------------------------------------------------------------------------- foreign import ccall unsafe "hess_l_R" dgehrd :: R :> R ::> Ok foreign import ccall unsafe "hess_l_C" zgehrd :: C :> C ::> Ok | Hessenberg factorization of a square real matrix , using LAPACK 's /dgehrd/. hessR :: Matrix Double -> (Matrix Double, Vector Double) hessR = hessAux dgehrd "hessR" | Hessenberg factorization of a square complex matrix , using LAPACK 's /zgehrd/. hessC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector (Complex Double)) hessC = hessAux zgehrd "hessC" hessAux f st a = unsafePerformIO $ do r <- copy ColumnMajor a tau <- createVector (mn-1) (tau #! r) f #| st return (r,tau) where m = rows a n = cols a mn = min m n ----------------------------------------------------------------------------------- foreign import ccall unsafe "schur_l_R" dgees :: R ::> R ::> Ok foreign import ccall unsafe "schur_l_C" zgees :: C ::> C ::> Ok | factorization of a square real matrix , using LAPACK 's /dgees/. schurR :: Matrix Double -> (Matrix Double, Matrix Double) schurR = schurAux dgees "schurR" | factorization of a square complex matrix , using LAPACK 's /zgees/. schurC :: Matrix (Complex Double) -> (Matrix (Complex Double), Matrix (Complex Double)) schurC = schurAux zgees "schurC" schurAux f st a = unsafePerformIO $ do u <- createMatrix ColumnMajor n n s <- copy ColumnMajor a (u #! s) f #| st return (u,s) where n = rows a ----------------------------------------------------------------------------------- foreign import ccall unsafe "lu_l_R" dgetrf :: R :> R ::> Ok foreign import ccall unsafe "lu_l_C" zgetrf :: R :> C ::> Ok | LU factorization of a general real matrix , using LAPACK 's /dgetrf/. luR :: Matrix Double -> (Matrix Double, [Int]) luR = luAux dgetrf "luR" | LU factorization of a general complex matrix , using LAPACK 's /zgetrf/. luC :: Matrix (Complex Double) -> (Matrix (Complex Double), [Int]) luC = luAux zgetrf "luC" luAux f st a = unsafePerformIO $ do lu <- copy ColumnMajor a piv <- createVector (min n m) (piv #! lu) f #| st return (lu, map (pred.round) (toList piv)) where n = rows a m = cols a ----------------------------------------------------------------------------------- foreign import ccall unsafe "luS_l_R" dgetrs :: R ::> R :> R ::> Ok foreign import ccall unsafe "luS_l_C" zgetrs :: C ::> R :> C ::> Ok | Solve a real linear system from a precomputed LU decomposition ( ' luR ' ) , using LAPACK 's /dgetrs/. lusR :: Matrix Double -> [Int] -> Matrix Double -> Matrix Double lusR a piv b = lusAux dgetrs "lusR" (fmat a) piv b | Solve a complex linear system from a precomputed LU decomposition ( ' luC ' ) , using LAPACK 's /zgetrs/. lusC :: Matrix (Complex Double) -> [Int] -> Matrix (Complex Double) -> Matrix (Complex Double) lusC a piv b = lusAux zgetrs "lusC" (fmat a) piv b lusAux f st a piv b | n1==n2 && n2==n =unsafePerformIO $ do x <- copy ColumnMajor b (a # piv' #! x) f #| st return x | otherwise = error st where n1 = rows a n2 = cols a n = rows b piv' = fromList (map (fromIntegral.succ) piv) :: Vector Double ----------------------------------------------------------------------------------- foreign import ccall unsafe "ldl_R" dsytrf :: R :> R ::> Ok foreign import ccall unsafe "ldl_C" zhetrf :: R :> C ::> Ok | LDL factorization of a symmetric real matrix , using LAPACK 's /dsytrf/. ldlR :: Matrix Double -> (Matrix Double, [Int]) ldlR = ldlAux dsytrf "ldlR" | LDL factorization of a hermitian complex matrix , using LAPACK 's /zhetrf/. ldlC :: Matrix (Complex Double) -> (Matrix (Complex Double), [Int]) ldlC = ldlAux zhetrf "ldlC" ldlAux f st a = unsafePerformIO $ do ldl <- copy ColumnMajor a piv <- createVector (rows a) (piv #! ldl) f #| st return (ldl, map (pred.round) (toList piv)) ----------------------------------------------------------------------------------- foreign import ccall unsafe "ldl_S_R" dsytrs :: R ::> R :> R ::> Ok foreign import ccall unsafe "ldl_S_C" zsytrs :: C ::> R :> C ::> Ok | Solve a real linear system from a precomputed LDL decomposition ( ' ldlR ' ) , using LAPACK 's /dsytrs/. ldlsR :: Matrix Double -> [Int] -> Matrix Double -> Matrix Double ldlsR a piv b = lusAux dsytrs "ldlsR" (fmat a) piv b | Solve a complex linear system from a precomputed LDL decomposition ( ' ldlC ' ) , using LAPACK 's /zsytrs/. ldlsC :: Matrix (Complex Double) -> [Int] -> Matrix (Complex Double) -> Matrix (Complex Double) ldlsC a piv b = lusAux zsytrs "ldlsC" (fmat a) piv b
null
https://raw.githubusercontent.com/haskell-numerics/hmatrix/2694f776c7b5034d239acb5d984c489417739225/packages/base/src/Internal/LAPACK.hs
haskell
--------------------------------------------------------------------------- | License : BSD3 Stability : provisional --------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- # SCC "multiplyR" # --------------------------------------------------------------------------- --------------------------------------------------------------------------- The eigenvectors are the columns of v. The eigenvalues are not sorted. The eigenvalues are not sorted. The eigenvectors are the columns of v. The eigenvalues are not sorted. However, this does not lead to Re alpha(i) == Re alpha(i+1), since beta(i) and beta(i+1) can be different. Therefore old 'fixeig' would fail for 'eigG'. The eigenvalues are not sorted. The eigenvectors are the columns of v. The eigenvalues are represented as alphas / betas and not sorted. The eigenvectors are the columns of v. The eigenvalues are represented as alphas / betas and not sorted. --------------------------------------------------------------------------- The eigenvectors are the columns of v. The eigenvalues are sorted in descending order (use 'eigS'' for ascending order). | 'eigS' in ascending order The eigenvectors are the columns of v. The eigenvalues are sorted in descending order (use 'eigH'' for ascending order). | 'eigH' in ascending order The eigenvalues are sorted in descending order. The eigenvalues are sorted in descending order. --------------------------------------------------------------------------- ------------------------------------------------------------------------------ | Solves a symmetric positive definite system of linear equations using a precomputed Cholesky factorization obtained by 'cholS'. ------------------------------------------------------------------------------ | Solves a triangular system of linear equations. | Solves a triangular system of linear equations. ------------------------------------------------------------------------------ | Solves a tridiagonal system of linear equations. --------------------------------------------------------------------------------- ^ rcond ^ coefficient matrix ^ right hand sides (as columns) ^ solution vectors (as columns) ^ rcond ^ coefficient matrix ^ right hand sides (as columns) ^ solution vectors (as columns) --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- | build rotation from reflectors | build rotation from reflectors --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- ---------------------------------------------------------------------------------
# LANGUAGE TypeOperators # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - missing - signatures # Module : Numeric . LinearAlgebra . LAPACK Copyright : ( c ) 2006 - 14 Maintainer : Functional interface to selected LAPACK functions ( < > ) . module Internal.LAPACK where import Data.Bifunctor (first) import Internal.Devel import Internal.Vector import Internal.Matrix hiding ((#), (#!)) import Internal.Conversion import Internal.Element import Foreign.Ptr(nullPtr) import Foreign.C.Types import Control.Monad(when) import System.IO.Unsafe(unsafePerformIO) infixr 1 # a # b = apply a b # INLINE ( # ) # a #! b = a # b # id # INLINE ( # ! ) # type TMMM t = t ::> t ::> t ::> Ok type F = Float type Q = Complex Float foreign import ccall unsafe "multiplyR" dgemmc :: CInt -> CInt -> TMMM R foreign import ccall unsafe "multiplyC" zgemmc :: CInt -> CInt -> TMMM C foreign import ccall unsafe "multiplyF" sgemmc :: CInt -> CInt -> TMMM F foreign import ccall unsafe "multiplyQ" cgemmc :: CInt -> CInt -> TMMM Q foreign import ccall unsafe "multiplyI" c_multiplyI :: I -> TMMM I foreign import ccall unsafe "multiplyL" c_multiplyL :: Z -> TMMM Z isT (rowOrder -> False) = 0 isT _ = 1 tt x@(rowOrder -> False) = x tt x = trans x multiplyAux f st a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ show (rows a,cols a) ++ " x " ++ show (rows b, cols b) s <- createMatrix ColumnMajor (rows a) (cols b) ((tt a) # (tt b) #! s) (f (isT a) (isT b)) #| st return s | Matrix product based on BLAS 's /dgemm/. multiplyR :: Matrix Double -> Matrix Double -> Matrix Double | Matrix product based on BLAS 's /zgemm/. multiplyC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) multiplyC a b = multiplyAux zgemmc "zgemmc" a b | Matrix product based on BLAS 's /sgemm/. multiplyF :: Matrix Float -> Matrix Float -> Matrix Float multiplyF a b = multiplyAux sgemmc "sgemmc" a b | Matrix product based on BLAS 's /cgemm/. multiplyQ :: Matrix (Complex Float) -> Matrix (Complex Float) -> Matrix (Complex Float) multiplyQ a b = multiplyAux cgemmc "cgemmc" a b multiplyI :: I -> Matrix CInt -> Matrix CInt -> Matrix CInt multiplyI m a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ shSize a ++ " x " ++ shSize b s <- createMatrix ColumnMajor (rows a) (cols b) (a # b #! s) (c_multiplyI m) #|"c_multiplyI" return s multiplyL :: Z -> Matrix Z -> Matrix Z -> Matrix Z multiplyL m a b = unsafePerformIO $ do when (cols a /= rows b) $ error $ "inconsistent dimensions in matrix product "++ shSize a ++ " x " ++ shSize b s <- createMatrix ColumnMajor (rows a) (cols b) (a # b #! s) (c_multiplyL m) #|"c_multiplyL" return s type TSVD t = t ::> t ::> R :> t ::> Ok foreign import ccall unsafe "svd_l_R" dgesvd :: TSVD R foreign import ccall unsafe "svd_l_C" zgesvd :: TSVD C foreign import ccall unsafe "svd_l_Rdd" dgesdd :: TSVD R foreign import ccall unsafe "svd_l_Cdd" zgesdd :: TSVD C | Full SVD of a real matrix using LAPACK 's /dgesvd/. svdR :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) svdR = svdAux dgesvd "svdR" | Full SVD of a real matrix using LAPACK 's /dgesdd/. svdRd :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) svdRd = svdAux dgesdd "svdRdd" | Full SVD of a complex matrix using LAPACK 's /zgesvd/. svdC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) svdC = svdAux zgesvd "svdC" | Full SVD of a complex matrix using LAPACK 's /zgesdd/. svdCd :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) svdCd = svdAux zgesdd "svdCdd" svdAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r r s <- createVector (min r c) v <- createMatrix ColumnMajor c c (a # u # s #! v) f #| st return (u,s,v) where r = rows x c = cols x | Thin SVD of a real matrix , using LAPACK 's /dgesvd/ with = = jobvt = = \'S\ ' . thinSVDR :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) thinSVDR = thinSVDAux dgesvd "thinSVDR" | Thin SVD of a complex matrix , using LAPACK 's /zgesvd/ with = = jobvt = = \'S\ ' . thinSVDC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) thinSVDC = thinSVDAux zgesvd "thinSVDC" | Thin SVD of a real matrix , using LAPACK 's /dgesdd/ with jobz = = \'S\ ' . thinSVDRd :: Matrix Double -> (Matrix Double, Vector Double, Matrix Double) thinSVDRd = thinSVDAux dgesdd "thinSVDRdd" | Thin SVD of a complex matrix , using LAPACK 's /zgesdd/ with jobz = = \'S\ ' . thinSVDCd :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double, Matrix (Complex Double)) thinSVDCd = thinSVDAux zgesdd "thinSVDCdd" thinSVDAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r q s <- createVector q v <- createMatrix ColumnMajor q c (a # u # s #! v) f #| st return (u,s,v) where r = rows x c = cols x q = min r c | Singular values of a real matrix , using LAPACK 's /dgesvd/ with = = jobvt = = \'N\ ' . svR :: Matrix Double -> Vector Double svR = svAux dgesvd "svR" | Singular values of a complex matrix , using LAPACK 's /zgesvd/ with = = jobvt = = \'N\ ' . svC :: Matrix (Complex Double) -> Vector Double svC = svAux zgesvd "svC" | Singular values of a real matrix , using LAPACK 's /dgesdd/ with jobz = = \'N\ ' . svRd :: Matrix Double -> Vector Double svRd = svAux dgesdd "svRd" | Singular values of a complex matrix , using LAPACK 's /zgesdd/ with jobz = = \'N\ ' . svCd :: Matrix (Complex Double) -> Vector Double svCd = svAux zgesdd "svCd" svAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x s <- createVector q (a #! s) g #| st return s where r = rows x c = cols x q = min r c g ra ca xra xca pa nb pb = f ra ca xra xca pa 0 0 0 0 nullPtr nb pb 0 0 0 0 nullPtr | Singular values and all right singular vectors of a real matrix , using LAPACK 's /dgesvd/ with = = \'N\ ' and jobvt = = \'A\ ' . rightSVR :: Matrix Double -> (Vector Double, Matrix Double) rightSVR = rightSVAux dgesvd "rightSVR" | Singular values and all right singular vectors of a complex matrix , using LAPACK 's /zgesvd/ with = = \'N\ ' and jobvt = = \'A\ ' . rightSVC :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) rightSVC = rightSVAux zgesvd "rightSVC" rightSVAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x s <- createVector q v <- createMatrix ColumnMajor c c (a # s #! v) g #| st return (s,v) where r = rows x c = cols x q = min r c g ra ca xra xca pa = f ra ca xra xca pa 0 0 0 0 nullPtr | Singular values and all left singular vectors of a real matrix , using LAPACK 's /dgesvd/ with = = \'A\ ' and jobvt = = \'N\ ' . leftSVR :: Matrix Double -> (Matrix Double, Vector Double) leftSVR = leftSVAux dgesvd "leftSVR" | Singular values and all left singular vectors of a complex matrix , using LAPACK 's /zgesvd/ with = = \'A\ ' and jobvt = = \'N\ ' . leftSVC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector Double) leftSVC = leftSVAux zgesvd "leftSVC" leftSVAux f st x = unsafePerformIO $ do a <- copy ColumnMajor x u <- createMatrix ColumnMajor r r s <- createVector q (a # u #! s) g #| st return (u,s) where r = rows x c = cols x q = min r c g ra ca xra xca pa ru cu xru xcu pu nb pb = f ra ca xra xca pa ru cu xru xcu pu nb pb 0 0 0 0 nullPtr foreign import ccall unsafe "eig_l_R" dgeev :: R ::> R ::> C :> R ::> Ok foreign import ccall unsafe "eig_l_G" dggev :: R ::> R ::> C :> R :> R ::> R ::> Ok foreign import ccall unsafe "eig_l_C" zgeev :: C ::> C ::> C :> C ::> Ok foreign import ccall unsafe "eig_l_GC" zggev :: C ::> C ::> C :> C :> C ::> C ::> Ok foreign import ccall unsafe "eig_l_S" dsyev :: CInt -> R :> R ::> Ok foreign import ccall unsafe "eig_l_H" zheev :: CInt -> R :> C ::> Ok eigAux f st m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r v <- createMatrix ColumnMajor r r (a # l #! v) g #| st return (l,v) where r = rows m g ra ca xra xca pa = f ra ca xra xca pa 0 0 0 0 nullPtr | Eigenvalues and right eigenvectors of a general complex matrix , using LAPACK 's /zgeev/. eigC :: Matrix (Complex Double) -> (Vector (Complex Double), Matrix (Complex Double)) eigC = eigAux zgeev "eigC" eigOnlyAux f st m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r (a #! l) g #| st return l where r = rows m g ra ca xra xca pa nl pl = f ra ca xra xca pa 0 0 0 0 nullPtr nl pl 0 0 0 0 nullPtr | Eigenvalues of a general complex matrix , using LAPACK 's with jobz = = \'N\ ' . eigOnlyC :: Matrix (Complex Double) -> Vector (Complex Double) eigOnlyC = eigOnlyAux zgeev "eigOnlyC" | Eigenvalues and right eigenvectors of a general real matrix , using LAPACK 's /dgeev/. eigR :: Matrix Double -> (Vector (Complex Double), Matrix (Complex Double)) eigR m = (s', v'') where (s,v) = eigRaux m s' = fixeig1 s v' = toRows $ trans v v'' = fromColumns $ fixeig (toList s') v' eigRaux :: Matrix Double -> (Vector (Complex Double), Matrix Double) eigRaux m = unsafePerformIO $ do a <- copy ColumnMajor m l <- createVector r v <- createMatrix ColumnMajor r r (a # l #! v) g #| "eigR" return (l,v) where r = rows m g ra ca xra xca pa = dgeev ra ca xra xca pa 0 0 0 0 nullPtr fixeig1 s = toComplex' (subVector 0 r (asReal s), subVector r r (asReal s)) where r = dim s fixeig [] _ = [] fixeig [_] [v] = [comp' v] fixeig ((r1:+i1):(r2:+i2):r) (v1:v2:vs) | r1 == r2 && i1 == (-i2) = toComplex' (v1,v2) : toComplex' (v1, mapVector negate v2) : fixeig r vs | otherwise = comp' v1 : fixeig ((r2:+i2):r) (v2:vs) fixeig _ _ = error "fixeig with impossible inputs" For dggev alpha(i ) / beta(i ) , alpha(i+1 ) / beta(i+1 ) form a complex conjugate pair when I m alpha(i ) ! = 0 . fixeigG [] _ = [] fixeigG [_] [v] = [comp' v] fixeigG ((_:+ai1) : an : as) (v1:v2:vs) | abs ai1 > 1e-13 = toComplex' (v1, v2) : toComplex' (v1, mapVector negate v2) : fixeigG as vs | otherwise = comp' v1 : fixeigG (an:as) (v2:vs) fixeigG _ _ = error "fixeigG with impossible inputs" | Eigenvalues of a general real matrix , using LAPACK 's /dgeev/ with jobz = = \'N\ ' . eigOnlyR :: Matrix Double -> Vector (Complex Double) eigOnlyR = fixeig1 . eigOnlyAux dgeev "eigOnlyR" | Generalized eigenvalues and right eigenvectors of a pair of real matrices , using LAPACK 's /dggev/. eigG :: Matrix Double -> Matrix Double -> (Vector (Complex Double), Vector Double, Matrix (Complex Double)) eigG a b = (alpha', beta, v'') where (alpha, beta, v) = eigGaux dggev a b "eigG" alpha' = fixeig1 alpha v' = toRows $ trans v v'' = fromColumns $ fixeigG (toList alpha') v' eigGaux f ma mb st = unsafePerformIO $ do a <- copy ColumnMajor ma b <- copy ColumnMajor mb alpha <- createVector r beta <- createVector r vr <- createMatrix ColumnMajor r r (a # b # alpha # beta #! vr) g #| st return (alpha, beta, vr) where r = rows ma g ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta = f ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta 0 0 0 0 nullPtr eigGOnlyAux f ma mb st = unsafePerformIO $ do a <- copy ColumnMajor ma b <- copy ColumnMajor mb alpha <- createVector r beta <- createVector r (a # b # alpha #! beta) g #| st return (alpha, beta) where r = rows ma g ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta = f ar ac xra xca pa br bc xrb xcb pb alphan palpha betan pbeta 0 0 0 0 nullPtr 0 0 0 0 nullPtr | Generalized eigenvalues and right eigenvectors of a pair of complex matrices , using LAPACK 's /zggev/. eigGC :: Matrix (Complex Double) -> Matrix (Complex Double) -> (Vector (Complex Double), Vector (Complex Double), Matrix (Complex Double)) eigGC a b = eigGaux zggev a b "eigGC" eigOnlyG :: Matrix Double -> Matrix Double -> (Vector (Complex Double), Vector Double) eigOnlyG a b = first fixeig1 $ eigGOnlyAux dggev a b "eigOnlyG" eigOnlyGC :: Matrix (Complex Double) -> Matrix (Complex Double) -> (Vector (Complex Double), Vector (Complex Double)) eigOnlyGC a b = eigGOnlyAux zggev a b "eigOnlyGC" eigSHAux f st m = unsafePerformIO $ do l <- createVector r v <- copy ColumnMajor m (l #! v) f #| st return (l,v) where r = rows m | Eigenvalues and right eigenvectors of a symmetric real matrix , using LAPACK 's /dsyev/. eigS :: Matrix Double -> (Vector Double, Matrix Double) eigS m = (s', fliprl v) where (s,v) = eigS' m s' = fromList . reverse . toList $ s eigS' :: Matrix Double -> (Vector Double, Matrix Double) eigS' = eigSHAux (dsyev 1) "eigS'" | Eigenvalues and right eigenvectors of a hermitian complex matrix , using LAPACK 's /zheev/. eigH :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) eigH m = (s', fliprl v) where (s,v) = eigH' m s' = fromList . reverse . toList $ s eigH' :: Matrix (Complex Double) -> (Vector Double, Matrix (Complex Double)) eigH' = eigSHAux (zheev 1) "eigH'" | Eigenvalues of a symmetric real matrix , using LAPACK 's /dsyev/ with jobz = = \'N\ ' . eigOnlyS :: Matrix Double -> Vector Double eigOnlyS = vrev . fst. eigSHAux (dsyev 0) "eigS'" | Eigenvalues of a hermitian complex matrix , using LAPACK 's /zheev/ with jobz = = \'N\ ' . eigOnlyH :: Matrix (Complex Double) -> Vector Double eigOnlyH = vrev . fst. eigSHAux (zheev 0) "eigH'" vrev = flatten . flipud . reshape 1 foreign import ccall unsafe "linearSolveR_l" dgesv :: R ::> R ::> Ok foreign import ccall unsafe "linearSolveC_l" zgesv :: C ::> C ::> Ok linearSolveSQAux g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do a' <- copy ColumnMajor a s <- copy ColumnMajor b (a' #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b | Solve a real linear system ( for square coefficient matrix and several right - hand sides ) using the LU decomposition , based on LAPACK 's /dgesv/. For underconstrained or overconstrained systems use ' linearSolveLSR ' or ' linearSolveSVDR ' . See also ' lusR ' . linearSolveR :: Matrix Double -> Matrix Double -> Matrix Double linearSolveR a b = linearSolveSQAux id dgesv "linearSolveR" a b mbLinearSolveR :: Matrix Double -> Matrix Double -> Maybe (Matrix Double) mbLinearSolveR a b = linearSolveSQAux mbCatch dgesv "linearSolveR" a b | Solve a complex linear system ( for square coefficient matrix and several right - hand sides ) using the LU decomposition , based on LAPACK 's /zgesv/. For underconstrained or overconstrained systems use ' linearSolveLSC ' or ' linearSolveSVDC ' . See also ' lusC ' . linearSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) linearSolveC a b = linearSolveSQAux id zgesv "linearSolveC" a b mbLinearSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Maybe (Matrix (Complex Double)) mbLinearSolveC a b = linearSolveSQAux mbCatch zgesv "linearSolveC" a b foreign import ccall unsafe "cholSolveR_l" dpotrs :: R ::> R ::> Ok foreign import ccall unsafe "cholSolveC_l" zpotrs :: C ::> C ::> Ok linearSolveSQAux2 g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do s <- copy ColumnMajor b (a #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b cholSolveR :: Matrix Double -> Matrix Double -> Matrix Double cholSolveR a b = linearSolveSQAux2 id dpotrs "cholSolveR" (fmat a) b | Solves a Hermitian positive definite system of linear equations using a precomputed Cholesky factorization obtained by ' cholH ' . cholSolveC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) cholSolveC a b = linearSolveSQAux2 id zpotrs "cholSolveC" (fmat a) b foreign import ccall unsafe "triSolveR_l_u" dtrtrs_u :: R ::> R ::> Ok foreign import ccall unsafe "triSolveC_l_u" ztrtrs_u :: C ::> C ::> Ok foreign import ccall unsafe "triSolveR_l_l" dtrtrs_l :: R ::> R ::> Ok foreign import ccall unsafe "triSolveC_l_l" ztrtrs_l :: C ::> C ::> Ok linearSolveTRAux2 g f st a b | n1==n2 && n1==r = unsafePerformIO . g $ do s <- copy ColumnMajor b (a #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where n1 = rows a n2 = cols a r = rows b data UpLo = Lower | Upper triSolveR :: UpLo -> Matrix Double -> Matrix Double -> Matrix Double triSolveR Lower a b = linearSolveTRAux2 id dtrtrs_l "triSolveR" (fmat a) b triSolveR Upper a b = linearSolveTRAux2 id dtrtrs_u "triSolveR" (fmat a) b triSolveC :: UpLo -> Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) triSolveC Lower a b = linearSolveTRAux2 id ztrtrs_l "triSolveC" (fmat a) b triSolveC Upper a b = linearSolveTRAux2 id ztrtrs_u "triSolveC" (fmat a) b foreign import ccall unsafe "triDiagSolveR_l" dgttrs :: R :> R :> R :> R ::> Ok foreign import ccall unsafe "triDiagSolveC_l" zgttrs :: C :> C :> C :> C ::> Ok linearSolveGTAux2 g f st dl d du b | ndl == nd - 1 && ndu == nd - 1 && nd == r = unsafePerformIO . g $ do dl' <- head . toRows <$> copy ColumnMajor (fromRows [dl]) du' <- head . toRows <$> copy ColumnMajor (fromRows [du]) s <- copy ColumnMajor b (dl' # d # du' #! s) f #| st return s | otherwise = error $ st ++ " of nonsquare matrix" where ndl = dim dl nd = dim d ndu = dim du r = rows b triDiagSolveR dl d du b = linearSolveGTAux2 id dgttrs "triDiagSolveR" dl d du b triDiagSolveC dl d du b = linearSolveGTAux2 id zgttrs "triDiagSolveC" dl d du b foreign import ccall unsafe "linearSolveLSR_l" dgels :: R ::> R ::> Ok foreign import ccall unsafe "linearSolveLSC_l" zgels :: C ::> C ::> Ok foreign import ccall unsafe "linearSolveSVDR_l" dgelss :: Double -> R ::> R ::> Ok foreign import ccall unsafe "linearSolveSVDC_l" zgelss :: Double -> C ::> C ::> Ok linearSolveAux f st a b | m == rows b = unsafePerformIO $ do a' <- copy ColumnMajor a r <- createMatrix ColumnMajor (max m n) nrhs setRect 0 0 b r (a' #! r) f #| st return r | otherwise = error $ "different number of rows in linearSolve ("++st++")" where m = rows a n = cols a nrhs = cols b | Least squared error solution of an overconstrained real linear system , or the minimum norm solution of an underconstrained system , using LAPACK 's /dgels/. For rank - deficient systems use ' linearSolveSVDR ' . linearSolveLSR :: Matrix Double -> Matrix Double -> Matrix Double linearSolveLSR a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux dgels "linearSolverLSR" a b | Least squared error solution of an overconstrained complex linear system , or the minimum norm solution of an underconstrained system , using LAPACK 's /zgels/. For rank - deficient systems use ' linearSolveSVDC ' . linearSolveLSC :: Matrix (Complex Double) -> Matrix (Complex Double) -> Matrix (Complex Double) linearSolveLSC a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux zgels "linearSolveLSC" a b | Minimum norm solution of a general real linear least squares problem Ax = B using the SVD , based on LAPACK 's /dgelss/. Admits rank - deficient systems but it is slower than ' linearSolveLSR ' . The effective rank of A is determined by treating as zero those singular valures which are less than rcond times the largest singular value . If rcond = = Nothing machine precision is used . linearSolveSVDR (Just rcond) a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux (dgelss rcond) "linearSolveSVDR" a b linearSolveSVDR Nothing a b = linearSolveSVDR (Just (-1)) a b | Minimum norm solution of a general complex linear least squares problem Ax = B using the SVD , based on LAPACK 's /zgelss/. Admits rank - deficient systems but it is slower than ' linearSolveLSC ' . The effective rank of A is determined by treating as zero those singular valures which are less than rcond times the largest singular value . If rcond = = Nothing machine precision is used . linearSolveSVDC (Just rcond) a b = subMatrix (0,0) (cols a, cols b) $ linearSolveAux (zgelss rcond) "linearSolveSVDC" a b linearSolveSVDC Nothing a b = linearSolveSVDC (Just (-1)) a b foreign import ccall unsafe "chol_l_H" zpotrf :: C ::> Ok foreign import ccall unsafe "chol_l_S" dpotrf :: R ::> Ok cholAux f st a = do r <- copy ColumnMajor a (r # id) f #| st return r | Cholesky factorization of a complex Hermitian positive definite matrix , using LAPACK 's /zpotrf/. cholH :: Matrix (Complex Double) -> Matrix (Complex Double) cholH = unsafePerformIO . cholAux zpotrf "cholH" | Cholesky factorization of a real symmetric positive definite matrix , using LAPACK 's /dpotrf/. cholS :: Matrix Double -> Matrix Double cholS = unsafePerformIO . cholAux dpotrf "cholS" | Cholesky factorization of a complex Hermitian positive definite matrix , using LAPACK 's /zpotrf/ ( ' Maybe ' version ) . mbCholH :: Matrix (Complex Double) -> Maybe (Matrix (Complex Double)) mbCholH = unsafePerformIO . mbCatch . cholAux zpotrf "cholH" | Cholesky factorization of a real symmetric positive definite matrix , using LAPACK 's /dpotrf/ ( ' Maybe ' version ) . mbCholS :: Matrix Double -> Maybe (Matrix Double) mbCholS = unsafePerformIO . mbCatch . cholAux dpotrf "cholS" type TMVM t = t ::> t :> t ::> Ok foreign import ccall unsafe "qr_l_R" dgeqr2 :: R :> R ::> Ok foreign import ccall unsafe "qr_l_C" zgeqr2 :: C :> C ::> Ok | QR factorization of a real matrix , using LAPACK 's /dgeqr2/. qrR :: Matrix Double -> (Matrix Double, Vector Double) qrR = qrAux dgeqr2 "qrR" | QR factorization of a complex matrix , using LAPACK 's /zgeqr2/. qrC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector (Complex Double)) qrC = qrAux zgeqr2 "qrC" qrAux f st a = unsafePerformIO $ do r <- copy ColumnMajor a tau <- createVector mn (tau #! r) f #| st return (r,tau) where m = rows a n = cols a mn = min m n foreign import ccall unsafe "c_dorgqr" dorgqr :: R :> R ::> Ok foreign import ccall unsafe "c_zungqr" zungqr :: C :> C ::> Ok qrgrR :: Int -> (Matrix Double, Vector Double) -> Matrix Double qrgrR = qrgrAux dorgqr "qrgrR" qrgrC :: Int -> (Matrix (Complex Double), Vector (Complex Double)) -> Matrix (Complex Double) qrgrC = qrgrAux zungqr "qrgrC" qrgrAux f st n (a, tau) = unsafePerformIO $ do res <- copy ColumnMajor (subMatrix (0,0) (rows a,n) a) ((subVector 0 n tau') #! res) f #| st return res where tau' = vjoin [tau, constantD 0 n] foreign import ccall unsafe "hess_l_R" dgehrd :: R :> R ::> Ok foreign import ccall unsafe "hess_l_C" zgehrd :: C :> C ::> Ok | Hessenberg factorization of a square real matrix , using LAPACK 's /dgehrd/. hessR :: Matrix Double -> (Matrix Double, Vector Double) hessR = hessAux dgehrd "hessR" | Hessenberg factorization of a square complex matrix , using LAPACK 's /zgehrd/. hessC :: Matrix (Complex Double) -> (Matrix (Complex Double), Vector (Complex Double)) hessC = hessAux zgehrd "hessC" hessAux f st a = unsafePerformIO $ do r <- copy ColumnMajor a tau <- createVector (mn-1) (tau #! r) f #| st return (r,tau) where m = rows a n = cols a mn = min m n foreign import ccall unsafe "schur_l_R" dgees :: R ::> R ::> Ok foreign import ccall unsafe "schur_l_C" zgees :: C ::> C ::> Ok | factorization of a square real matrix , using LAPACK 's /dgees/. schurR :: Matrix Double -> (Matrix Double, Matrix Double) schurR = schurAux dgees "schurR" | factorization of a square complex matrix , using LAPACK 's /zgees/. schurC :: Matrix (Complex Double) -> (Matrix (Complex Double), Matrix (Complex Double)) schurC = schurAux zgees "schurC" schurAux f st a = unsafePerformIO $ do u <- createMatrix ColumnMajor n n s <- copy ColumnMajor a (u #! s) f #| st return (u,s) where n = rows a foreign import ccall unsafe "lu_l_R" dgetrf :: R :> R ::> Ok foreign import ccall unsafe "lu_l_C" zgetrf :: R :> C ::> Ok | LU factorization of a general real matrix , using LAPACK 's /dgetrf/. luR :: Matrix Double -> (Matrix Double, [Int]) luR = luAux dgetrf "luR" | LU factorization of a general complex matrix , using LAPACK 's /zgetrf/. luC :: Matrix (Complex Double) -> (Matrix (Complex Double), [Int]) luC = luAux zgetrf "luC" luAux f st a = unsafePerformIO $ do lu <- copy ColumnMajor a piv <- createVector (min n m) (piv #! lu) f #| st return (lu, map (pred.round) (toList piv)) where n = rows a m = cols a foreign import ccall unsafe "luS_l_R" dgetrs :: R ::> R :> R ::> Ok foreign import ccall unsafe "luS_l_C" zgetrs :: C ::> R :> C ::> Ok | Solve a real linear system from a precomputed LU decomposition ( ' luR ' ) , using LAPACK 's /dgetrs/. lusR :: Matrix Double -> [Int] -> Matrix Double -> Matrix Double lusR a piv b = lusAux dgetrs "lusR" (fmat a) piv b | Solve a complex linear system from a precomputed LU decomposition ( ' luC ' ) , using LAPACK 's /zgetrs/. lusC :: Matrix (Complex Double) -> [Int] -> Matrix (Complex Double) -> Matrix (Complex Double) lusC a piv b = lusAux zgetrs "lusC" (fmat a) piv b lusAux f st a piv b | n1==n2 && n2==n =unsafePerformIO $ do x <- copy ColumnMajor b (a # piv' #! x) f #| st return x | otherwise = error st where n1 = rows a n2 = cols a n = rows b piv' = fromList (map (fromIntegral.succ) piv) :: Vector Double foreign import ccall unsafe "ldl_R" dsytrf :: R :> R ::> Ok foreign import ccall unsafe "ldl_C" zhetrf :: R :> C ::> Ok | LDL factorization of a symmetric real matrix , using LAPACK 's /dsytrf/. ldlR :: Matrix Double -> (Matrix Double, [Int]) ldlR = ldlAux dsytrf "ldlR" | LDL factorization of a hermitian complex matrix , using LAPACK 's /zhetrf/. ldlC :: Matrix (Complex Double) -> (Matrix (Complex Double), [Int]) ldlC = ldlAux zhetrf "ldlC" ldlAux f st a = unsafePerformIO $ do ldl <- copy ColumnMajor a piv <- createVector (rows a) (piv #! ldl) f #| st return (ldl, map (pred.round) (toList piv)) foreign import ccall unsafe "ldl_S_R" dsytrs :: R ::> R :> R ::> Ok foreign import ccall unsafe "ldl_S_C" zsytrs :: C ::> R :> C ::> Ok | Solve a real linear system from a precomputed LDL decomposition ( ' ldlR ' ) , using LAPACK 's /dsytrs/. ldlsR :: Matrix Double -> [Int] -> Matrix Double -> Matrix Double ldlsR a piv b = lusAux dsytrs "ldlsR" (fmat a) piv b | Solve a complex linear system from a precomputed LDL decomposition ( ' ldlC ' ) , using LAPACK 's /zsytrs/. ldlsC :: Matrix (Complex Double) -> [Int] -> Matrix (Complex Double) -> Matrix (Complex Double) ldlsC a piv b = lusAux zsytrs "ldlsC" (fmat a) piv b
0fbd6f2b0691263738c772023f951b36df143cb1b773168f229142461e91b672
dongcarl/guix
git.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix scripts git) #:use-module (ice-9 match) #:use-module (guix ui) #:use-module (guix scripts) #:export (guix-git)) (define (show-help) (display (G_ "Usage: guix git COMMAND ARGS... Operate on Git repositories.\n")) (newline) (display (G_ "The valid values for ACTION are:\n")) (newline) (display (G_ "\ authenticate verify commit signatures and authorizations\n")) (newline) (display (G_ " -h, --help display this help and exit")) (display (G_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %sub-commands '("authenticate")) (define (resolve-sub-command name) (let ((module (resolve-interface `(guix scripts git ,(string->symbol name)))) (proc (string->symbol (string-append "guix-git-" name)))) (module-ref module proc))) (define-command (guix-git . args) (category plumbing) (synopsis "operate on Git repositories") (with-error-handling (match args (() (format (current-error-port) (G_ "guix git: missing sub-command~%"))) ((or ("-h") ("--help")) (show-help) (exit 0)) ((or ("-V") ("--version")) (show-version-and-exit "guix git")) ((sub-command args ...) (if (member sub-command %sub-commands) (apply (resolve-sub-command sub-command) args) (format (current-error-port) (G_ "guix git: invalid sub-command~%")))))))
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/guix/scripts/git.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
Copyright © 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix scripts git) #:use-module (ice-9 match) #:use-module (guix ui) #:use-module (guix scripts) #:export (guix-git)) (define (show-help) (display (G_ "Usage: guix git COMMAND ARGS... Operate on Git repositories.\n")) (newline) (display (G_ "The valid values for ACTION are:\n")) (newline) (display (G_ "\ authenticate verify commit signatures and authorizations\n")) (newline) (display (G_ " -h, --help display this help and exit")) (display (G_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %sub-commands '("authenticate")) (define (resolve-sub-command name) (let ((module (resolve-interface `(guix scripts git ,(string->symbol name)))) (proc (string->symbol (string-append "guix-git-" name)))) (module-ref module proc))) (define-command (guix-git . args) (category plumbing) (synopsis "operate on Git repositories") (with-error-handling (match args (() (format (current-error-port) (G_ "guix git: missing sub-command~%"))) ((or ("-h") ("--help")) (show-help) (exit 0)) ((or ("-V") ("--version")) (show-version-and-exit "guix git")) ((sub-command args ...) (if (member sub-command %sub-commands) (apply (resolve-sub-command sub-command) args) (format (current-error-port) (G_ "guix git: invalid sub-command~%")))))))
d234690c10938f2f9114248d81f48b3c9c060e526e0c1975aa76f8b9268e2b38
a13x/aberth
aberth_app.erl
Copyright ( c ) 2013 < > %% %% Permission to use, copy, modify, and/or distribute this software for any %% purpose with or without fee is hereby granted, provided that the above %% copyright notice and this permission notice appear in all copies. %% THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -module(aberth_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== start(_StartType, _StartArgs) -> aberth_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/a13x/aberth/e09b721b40782d337970aebe3d126e0ab27b1089/src/aberth_app.erl
erlang
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Application callbacks =================================================================== Application callbacks ===================================================================
Copyright ( c ) 2013 < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(aberth_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> aberth_sup:start_link(). stop(_State) -> ok.
99f7ff2c03adc7145df49dcc9c958de1c657ce4003316c928e8cbc26db23d00b
agda/agda
CallGraph.hs
# LANGUAGE ImplicitParams # module Internal.Termination.CallGraph ( tests ) where import Agda.Termination.CallGraph import Agda.Termination.CutOff import Agda.Termination.SparseMatrix import qualified Data.List as List import Internal.Helpers import Internal.Termination.CallMatrix ( callMatrix ) ------------------------------------------------------------------------------ -- prop_complete :: (?cutoff :: CutOff) => Property -- prop_complete = forAll ( callGraph : : Gen ( CallGraph [ Integer ] ) ) $ \cs - > -- isComplete (complete cs) -- -- | Returns 'True' iff the call graph is complete. isComplete : : ( , , ? cutoff : : CutOff ) = > Bool -- isComplete s = (s `union` (s `combine` s)) `notWorse` s ------------------------------------------------------------------------ -- * Generators and properties ------------------------------------------------------------------------ -- | Generates a call graph. callGraph :: Arbitrary cinfo => Gen (CallGraph cinfo) callGraph = do indices <- fmap List.nub arbitrary n <- natural let noMatrices | List.null indices = 0 | otherwise = n `min` 3 -- Not too many. fromList <$> vectorOf noMatrices (matGen indices) where matGen indices = do [s, t] <- vectorOf 2 (elements indices) [c, r] <- vectorOf 2 (choose (0, 2)) -- Not too large. m <- callMatrix (Size { rows = r, cols = c }) mkCall s t m <$> arbitrary ------------------------------------------------------------------------ -- * All tests ------------------------------------------------------------------------ ( ASR 2018 - 01 - 06 ) Since some properties use implicit parameters we can not use ' allProperties ' for collecting all the tests ( see -- ). tests :: TestTree tests = testGroup "Internal.Termination.CallGraph" [] -- [ testProperty "prop_complete" prop_complete -- , testProperty "prop_ensureCompletePrecondition" -- ] CutOff 2 -- do n't cut off in tests !
null
https://raw.githubusercontent.com/agda/agda/f50c14d3a4e92ed695783e26dbe11ad1ad7b73f7/test/Internal/Termination/CallGraph.hs
haskell
---------------------------------------------------------------------------- prop_complete :: (?cutoff :: CutOff) => Property prop_complete = isComplete (complete cs) -- | Returns 'True' iff the call graph is complete. isComplete s = (s `union` (s `combine` s)) `notWorse` s ---------------------------------------------------------------------- * Generators and properties ---------------------------------------------------------------------- | Generates a call graph. Not too many. Not too large. ---------------------------------------------------------------------- * All tests ---------------------------------------------------------------------- ). [ testProperty "prop_complete" prop_complete , testProperty "prop_ensureCompletePrecondition" ] do n't cut off in tests !
# LANGUAGE ImplicitParams # module Internal.Termination.CallGraph ( tests ) where import Agda.Termination.CallGraph import Agda.Termination.CutOff import Agda.Termination.SparseMatrix import qualified Data.List as List import Internal.Helpers import Internal.Termination.CallMatrix ( callMatrix ) forAll ( callGraph : : Gen ( CallGraph [ Integer ] ) ) $ \cs - > isComplete : : ( , , ? cutoff : : CutOff ) = > Bool callGraph :: Arbitrary cinfo => Gen (CallGraph cinfo) callGraph = do indices <- fmap List.nub arbitrary n <- natural let noMatrices | List.null indices = 0 fromList <$> vectorOf noMatrices (matGen indices) where matGen indices = do [s, t] <- vectorOf 2 (elements indices) m <- callMatrix (Size { rows = r, cols = c }) mkCall s t m <$> arbitrary ( ASR 2018 - 01 - 06 ) Since some properties use implicit parameters we can not use ' allProperties ' for collecting all the tests ( see tests :: TestTree tests = testGroup "Internal.Termination.CallGraph" []
0e01fdb77ad67259b310968f626e04ef7c11610da875559b8b9423bf095108bb
acieroid/scala-am
f-0.scm
(letrec ((f (lambda (x) (+ (* x x) (* x x)))) (g (lambda (x) (+ (* x x) (* x x))))) (let ((_tmp1 (f 1))) (let ((_tmp2 (f 2))) (let ((_tmp3 (f 3))) (let ((_tmp4 (f 4))) (let ((_tmp5 (f 5))) (let ((_tmp6 (f 6))) (let ((_tmp7 (f 7))) (let ((_tmp8 (f 8))) (let ((_tmp9 (f 9))) (f 10)))))))))))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/changesBenevolPaper/f1-tests/f-0.scm
scheme
(letrec ((f (lambda (x) (+ (* x x) (* x x)))) (g (lambda (x) (+ (* x x) (* x x))))) (let ((_tmp1 (f 1))) (let ((_tmp2 (f 2))) (let ((_tmp3 (f 3))) (let ((_tmp4 (f 4))) (let ((_tmp5 (f 5))) (let ((_tmp6 (f 6))) (let ((_tmp7 (f 7))) (let ((_tmp8 (f 8))) (let ((_tmp9 (f 9))) (f 10)))))))))))
bcff33f9d5be45875f28ff3c02e838394380d7865e193f5ee1b98e21f4ce9604
dcastro/twenty48
Twenty48.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} # LANGUAGE TemplateHaskell # module Handler.Twenty48 where import Import import Text.Hamlet (hamletFile) import Text.Julius (juliusFile) import Text.Shakespeare.Sass getTwenty48R :: Handler Html getTwenty48R = do pc <- widgetToPageContent $ do traverse_ toWidget [ $(juliusFile "templates/js/bind_polyfill.js") , $(juliusFile "templates/js/classlist_polyfill.js") , $(juliusFile "templates/js/animframe_polyfill.js") , $(juliusFile "templates/js/keyboard_input_manager.js") , $(juliusFile "templates/js/html_actuator.js") , $(juliusFile "templates/js/login_service.js") , $(juliusFile "templates/js/grid.js") , $(juliusFile "templates/js/tile.js") , $(juliusFile "templates/js/local_storage_manager.js") , $(juliusFile "templates/js/game_manager.julius") , $(juliusFile "templates/js/application.js") ] toWidget $(wsass' [] "templates/sass/main.scss") withUrlRenderer $(hamletFile "templates/twenty48.hamlet")
null
https://raw.githubusercontent.com/dcastro/twenty48/d4a58bfa389bb247525fd18f80ef428d84ef5fe9/src/Handler/Twenty48.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE QuasiQuotes #
# LANGUAGE TemplateHaskell # module Handler.Twenty48 where import Import import Text.Hamlet (hamletFile) import Text.Julius (juliusFile) import Text.Shakespeare.Sass getTwenty48R :: Handler Html getTwenty48R = do pc <- widgetToPageContent $ do traverse_ toWidget [ $(juliusFile "templates/js/bind_polyfill.js") , $(juliusFile "templates/js/classlist_polyfill.js") , $(juliusFile "templates/js/animframe_polyfill.js") , $(juliusFile "templates/js/keyboard_input_manager.js") , $(juliusFile "templates/js/html_actuator.js") , $(juliusFile "templates/js/login_service.js") , $(juliusFile "templates/js/grid.js") , $(juliusFile "templates/js/tile.js") , $(juliusFile "templates/js/local_storage_manager.js") , $(juliusFile "templates/js/game_manager.julius") , $(juliusFile "templates/js/application.js") ] toWidget $(wsass' [] "templates/sass/main.scss") withUrlRenderer $(hamletFile "templates/twenty48.hamlet")
ec6e3e66fca1ca04a521687e5ebfa4b1f53f1746c99fd19b8fe3f93d743dc436
jrclogic/SMCDEL
S5.hs
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts # module SMCDEL.Explicit.S5 where import Control.Arrow (second,(&&&)) import Data.Dynamic import Data.GraphViz import Data.List import Data.Tuple (swap) import Data.Maybe (fromMaybe) import SMCDEL.Language import SMCDEL.Internal.TexDisplay import SMCDEL.Internal.Help (alleqWith,fusion,apply,(!),lfp) import Test.QuickCheck type World = Int class HasWorlds a where worldsOf :: a -> [World] instance (HasWorlds a, Pointed a b) => HasWorlds (a,b) where worldsOf = worldsOf . fst type Partition = [[World]] type Assignment = [(Prp,Bool)] data KripkeModelS5 = KrMS5 [World] [(Agent,Partition)] [(World,Assignment)] deriving (Eq,Ord,Show) instance Pointed KripkeModelS5 World type PointedModelS5 = (KripkeModelS5,World) instance Pointed KripkeModelS5 [World] type MultipointedModelS5 = (KripkeModelS5,[World]) instance HasAgents KripkeModelS5 where agentsOf (KrMS5 _ rel _) = map fst rel instance HasVocab KripkeModelS5 where vocabOf (KrMS5 _ _ val) = map fst $ snd (head val) instance HasWorlds KripkeModelS5 where worldsOf (KrMS5 ws _ _) = ws newtype PropList = PropList [Prp] withoutWorld :: KripkeModelS5 -> World -> KripkeModelS5 withoutWorld (KrMS5 worlds parts val) w = KrMS5 (delete w worlds) (map (second (filter (/=[]) . map (delete w))) parts) (filter ((/=w).fst) val) withoutProps :: KripkeModelS5 -> [Prp] -> KripkeModelS5 withoutProps (KrMS5 worlds parts val) dropProps = KrMS5 worlds parts (map (second $ filter ((`notElem` dropProps) . fst)) val) instance Arbitrary PropList where arbitrary = do moreprops <- sublistOf (map P [1..10]) return $ PropList $ P 0 : moreprops randomPartFor :: [World] -> Gen Partition randomPartFor worlds = do indices <- infiniteListOf $ choose (1, length worlds) let pairs = zip worlds indices let parts = [ sort $ map fst $ filter ((==k).snd) pairs | k <- [1 .. (length worlds)] ] return $ sort $ filter (/=[]) parts instance Arbitrary KripkeModelS5 where arbitrary = do nonActualWorlds <- sublistOf [1..8] let worlds = 0 : nonActualWorlds val <- mapM (\w -> do myAssignment <- zip defaultVocabulary <$> infiniteListOf (choose (True,False)) return (w,myAssignment) ) worlds parts <- mapM (\i -> do myPartition <- randomPartFor worlds return (i,myPartition) ) defaultAgents return $ KrMS5 worlds parts val shrink m@(KrMS5 worlds _ _) = [ m `withoutWorld` w | w <- worlds, not (null $ delete w worlds) ] eval :: PointedModelS5 -> Form -> Bool eval _ Top = True eval _ Bot = False eval (KrMS5 _ _ val, cur) (PrpF p) = apply (apply val cur) p eval pm (Neg form) = not $ eval pm form eval pm (Conj forms) = all (eval pm) forms eval pm (Disj forms) = any (eval pm) forms eval pm (Xor forms) = odd $ length (filter id $ map (eval pm) forms) eval pm (Impl f g) = not (eval pm f) || eval pm g eval pm (Equi f g) = eval pm f == eval pm g eval pm (Forall ps f) = eval pm (foldl singleForall f ps) where singleForall g p = Conj [ substit p Top g, substit p Bot g ] eval pm (Exists ps f) = eval pm (foldl singleExists f ps) where singleExists g p = Disj [ substit p Top g, substit p Bot g ] eval (m@(KrMS5 _ rel _),w) (K ag form) = all (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) (apply rel ag) eval (m@(KrMS5 _ rel _),w) (Kw ag form) = alleqWith (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) (apply rel ag) eval (m@(KrMS5 _ rel _),w) (Ck ags form) = all (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) ckrel ckrel = fusion $ concat [ apply rel i | i <- ags ] eval (m@(KrMS5 _ rel _),w) (Ckw ags form) = alleqWith (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) ckrel ckrel = fusion $ concat [ apply rel i | i <- ags ] eval pm (PubAnnounce form1 form2) = not (eval pm form1) || eval (update pm form1) form2 eval pm (PubAnnounceW form1 form2) = if eval pm form1 then eval (update pm form1) form2 else eval (update pm (Neg form1)) form2 eval pm (Announce ags form1 form2) = not (eval pm form1) || eval (announce pm ags form1) form2 eval pm (AnnounceW ags form1 form2) = if eval pm form1 then eval (announce pm ags form1) form2 else eval (announce pm ags (Neg form1)) form2 eval pm (Dia (Dyn dynLabel d) f) = case fromDynamic d of Just pactm -> eval pm (preOf (pactm :: PointedActionModelS5)) && eval (pm `update` pactm) f Nothing -> case fromDynamic d of Just mpactm -> eval pm (preOf (mpactm :: MultipointedActionModelS5)) && eval (pm `update` mpactm) f Nothing -> error $ "cannot update S5 Kripke model with '" ++ dynLabel ++ "':\n " ++ show d valid :: KripkeModelS5 -> Form -> Bool valid m@(KrMS5 worlds _ _) f = all (\w -> eval (m,w) f) worlds instance Semantics KripkeModelS5 where isTrue m f = all (\w -> isTrue (m,w) f) (worldsOf m) instance Semantics PointedModelS5 where isTrue = eval instance Semantics MultipointedModelS5 where isTrue (m,ws) f = all (\w -> isTrue (m,w) f) ws | Public announcements on models . instance Update KripkeModelS5 Form where checks = [] -- allow updating with formulas that are not globally true. unsafeUpdate m@(KrMS5 sts rel val) form = KrMS5 newsts newrel newval where newsts = filter (\s -> eval (m,s) form) sts newrel = map (second relfil) rel relfil = filter ([]/=) . map (filter (`elem` newsts)) newval = filter (\p -> fst p `elem` newsts) val instance Update PointedModelS5 Form where unsafeUpdate (m,w) f = (unsafeUpdate m f, w) instance Update MultipointedModelS5 Form where unsafeUpdate (m,ws) f = let newm = unsafeUpdate m f in (newm, ws `intersect` worldsOf newm) announce :: PointedModelS5 -> [Agent] -> Form -> PointedModelS5 announce pm@(m@(KrMS5 sts rel val), cur) ags form = if eval pm form then (KrMS5 sts newrel val, cur) else error "announce failed: Liar!" where split ws = map sort.(\(x,y) -> [x,y]) $ partition (\s -> eval (m,s) form) ws newrel = map nrel rel nrel (i,ri) | i `elem` ags = (i,filter ([]/=) (concatMap split ri)) | otherwise = (i,ri) announceAction :: [Agent] -> [Agent] -> Form -> PointedActionModelS5 announceAction everyone listeners f = (am, 1) where [ ( Action,(Form , PostCondition ) ) ] [ ( Agent , Partition ) ] [ (1, (f, [])), (2, (Top, [])) ] [ (i, if i `elem` listeners then [[1],[2]] else [[1,2]] ) | i <- everyone ] instance KripkeLike KripkeModelS5 where directed = const False getNodes (KrMS5 ws _ val) = map (show &&& labelOf) ws where labelOf w = tex $ apply val w getEdges (KrMS5 _ rel _) = nub [ (a,show x,show y) | a <- map fst rel, part <- apply rel a, x <- part, y <- part, x < y ] instance TexAble KripkeModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike PointedModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, cur) = [show cur] instance TexAble PointedModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike MultipointedModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, curs) = map show curs instance TexAble MultipointedModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot type Bisimulation = [(World,World)] checkBisim :: Bisimulation -> KripkeModelS5 -> KripkeModelS5 -> Bool checkBisim [] _ _ = False checkBisim z m1@(KrMS5 _ rel1 val1) m2@(KrMS5 _ rel2 val2) = all (\(w1,w2) -> (val1 ! w1 == val2 ! w2) -- same valuation && and [ any (\v2 -> (v1,v2) `elem` z) (concat $ filter (elem w2) (rel2 ! ag)) -- forth | ag <- agentsOf m1, v1 <- concat $ filter (elem w1) (rel1 ! ag) ] && and [ any (\v1 -> (v1,v2) `elem` z) (concat $ filter (elem w1) (rel1 ! ag)) -- back | ag <- agentsOf m2, v2 <- concat $ filter (elem w2) (rel2 ! ag) ] ) z checkBisimPointed :: Bisimulation -> PointedModelS5 -> PointedModelS5 -> Bool checkBisimPointed z (m1,w1) (m2,w2) = (w1,w2) `elem` z && checkBisim z m1 m2 generatedSubmodel :: PointedModelS5 -> PointedModelS5 generatedSubmodel (KrMS5 oldWorlds rel val, cur) = if cur `notElem` oldWorlds then error "Actual world is not in the model!" else (KrMS5 newWorlds newrel newval, cur) where newWorlds :: [World] newWorlds = lfp follow [cur] where follow xs = sort . nub $ concat [ part | (_,parts) <- rel, part <- parts, any (`elem` part) xs ] newrel = map (second $ filter (any (`elem` newWorlds))) rel newval = filter (\p -> fst p `elem` newWorlds) val bisimClasses :: KripkeModelS5 -> [[World]] bisimClasses m@(KrMS5 _ rel val) = refine sameAssignmentPartition where sameAssignmentPartition = map (map snd) $ groupBy (\x y -> fst x == fst y) $ sort (map swap val) refine parts = sort $ map sort $ foldl splitByAgent parts (agentsOf m) splitByAgent parts a = concat [ filter (not . null) [ ws `intersect` aPart | aPart <- rel ! a ] | ws <- parts ] checkBisimClasses :: KripkeModelS5 -> Bool checkBisimClasses m = and [ checkBisimPointed (swapZ w1 w2) (m,w1) (m,w2) | part <- bisimClasses m, w1 <- part, w2 <-part, w1 /= w2 ] where swapZ w1 w2 = sort $ [(w1,w2),(w2,w1)] ++ [ (w,w) | w <- worldsOf m \\ [w1,w2] ] bisiminimize :: PointedModelS5 -> PointedModelS5 bisiminimize (m,w) = if all ((==1) . length) (bisimClasses m) then (m,w) -- nothing to minimize else (KrMS5 newWorlds newRel newVal, copyFct w) where KrMS5 _ oldRel oldVal = m copyRel = zip (bisimClasses m) [1..] copyFct wOld = snd $ head $ filter ((wOld `elem`) . fst) copyRel newWorlds = map snd copyRel newRel = [ (a,newRelFor a) | a <- agentsOf m ] newRelFor a = [ nub [ copyFct wOld | wOld <- part ] | part <- oldRel ! a ] newVal = [ (wNew, oldVal ! wOld) | (wOld:_,wNew) <- copyRel ] instance Optimizable PointedModelS5 where optimize _ = bisiminimize . generatedSubmodel type Action = Int type PostCondition = [(Prp,Form)] data ActionModelS5 = ActMS5 [(Action,(Form,PostCondition))] [(Agent,Partition)] deriving (Eq,Ord,Show) instance HasAgents ActionModelS5 where agentsOf (ActMS5 _ rel) = map fst rel -- | A safe way to `lookup` all postconditions safepost :: PostCondition -> Prp -> Form safepost posts p = fromMaybe (PrpF p) (lookup p posts) instance Pointed ActionModelS5 Action type PointedActionModelS5 = (ActionModelS5, Action) instance HasPrecondition ActionModelS5 where preOf _ = Top instance HasPrecondition PointedActionModelS5 where preOf (ActMS5 acts _, actual) = fst (acts ! actual) instance Pointed ActionModelS5 [Action] type MultipointedActionModelS5 = (ActionModelS5,[Action]) instance HasPrecondition MultipointedActionModelS5 where preOf (am, actuals) = Disj [ preOf (am, a) | a <- actuals ] instance KripkeLike ActionModelS5 where directed = const False getNodes (ActMS5 acts _) = map labelOf acts where labelOf (a,(pre,posts)) = (show a, concat [ "$\\begin{array}{c} ? " , tex pre, "\\\\" , intercalate "\\\\" (map showPost posts) , "\\end{array}$" ]) showPost (p,f) = tex p ++ " := " ++ tex f getEdges am@(ActMS5 _ rel) = nub [ (a, show x, show y) | a <- agentsOf am, part <- rel ! a, x <- part, y <- part, x < y ] getActuals _ = [ ] nodeAts _ True = [shape BoxShape, style solid] nodeAts _ False = [shape BoxShape, style dashed] instance TexAble ActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike PointedActionModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, cur) = [show cur] instance TexAble PointedActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike MultipointedActionModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, curs) = map show curs instance TexAble MultipointedActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance Arbitrary ActionModelS5 where arbitrary = do BF f <- sized $ randomboolformWith [P 0 .. P 4] BF g <- sized $ randomboolformWith [P 0 .. P 4] BF h <- sized $ randomboolformWith [P 0 .. P 4] myPost <- (\_ -> do proptochange <- elements [P 0 .. P 4] postconcon <- elements $ [Top,Bot] ++ map PrpF [P 0 .. P 4] return [ (proptochange, postconcon) ] ) (0::Action) return $ ActMS5 [ (0,(Top,[])) , (1,(f ,[])) , (2,(g ,myPost)) , (3,(h ,[])) ] ( ("0",[[0],[1],[2],[3]]):[(show k,[[0..3::Int]]) | k<-[1..5::Int] ]) instance Update KripkeModelS5 ActionModelS5 where checks = [haveSameAgents] unsafeUpdate m am@(ActMS5 acts _) = let (newModel,_) = unsafeUpdate (m, worldsOf m) (am, map fst acts) in newModel instance Update PointedModelS5 PointedActionModelS5 where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) (actm, a) = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) (actm, [a]) in (newModel,newWorld) instance Update PointedModelS5 MultipointedActionModelS5 where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) mpactm = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) mpactm in (newModel,newWorld) instance Update MultipointedModelS5 PointedActionModelS5 where checks = [haveSameAgents] -- do not check precondition! unsafeUpdate mpm (actm, a) = unsafeUpdate mpm (actm, [a]) instance Update MultipointedModelS5 MultipointedActionModelS5 where checks = [haveSameAgents] -- do not check precondition! unsafeUpdate (m@(KrMS5 oldWorlds oldrel oldval), oldcurs) (ActMS5 acts actrel, factions) = (KrMS5 newWorlds newrel newval, newcurs) where startcount = maximum oldWorlds + 1 copiesOf (s,a) = [ (s, a, a * startcount + s) | eval (m, s) (fst $ acts ! a) ] newWorldsTriples = concat [ copiesOf (s,a) | s <- oldWorlds, (a,_) <- acts ] newWorlds = map (\(_,_,x) -> x) newWorldsTriples newval = map (\(s,a,t) -> (t, newValAt (s,a))) newWorldsTriples where newValAt sa = [ (p, newValAtFor sa p) | p <- vocabOf m ] newValAtFor (s,a) p = case lookup p (snd (acts ! a)) of Just postOfP -> eval (m, s) postOfP Nothing -> (oldval ! s) ! p listFor ag = cartProd (apply oldrel ag) (apply actrel ag) newPartsFor ag = [ cartProd as bs | (as,bs) <- listFor ag ] translSingle pair = filter (`elem` newWorlds) $ map (\(_,_,x) -> x) $ copiesOf pair transEqClass = concatMap translSingle nTransPartsFor ag = filter (/= []) $ map transEqClass (newPartsFor ag) newrel = [ (a, nTransPartsFor a) | a <- map fst oldrel ] newcurs = concat [ map (\(_,_,x) -> x) $ copiesOf (s,a) | s <- oldcurs, a <- factions ] cartProd xs ys = [ (x,y) | x <- xs, y <- ys ]
null
https://raw.githubusercontent.com/jrclogic/SMCDEL/b20eeaac9900879b1636fba9a0968a80de4eb1c6/src/SMCDEL/Explicit/S5.hs
haskell
allow updating with formulas that are not globally true. same valuation forth back nothing to minimize | A safe way to `lookup` all postconditions do not check precondition! do not check precondition!
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , FlexibleContexts # module SMCDEL.Explicit.S5 where import Control.Arrow (second,(&&&)) import Data.Dynamic import Data.GraphViz import Data.List import Data.Tuple (swap) import Data.Maybe (fromMaybe) import SMCDEL.Language import SMCDEL.Internal.TexDisplay import SMCDEL.Internal.Help (alleqWith,fusion,apply,(!),lfp) import Test.QuickCheck type World = Int class HasWorlds a where worldsOf :: a -> [World] instance (HasWorlds a, Pointed a b) => HasWorlds (a,b) where worldsOf = worldsOf . fst type Partition = [[World]] type Assignment = [(Prp,Bool)] data KripkeModelS5 = KrMS5 [World] [(Agent,Partition)] [(World,Assignment)] deriving (Eq,Ord,Show) instance Pointed KripkeModelS5 World type PointedModelS5 = (KripkeModelS5,World) instance Pointed KripkeModelS5 [World] type MultipointedModelS5 = (KripkeModelS5,[World]) instance HasAgents KripkeModelS5 where agentsOf (KrMS5 _ rel _) = map fst rel instance HasVocab KripkeModelS5 where vocabOf (KrMS5 _ _ val) = map fst $ snd (head val) instance HasWorlds KripkeModelS5 where worldsOf (KrMS5 ws _ _) = ws newtype PropList = PropList [Prp] withoutWorld :: KripkeModelS5 -> World -> KripkeModelS5 withoutWorld (KrMS5 worlds parts val) w = KrMS5 (delete w worlds) (map (second (filter (/=[]) . map (delete w))) parts) (filter ((/=w).fst) val) withoutProps :: KripkeModelS5 -> [Prp] -> KripkeModelS5 withoutProps (KrMS5 worlds parts val) dropProps = KrMS5 worlds parts (map (second $ filter ((`notElem` dropProps) . fst)) val) instance Arbitrary PropList where arbitrary = do moreprops <- sublistOf (map P [1..10]) return $ PropList $ P 0 : moreprops randomPartFor :: [World] -> Gen Partition randomPartFor worlds = do indices <- infiniteListOf $ choose (1, length worlds) let pairs = zip worlds indices let parts = [ sort $ map fst $ filter ((==k).snd) pairs | k <- [1 .. (length worlds)] ] return $ sort $ filter (/=[]) parts instance Arbitrary KripkeModelS5 where arbitrary = do nonActualWorlds <- sublistOf [1..8] let worlds = 0 : nonActualWorlds val <- mapM (\w -> do myAssignment <- zip defaultVocabulary <$> infiniteListOf (choose (True,False)) return (w,myAssignment) ) worlds parts <- mapM (\i -> do myPartition <- randomPartFor worlds return (i,myPartition) ) defaultAgents return $ KrMS5 worlds parts val shrink m@(KrMS5 worlds _ _) = [ m `withoutWorld` w | w <- worlds, not (null $ delete w worlds) ] eval :: PointedModelS5 -> Form -> Bool eval _ Top = True eval _ Bot = False eval (KrMS5 _ _ val, cur) (PrpF p) = apply (apply val cur) p eval pm (Neg form) = not $ eval pm form eval pm (Conj forms) = all (eval pm) forms eval pm (Disj forms) = any (eval pm) forms eval pm (Xor forms) = odd $ length (filter id $ map (eval pm) forms) eval pm (Impl f g) = not (eval pm f) || eval pm g eval pm (Equi f g) = eval pm f == eval pm g eval pm (Forall ps f) = eval pm (foldl singleForall f ps) where singleForall g p = Conj [ substit p Top g, substit p Bot g ] eval pm (Exists ps f) = eval pm (foldl singleExists f ps) where singleExists g p = Disj [ substit p Top g, substit p Bot g ] eval (m@(KrMS5 _ rel _),w) (K ag form) = all (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) (apply rel ag) eval (m@(KrMS5 _ rel _),w) (Kw ag form) = alleqWith (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) (apply rel ag) eval (m@(KrMS5 _ rel _),w) (Ck ags form) = all (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) ckrel ckrel = fusion $ concat [ apply rel i | i <- ags ] eval (m@(KrMS5 _ rel _),w) (Ckw ags form) = alleqWith (\w' -> eval (m,w') form) vs where vs = concat $ filter (elem w) ckrel ckrel = fusion $ concat [ apply rel i | i <- ags ] eval pm (PubAnnounce form1 form2) = not (eval pm form1) || eval (update pm form1) form2 eval pm (PubAnnounceW form1 form2) = if eval pm form1 then eval (update pm form1) form2 else eval (update pm (Neg form1)) form2 eval pm (Announce ags form1 form2) = not (eval pm form1) || eval (announce pm ags form1) form2 eval pm (AnnounceW ags form1 form2) = if eval pm form1 then eval (announce pm ags form1) form2 else eval (announce pm ags (Neg form1)) form2 eval pm (Dia (Dyn dynLabel d) f) = case fromDynamic d of Just pactm -> eval pm (preOf (pactm :: PointedActionModelS5)) && eval (pm `update` pactm) f Nothing -> case fromDynamic d of Just mpactm -> eval pm (preOf (mpactm :: MultipointedActionModelS5)) && eval (pm `update` mpactm) f Nothing -> error $ "cannot update S5 Kripke model with '" ++ dynLabel ++ "':\n " ++ show d valid :: KripkeModelS5 -> Form -> Bool valid m@(KrMS5 worlds _ _) f = all (\w -> eval (m,w) f) worlds instance Semantics KripkeModelS5 where isTrue m f = all (\w -> isTrue (m,w) f) (worldsOf m) instance Semantics PointedModelS5 where isTrue = eval instance Semantics MultipointedModelS5 where isTrue (m,ws) f = all (\w -> isTrue (m,w) f) ws | Public announcements on models . instance Update KripkeModelS5 Form where unsafeUpdate m@(KrMS5 sts rel val) form = KrMS5 newsts newrel newval where newsts = filter (\s -> eval (m,s) form) sts newrel = map (second relfil) rel relfil = filter ([]/=) . map (filter (`elem` newsts)) newval = filter (\p -> fst p `elem` newsts) val instance Update PointedModelS5 Form where unsafeUpdate (m,w) f = (unsafeUpdate m f, w) instance Update MultipointedModelS5 Form where unsafeUpdate (m,ws) f = let newm = unsafeUpdate m f in (newm, ws `intersect` worldsOf newm) announce :: PointedModelS5 -> [Agent] -> Form -> PointedModelS5 announce pm@(m@(KrMS5 sts rel val), cur) ags form = if eval pm form then (KrMS5 sts newrel val, cur) else error "announce failed: Liar!" where split ws = map sort.(\(x,y) -> [x,y]) $ partition (\s -> eval (m,s) form) ws newrel = map nrel rel nrel (i,ri) | i `elem` ags = (i,filter ([]/=) (concatMap split ri)) | otherwise = (i,ri) announceAction :: [Agent] -> [Agent] -> Form -> PointedActionModelS5 announceAction everyone listeners f = (am, 1) where [ ( Action,(Form , PostCondition ) ) ] [ ( Agent , Partition ) ] [ (1, (f, [])), (2, (Top, [])) ] [ (i, if i `elem` listeners then [[1],[2]] else [[1,2]] ) | i <- everyone ] instance KripkeLike KripkeModelS5 where directed = const False getNodes (KrMS5 ws _ val) = map (show &&& labelOf) ws where labelOf w = tex $ apply val w getEdges (KrMS5 _ rel _) = nub [ (a,show x,show y) | a <- map fst rel, part <- apply rel a, x <- part, y <- part, x < y ] instance TexAble KripkeModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike PointedModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, cur) = [show cur] instance TexAble PointedModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike MultipointedModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, curs) = map show curs instance TexAble MultipointedModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot type Bisimulation = [(World,World)] checkBisim :: Bisimulation -> KripkeModelS5 -> KripkeModelS5 -> Bool checkBisim [] _ _ = False checkBisim z m1@(KrMS5 _ rel1 val1) m2@(KrMS5 _ rel2 val2) = all (\(w1,w2) -> | ag <- agentsOf m1, v1 <- concat $ filter (elem w1) (rel1 ! ag) ] | ag <- agentsOf m2, v2 <- concat $ filter (elem w2) (rel2 ! ag) ] ) z checkBisimPointed :: Bisimulation -> PointedModelS5 -> PointedModelS5 -> Bool checkBisimPointed z (m1,w1) (m2,w2) = (w1,w2) `elem` z && checkBisim z m1 m2 generatedSubmodel :: PointedModelS5 -> PointedModelS5 generatedSubmodel (KrMS5 oldWorlds rel val, cur) = if cur `notElem` oldWorlds then error "Actual world is not in the model!" else (KrMS5 newWorlds newrel newval, cur) where newWorlds :: [World] newWorlds = lfp follow [cur] where follow xs = sort . nub $ concat [ part | (_,parts) <- rel, part <- parts, any (`elem` part) xs ] newrel = map (second $ filter (any (`elem` newWorlds))) rel newval = filter (\p -> fst p `elem` newWorlds) val bisimClasses :: KripkeModelS5 -> [[World]] bisimClasses m@(KrMS5 _ rel val) = refine sameAssignmentPartition where sameAssignmentPartition = map (map snd) $ groupBy (\x y -> fst x == fst y) $ sort (map swap val) refine parts = sort $ map sort $ foldl splitByAgent parts (agentsOf m) splitByAgent parts a = concat [ filter (not . null) [ ws `intersect` aPart | aPart <- rel ! a ] | ws <- parts ] checkBisimClasses :: KripkeModelS5 -> Bool checkBisimClasses m = and [ checkBisimPointed (swapZ w1 w2) (m,w1) (m,w2) | part <- bisimClasses m, w1 <- part, w2 <-part, w1 /= w2 ] where swapZ w1 w2 = sort $ [(w1,w2),(w2,w1)] ++ [ (w,w) | w <- worldsOf m \\ [w1,w2] ] bisiminimize :: PointedModelS5 -> PointedModelS5 bisiminimize (m,w) = if all ((==1) . length) (bisimClasses m) else (KrMS5 newWorlds newRel newVal, copyFct w) where KrMS5 _ oldRel oldVal = m copyRel = zip (bisimClasses m) [1..] copyFct wOld = snd $ head $ filter ((wOld `elem`) . fst) copyRel newWorlds = map snd copyRel newRel = [ (a,newRelFor a) | a <- agentsOf m ] newRelFor a = [ nub [ copyFct wOld | wOld <- part ] | part <- oldRel ! a ] newVal = [ (wNew, oldVal ! wOld) | (wOld:_,wNew) <- copyRel ] instance Optimizable PointedModelS5 where optimize _ = bisiminimize . generatedSubmodel type Action = Int type PostCondition = [(Prp,Form)] data ActionModelS5 = ActMS5 [(Action,(Form,PostCondition))] [(Agent,Partition)] deriving (Eq,Ord,Show) instance HasAgents ActionModelS5 where agentsOf (ActMS5 _ rel) = map fst rel safepost :: PostCondition -> Prp -> Form safepost posts p = fromMaybe (PrpF p) (lookup p posts) instance Pointed ActionModelS5 Action type PointedActionModelS5 = (ActionModelS5, Action) instance HasPrecondition ActionModelS5 where preOf _ = Top instance HasPrecondition PointedActionModelS5 where preOf (ActMS5 acts _, actual) = fst (acts ! actual) instance Pointed ActionModelS5 [Action] type MultipointedActionModelS5 = (ActionModelS5,[Action]) instance HasPrecondition MultipointedActionModelS5 where preOf (am, actuals) = Disj [ preOf (am, a) | a <- actuals ] instance KripkeLike ActionModelS5 where directed = const False getNodes (ActMS5 acts _) = map labelOf acts where labelOf (a,(pre,posts)) = (show a, concat [ "$\\begin{array}{c} ? " , tex pre, "\\\\" , intercalate "\\\\" (map showPost posts) , "\\end{array}$" ]) showPost (p,f) = tex p ++ " := " ++ tex f getEdges am@(ActMS5 _ rel) = nub [ (a, show x, show y) | a <- agentsOf am, part <- rel ! a, x <- part, y <- part, x < y ] getActuals _ = [ ] nodeAts _ True = [shape BoxShape, style solid] nodeAts _ False = [shape BoxShape, style dashed] instance TexAble ActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike PointedActionModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, cur) = [show cur] instance TexAble PointedActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance KripkeLike MultipointedActionModelS5 where directed = directed . fst getNodes = getNodes . fst getEdges = getEdges . fst getActuals (_, curs) = map show curs instance TexAble MultipointedActionModelS5 where tex = tex.ViaDot texTo = texTo.ViaDot texDocumentTo = texDocumentTo.ViaDot instance Arbitrary ActionModelS5 where arbitrary = do BF f <- sized $ randomboolformWith [P 0 .. P 4] BF g <- sized $ randomboolformWith [P 0 .. P 4] BF h <- sized $ randomboolformWith [P 0 .. P 4] myPost <- (\_ -> do proptochange <- elements [P 0 .. P 4] postconcon <- elements $ [Top,Bot] ++ map PrpF [P 0 .. P 4] return [ (proptochange, postconcon) ] ) (0::Action) return $ ActMS5 [ (0,(Top,[])) , (1,(f ,[])) , (2,(g ,myPost)) , (3,(h ,[])) ] ( ("0",[[0],[1],[2],[3]]):[(show k,[[0..3::Int]]) | k<-[1..5::Int] ]) instance Update KripkeModelS5 ActionModelS5 where checks = [haveSameAgents] unsafeUpdate m am@(ActMS5 acts _) = let (newModel,_) = unsafeUpdate (m, worldsOf m) (am, map fst acts) in newModel instance Update PointedModelS5 PointedActionModelS5 where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) (actm, a) = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) (actm, [a]) in (newModel,newWorld) instance Update PointedModelS5 MultipointedActionModelS5 where checks = [haveSameAgents,preCheck] unsafeUpdate (m, w) mpactm = let (newModel,[newWorld]) = unsafeUpdate (m, [w]) mpactm in (newModel,newWorld) instance Update MultipointedModelS5 PointedActionModelS5 where unsafeUpdate mpm (actm, a) = unsafeUpdate mpm (actm, [a]) instance Update MultipointedModelS5 MultipointedActionModelS5 where unsafeUpdate (m@(KrMS5 oldWorlds oldrel oldval), oldcurs) (ActMS5 acts actrel, factions) = (KrMS5 newWorlds newrel newval, newcurs) where startcount = maximum oldWorlds + 1 copiesOf (s,a) = [ (s, a, a * startcount + s) | eval (m, s) (fst $ acts ! a) ] newWorldsTriples = concat [ copiesOf (s,a) | s <- oldWorlds, (a,_) <- acts ] newWorlds = map (\(_,_,x) -> x) newWorldsTriples newval = map (\(s,a,t) -> (t, newValAt (s,a))) newWorldsTriples where newValAt sa = [ (p, newValAtFor sa p) | p <- vocabOf m ] newValAtFor (s,a) p = case lookup p (snd (acts ! a)) of Just postOfP -> eval (m, s) postOfP Nothing -> (oldval ! s) ! p listFor ag = cartProd (apply oldrel ag) (apply actrel ag) newPartsFor ag = [ cartProd as bs | (as,bs) <- listFor ag ] translSingle pair = filter (`elem` newWorlds) $ map (\(_,_,x) -> x) $ copiesOf pair transEqClass = concatMap translSingle nTransPartsFor ag = filter (/= []) $ map transEqClass (newPartsFor ag) newrel = [ (a, nTransPartsFor a) | a <- map fst oldrel ] newcurs = concat [ map (\(_,_,x) -> x) $ copiesOf (s,a) | s <- oldcurs, a <- factions ] cartProd xs ys = [ (x,y) | x <- xs, y <- ys ]
ad07d6dd4435b7e11e76fbb8e56d6302c0beed7a7d19735cca622954e0f9d366
haskell-suite/haskell-src-exts
FixityTests.hs
main = forM_ cmdReports $ \x -> do putStrLn $ "Writing report to " ++ x ++ " ..." writeReport x ideas
null
https://raw.githubusercontent.com/haskell-suite/haskell-src-exts/84a4930e0e5c051b7d9efd20ef7c822d5fc1c33b/tests/examples/FixityTests.hs
haskell
main = forM_ cmdReports $ \x -> do putStrLn $ "Writing report to " ++ x ++ " ..." writeReport x ideas
1a463e1237cd30bed4ba9f2eea24ac74f55a6e403b9cbea917b9bce0ea5ec37a
cushon/project-euler
48.rkt
#lang racket (require "common.rkt") Find the last 10 digits of the series 1 ^ 1 + 2 ^ 2 + ... + 1000 ^ 1000 . (define (solve) (define (last10 n) (remainder n (expt 10 10))) (last10 (foldr + 0 (map (lambda (x) (last10 (expt x x))) (range 1 1000))))) (provide solve)
null
https://raw.githubusercontent.com/cushon/project-euler/d7fcbfff0cd59b2c3691293ff35bb2043b409f68/48.rkt
racket
#lang racket (require "common.rkt") Find the last 10 digits of the series 1 ^ 1 + 2 ^ 2 + ... + 1000 ^ 1000 . (define (solve) (define (last10 n) (remainder n (expt 10 10))) (last10 (foldr + 0 (map (lambda (x) (last10 (expt x x))) (range 1 1000))))) (provide solve)
b8718cae021be9de2a7d3747fc3ffe2cc27030dd409a7791140d9dcf85560cd0
lexi-lambda/freer-simple
Coroutine.hs
-- | Module : Control . . Freer . Coroutine -- Description: Composable coroutine effects layer. Copyright : ( c ) 2016 Allele Dev ; 2017 Ixperta Solutions s.r.o . ; 2017 -- License: BSD3 Maintainer : < > -- Stability: experimental Portability : GHC specific language extensions . -- -- An effect to compose functions with the ability to yield. -- -- Using <> as a starting point. module Control.Monad.Freer.Coroutine ( -- * Yield Control Yield(..) , yield -- * Handle Yield Effect , Status(..) , runC , interposeC , replyC ) where import Control.Monad.Freer.Internal (Eff, Member, handleRelay, interpose, send) -- | A type representing a yielding of control. -- -- Type variables have following meaning: -- -- [@a@] -- The current type. -- -- [@b@] -- The input to the continuation function. -- -- [@c@] -- The output of the continuation. data Yield a b c = Yield a (b -> c) deriving (Functor) | Lifts a value and a function into the Coroutine effect . yield :: Member (Yield a b) effs => a -> (b -> c) -> Eff effs c yield x f = send (Yield x f) -- | Represents status of a coroutine. data Status effs a b r = Done r ^ Coroutine is done with a result value of type @r@. | Continue a (b -> Eff effs (Status effs a b r)) -- ^ Reporting a value of the type @a@, and resuming with the value of type @b@ , possibly ending with a value of type @x@. | Reply to a coroutine effect by returning the Continue constructor . replyC :: Yield a b c -> (c -> Eff effs (Status effs a b r)) -> Eff effs (Status effs a b r) replyC (Yield a k) arr = pure $ Continue a (arr . k) -- | Launch a coroutine and report its status. runC :: Eff (Yield a b ': effs) r -> Eff effs (Status effs a b r) runC = handleRelay (pure . Done) replyC -- | Launch a coroutine and report its status, without handling (removing) -- 'Yield' from the typelist. This is useful for reducing nested coroutines. interposeC :: Member (Yield a b) effs => Eff effs r -> Eff effs (Status effs a b r) interposeC = interpose (pure . Done) replyC
null
https://raw.githubusercontent.com/lexi-lambda/freer-simple/e5ef0fec4a79585f99c0df8bc9e2e67cc0c0fb4a/src/Control/Monad/Freer/Coroutine.hs
haskell
| Description: Composable coroutine effects layer. License: BSD3 Stability: experimental An effect to compose functions with the ability to yield. Using <> as a starting point. * Yield Control * Handle Yield Effect | A type representing a yielding of control. Type variables have following meaning: [@a@] The current type. [@b@] The input to the continuation function. [@c@] The output of the continuation. | Represents status of a coroutine. ^ Reporting a value of the type @a@, and resuming with the value of type | Launch a coroutine and report its status. | Launch a coroutine and report its status, without handling (removing) 'Yield' from the typelist. This is useful for reducing nested coroutines.
Module : Control . . Freer . Coroutine Copyright : ( c ) 2016 Allele Dev ; 2017 Ixperta Solutions s.r.o . ; 2017 Maintainer : < > Portability : GHC specific language extensions . module Control.Monad.Freer.Coroutine Yield(..) , yield , Status(..) , runC , interposeC , replyC ) where import Control.Monad.Freer.Internal (Eff, Member, handleRelay, interpose, send) data Yield a b c = Yield a (b -> c) deriving (Functor) | Lifts a value and a function into the Coroutine effect . yield :: Member (Yield a b) effs => a -> (b -> c) -> Eff effs c yield x f = send (Yield x f) data Status effs a b r = Done r ^ Coroutine is done with a result value of type @r@. | Continue a (b -> Eff effs (Status effs a b r)) @b@ , possibly ending with a value of type @x@. | Reply to a coroutine effect by returning the Continue constructor . replyC :: Yield a b c -> (c -> Eff effs (Status effs a b r)) -> Eff effs (Status effs a b r) replyC (Yield a k) arr = pure $ Continue a (arr . k) runC :: Eff (Yield a b ': effs) r -> Eff effs (Status effs a b r) runC = handleRelay (pure . Done) replyC interposeC :: Member (Yield a b) effs => Eff effs r -> Eff effs (Status effs a b r) interposeC = interpose (pure . Done) replyC
b2e0b630cc23498a39c6df8bf9209424bed79a2f4e78002e6a392e0410e357bd
verystable/warframe-autobuilder
MultishotMods.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} -- | -- Module : Builder.Mods.PistolMods.AmmoMods -- Maintainer : -- Stability : experimental -- Contains function that modify multishot , applicable on secondary weapons . module Builder.Mods.PistolMods.MultishotMods where import ClassyPrelude import Control.Lens import GenericFunctions.GenericFunctions import Types.GenericWeapon barrelDiffusion3 :: GenericWeapon -> GenericWeapon -> GenericWeapon barrelDiffusion3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 1.2) (+) targetWeapon # INLINE barrelDiffusion3 # -- | Barrel Diffusion [+120% Multishot] Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) barrelDiffusion :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) barrelDiffusion baseWeapon (targetWeapon, mods) = ( barrelDiffusion3 baseWeapon targetWeapon , "Barrel Diffusion [+120% Multishot]" : mods ) # INLINE barrelDiffusion # lethalTorrent5 :: GenericWeapon -> GenericWeapon -> GenericWeapon lethalTorrent5 baseWeapon targetWeapon = modifyGeneralProperty gwFireRate (baseWeapon ^. gwFireRate) (Just 0.6) (+) targetWeapon # INLINE lethalTorrent5 # lethalTorrent3 :: GenericWeapon -> GenericWeapon -> GenericWeapon lethalTorrent3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 0.6) (+) targetWeapon # INLINE lethalTorrent3 # | Lethal Torrent [ +60 % Multishot , +60 % Fire Rate ] Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) lethalTorrent :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) lethalTorrent baseWeapon (targetWeapon, mods) = ( lethalTorrent3 baseWeapon $ lethalTorrent5 baseWeapon targetWeapon , "Lethal Torrent [+60% Multishot]" : mods ) # INLINE lethalTorrent # amalgamBarrelDiffusion3 :: GenericWeapon -> GenericWeapon -> GenericWeapon amalgamBarrelDiffusion3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 1.1) (+) targetWeapon # INLINE amalgamBarrelDiffusion3 # -- | Amalgam Barrel Diffusion [+110% Multishot] Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) amalgamBarrelDiffusion :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) amalgamBarrelDiffusion baseWeapon (targetWeapon, mods) = ( amalgamBarrelDiffusion3 baseWeapon targetWeapon , "Amalgam Barrel Diffusion [+120% Multishot]" : mods ) # INLINE amalgamBarrelDiffusion #
null
https://raw.githubusercontent.com/verystable/warframe-autobuilder/015e0bb6812711ea27071816d054cbaa1c65770b/src/Builder/Mods/PistolMods/MultishotMods.hs
haskell
# LANGUAGE OverloadedStrings # | Module : Builder.Mods.PistolMods.AmmoMods Maintainer : Stability : experimental | Barrel Diffusion [+120% Multishot] | Amalgam Barrel Diffusion [+110% Multishot]
# LANGUAGE NoImplicitPrelude # Contains function that modify multishot , applicable on secondary weapons . module Builder.Mods.PistolMods.MultishotMods where import ClassyPrelude import Control.Lens import GenericFunctions.GenericFunctions import Types.GenericWeapon barrelDiffusion3 :: GenericWeapon -> GenericWeapon -> GenericWeapon barrelDiffusion3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 1.2) (+) targetWeapon # INLINE barrelDiffusion3 # Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) barrelDiffusion :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) barrelDiffusion baseWeapon (targetWeapon, mods) = ( barrelDiffusion3 baseWeapon targetWeapon , "Barrel Diffusion [+120% Multishot]" : mods ) # INLINE barrelDiffusion # lethalTorrent5 :: GenericWeapon -> GenericWeapon -> GenericWeapon lethalTorrent5 baseWeapon targetWeapon = modifyGeneralProperty gwFireRate (baseWeapon ^. gwFireRate) (Just 0.6) (+) targetWeapon # INLINE lethalTorrent5 # lethalTorrent3 :: GenericWeapon -> GenericWeapon -> GenericWeapon lethalTorrent3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 0.6) (+) targetWeapon # INLINE lethalTorrent3 # | Lethal Torrent [ +60 % Multishot , +60 % Fire Rate ] Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) lethalTorrent :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) lethalTorrent baseWeapon (targetWeapon, mods) = ( lethalTorrent3 baseWeapon $ lethalTorrent5 baseWeapon targetWeapon , "Lethal Torrent [+60% Multishot]" : mods ) # INLINE lethalTorrent # amalgamBarrelDiffusion3 :: GenericWeapon -> GenericWeapon -> GenericWeapon amalgamBarrelDiffusion3 baseWeapon targetWeapon = modifyGeneralProperty gwMultishot (baseWeapon ^. gwMultishot) (Just 1.1) (+) targetWeapon # INLINE amalgamBarrelDiffusion3 # Status Chance affected by multishot 1 - ( ( 1 - status chance ) ^ multishot modifier ) amalgamBarrelDiffusion :: GenericWeapon -> (GenericWeapon, [Text]) -> (GenericWeapon, [Text]) amalgamBarrelDiffusion baseWeapon (targetWeapon, mods) = ( amalgamBarrelDiffusion3 baseWeapon targetWeapon , "Amalgam Barrel Diffusion [+120% Multishot]" : mods ) # INLINE amalgamBarrelDiffusion #
b3ddcde6b65223740c14166b768e84f66804f0e9f0049e0ec52b527cd782f094
jrm-code-project/LISP-Machine
lmfile.lisp
;;; -*- Mode:LISP; Package:ZWEI; Base:8 -*- ;;; LMFILE mail files. ( DEFMETHOD ( FS : LM - PARSING - MIXIN : MAIL - FILE - FORMAT - COMPUTER ) ( STREAM & AUX FLAVOR APPEND - P ) ; (IF (NULL STREAM) ( SETQ FLAVOR ' RMAIL - FILE - BUFFER ) ; (LET ((FIRST-LINE (SEND STREAM :LINE-IN))) ; (SEND STREAM :SET-POINTER 0) ( IF ( STRING - EQUAL FIRST - LINE " Babyl Options : " ) ; ; Looks like a babyl file ( SETQ FLAVOR ' BABYL - MAIL - FILE - BUFFER ) ; ; is rmail file ( SETQ FLAVOR ' RMAIL - FILE - BUFFER ) ( AND ( STRING - EQUAL FIRST - LINE " * * " ) ( SETQ APPEND - P T ) ) ) ) ) ; (VALUES FLAVOR APPEND-P)) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : POSSIBLE - MAIL - FILE - NAMES ) ( ) ; (LOOP FOR FN2 IN *ZMAIL-FILE-FN2S* ; COLLECT (SEND SELF :NEW-PATHNAME :NAME USER-ID :TYPE FN2 :VERSION :NEWEST))) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : POSSIBLE - MAIL - FILE - BUFFER - FLAVORS ) ( ) ' ( RMAIL - FILE - BUFFER BABYL - MAIL - FILE - BUFFER ) ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : NEW - MAIL - PATHNAME ) ( ) ; (SEND SELF :NEW-PATHNAME :NAME (OR FS:NAME USER-ID) ; :TYPE "MAIL")) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : ZMAIL - TEMP - FILE - NAME ) ( ) ; (STRING-APPEND "_Z" (SEND SELF :TYPE))) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : INBOX - BUFFER - FLAVOR ) ( ) ; 'ITS-INBOX-BUFFER)
null
https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/zmail/lmfile.lisp
lisp
-*- Mode:LISP; Package:ZWEI; Base:8 -*- LMFILE mail files. (IF (NULL STREAM) (LET ((FIRST-LINE (SEND STREAM :LINE-IN))) (SEND STREAM :SET-POINTER 0) ; Looks like a babyl file ; is rmail file (VALUES FLAVOR APPEND-P)) (LOOP FOR FN2 IN *ZMAIL-FILE-FN2S* COLLECT (SEND SELF :NEW-PATHNAME :NAME USER-ID :TYPE FN2 :VERSION :NEWEST))) (SEND SELF :NEW-PATHNAME :NAME (OR FS:NAME USER-ID) :TYPE "MAIL")) (STRING-APPEND "_Z" (SEND SELF :TYPE))) 'ITS-INBOX-BUFFER)
( DEFMETHOD ( FS : LM - PARSING - MIXIN : MAIL - FILE - FORMAT - COMPUTER ) ( STREAM & AUX FLAVOR APPEND - P ) ( SETQ FLAVOR ' RMAIL - FILE - BUFFER ) ( IF ( STRING - EQUAL FIRST - LINE " Babyl Options : " ) ( SETQ FLAVOR ' BABYL - MAIL - FILE - BUFFER ) ( SETQ FLAVOR ' RMAIL - FILE - BUFFER ) ( AND ( STRING - EQUAL FIRST - LINE " * * " ) ( SETQ APPEND - P T ) ) ) ) ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : POSSIBLE - MAIL - FILE - NAMES ) ( ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : POSSIBLE - MAIL - FILE - BUFFER - FLAVORS ) ( ) ' ( RMAIL - FILE - BUFFER BABYL - MAIL - FILE - BUFFER ) ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : NEW - MAIL - PATHNAME ) ( ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : ZMAIL - TEMP - FILE - NAME ) ( ) ( DEFMETHOD ( FS : LM - PARSING - MIXIN : INBOX - BUFFER - FLAVOR ) ( )
ffa38ee2683dff2a782bb750ad3bc876ebbe803c2804e10bc2aba99a7706a874
ekmett/thrists
Tarjan.hs
# LANGUAGE RankNTypes , GADTs , PolyKinds # module Tarjan where import Control.Applicative import Control.Category import Data.Monoid import Prelude hiding ((.),id) and TODO : we need fast access to class Cat (t :: (i -> i -> *) -> i -> i -> *) where foldCat :: Category m => (forall a b. r a b -> m a b) -> t r a b -> m a b traverseCat :: Applicative m => (forall a b. r a b -> m (s a b)) -> t r a b -> m (t s a b) data Digit r a b where D3 :: r a b -> r b c -> r c d -> Digit r a d D4 :: r a b -> r b c -> r c d -> r d e -> Digit r a e D5 :: r a b -> r b c -> r c d -> r d e -> r e f -> Digit r a f D6 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> Digit r a g instance Cat Digit where foldCat k (D3 a b c) = k a >>> k b >>> k c foldCat k (D4 a b c d) = k a >>> k b >>> k c >>> k d foldCat k (D5 a b c d e) = k a >>> k b >>> k c >>> k d >>> k e foldCat k (D6 a b c d e f) = k a >>> k b >>> k c >>> k d >>> k e >>> k f traverseCat k (D3 a b c) = D3 <$> k a <*> k b <*> k c traverseCat k (D4 a b c d) = D4 <$> k a <*> k b <*> k c <*> k d traverseCat k (D5 a b c d e) = D5 <$> k a <*> k b <*> k c <*> k d <*> k e traverseCat k (D6 a b c d e f) = D6 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f data Node (r :: i -> i -> *) (a :: i) (b :: i) where N2 :: r a b -> r b c -> Node r a c N3 :: r a b -> r b c -> r c d -> Node r a d instance Cat Node where foldCat k (N2 a b) = k a >>> k b foldCat k (N3 a b c) = k a >>> k b >>> k c traverseCat k (N2 a b) = N2 <$> k a <*> k b traverseCat k (N3 a b c) = N3 <$> k a <*> k b <*> k c data Entry (k :: i -> i -> *) (a :: i) (b :: i) where E1 :: !(Node k a b) -> Entry k a b E3 :: !(Node k a b) -> Deque (Entry k) b c -> !(Node k c d) -> Entry k a d instance Cat Entry where foldCat k (E1 m) = foldCat k m foldCat k (E3 l m r) = foldCat k l >>> foldCat (foldCat k) m >>> foldCat k r traverseCat k (E1 m) = E1 <$> traverseCat k m traverseCat k (E3 l m r) = E3 <$> traverseCat k l <*> traverseCat (traverseCat k) m <*> traverseCat k r data Deque k a b where B0 :: Deque r a a B1 :: r a b -> Deque r a b B2 :: r a b -> r b c -> Deque r a c B3 :: r a b -> r b c -> r c d -> Deque r a d B4 :: r a b -> r b c -> r c d -> r d e -> Deque r a e B5 :: r a b -> r b c -> r c d -> r d e -> r e f -> Deque r a f B6 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> Deque r a g B7 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> r g h -> Deque r a h Q1 :: !(Digit k a b) -> Deque (Entry k) b c -> !(Digit k c d) -> Deque k a d Q2 :: !(Digit k a b) -> Deque (Entry k) b c -> k c d -> k d e -> Deque (Entry k) e f -> !(Digit k f g) -> Deque k a g instance Cat Deque where foldCat _ B0 = id foldCat k (B1 a) = k a foldCat k (B2 a b) = k a >>> k b foldCat k (B3 a b c) = k a >>> k b >>> k c foldCat k (B4 a b c d) = k a >>> k b >>> k c >>> k d foldCat k (B5 a b c d e) = k a >>> k b >>> k c >>> k d >>> k e foldCat k (B6 a b c d e f) = k a >>> k b >>> k c >>> k d >>> k e >>> k f foldCat k (B7 a b c d e f g) = k a >>> k b >>> k c >>> k d >>> k e >>> k f >>> k g foldCat k (Q1 f m r) = foldCat k f >>> foldCat (foldCat k) m >>> foldCat k r foldCat k (Q2 f a m n p r) = foldCat k f >>> foldCat (foldCat k) a >>> k m >>> k n >>> foldCat (foldCat k) p >>> foldCat k r traverseCat _ B0 = pure B0 traverseCat k (B1 a) = B1 <$> k a traverseCat k (B2 a b) = B2 <$> k a <*> k b traverseCat k (B3 a b c) = B3 <$> k a <*> k b <*> k c traverseCat k (B4 a b c d) = B4 <$> k a <*> k b <*> k c <*> k d traverseCat k (B5 a b c d e) = B5 <$> k a <*> k b <*> k c <*> k d <*> k e traverseCat k (B6 a b c d e f) = B6 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f traverseCat k (B7 a b c d e f g) = B7 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f <*> k g traverseCat k (Q1 f m r) = Q1 <$> traverseCat k f <*> traverseCat (traverseCat k) m <*> traverseCat k r traverseCat k (Q2 f a m n p r) = Q2 <$> traverseCat k f <*> traverseCat (traverseCat k) a <*> k m <*> k n <*> traverseCat (traverseCat k) p <*> traverseCat k r data View l r a c where Empty :: View l r a a (:|) :: l a b -> r b c -> View l r a c fixl3 :: Deque k a b -> Deque k a b fixl3 (Q1 p@D4{} m r) = Q1 p (fixl3 m) r fixl3 (Q1 (D3 a b c) B0 (D3 d e f)) = B6 a b c d e f fixl3 (Q1 (D3 a b c) B0 (D4 d e f g)) = B7 a b c d e f g fixl3 (Q1 (D3 a b c) B0 (D5 d e f g h)) = Q1 (D4 a b c d) B0 (D4 e f g h) fixl3 (Q1 (D3 a b c) B0 (D6 d e f g h i)) = Q1 (D4 a b c d) B0 (D5 e f g h i) -- fixl3 (Q1 (D3 a b c) m r = Q1 (E1 (N2 b c) <| m) r fixl3 xs = xs uncons :: Deque k a b -> View k (Deque k) a b uncons B0 = Empty uncons (B1 a) = a :| B0 uncons (B2 a b) = a :| B1 b uncons (B3 a b c) = a :| B2 b c uncons (B4 a b c d) = a :| B3 b c d uncons (B5 a b c d e) = a :| B4 b c d e uncons (B6 a b c d e f) = a :| B5 b c d e f uncons (B7 a b c d e f g) = a :| B6 b c d e f g uncons (Q1 (D3 a b c) B0 (D3 d e f)) = a :| B5 b c d e f uncons (Q1 (D3 a b c) B0 (D4 d e f g)) = a :| B6 b c d e f g uncons (Q1 (D3 a b c) B0 (D5 d e f g h)) = a :| B7 b c d e f g h uncons (Q1 (D3 a b c) B0 (D6 d e f g h i)) = a :| Q1 (D4 b c d e) B0 (D4 f g h i) uncons ( Q1 ( D3 a b c ) m r = case uncons m of E1 ( N2 d e ) :| m ' - > a :| Q1 ( D4 b c d e ) m ' r E3 ( N2 d e ) l ' :| : : ! ( Node k a b ) - > Deque ( Entry k ) b c - > ! ( Node k c d ) - > Entry k a d uncons (Q1 (D3 a b c) m r = case uncons m of E1 (N2 d e) :| m' -> a :| Q1 (D4 b c d e) m' r E3 (N2 d e) l' :| :: !(Node k a b) -> Deque (Entry k) b c -> !(Node k c d) -> Entry k a d -} -- -- a :| Q1 (E1 (N2 b c) <| m) r uncons (Q1 (D4 a b c d) m r) = a :| Q1 (D3 b c d) (fixl3 m) r uncons (Q1 (D5 a b c d e) m r) = a :| Q1 (D4 b c d e) m r uncons (Q1 (D6 a b c d e f) m r) = a :| Q1 (D5 b c d e f) m r infixr 5 <|, >< infixl 5 |> (<|) :: k a b -> Deque k b c -> Deque k a c a <| B0 = B1 a a <| B1 b = B2 a b a <| B2 b c = B3 a b c a <| B3 b c d = B4 a b c d a <| B4 b c d e = B5 a b c d e a <| B5 b c d e f = B6 a b c d e f a <| B6 b c d e f g = B7 a b c d e f g a <| B7 b c d e f g h = Q1 (D4 a b c d) B0 (D4 e f g h) a <| Q1 (D3 b c d) m r = Q1 (D4 a b c d) m r a <| Q1 (D4 b c d e) m r = Q1 (D5 a b c d e) (fixl56 m) r a <| Q1 (D5 b c d e f) m r = Q1 (D4 a b c d) (E1 (N2 e f) <| m) r a <| Q1 (D6 b c d e f g) m r = Q1 (D4 a b c d) (E1 (N3 e f g) <| m) r a <| Q2 (D3 b c d) l m n r s = Q2 (D4 a b c d) l m n r s a <| Q2 (D4 b c d e) l m n r s = Q2 (D5 a b c d e) (fixl56 l) m n r s a <| Q2 (D5 b c d e f) l m n r s = Q2 (D4 a b c d) (E1 (N2 e f) <| l ) m n r s a <| Q2 (D6 b c d e f g) l m n r s = Q2 (D4 a b c d) (E1 (N3 e f g) <| l) m n r s -- ensure the deque is not 5,6 exposed on the left fixl56 :: Deque k a c -> Deque k a c fixl56 (Q1 p@D4{} m r) = Q1 p (fixl56 m) r fixl56 (Q1 (D5 a b c d e) m r) = Q1 (D3 a b c) (E1 (N2 d e) <| m) r fixl56 (Q1 (D6 a b c d e f) m r) = Q1 (D3 a b c) (E1 (N3 d e f) <| m) r fixl56 (Q2 p@D4{} l m n r s) = Q2 p (fixl56 l) m n r s fixl56 (Q2 (D5 a b c d e) l m n r s) = Q2 (D3 a b c) (E1 (N2 d e) <| l) m n r s fixl56 (Q2 (D6 a b c d e f) l m n r s) = Q2 (D3 a b c) (E1 (N3 d e f) <| l) m n r s fixl56 xs = xs (|>) :: Deque k a b -> k b c -> Deque k a c B0 |> a = B1 a B1 b |> a = B2 b a B2 c b |> a = B3 c b a B3 d c b |> a = B4 d c b a B4 e d c b |> a = B5 e d c b a B5 f e d c b |> a = B6 f e d c b a B6 g f e d c b |> a = B7 g f e d c b a B7 h g f e d c b |> a = Q1 (D4 h g f e) B0 (D4 d c b a) Q1 p m (D3 d c b) |> a = Q1 p m (D4 d c b a) Q1 p m (D4 e d c b) |> a = Q1 p (fixr56 m) (D5 e d c b a) Q1 p m (D5 f e d c b) |> a = Q1 p (m |> E1 (N2 f e)) (D4 d c b a) Q1 p m (D6 g f e d c b) |> a = Q1 p (m |> E1 (N3 g f e)) (D4 d c b a) Q2 p l m n r (D3 d c b) |> a = Q2 p l m n r (D4 d c b a) Q2 p l m n r (D4 e d c b) |> a = Q2 p l m n (fixr56 r) (D5 e d c b a) Q2 p l m n r (D5 f e d c b) |> a = Q2 p l m n (r |> E1 (N2 f e)) (D4 d c b a) Q2 p l m n r (D6 g f e d c b) |> a = Q2 p l m n (r |> E1 (N3 g f e)) (D4 d c b a) -- ensure the deque is not 5,6 exposed on the right fixr56 :: Deque k a c -> Deque k a c fixr56 (Q1 p m r@D4{}) = Q1 p (fixr56 m) r fixr56 (Q1 p m (D5 a b c d e)) = Q1 p (m |> E1 (N2 a b)) (D3 c d e) fixr56 (Q1 p m (D6 a b c d e f)) = Q1 p (m |> E1 (N3 a b c)) (D3 d e f) fixr56 (Q2 p l m n r s@D4{}) = Q2 p l m n (fixr56 r) s fixr56 (Q2 p l m n r (D5 a b c d e)) = Q2 p l m n (r |> E1 (N2 a b)) (D3 c d e) fixr56 (Q2 p l m n r (D6 a b c d e f)) = Q2 p l m n (r |> E1 (N3 a b c)) (D3 d e f) fixr56 xs = xs (><) :: Deque k a b -> Deque k b c -> Deque k a c B0 >< ys = ys xs >< B0 = xs B1 a >< ys = a <| ys xs >< B1 a = xs |> a B2 a b >< ys = a <| b <| ys xs >< B2 a b = xs |> a |> b B3 a b c >< ys = a <| b <| c <| ys xs >< B3 a b c = xs |> a |> b |> c B4 a b c d >< ys = a <| b <| c <| d <| ys xs >< B4 a b c d = xs |> a |> b |> c |> d B5 a b c d e >< ys = a <| b <| c <| d <| e <| ys xs >< B5 a b c d e = xs |> a |> b |> c |> d |> e B6 a b c d e f >< ys = a <| b <| c <| d <| e <| f <| ys xs >< B6 a b c d e f = xs |> a |> b |> c |> d |> e |> f B7 a b c d e f g >< ys = a <| b <| c <| d <| e <| f <| g <| ys xs >< B7 a b c d e f g = xs |> a |> b |> c |> d |> e |> f |> g xs >< ys = case prefix xs of Half l m r -> case suffix ys of Half l' m' r' -> Q2 l m r l' m' r' data Half l m r a c where Half :: l a b -> m b c -> r c d -> Half l m r a d prefix :: Deque k a b -> Half (Digit k) (Deque (Entry k)) k a b prefix (Q1 p m (D3 a b c)) = Half p (m |> E1 (N2 a b)) c prefix (Q1 p m (D4 a b c d)) = Half p (m |> E1 (N3 a b c)) d prefix (Q1 p m (D5 a b c d e)) = Half p (m |> E1 (N2 a b) |> E1 (N2 c d)) e prefix (Q1 p m (D6 a b c d e f)) = Half p (m |> E1 (N2 a b) |> E1 (N3 c d e)) f prefix (Q2 p l m n r (D3 a b c)) = Half p (l |> E3 (N2 m n) r (N2 a b)) c prefix (Q2 p l m n r (D4 a b c d)) = Half p (l |> E3 (N2 m n) r (N3 a b c)) d prefix (Q2 p l m n r (D5 a b c d e)) = Half p (l |> E3 (N2 m n) r (N2 a b) |> E1 (N2 c d)) e prefix (Q2 p l m n r (D6 a b c d e f)) = Half p (l |> E3 (N2 m n) r (N3 a b c) |> E1 (N2 d e)) f suffix :: Deque k a b -> Half k (Deque (Entry k)) (Digit k) a b suffix (Q1 (D3 a b c) m r) = Half a (E1 (N2 b c) <| m) r suffix (Q1 (D4 a b c d) m r) = Half a (E1 (N3 b c d) <| m) r suffix (Q1 (D5 a b c d e) m r) = Half a (E1 (N2 b c) <| E1 (N2 d e) <| m) r suffix (Q1 (D6 a b c d e f) m r) = Half a (E1 (N3 b c d) <| E1 (N2 e f) <| m) r suffix (Q2 (D3 a b c) l m n r s) = Half a (E3 (N2 b c) l (N2 m n) <| r) s suffix (Q2 (D4 a b c d) l m n r s) = Half a (E3 (N3 b c d) l (N2 m n) <| r) s suffix (Q2 (D5 a b c d e) l m n r s) = Half a (E1 (N2 b c) <| E3 (N2 d e) l (N2 m n) <| r) s suffix (Q2 (D6 a b c d e f) l m n r s) = Half a (E1 (N3 b c d) <| E3 (N2 e f) l (N2 m n) <| r) s
null
https://raw.githubusercontent.com/ekmett/thrists/49c4a0a86712a91bb435c938147173676b8c005c/wip/Tarjan.hs
haskell
fixl3 (Q1 (D3 a b c) m r = Q1 (E1 (N2 b c) <| m) r a :| Q1 (E1 (N2 b c) <| m) r ensure the deque is not 5,6 exposed on the left ensure the deque is not 5,6 exposed on the right
# LANGUAGE RankNTypes , GADTs , PolyKinds # module Tarjan where import Control.Applicative import Control.Category import Data.Monoid import Prelude hiding ((.),id) and TODO : we need fast access to class Cat (t :: (i -> i -> *) -> i -> i -> *) where foldCat :: Category m => (forall a b. r a b -> m a b) -> t r a b -> m a b traverseCat :: Applicative m => (forall a b. r a b -> m (s a b)) -> t r a b -> m (t s a b) data Digit r a b where D3 :: r a b -> r b c -> r c d -> Digit r a d D4 :: r a b -> r b c -> r c d -> r d e -> Digit r a e D5 :: r a b -> r b c -> r c d -> r d e -> r e f -> Digit r a f D6 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> Digit r a g instance Cat Digit where foldCat k (D3 a b c) = k a >>> k b >>> k c foldCat k (D4 a b c d) = k a >>> k b >>> k c >>> k d foldCat k (D5 a b c d e) = k a >>> k b >>> k c >>> k d >>> k e foldCat k (D6 a b c d e f) = k a >>> k b >>> k c >>> k d >>> k e >>> k f traverseCat k (D3 a b c) = D3 <$> k a <*> k b <*> k c traverseCat k (D4 a b c d) = D4 <$> k a <*> k b <*> k c <*> k d traverseCat k (D5 a b c d e) = D5 <$> k a <*> k b <*> k c <*> k d <*> k e traverseCat k (D6 a b c d e f) = D6 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f data Node (r :: i -> i -> *) (a :: i) (b :: i) where N2 :: r a b -> r b c -> Node r a c N3 :: r a b -> r b c -> r c d -> Node r a d instance Cat Node where foldCat k (N2 a b) = k a >>> k b foldCat k (N3 a b c) = k a >>> k b >>> k c traverseCat k (N2 a b) = N2 <$> k a <*> k b traverseCat k (N3 a b c) = N3 <$> k a <*> k b <*> k c data Entry (k :: i -> i -> *) (a :: i) (b :: i) where E1 :: !(Node k a b) -> Entry k a b E3 :: !(Node k a b) -> Deque (Entry k) b c -> !(Node k c d) -> Entry k a d instance Cat Entry where foldCat k (E1 m) = foldCat k m foldCat k (E3 l m r) = foldCat k l >>> foldCat (foldCat k) m >>> foldCat k r traverseCat k (E1 m) = E1 <$> traverseCat k m traverseCat k (E3 l m r) = E3 <$> traverseCat k l <*> traverseCat (traverseCat k) m <*> traverseCat k r data Deque k a b where B0 :: Deque r a a B1 :: r a b -> Deque r a b B2 :: r a b -> r b c -> Deque r a c B3 :: r a b -> r b c -> r c d -> Deque r a d B4 :: r a b -> r b c -> r c d -> r d e -> Deque r a e B5 :: r a b -> r b c -> r c d -> r d e -> r e f -> Deque r a f B6 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> Deque r a g B7 :: r a b -> r b c -> r c d -> r d e -> r e f -> r f g -> r g h -> Deque r a h Q1 :: !(Digit k a b) -> Deque (Entry k) b c -> !(Digit k c d) -> Deque k a d Q2 :: !(Digit k a b) -> Deque (Entry k) b c -> k c d -> k d e -> Deque (Entry k) e f -> !(Digit k f g) -> Deque k a g instance Cat Deque where foldCat _ B0 = id foldCat k (B1 a) = k a foldCat k (B2 a b) = k a >>> k b foldCat k (B3 a b c) = k a >>> k b >>> k c foldCat k (B4 a b c d) = k a >>> k b >>> k c >>> k d foldCat k (B5 a b c d e) = k a >>> k b >>> k c >>> k d >>> k e foldCat k (B6 a b c d e f) = k a >>> k b >>> k c >>> k d >>> k e >>> k f foldCat k (B7 a b c d e f g) = k a >>> k b >>> k c >>> k d >>> k e >>> k f >>> k g foldCat k (Q1 f m r) = foldCat k f >>> foldCat (foldCat k) m >>> foldCat k r foldCat k (Q2 f a m n p r) = foldCat k f >>> foldCat (foldCat k) a >>> k m >>> k n >>> foldCat (foldCat k) p >>> foldCat k r traverseCat _ B0 = pure B0 traverseCat k (B1 a) = B1 <$> k a traverseCat k (B2 a b) = B2 <$> k a <*> k b traverseCat k (B3 a b c) = B3 <$> k a <*> k b <*> k c traverseCat k (B4 a b c d) = B4 <$> k a <*> k b <*> k c <*> k d traverseCat k (B5 a b c d e) = B5 <$> k a <*> k b <*> k c <*> k d <*> k e traverseCat k (B6 a b c d e f) = B6 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f traverseCat k (B7 a b c d e f g) = B7 <$> k a <*> k b <*> k c <*> k d <*> k e <*> k f <*> k g traverseCat k (Q1 f m r) = Q1 <$> traverseCat k f <*> traverseCat (traverseCat k) m <*> traverseCat k r traverseCat k (Q2 f a m n p r) = Q2 <$> traverseCat k f <*> traverseCat (traverseCat k) a <*> k m <*> k n <*> traverseCat (traverseCat k) p <*> traverseCat k r data View l r a c where Empty :: View l r a a (:|) :: l a b -> r b c -> View l r a c fixl3 :: Deque k a b -> Deque k a b fixl3 (Q1 p@D4{} m r) = Q1 p (fixl3 m) r fixl3 (Q1 (D3 a b c) B0 (D3 d e f)) = B6 a b c d e f fixl3 (Q1 (D3 a b c) B0 (D4 d e f g)) = B7 a b c d e f g fixl3 (Q1 (D3 a b c) B0 (D5 d e f g h)) = Q1 (D4 a b c d) B0 (D4 e f g h) fixl3 (Q1 (D3 a b c) B0 (D6 d e f g h i)) = Q1 (D4 a b c d) B0 (D5 e f g h i) fixl3 xs = xs uncons :: Deque k a b -> View k (Deque k) a b uncons B0 = Empty uncons (B1 a) = a :| B0 uncons (B2 a b) = a :| B1 b uncons (B3 a b c) = a :| B2 b c uncons (B4 a b c d) = a :| B3 b c d uncons (B5 a b c d e) = a :| B4 b c d e uncons (B6 a b c d e f) = a :| B5 b c d e f uncons (B7 a b c d e f g) = a :| B6 b c d e f g uncons (Q1 (D3 a b c) B0 (D3 d e f)) = a :| B5 b c d e f uncons (Q1 (D3 a b c) B0 (D4 d e f g)) = a :| B6 b c d e f g uncons (Q1 (D3 a b c) B0 (D5 d e f g h)) = a :| B7 b c d e f g h uncons (Q1 (D3 a b c) B0 (D6 d e f g h i)) = a :| Q1 (D4 b c d e) B0 (D4 f g h i) uncons ( Q1 ( D3 a b c ) m r = case uncons m of E1 ( N2 d e ) :| m ' - > a :| Q1 ( D4 b c d e ) m ' r E3 ( N2 d e ) l ' :| : : ! ( Node k a b ) - > Deque ( Entry k ) b c - > ! ( Node k c d ) - > Entry k a d uncons (Q1 (D3 a b c) m r = case uncons m of E1 (N2 d e) :| m' -> a :| Q1 (D4 b c d e) m' r E3 (N2 d e) l' :| :: !(Node k a b) -> Deque (Entry k) b c -> !(Node k c d) -> Entry k a d -} uncons (Q1 (D4 a b c d) m r) = a :| Q1 (D3 b c d) (fixl3 m) r uncons (Q1 (D5 a b c d e) m r) = a :| Q1 (D4 b c d e) m r uncons (Q1 (D6 a b c d e f) m r) = a :| Q1 (D5 b c d e f) m r infixr 5 <|, >< infixl 5 |> (<|) :: k a b -> Deque k b c -> Deque k a c a <| B0 = B1 a a <| B1 b = B2 a b a <| B2 b c = B3 a b c a <| B3 b c d = B4 a b c d a <| B4 b c d e = B5 a b c d e a <| B5 b c d e f = B6 a b c d e f a <| B6 b c d e f g = B7 a b c d e f g a <| B7 b c d e f g h = Q1 (D4 a b c d) B0 (D4 e f g h) a <| Q1 (D3 b c d) m r = Q1 (D4 a b c d) m r a <| Q1 (D4 b c d e) m r = Q1 (D5 a b c d e) (fixl56 m) r a <| Q1 (D5 b c d e f) m r = Q1 (D4 a b c d) (E1 (N2 e f) <| m) r a <| Q1 (D6 b c d e f g) m r = Q1 (D4 a b c d) (E1 (N3 e f g) <| m) r a <| Q2 (D3 b c d) l m n r s = Q2 (D4 a b c d) l m n r s a <| Q2 (D4 b c d e) l m n r s = Q2 (D5 a b c d e) (fixl56 l) m n r s a <| Q2 (D5 b c d e f) l m n r s = Q2 (D4 a b c d) (E1 (N2 e f) <| l ) m n r s a <| Q2 (D6 b c d e f g) l m n r s = Q2 (D4 a b c d) (E1 (N3 e f g) <| l) m n r s fixl56 :: Deque k a c -> Deque k a c fixl56 (Q1 p@D4{} m r) = Q1 p (fixl56 m) r fixl56 (Q1 (D5 a b c d e) m r) = Q1 (D3 a b c) (E1 (N2 d e) <| m) r fixl56 (Q1 (D6 a b c d e f) m r) = Q1 (D3 a b c) (E1 (N3 d e f) <| m) r fixl56 (Q2 p@D4{} l m n r s) = Q2 p (fixl56 l) m n r s fixl56 (Q2 (D5 a b c d e) l m n r s) = Q2 (D3 a b c) (E1 (N2 d e) <| l) m n r s fixl56 (Q2 (D6 a b c d e f) l m n r s) = Q2 (D3 a b c) (E1 (N3 d e f) <| l) m n r s fixl56 xs = xs (|>) :: Deque k a b -> k b c -> Deque k a c B0 |> a = B1 a B1 b |> a = B2 b a B2 c b |> a = B3 c b a B3 d c b |> a = B4 d c b a B4 e d c b |> a = B5 e d c b a B5 f e d c b |> a = B6 f e d c b a B6 g f e d c b |> a = B7 g f e d c b a B7 h g f e d c b |> a = Q1 (D4 h g f e) B0 (D4 d c b a) Q1 p m (D3 d c b) |> a = Q1 p m (D4 d c b a) Q1 p m (D4 e d c b) |> a = Q1 p (fixr56 m) (D5 e d c b a) Q1 p m (D5 f e d c b) |> a = Q1 p (m |> E1 (N2 f e)) (D4 d c b a) Q1 p m (D6 g f e d c b) |> a = Q1 p (m |> E1 (N3 g f e)) (D4 d c b a) Q2 p l m n r (D3 d c b) |> a = Q2 p l m n r (D4 d c b a) Q2 p l m n r (D4 e d c b) |> a = Q2 p l m n (fixr56 r) (D5 e d c b a) Q2 p l m n r (D5 f e d c b) |> a = Q2 p l m n (r |> E1 (N2 f e)) (D4 d c b a) Q2 p l m n r (D6 g f e d c b) |> a = Q2 p l m n (r |> E1 (N3 g f e)) (D4 d c b a) fixr56 :: Deque k a c -> Deque k a c fixr56 (Q1 p m r@D4{}) = Q1 p (fixr56 m) r fixr56 (Q1 p m (D5 a b c d e)) = Q1 p (m |> E1 (N2 a b)) (D3 c d e) fixr56 (Q1 p m (D6 a b c d e f)) = Q1 p (m |> E1 (N3 a b c)) (D3 d e f) fixr56 (Q2 p l m n r s@D4{}) = Q2 p l m n (fixr56 r) s fixr56 (Q2 p l m n r (D5 a b c d e)) = Q2 p l m n (r |> E1 (N2 a b)) (D3 c d e) fixr56 (Q2 p l m n r (D6 a b c d e f)) = Q2 p l m n (r |> E1 (N3 a b c)) (D3 d e f) fixr56 xs = xs (><) :: Deque k a b -> Deque k b c -> Deque k a c B0 >< ys = ys xs >< B0 = xs B1 a >< ys = a <| ys xs >< B1 a = xs |> a B2 a b >< ys = a <| b <| ys xs >< B2 a b = xs |> a |> b B3 a b c >< ys = a <| b <| c <| ys xs >< B3 a b c = xs |> a |> b |> c B4 a b c d >< ys = a <| b <| c <| d <| ys xs >< B4 a b c d = xs |> a |> b |> c |> d B5 a b c d e >< ys = a <| b <| c <| d <| e <| ys xs >< B5 a b c d e = xs |> a |> b |> c |> d |> e B6 a b c d e f >< ys = a <| b <| c <| d <| e <| f <| ys xs >< B6 a b c d e f = xs |> a |> b |> c |> d |> e |> f B7 a b c d e f g >< ys = a <| b <| c <| d <| e <| f <| g <| ys xs >< B7 a b c d e f g = xs |> a |> b |> c |> d |> e |> f |> g xs >< ys = case prefix xs of Half l m r -> case suffix ys of Half l' m' r' -> Q2 l m r l' m' r' data Half l m r a c where Half :: l a b -> m b c -> r c d -> Half l m r a d prefix :: Deque k a b -> Half (Digit k) (Deque (Entry k)) k a b prefix (Q1 p m (D3 a b c)) = Half p (m |> E1 (N2 a b)) c prefix (Q1 p m (D4 a b c d)) = Half p (m |> E1 (N3 a b c)) d prefix (Q1 p m (D5 a b c d e)) = Half p (m |> E1 (N2 a b) |> E1 (N2 c d)) e prefix (Q1 p m (D6 a b c d e f)) = Half p (m |> E1 (N2 a b) |> E1 (N3 c d e)) f prefix (Q2 p l m n r (D3 a b c)) = Half p (l |> E3 (N2 m n) r (N2 a b)) c prefix (Q2 p l m n r (D4 a b c d)) = Half p (l |> E3 (N2 m n) r (N3 a b c)) d prefix (Q2 p l m n r (D5 a b c d e)) = Half p (l |> E3 (N2 m n) r (N2 a b) |> E1 (N2 c d)) e prefix (Q2 p l m n r (D6 a b c d e f)) = Half p (l |> E3 (N2 m n) r (N3 a b c) |> E1 (N2 d e)) f suffix :: Deque k a b -> Half k (Deque (Entry k)) (Digit k) a b suffix (Q1 (D3 a b c) m r) = Half a (E1 (N2 b c) <| m) r suffix (Q1 (D4 a b c d) m r) = Half a (E1 (N3 b c d) <| m) r suffix (Q1 (D5 a b c d e) m r) = Half a (E1 (N2 b c) <| E1 (N2 d e) <| m) r suffix (Q1 (D6 a b c d e f) m r) = Half a (E1 (N3 b c d) <| E1 (N2 e f) <| m) r suffix (Q2 (D3 a b c) l m n r s) = Half a (E3 (N2 b c) l (N2 m n) <| r) s suffix (Q2 (D4 a b c d) l m n r s) = Half a (E3 (N3 b c d) l (N2 m n) <| r) s suffix (Q2 (D5 a b c d e) l m n r s) = Half a (E1 (N2 b c) <| E3 (N2 d e) l (N2 m n) <| r) s suffix (Q2 (D6 a b c d e f) l m n r s) = Half a (E1 (N3 b c d) <| E3 (N2 e f) l (N2 m n) <| r) s
81567d359d137b2667a888ff09418376b0da697049c6babbf882c945f91660e5
ucsd-progsys/liquidhaskell
ApplicativeId.hs
{-@ LIQUID "--reflection" @-} {-@ LIQUID "--ple" @-} {-# LANGUAGE IncoherentInstances #-} # LANGUAGE FlexibleContexts # module ApplicativeId where import Prelude hiding (fmap, id, pure, seq) import Language.Haskell.Liquid.ProofCombinators -- | Applicative Laws : -- | identity pure id <*> v = v -- | composition pure (.) <*> u <*> v <*> w = u <*> (v <*> w) -- | homomorphism pure f <*> pure x = pure (f x) -- | interchange u <*> pure y = pure ($ y) <*> u {-@ reflect pure @-} pure :: a -> Identity a pure x = Identity x {-@ reflect seq @-} seq :: Identity (a -> b) -> Identity a -> Identity b seq (Identity f) (Identity x) = Identity (f x) {-@ reflect id @-} id :: a -> a id x = x @ reflect @ idollar :: a -> (a -> b) -> b idollar x f = f x {-@ reflect compose @-} compose :: (b -> c) -> (a -> b) -> a -> c compose f g x = f (g x) {-@ data Identity a = Identity { runIdentity :: a } @-} data Identity a = Identity a -- | Identity {-@ identity :: x:Identity a -> { seq (pure id) x == x } @-} identity :: Identity a -> Proof identity (Identity x) = trivial -- | Composition {-@ composition :: x:Identity (a -> a) -> y:Identity (a -> a) -> z:Identity a -> { (seq (seq (seq (pure compose) x) y) z) == seq x (seq y z) } @-} composition :: Identity (a -> a) -> Identity (a -> a) -> Identity a -> Proof composition (Identity x) (Identity y) (Identity z) = trivial -- | homomorphism pure f <*> pure x = pure (f x) {-@ homomorphism :: f:(a -> a) -> x:a -> { seq (pure f) (pure x) == pure (f x) } @-} homomorphism :: (a -> a) -> a -> Proof homomorphism f x = trivial interchange :: Identity (a -> a) -> a -> Proof {-@ interchange :: u:(Identity (a -> a)) -> y:a -> { seq u (pure y) == seq (pure (idollar y)) u } @-} interchange (Identity f) x = trivial
null
https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/20cd67af038930cb592d68d272c8eb1cbe3cb6bf/tests/benchmarks/popl18/ple/pos/ApplicativeId.hs
haskell
@ LIQUID "--reflection" @ @ LIQUID "--ple" @ # LANGUAGE IncoherentInstances # | Applicative Laws : | identity pure id <*> v = v | composition pure (.) <*> u <*> v <*> w = u <*> (v <*> w) | homomorphism pure f <*> pure x = pure (f x) | interchange u <*> pure y = pure ($ y) <*> u @ reflect pure @ @ reflect seq @ @ reflect id @ @ reflect compose @ @ data Identity a = Identity { runIdentity :: a } @ | Identity @ identity :: x:Identity a -> { seq (pure id) x == x } @ | Composition @ composition :: x:Identity (a -> a) -> y:Identity (a -> a) -> z:Identity a -> { (seq (seq (seq (pure compose) x) y) z) == seq x (seq y z) } @ | homomorphism pure f <*> pure x = pure (f x) @ homomorphism :: f:(a -> a) -> x:a -> { seq (pure f) (pure x) == pure (f x) } @ @ interchange :: u:(Identity (a -> a)) -> y:a -> { seq u (pure y) == seq (pure (idollar y)) u } @
# LANGUAGE FlexibleContexts # module ApplicativeId where import Prelude hiding (fmap, id, pure, seq) import Language.Haskell.Liquid.ProofCombinators pure :: a -> Identity a pure x = Identity x seq :: Identity (a -> b) -> Identity a -> Identity b seq (Identity f) (Identity x) = Identity (f x) id :: a -> a id x = x @ reflect @ idollar :: a -> (a -> b) -> b idollar x f = f x compose :: (b -> c) -> (a -> b) -> a -> c compose f g x = f (g x) data Identity a = Identity a identity :: Identity a -> Proof identity (Identity x) = trivial composition :: Identity (a -> a) -> Identity (a -> a) -> Identity a -> Proof composition (Identity x) (Identity y) (Identity z) = trivial homomorphism :: (a -> a) -> a -> Proof homomorphism f x = trivial interchange :: Identity (a -> a) -> a -> Proof interchange (Identity f) x = trivial
58af9341e241fabdcf0147dd1cc6d8e552fc4c920d865b2b6c9a4526dc5e85ae
drathier/elm-offline
Functions.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # module Generate.Functions (functions) where import qualified Data.ByteString.Builder as B import Text.RawString.QQ (r) -- FUNCTIONS functions :: B.Builder functions = [r| function F(arity, fun, wrapper) { wrapper.a = arity; wrapper.f = fun; return wrapper; } function F2(fun) { return F(2, fun, function(a) { return function(b) { return fun(a,b); }; }) } function F3(fun) { return F(3, fun, function(a) { return function(b) { return function(c) { return fun(a, b, c); }; }; }); } function F4(fun) { return F(4, fun, function(a) { return function(b) { return function(c) { return function(d) { return fun(a, b, c, d); }; }; }; }); } function F5(fun) { return F(5, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return fun(a, b, c, d, e); }; }; }; }; }); } function F6(fun) { return F(6, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return fun(a, b, c, d, e, f); }; }; }; }; }; }); } function F7(fun) { return F(7, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return fun(a, b, c, d, e, f, g); }; }; }; }; }; }; }); } function F8(fun) { return F(8, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return fun(a, b, c, d, e, f, g, h); }; }; }; }; }; }; }; }); } function F9(fun) { return F(9, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return function(i) { return fun(a, b, c, d, e, f, g, h, i); }; }; }; }; }; }; }; }; }); } function A2(fun, a, b) { return fun.a === 2 ? fun.f(a, b) : fun(a)(b); } function A3(fun, a, b, c) { return fun.a === 3 ? fun.f(a, b, c) : fun(a)(b)(c); } function A4(fun, a, b, c, d) { return fun.a === 4 ? fun.f(a, b, c, d) : fun(a)(b)(c)(d); } function A5(fun, a, b, c, d, e) { return fun.a === 5 ? fun.f(a, b, c, d, e) : fun(a)(b)(c)(d)(e); } function A6(fun, a, b, c, d, e, f) { return fun.a === 6 ? fun.f(a, b, c, d, e, f) : fun(a)(b)(c)(d)(e)(f); } function A7(fun, a, b, c, d, e, f, g) { return fun.a === 7 ? fun.f(a, b, c, d, e, f, g) : fun(a)(b)(c)(d)(e)(f)(g); } function A8(fun, a, b, c, d, e, f, g, h) { return fun.a === 8 ? fun.f(a, b, c, d, e, f, g, h) : fun(a)(b)(c)(d)(e)(f)(g)(h); } function A9(fun, a, b, c, d, e, f, g, h, i) { return fun.a === 9 ? fun.f(a, b, c, d, e, f, g, h, i) : fun(a)(b)(c)(d)(e)(f)(g)(h)(i); } |]
null
https://raw.githubusercontent.com/drathier/elm-offline/f562198cac29f4cda15b69fde7e66edde89b34fa/builder/src/Generate/Functions.hs
haskell
# LANGUAGE OverloadedStrings # FUNCTIONS
# LANGUAGE QuasiQuotes # module Generate.Functions (functions) where import qualified Data.ByteString.Builder as B import Text.RawString.QQ (r) functions :: B.Builder functions = [r| function F(arity, fun, wrapper) { wrapper.a = arity; wrapper.f = fun; return wrapper; } function F2(fun) { return F(2, fun, function(a) { return function(b) { return fun(a,b); }; }) } function F3(fun) { return F(3, fun, function(a) { return function(b) { return function(c) { return fun(a, b, c); }; }; }); } function F4(fun) { return F(4, fun, function(a) { return function(b) { return function(c) { return function(d) { return fun(a, b, c, d); }; }; }; }); } function F5(fun) { return F(5, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return fun(a, b, c, d, e); }; }; }; }; }); } function F6(fun) { return F(6, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return fun(a, b, c, d, e, f); }; }; }; }; }; }); } function F7(fun) { return F(7, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return fun(a, b, c, d, e, f, g); }; }; }; }; }; }; }); } function F8(fun) { return F(8, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return fun(a, b, c, d, e, f, g, h); }; }; }; }; }; }; }; }); } function F9(fun) { return F(9, fun, function(a) { return function(b) { return function(c) { return function(d) { return function(e) { return function(f) { return function(g) { return function(h) { return function(i) { return fun(a, b, c, d, e, f, g, h, i); }; }; }; }; }; }; }; }; }); } function A2(fun, a, b) { return fun.a === 2 ? fun.f(a, b) : fun(a)(b); } function A3(fun, a, b, c) { return fun.a === 3 ? fun.f(a, b, c) : fun(a)(b)(c); } function A4(fun, a, b, c, d) { return fun.a === 4 ? fun.f(a, b, c, d) : fun(a)(b)(c)(d); } function A5(fun, a, b, c, d, e) { return fun.a === 5 ? fun.f(a, b, c, d, e) : fun(a)(b)(c)(d)(e); } function A6(fun, a, b, c, d, e, f) { return fun.a === 6 ? fun.f(a, b, c, d, e, f) : fun(a)(b)(c)(d)(e)(f); } function A7(fun, a, b, c, d, e, f, g) { return fun.a === 7 ? fun.f(a, b, c, d, e, f, g) : fun(a)(b)(c)(d)(e)(f)(g); } function A8(fun, a, b, c, d, e, f, g, h) { return fun.a === 8 ? fun.f(a, b, c, d, e, f, g, h) : fun(a)(b)(c)(d)(e)(f)(g)(h); } function A9(fun, a, b, c, d, e, f, g, h, i) { return fun.a === 9 ? fun.f(a, b, c, d, e, f, g, h, i) : fun(a)(b)(c)(d)(e)(f)(g)(h)(i); } |]
f63eb2ecb20b33ce03a3ea5253bb1fe83cd60bf420ebf6b2474d6a1230137a83
haskell-servant/servant
StaticFiles.hs
# LANGUAGE CPP # -- | This module defines server-side handlers that lets you serve static files. -- -- The most common needs for a web application are covered by -- 'serveDirectoryWebApp`, but the other variants allow you to use different ` StaticSettings ` and ' serveDirectoryWith ' even allows you to specify arbitrary ' StaticSettings ' to be used for serving static files . module Servant.Server.StaticFiles ( serveDirectoryWebApp , serveDirectoryWebAppLookup , serveDirectoryFileServer , serveDirectoryEmbedded , serveDirectoryWith , -- * Deprecated serveDirectory ) where import Data.ByteString (ByteString) import Network.Wai.Application.Static import Servant.API.Raw (Raw) import Servant.Server (ServerT, Tagged (..)) import System.FilePath (addTrailingPathSeparator) import WaiAppStatic.Storage.Filesystem (ETagLookup) -- | Serve anything under the specified directory as a 'Raw' endpoint. -- -- @ type MyApi = " static " :> Raw -- -- server :: Server MyApi server = serveDirectoryWebApp " \/var\/www " -- @ -- -- would capture any request to @\/static\/\<something>@ and look for -- @\<something>@ under @\/var\/www@. -- -- It will do its best to guess the MIME type for that file, based on the extension, and send an appropriate /Content - header if possible . -- If your goal is to serve HTML , CSS and Javascript files that use the rest of the API -- as a webapp backend, you will most likely not want the static files to be hidden behind a /\/static\// prefix . In that case , remember to put the ' serveDirectoryWebApp ' handler in the last position , because will try to match the handlers -- in order. -- Corresponds to the ` defaultWebAppSettings ` ` StaticSettings ` value . serveDirectoryWebApp :: FilePath -> ServerT Raw m serveDirectoryWebApp = serveDirectoryWith . defaultWebAppSettings . fixPath | Same as ' serveDirectoryWebApp ' , but uses ` defaultFileServerSettings ` . serveDirectoryFileServer :: FilePath -> ServerT Raw m serveDirectoryFileServer = serveDirectoryWith . defaultFileServerSettings . fixPath | Same as ' serveDirectoryWebApp ' , but uses ' webAppSettingsWithLookup ' . serveDirectoryWebAppLookup :: ETagLookup -> FilePath -> ServerT Raw m serveDirectoryWebAppLookup etag = serveDirectoryWith . flip webAppSettingsWithLookup etag . fixPath -- | Uses 'embeddedSettings'. serveDirectoryEmbedded :: [(FilePath, ByteString)] -> ServerT Raw m serveDirectoryEmbedded files = serveDirectoryWith (embeddedSettings files) | for ' staticApp ' . Lets you serve a directory with arbitrary ' StaticSettings ' . Useful when you want particular settings not covered by the four other -- variants. This is the most flexible method. serveDirectoryWith :: StaticSettings -> ServerT Raw m serveDirectoryWith = Tagged . staticApp -- | Same as 'serveDirectoryFileServer'. It used to be the only -- file serving function in servant pre-0.10 and will be kept -- around for a few versions, but is deprecated. serveDirectory :: FilePath -> ServerT Raw m serveDirectory = serveDirectoryFileServer {-# DEPRECATED serveDirectory "Use serveDirectoryFileServer instead" #-} fixPath :: FilePath -> FilePath fixPath = addTrailingPathSeparator
null
https://raw.githubusercontent.com/haskell-servant/servant/d06b65c4e6116f992debbac2eeeb83eafb960321/servant-server/src/Servant/Server/StaticFiles.hs
haskell
| This module defines server-side handlers that lets you serve static files. The most common needs for a web application are covered by 'serveDirectoryWebApp`, but the other variants allow you to use * Deprecated | Serve anything under the specified directory as a 'Raw' endpoint. @ server :: Server MyApi @ would capture any request to @\/static\/\<something>@ and look for @\<something>@ under @\/var\/www@. It will do its best to guess the MIME type for that file, based on the extension, as a webapp backend, you will most likely not want the static files to be hidden in order. | Uses 'embeddedSettings'. variants. This is the most flexible method. | Same as 'serveDirectoryFileServer'. It used to be the only file serving function in servant pre-0.10 and will be kept around for a few versions, but is deprecated. # DEPRECATED serveDirectory "Use serveDirectoryFileServer instead" #
# LANGUAGE CPP # different ` StaticSettings ` and ' serveDirectoryWith ' even allows you to specify arbitrary ' StaticSettings ' to be used for serving static files . module Servant.Server.StaticFiles ( serveDirectoryWebApp , serveDirectoryWebAppLookup , serveDirectoryFileServer , serveDirectoryEmbedded , serveDirectoryWith serveDirectory ) where import Data.ByteString (ByteString) import Network.Wai.Application.Static import Servant.API.Raw (Raw) import Servant.Server (ServerT, Tagged (..)) import System.FilePath (addTrailingPathSeparator) import WaiAppStatic.Storage.Filesystem (ETagLookup) type MyApi = " static " :> Raw server = serveDirectoryWebApp " \/var\/www " and send an appropriate /Content - header if possible . If your goal is to serve HTML , CSS and Javascript files that use the rest of the API behind a /\/static\// prefix . In that case , remember to put the ' serveDirectoryWebApp ' handler in the last position , because will try to match the handlers Corresponds to the ` defaultWebAppSettings ` ` StaticSettings ` value . serveDirectoryWebApp :: FilePath -> ServerT Raw m serveDirectoryWebApp = serveDirectoryWith . defaultWebAppSettings . fixPath | Same as ' serveDirectoryWebApp ' , but uses ` defaultFileServerSettings ` . serveDirectoryFileServer :: FilePath -> ServerT Raw m serveDirectoryFileServer = serveDirectoryWith . defaultFileServerSettings . fixPath | Same as ' serveDirectoryWebApp ' , but uses ' webAppSettingsWithLookup ' . serveDirectoryWebAppLookup :: ETagLookup -> FilePath -> ServerT Raw m serveDirectoryWebAppLookup etag = serveDirectoryWith . flip webAppSettingsWithLookup etag . fixPath serveDirectoryEmbedded :: [(FilePath, ByteString)] -> ServerT Raw m serveDirectoryEmbedded files = serveDirectoryWith (embeddedSettings files) | for ' staticApp ' . Lets you serve a directory with arbitrary ' StaticSettings ' . Useful when you want particular settings not covered by the four other serveDirectoryWith :: StaticSettings -> ServerT Raw m serveDirectoryWith = Tagged . staticApp serveDirectory :: FilePath -> ServerT Raw m serveDirectory = serveDirectoryFileServer fixPath :: FilePath -> FilePath fixPath = addTrailingPathSeparator
4d8c9104f60216f6871f13a938024645ca34e7caf1de4d60f96aed26f453144f
Frama-C/Frama-C-snapshot
clabels.ml
(**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- Normalized C-labels --- *) (* -------------------------------------------------------------------------- *) open Cil_types type c_label = string let compare = String.compare let equal (a:string) (b:string) = (a = b) module T = struct type t = c_label let compare = compare end module LabelMap = Datatype.String.Map module LabelSet = Datatype.String.Set let init = "wp:init" let here = "wp:here" let next = "wp:next" let pre = "wp:pre" let post = "wp:post" let old = "wp:old" let break = "wp:break" let continue = "wp:continue" let default = "wp:default" let at_exit = "wp:exit" let loopcurrent = "wp:loopcurrent" let loopentry = "wp:loopentry" let formal a = a let pretty = Format.pp_print_string let is_here h = (h = here) let mem l lbl = List.mem l lbl let case n = "wp:case" ^ Int64.to_string n let stmt s = "wp:sid" ^ string_of_int s.sid let loop_entry s = stmt s (* same point *) let loop_current s = "wp:head" ^ string_of_int s.sid let to_logic a = FormalLabel a let of_logic = function | BuiltinLabel Here -> here | BuiltinLabel Init -> init | BuiltinLabel Pre -> pre | BuiltinLabel Post -> post | FormalLabel name -> name | BuiltinLabel Old -> old | BuiltinLabel LoopCurrent -> loopcurrent | BuiltinLabel LoopEntry -> loopentry | StmtLabel s -> stmt !s let name = function FormalLabel a -> a | _ -> "" let lookup labels a = try List.find (fun (l,_) -> name l = a) labels |> snd with Not_found -> Wp_parameters.fatal "Unbound label parameter '%s' in predicate or function call" a (* -------------------------------------------------------------------------- *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/clabels.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. ************************************************************************ -------------------------------------------------------------------------- --- Normalized C-labels --- -------------------------------------------------------------------------- same point --------------------------------------------------------------------------
This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Cil_types type c_label = string let compare = String.compare let equal (a:string) (b:string) = (a = b) module T = struct type t = c_label let compare = compare end module LabelMap = Datatype.String.Map module LabelSet = Datatype.String.Set let init = "wp:init" let here = "wp:here" let next = "wp:next" let pre = "wp:pre" let post = "wp:post" let old = "wp:old" let break = "wp:break" let continue = "wp:continue" let default = "wp:default" let at_exit = "wp:exit" let loopcurrent = "wp:loopcurrent" let loopentry = "wp:loopentry" let formal a = a let pretty = Format.pp_print_string let is_here h = (h = here) let mem l lbl = List.mem l lbl let case n = "wp:case" ^ Int64.to_string n let stmt s = "wp:sid" ^ string_of_int s.sid let loop_current s = "wp:head" ^ string_of_int s.sid let to_logic a = FormalLabel a let of_logic = function | BuiltinLabel Here -> here | BuiltinLabel Init -> init | BuiltinLabel Pre -> pre | BuiltinLabel Post -> post | FormalLabel name -> name | BuiltinLabel Old -> old | BuiltinLabel LoopCurrent -> loopcurrent | BuiltinLabel LoopEntry -> loopentry | StmtLabel s -> stmt !s let name = function FormalLabel a -> a | _ -> "" let lookup labels a = try List.find (fun (l,_) -> name l = a) labels |> snd with Not_found -> Wp_parameters.fatal "Unbound label parameter '%s' in predicate or function call" a
3c216cd9bd86e4dc1c3c368fdc07f2ad731a4f4069b6214512c97e385e2865e4
mirage/ptt-deployer
certificate.ml
open Rresult let prefix = X509.Distinguished_name.[ Relative_distinguished_name.singleton (CN "PTT") ] let cacert_dn = X509.Distinguished_name.( prefix @ [ Relative_distinguished_name.singleton (CN "Ephemeral CA for PTT") ]) let cacert_lifetime = Ptime.Span.v (365, 0L) let cacert_serial_number = Z.zero let v domain_name seed = Domain_name.of_string domain_name >>= Domain_name.host >>= fun domain_name -> let private_key = let seed = Cstruct.of_string (Base64.decode_exn ~pad:false seed) in let g = Mirage_crypto_rng.(create ~seed (module Fortuna)) in Mirage_crypto_pk.Rsa.generate ~g ~bits:2048 () in let valid_from = Ptime.v (Ptime_clock.now_d_ps ()) in Ptime.add_span valid_from cacert_lifetime |> Option.to_result ~none:(R.msgf "End time out of range") >>= fun valid_until -> X509.Signing_request.create cacert_dn (`RSA private_key) >>= fun ca_csr -> let extensions = let open X509.Extension in let key_id = X509.Public_key.id X509.Signing_request.((info ca_csr).public_key) in let authority_key_id = ( Some key_id, X509.General_name.(singleton Directory [ cacert_dn ]), Some cacert_serial_number ) in empty |> add Subject_alt_name ( true, X509.General_name.( singleton DNS [ Domain_name.to_string domain_name ]) ) |> add Basic_constraints (true, (false, None)) |> add Key_usage (true, [ `Digital_signature; `Content_commitment; `Key_encipherment ]) |> add Subject_key_id (false, key_id) |> add Authority_key_id (false, authority_key_id) in X509.Signing_request.sign ~valid_from ~valid_until ~extensions ~serial:cacert_serial_number ca_csr (`RSA private_key) cacert_dn |> R.reword_error (R.msgf "%a" X509.Validation.pp_signature_error) >>= fun certificate -> let fingerprint = X509.Certificate.fingerprint `SHA256 certificate in Ok ( Base64.encode_string (Cstruct.to_string (X509.Certificate.encode_der certificate)), Base64.encode_string (Cstruct.to_string fingerprint) ) let generate len = let res = Bytes.create len in for _ = 0 to len - 1 do Bytes.set res 0 (Char.unsafe_chr (Random.bits () land 0xff)) done; Base64.encode_string (Bytes.unsafe_to_string res)
null
https://raw.githubusercontent.com/mirage/ptt-deployer/9a2bd4464c6dbc189ba1331adeaedc73defe01d2/src/certificate.ml
ocaml
open Rresult let prefix = X509.Distinguished_name.[ Relative_distinguished_name.singleton (CN "PTT") ] let cacert_dn = X509.Distinguished_name.( prefix @ [ Relative_distinguished_name.singleton (CN "Ephemeral CA for PTT") ]) let cacert_lifetime = Ptime.Span.v (365, 0L) let cacert_serial_number = Z.zero let v domain_name seed = Domain_name.of_string domain_name >>= Domain_name.host >>= fun domain_name -> let private_key = let seed = Cstruct.of_string (Base64.decode_exn ~pad:false seed) in let g = Mirage_crypto_rng.(create ~seed (module Fortuna)) in Mirage_crypto_pk.Rsa.generate ~g ~bits:2048 () in let valid_from = Ptime.v (Ptime_clock.now_d_ps ()) in Ptime.add_span valid_from cacert_lifetime |> Option.to_result ~none:(R.msgf "End time out of range") >>= fun valid_until -> X509.Signing_request.create cacert_dn (`RSA private_key) >>= fun ca_csr -> let extensions = let open X509.Extension in let key_id = X509.Public_key.id X509.Signing_request.((info ca_csr).public_key) in let authority_key_id = ( Some key_id, X509.General_name.(singleton Directory [ cacert_dn ]), Some cacert_serial_number ) in empty |> add Subject_alt_name ( true, X509.General_name.( singleton DNS [ Domain_name.to_string domain_name ]) ) |> add Basic_constraints (true, (false, None)) |> add Key_usage (true, [ `Digital_signature; `Content_commitment; `Key_encipherment ]) |> add Subject_key_id (false, key_id) |> add Authority_key_id (false, authority_key_id) in X509.Signing_request.sign ~valid_from ~valid_until ~extensions ~serial:cacert_serial_number ca_csr (`RSA private_key) cacert_dn |> R.reword_error (R.msgf "%a" X509.Validation.pp_signature_error) >>= fun certificate -> let fingerprint = X509.Certificate.fingerprint `SHA256 certificate in Ok ( Base64.encode_string (Cstruct.to_string (X509.Certificate.encode_der certificate)), Base64.encode_string (Cstruct.to_string fingerprint) ) let generate len = let res = Bytes.create len in for _ = 0 to len - 1 do Bytes.set res 0 (Char.unsafe_chr (Random.bits () land 0xff)) done; Base64.encode_string (Bytes.unsafe_to_string res)
8a3a155f5d4946e909ed24cfbb3c74fd7db0ddb6f70d751933c35b7ce10ad736
functionally/pigy-genetics
Types.hs
----------------------------------------------------------------------------- -- -- Module : $Headers Copyright : ( c ) 2021 License : MIT -- Maintainer : < > -- Stability : Experimental Portability : Portable -- -- | Types for the pig-image service. -- ----------------------------------------------------------------------------- # LANGUAGE RecordWildCards # module Pigy.Types ( -- * Configuration Configuration(..) , readConfiguration -- * Context , Context(..) , makeContext -- * Operations , Mode(..) -- * Keys , KeyInfo(..) , KeyedAddress(..) , readKeyedAddress ) where import Cardano.Api (AddressAny, AssetId(..), AsType (AsAssetName, AsPolicyId), CardanoMode, ConsensusModeParams(CardanoModeParams), EpochSlots(..), Hash, NetworkId(..), NetworkMagic(..), PaymentKey, ShelleyBasedEra(..), deserialiseFromRawBytes, deserialiseFromRawBytesHex) import Cardano.Api.Shelley (ProtocolParameters) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Word (Word32, Word64) import Mantra.Query (queryProtocol) import Mantra.Types (MantraM, foistMantraMaybe) import Mantra.Wallet (SomePaymentSigningKey, SomePaymentVerificationKey, makeVerificationKeyHash, readAddress, readSigningKey, readVerificationKey) import System.Random (StdGen, getStdGen) import System.Random.Stateful (IOGenM, newIOGenM) import qualified Data.ByteString.Char8 as BS (pack) -- | The service configuration. data Configuration = Configuration { ^ The path for the Cardano node 's socket . , magic :: Maybe Word32 -- ^ The magic number for the Cardano network, unless using mainnet. , epochSlots :: Word64 -- ^ The number of slots per epoch. , rollbacks :: Int -- ^ The number of rollbacks to allow. , policyId :: String -- ^ The policy ID of the payment token. , assetName :: String -- ^ The asset name of the payment token. , keyInfo :: KeyInfo -- ^ The service's key. ^ The path to the IPFS pinning script . , imageFolder :: FilePath -- ^ The path to the folder of images. , mode :: Mode -- ^ The operational mode. , quiet :: Bool -- ^ The verbosity. } deriving (Read, Show) -- | The operational mode. data Mode = Strict -- ^ Only accept requests as single transactions. | Lenient -- ^ Accept split transactions, processing when idle. | Aggressive -- ^ Accept split transactions, processing as soon as possible. deriving (Eq, Ord, Read, Show) -- | Key information. data KeyInfo = KeyInfo { addressString :: String -- ^ The address. , verificationKeyFile :: FilePath -- ^ The path to the verification key file. , signingKeyFile :: FilePath -- ^ The path to the signing key file. } deriving (Read, Show) -- | The contetual parameters for the service. data Context = Context { ^ The path for the Cardano node 's socket . , protocol :: ConsensusModeParams CardanoMode -- ^ The Cardano consensus mode. , network :: NetworkId -- ^ The Cardano network. , pparams :: ProtocolParameters -- ^ The Cardano protocol. , kSecurity :: Int -- ^ The number of rollbacks to allow. , token :: AssetId -- ^ The asset ID for the payment token. , keyedAddress :: KeyedAddress -- ^ The service address. , gRandom :: IOGenM StdGen -- ^ The random-number generator. ^ The path to the IPFS script for pinning images . , images :: FilePath -- ^ The path to the folder for images. , operation :: Mode -- ^ The operational mode. , verbose :: Bool -- ^ The verbosity. } -- | A key and it hashes. data KeyedAddress = KeyedAddress { keyAddress :: AddressAny -- ^ The address. , verificationHash :: Hash PaymentKey -- ^ The hash of the verification key. , verification :: SomePaymentVerificationKey -- ^ The verification key. , signing :: SomePaymentSigningKey -- ^ The signing key. } deriving (Show) -- | Read a configuration file. readConfiguration :: MonadIO m => FilePath -- ^ The path to the configuration file. -> MantraM m Configuration -- ^ The action returning the configuration. readConfiguration = liftIO . fmap read . readFile -- | Convert a configuration into a service context. makeContext :: MonadFail m => MonadIO m => Configuration -- ^ The configuration. -> MantraM m Context -- ^ The action returning the context. makeContext Configuration{..} = do policyId' <- foistMantraMaybe "Could not decode policy ID." . deserialiseFromRawBytesHex AsPolicyId $ BS.pack policyId assetName' <- foistMantraMaybe "Could not decode asset name." . deserialiseFromRawBytes AsAssetName $ BS.pack assetName keyedAddress <- readKeyedAddress keyInfo gRandom <- newIOGenM =<< getStdGen let socket = socketPath protocol = CardanoModeParams $ EpochSlots epochSlots network = maybe Mainnet (Testnet . NetworkMagic) magic kSecurity = rollbacks token = AssetId policyId' assetName' ipfsPin = ipfsScript images = imageFolder operation = mode verbose = not quiet pparams <- queryProtocol ShelleyBasedEraAlonzo socketPath protocol network return Context{..} -- | Read a key. readKeyedAddress :: MonadIO m => KeyInfo -- ^ The key information. -> MantraM m KeyedAddress -- ^ The key and its hashes. readKeyedAddress KeyInfo{..} = do keyAddress <- readAddress addressString verification <- readVerificationKey verificationKeyFile signing <- readSigningKey signingKeyFile let verificationHash = makeVerificationKeyHash verification return KeyedAddress{..}
null
https://raw.githubusercontent.com/functionally/pigy-genetics/ed2784faabfa77d8a94a147e9f7b11cac0f545b6/app/Pigy/Types.hs
haskell
--------------------------------------------------------------------------- Module : $Headers Stability : Experimental | Types for the pig-image service. --------------------------------------------------------------------------- * Configuration * Context * Operations * Keys | The service configuration. ^ The magic number for the Cardano network, unless using mainnet. ^ The number of slots per epoch. ^ The number of rollbacks to allow. ^ The policy ID of the payment token. ^ The asset name of the payment token. ^ The service's key. ^ The path to the folder of images. ^ The operational mode. ^ The verbosity. | The operational mode. ^ Only accept requests as single transactions. ^ Accept split transactions, processing when idle. ^ Accept split transactions, processing as soon as possible. | Key information. ^ The address. ^ The path to the verification key file. ^ The path to the signing key file. | The contetual parameters for the service. ^ The Cardano consensus mode. ^ The Cardano network. ^ The Cardano protocol. ^ The number of rollbacks to allow. ^ The asset ID for the payment token. ^ The service address. ^ The random-number generator. ^ The path to the folder for images. ^ The operational mode. ^ The verbosity. | A key and it hashes. ^ The address. ^ The hash of the verification key. ^ The verification key. ^ The signing key. | Read a configuration file. ^ The path to the configuration file. ^ The action returning the configuration. | Convert a configuration into a service context. ^ The configuration. ^ The action returning the context. | Read a key. ^ The key information. ^ The key and its hashes.
Copyright : ( c ) 2021 License : MIT Maintainer : < > Portability : Portable # LANGUAGE RecordWildCards # module Pigy.Types ( Configuration(..) , readConfiguration , Context(..) , makeContext , Mode(..) , KeyInfo(..) , KeyedAddress(..) , readKeyedAddress ) where import Cardano.Api (AddressAny, AssetId(..), AsType (AsAssetName, AsPolicyId), CardanoMode, ConsensusModeParams(CardanoModeParams), EpochSlots(..), Hash, NetworkId(..), NetworkMagic(..), PaymentKey, ShelleyBasedEra(..), deserialiseFromRawBytes, deserialiseFromRawBytesHex) import Cardano.Api.Shelley (ProtocolParameters) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Word (Word32, Word64) import Mantra.Query (queryProtocol) import Mantra.Types (MantraM, foistMantraMaybe) import Mantra.Wallet (SomePaymentSigningKey, SomePaymentVerificationKey, makeVerificationKeyHash, readAddress, readSigningKey, readVerificationKey) import System.Random (StdGen, getStdGen) import System.Random.Stateful (IOGenM, newIOGenM) import qualified Data.ByteString.Char8 as BS (pack) data Configuration = Configuration { ^ The path for the Cardano node 's socket . ^ The path to the IPFS pinning script . } deriving (Read, Show) data Mode = deriving (Eq, Ord, Read, Show) data KeyInfo = KeyInfo { } deriving (Read, Show) data Context = Context { ^ The path for the Cardano node 's socket . ^ The path to the IPFS script for pinning images . } data KeyedAddress = KeyedAddress { } deriving (Show) readConfiguration :: MonadIO m readConfiguration = liftIO . fmap read . readFile makeContext :: MonadFail m => MonadIO m makeContext Configuration{..} = do policyId' <- foistMantraMaybe "Could not decode policy ID." . deserialiseFromRawBytesHex AsPolicyId $ BS.pack policyId assetName' <- foistMantraMaybe "Could not decode asset name." . deserialiseFromRawBytes AsAssetName $ BS.pack assetName keyedAddress <- readKeyedAddress keyInfo gRandom <- newIOGenM =<< getStdGen let socket = socketPath protocol = CardanoModeParams $ EpochSlots epochSlots network = maybe Mainnet (Testnet . NetworkMagic) magic kSecurity = rollbacks token = AssetId policyId' assetName' ipfsPin = ipfsScript images = imageFolder operation = mode verbose = not quiet pparams <- queryProtocol ShelleyBasedEraAlonzo socketPath protocol network return Context{..} readKeyedAddress :: MonadIO m readKeyedAddress KeyInfo{..} = do keyAddress <- readAddress addressString verification <- readVerificationKey verificationKeyFile signing <- readSigningKey signingKeyFile let verificationHash = makeVerificationKeyHash verification return KeyedAddress{..}
5299fdf3ac8d968f0e1493fd559d90359f81796b03aac4aa334284a0255627ed
clojure-interop/java-jdk
MetalToolBarUI.clj
(ns javax.swing.plaf.metal.MetalToolBarUI "A Metal Look and Feel implementation of ToolBarUI. This implementation is a \"combined\" view/controller." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.metal MetalToolBarUI])) (defn ->metal-tool-bar-ui "Constructor." (^MetalToolBarUI [] (new MetalToolBarUI ))) (defn *create-ui "c - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent c] (MetalToolBarUI/createUI c))) (defn install-ui "Description copied from class: ComponentUI c - the component where this UI delegate is being installed - `javax.swing.JComponent`" ([^MetalToolBarUI this ^javax.swing.JComponent c] (-> this (.installUI c)))) (defn uninstall-ui "Description copied from class: ComponentUI this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MetalToolBarUI this ^javax.swing.JComponent c] (-> this (.uninstallUI c)))) (defn update "If necessary paints the background of the component, then invokes paint. g - Graphics to paint to - `java.awt.Graphics` c - JComponent painting on - `javax.swing.JComponent` throws: java.lang.NullPointerException - if g or c is null" ([^MetalToolBarUI this ^java.awt.Graphics g ^javax.swing.JComponent c] (-> this (.update g c))))
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.swing/src/javax/swing/plaf/metal/MetalToolBarUI.clj
clojure
(ns javax.swing.plaf.metal.MetalToolBarUI "A Metal Look and Feel implementation of ToolBarUI. This implementation is a \"combined\" view/controller." (:refer-clojure :only [require comment defn ->]) (:import [javax.swing.plaf.metal MetalToolBarUI])) (defn ->metal-tool-bar-ui "Constructor." (^MetalToolBarUI [] (new MetalToolBarUI ))) (defn *create-ui "c - `javax.swing.JComponent` returns: `javax.swing.plaf.ComponentUI`" (^javax.swing.plaf.ComponentUI [^javax.swing.JComponent c] (MetalToolBarUI/createUI c))) (defn install-ui "Description copied from class: ComponentUI c - the component where this UI delegate is being installed - `javax.swing.JComponent`" ([^MetalToolBarUI this ^javax.swing.JComponent c] (-> this (.installUI c)))) (defn uninstall-ui "Description copied from class: ComponentUI this argument is often ignored , but might be used if the UI object is stateless and shared by multiple components - ` javax.swing . ` " ([^MetalToolBarUI this ^javax.swing.JComponent c] (-> this (.uninstallUI c)))) (defn update "If necessary paints the background of the component, then invokes paint. g - Graphics to paint to - `java.awt.Graphics` c - JComponent painting on - `javax.swing.JComponent` throws: java.lang.NullPointerException - if g or c is null" ([^MetalToolBarUI this ^java.awt.Graphics g ^javax.swing.JComponent c] (-> this (.update g c))))
204761aa4dfd293fe654447fce2f3b39362d1f0ae4413891daf0a0ba6021b36d
slindley/effect-handlers
UpDown.hs
This example ( due to ) illustrates the limitations of our encoding of effect typing in Haskell . The effects have been replaced by concrete handlers Up and Down which are different types . Tested with ghc 7.8.4 . This example (due to Oscar Key) illustrates the limitations of our encoding of effect typing in Haskell. The effects have been replaced by concrete handlers Up and Down which are different types. Tested with ghc 7.8.4. -} # LANGUAGE TypeFamilies , GADTs , NoMonomorphismRestriction , RankNTypes , MultiParamTypeClasses , FlexibleInstances , OverlappingInstances , FlexibleContexts , UndecidableInstances , QuasiQuotes # MultiParamTypeClasses, FlexibleInstances, OverlappingInstances, FlexibleContexts, UndecidableInstances, QuasiQuotes #-} module Examples.UpDown where import ShallowFreeHandlers import DesugarHandlers [operation|Move :: ()|] [shallowHandler| Down a :: a handles {Move} where Return x -> x Move k -> up (k ()) |] [shallowHandler| Up a :: a handles {Move} where Return x -> x Move k -> down (k ()) |]
null
https://raw.githubusercontent.com/slindley/effect-handlers/39d0d09582d198dd6210177a0896db55d92529f4/Examples/UpDown.hs
haskell
This example ( due to ) illustrates the limitations of our encoding of effect typing in Haskell . The effects have been replaced by concrete handlers Up and Down which are different types . Tested with ghc 7.8.4 . This example (due to Oscar Key) illustrates the limitations of our encoding of effect typing in Haskell. The effects have been replaced by concrete handlers Up and Down which are different types. Tested with ghc 7.8.4. -} # LANGUAGE TypeFamilies , GADTs , NoMonomorphismRestriction , RankNTypes , MultiParamTypeClasses , FlexibleInstances , OverlappingInstances , FlexibleContexts , UndecidableInstances , QuasiQuotes # MultiParamTypeClasses, FlexibleInstances, OverlappingInstances, FlexibleContexts, UndecidableInstances, QuasiQuotes #-} module Examples.UpDown where import ShallowFreeHandlers import DesugarHandlers [operation|Move :: ()|] [shallowHandler| Down a :: a handles {Move} where Return x -> x Move k -> up (k ()) |] [shallowHandler| Up a :: a handles {Move} where Return x -> x Move k -> down (k ()) |]
89b9dded605bb85d7e3c17ef2ffc0d5144b429d615e39e031e3a517367795d44
mark-gerarts/nature-of-code
sketch.lisp
(defpackage :nature-of-code.fractals.exercise-8.9 (:export :start-sketch) (:use :cl :trivial-gamekit) (:import-from :alexandria :random-elt)) (in-package :nature-of-code.fractals.exercise-8.9) (defvar *width* 600) (defvar *height* 400) (defvar *center-x* (/ *width* 2)) (defvar *center-y* (/ *height* 2)) (defvar *black* (vec4 0 0 0 1)) (defvar *theta* (/ pi 6)) (defvar *length-reduction* 0.66) (defun rotate (vector theta) "Rotates a (unit) vector." (with-accessors ((x x) (y y)) vector (vec2 (- (* x (cos theta)) (* y (sin theta))) (+ (* x (sin theta)) (* y (cos theta)))))) ;;; This is a remnant of a previous exercise, where it made sense to share some ;;; properties between leaves and branches. (defclass tree-part () ((origin :initarg :origin :accessor origin) (direction :initarg :direction :accessor direction :documentation "Unit vector indicating the direction."))) (defclass leaf (tree-part) ((color :initarg :color :accessor color) (radius :initarg :radius :accessor radius))) ;;; See above. Leaves are put in the branches array as well. Might be a good ;;; idea to refactor this. (defmethod grow ((leaf leaf) dt)) (defmethod fully-grown-p ((leaf leaf)) t) (defmethod can-have-leaf-p ((leaf leaf)) nil) (defmethod display ((leaf leaf)) (with-pushed-canvas () (draw-circle (origin leaf) (radius leaf) :fill-paint (color leaf)))) (defclass branch (tree-part) ((branch-length :initform 0 :accessor branch-length) (max-length :initarg :max-length :accessor max-length) (splitp :initform 'nil :accessor splitp :documentation "Indicates if this branch has been split.") (has-leaf-p :initform 'nil :accessor has-leaf-p))) (defmethod end ((branch branch)) (with-slots (origin branch-length direction) branch (add (mult direction branch-length) origin))) (defmethod grow ((branch branch) dt) (with-accessors ((current branch-length) (max max-length)) branch (incf current dt) (when (> current max) (setf current max)))) (defmethod fully-grown-p ((branch branch)) (>= (branch-length branch) (max-length branch))) (defmethod can-have-leaf-p ((branch branch)) (and (not (splitp branch)) (not (has-leaf-p branch)))) (defmethod split-branch ((branch branch) &key (direction :left)) (let ((theta (if (equalp direction :left) *theta* (- *theta*)))) (setf (splitp branch) t) (make-instance 'branch :origin (end branch) :max-length (* *length-reduction* (max-length branch)) :direction (rotate (direction branch) theta)))) (defmethod display ((branch branch)) (with-accessors ((origin origin) (end end)) branch (draw-line origin end *black* :thickness 3))) (defun split (branches) (loop for branch across branches unless (splitp branch) do (progn (vector-push-extend (split-branch branch :direction :left) branches) (vector-push-extend (split-branch branch :direction :right) branches))) branches) (defun add-random-leaf (branches) (let ((endpoints (remove-if-not #'can-have-leaf-p branches))) (unless (= 0 (length endpoints)) (let ((branch (random-elt endpoints))) (vector-push-extend (make-instance 'leaf :color (vec4 0.2 0.6 0.2 0.8) :radius (+ 5 (random 10)) :origin (end branch) :direction (direction branch)) branches) (setf (has-leaf-p branch) t))))) (defun branch (len &optional (theta (/ pi 6)) (thickness 8)) (draw-line (vec2 0 0) (vec2 0 len) *black* :thickness thickness) (translate-canvas 0 len) (setf len (* 0.66 len)) (setf thickness (* 0.8 thickness)) (when (and (> len 2) (> thickness 0)) (with-pushed-canvas () (rotate-canvas (- theta)) (branch len theta thickness)) (with-pushed-canvas () (rotate-canvas theta) (branch len theta thickness)))) (defun animate-growth (branches dt) (loop for branch across branches do (grow branch dt)) (when (every #'fully-grown-p branches) (if (< (length branches) 128) (split branches) (add-random-leaf branches)))) (defgame sketch () ((branches :initform (make-array 0 :adjustable t :fill-pointer 0) :accessor branches) (dt :initform 0 :accessor dt)) (:viewport-width *width*) (:viewport-height *height*) (:viewport-title "List tree")) (defmethod increment-time ((this sketch)) (incf (dt this) 0.05)) (defmethod post-initialize ((this sketch)) (with-accessors ((branches branches)) this (vector-push-extend (make-instance 'branch :origin (vec2 300 0) :max-length 100 :direction (vec2 0 1)) branches))) (defmethod draw ((this sketch)) (loop for branch across (branches this) do (display branch))) (defmethod act ((this sketch)) (increment-time this) (animate-growth (branches this) (dt this))) (defun start-sketch () (start 'sketch))
null
https://raw.githubusercontent.com/mark-gerarts/nature-of-code/4f8612e18a2a62012e44f08a8e0a4f8aec21a1ec/08.%20Fractals/Exercise%208.9%20-%20Growing%20tree/sketch.lisp
lisp
This is a remnant of a previous exercise, where it made sense to share some properties between leaves and branches. See above. Leaves are put in the branches array as well. Might be a good idea to refactor this.
(defpackage :nature-of-code.fractals.exercise-8.9 (:export :start-sketch) (:use :cl :trivial-gamekit) (:import-from :alexandria :random-elt)) (in-package :nature-of-code.fractals.exercise-8.9) (defvar *width* 600) (defvar *height* 400) (defvar *center-x* (/ *width* 2)) (defvar *center-y* (/ *height* 2)) (defvar *black* (vec4 0 0 0 1)) (defvar *theta* (/ pi 6)) (defvar *length-reduction* 0.66) (defun rotate (vector theta) "Rotates a (unit) vector." (with-accessors ((x x) (y y)) vector (vec2 (- (* x (cos theta)) (* y (sin theta))) (+ (* x (sin theta)) (* y (cos theta)))))) (defclass tree-part () ((origin :initarg :origin :accessor origin) (direction :initarg :direction :accessor direction :documentation "Unit vector indicating the direction."))) (defclass leaf (tree-part) ((color :initarg :color :accessor color) (radius :initarg :radius :accessor radius))) (defmethod grow ((leaf leaf) dt)) (defmethod fully-grown-p ((leaf leaf)) t) (defmethod can-have-leaf-p ((leaf leaf)) nil) (defmethod display ((leaf leaf)) (with-pushed-canvas () (draw-circle (origin leaf) (radius leaf) :fill-paint (color leaf)))) (defclass branch (tree-part) ((branch-length :initform 0 :accessor branch-length) (max-length :initarg :max-length :accessor max-length) (splitp :initform 'nil :accessor splitp :documentation "Indicates if this branch has been split.") (has-leaf-p :initform 'nil :accessor has-leaf-p))) (defmethod end ((branch branch)) (with-slots (origin branch-length direction) branch (add (mult direction branch-length) origin))) (defmethod grow ((branch branch) dt) (with-accessors ((current branch-length) (max max-length)) branch (incf current dt) (when (> current max) (setf current max)))) (defmethod fully-grown-p ((branch branch)) (>= (branch-length branch) (max-length branch))) (defmethod can-have-leaf-p ((branch branch)) (and (not (splitp branch)) (not (has-leaf-p branch)))) (defmethod split-branch ((branch branch) &key (direction :left)) (let ((theta (if (equalp direction :left) *theta* (- *theta*)))) (setf (splitp branch) t) (make-instance 'branch :origin (end branch) :max-length (* *length-reduction* (max-length branch)) :direction (rotate (direction branch) theta)))) (defmethod display ((branch branch)) (with-accessors ((origin origin) (end end)) branch (draw-line origin end *black* :thickness 3))) (defun split (branches) (loop for branch across branches unless (splitp branch) do (progn (vector-push-extend (split-branch branch :direction :left) branches) (vector-push-extend (split-branch branch :direction :right) branches))) branches) (defun add-random-leaf (branches) (let ((endpoints (remove-if-not #'can-have-leaf-p branches))) (unless (= 0 (length endpoints)) (let ((branch (random-elt endpoints))) (vector-push-extend (make-instance 'leaf :color (vec4 0.2 0.6 0.2 0.8) :radius (+ 5 (random 10)) :origin (end branch) :direction (direction branch)) branches) (setf (has-leaf-p branch) t))))) (defun branch (len &optional (theta (/ pi 6)) (thickness 8)) (draw-line (vec2 0 0) (vec2 0 len) *black* :thickness thickness) (translate-canvas 0 len) (setf len (* 0.66 len)) (setf thickness (* 0.8 thickness)) (when (and (> len 2) (> thickness 0)) (with-pushed-canvas () (rotate-canvas (- theta)) (branch len theta thickness)) (with-pushed-canvas () (rotate-canvas theta) (branch len theta thickness)))) (defun animate-growth (branches dt) (loop for branch across branches do (grow branch dt)) (when (every #'fully-grown-p branches) (if (< (length branches) 128) (split branches) (add-random-leaf branches)))) (defgame sketch () ((branches :initform (make-array 0 :adjustable t :fill-pointer 0) :accessor branches) (dt :initform 0 :accessor dt)) (:viewport-width *width*) (:viewport-height *height*) (:viewport-title "List tree")) (defmethod increment-time ((this sketch)) (incf (dt this) 0.05)) (defmethod post-initialize ((this sketch)) (with-accessors ((branches branches)) this (vector-push-extend (make-instance 'branch :origin (vec2 300 0) :max-length 100 :direction (vec2 0 1)) branches))) (defmethod draw ((this sketch)) (loop for branch across (branches this) do (display branch))) (defmethod act ((this sketch)) (increment-time this) (animate-growth (branches this) (dt this))) (defun start-sketch () (start 'sketch))
f937893b2d499fb0ff2690d36411ac85e1a00dd22210de0c654b06af6519ea02
inhabitedtype/ocaml-aws
setQueueAttributes.mli
open Types type input = SetQueueAttributesRequest.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
null
https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/sqs/lib/setQueueAttributes.mli
ocaml
open Types type input = SetQueueAttributesRequest.t type output = unit type error = Errors_internal.t include Aws.Call with type input := input and type output := output and type error := error
176739b44009a4177046a063b55ce345ea2f37442ca640fddf536b8b717a5c35
reasonml/reason
migrate_parsetree_408_409.ml
(**************************************************************************) (* *) (* OCaml Migrate Parsetree *) (* *) (* *) Copyright 2017 Institut National de Recherche en Informatique et (* en Automatique (INRIA). *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) include Migrate_parsetree_408_409_migrate $ open Printf let fields = [ " attribute " ; " attributes " ; " case " ; " cases " ; " class_declaration " ; " class_description " ; " class_expr " ; " class_field " ; " class_signature " ; " class_structure " ; " class_type " ; " class_type_declaration " ; " class_type_field " ; " constructor_declaration " ; " expr " ; " extension " ; " extension_constructor " ; " include_declaration " ; " include_description " ; " label_declaration " ; " location " ; " module_binding " ; " module_declaration " ; " module_expr " ; " module_type " ; " module_type_declaration " ; " open_description " ; " pat " ; " signature " ; " signature_item " ; " structure " ; " structure_item " ; " typ " ; " type_declaration " ; " type_extension " ; " type_kind " ; " value_binding " ; " value_description " ; " with_constraint " ; " payload " ; " binding_op " ; " module_substitution " ; " open_declaration " ; " type_exception " ] let foreach_field f = printf " \n " ; List.iter f fields let fields = [ "attribute"; "attributes"; "case"; "cases"; "class_declaration"; "class_description"; "class_expr"; "class_field"; "class_signature"; "class_structure"; "class_type"; "class_type_declaration"; "class_type_field"; "constructor_declaration"; "expr"; "extension"; "extension_constructor"; "include_declaration"; "include_description"; "label_declaration"; "location"; "module_binding"; "module_declaration"; "module_expr"; "module_type"; "module_type_declaration"; "open_description"; "pat"; "signature"; "signature_item"; "structure"; "structure_item"; "typ"; "type_declaration"; "type_extension"; "type_kind"; "value_binding"; "value_description"; "with_constraint"; "payload"; "binding_op"; "module_substitution"; "open_declaration"; "type_exception" ] let foreach_field f = printf "\n"; List.iter f fields *)(*$*) let copy_mapper = fun ({ From.Ast_mapper. (*$ foreach_field (printf "%s;\n")*) attribute; attributes; case; cases; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; constructor_declaration; expr; extension; extension_constructor; include_declaration; include_description; label_declaration; location; module_binding; module_declaration; module_expr; module_type; module_type_declaration; open_description; pat; signature; signature_item; structure; structure_item; typ; type_declaration; type_extension; type_kind; value_binding; value_description; with_constraint; payload; binding_op; module_substitution; open_declaration; type_exception; (*$*) } as mapper) -> let module Def = Migrate_parsetree_def in let module R = Migrate_parsetree_409_408_migrate in { To.Ast_mapper. $ foreach_field ( fun s - > printf " % s = ( fun _ x - > copy_%s ( % s mapper ( R.copy_%s x)));\n " s s s s ) printf "%s = (fun _ x -> copy_%s (%s mapper (R.copy_%s x)));\n" s s s s) *) attribute = (fun _ x -> copy_attribute (attribute mapper (R.copy_attribute x))); attributes = (fun _ x -> copy_attributes (attributes mapper (R.copy_attributes x))); case = (fun _ x -> copy_case (case mapper (R.copy_case x))); cases = (fun _ x -> copy_cases (cases mapper (R.copy_cases x))); class_declaration = (fun _ x -> copy_class_declaration (class_declaration mapper (R.copy_class_declaration x))); class_description = (fun _ x -> copy_class_description (class_description mapper (R.copy_class_description x))); class_expr = (fun _ x -> copy_class_expr (class_expr mapper (R.copy_class_expr x))); class_field = (fun _ x -> copy_class_field (class_field mapper (R.copy_class_field x))); class_signature = (fun _ x -> copy_class_signature (class_signature mapper (R.copy_class_signature x))); class_structure = (fun _ x -> copy_class_structure (class_structure mapper (R.copy_class_structure x))); class_type = (fun _ x -> copy_class_type (class_type mapper (R.copy_class_type x))); class_type_declaration = (fun _ x -> copy_class_type_declaration (class_type_declaration mapper (R.copy_class_type_declaration x))); class_type_field = (fun _ x -> copy_class_type_field (class_type_field mapper (R.copy_class_type_field x))); constructor_declaration = (fun _ x -> copy_constructor_declaration (constructor_declaration mapper (R.copy_constructor_declaration x))); expr = (fun _ x -> copy_expr (expr mapper (R.copy_expr x))); extension = (fun _ x -> copy_extension (extension mapper (R.copy_extension x))); extension_constructor = (fun _ x -> copy_extension_constructor (extension_constructor mapper (R.copy_extension_constructor x))); include_declaration = (fun _ x -> copy_include_declaration (include_declaration mapper (R.copy_include_declaration x))); include_description = (fun _ x -> copy_include_description (include_description mapper (R.copy_include_description x))); label_declaration = (fun _ x -> copy_label_declaration (label_declaration mapper (R.copy_label_declaration x))); location = (fun _ x -> copy_location (location mapper (R.copy_location x))); module_binding = (fun _ x -> copy_module_binding (module_binding mapper (R.copy_module_binding x))); module_declaration = (fun _ x -> copy_module_declaration (module_declaration mapper (R.copy_module_declaration x))); module_expr = (fun _ x -> copy_module_expr (module_expr mapper (R.copy_module_expr x))); module_type = (fun _ x -> copy_module_type (module_type mapper (R.copy_module_type x))); module_type_declaration = (fun _ x -> copy_module_type_declaration (module_type_declaration mapper (R.copy_module_type_declaration x))); open_description = (fun _ x -> copy_open_description (open_description mapper (R.copy_open_description x))); pat = (fun _ x -> copy_pat (pat mapper (R.copy_pat x))); signature = (fun _ x -> copy_signature (signature mapper (R.copy_signature x))); signature_item = (fun _ x -> copy_signature_item (signature_item mapper (R.copy_signature_item x))); structure = (fun _ x -> copy_structure (structure mapper (R.copy_structure x))); structure_item = (fun _ x -> copy_structure_item (structure_item mapper (R.copy_structure_item x))); typ = (fun _ x -> copy_typ (typ mapper (R.copy_typ x))); type_declaration = (fun _ x -> copy_type_declaration (type_declaration mapper (R.copy_type_declaration x))); type_extension = (fun _ x -> copy_type_extension (type_extension mapper (R.copy_type_extension x))); type_kind = (fun _ x -> copy_type_kind (type_kind mapper (R.copy_type_kind x))); value_binding = (fun _ x -> copy_value_binding (value_binding mapper (R.copy_value_binding x))); value_description = (fun _ x -> copy_value_description (value_description mapper (R.copy_value_description x))); with_constraint = (fun _ x -> copy_with_constraint (with_constraint mapper (R.copy_with_constraint x))); payload = (fun _ x -> copy_payload (payload mapper (R.copy_payload x))); binding_op = (fun _ x -> copy_binding_op (binding_op mapper (R.copy_binding_op x))); module_substitution = (fun _ x -> copy_module_substitution (module_substitution mapper (R.copy_module_substitution x))); open_declaration = (fun _ x -> copy_open_declaration (open_declaration mapper (R.copy_open_declaration x))); type_exception = (fun _ x -> copy_type_exception (type_exception mapper (R.copy_type_exception x))); (*$*) }
null
https://raw.githubusercontent.com/reasonml/reason/4f6ff7616bfa699059d642a3d16d8905d83555f6/src/vendored-omp/src/migrate_parsetree_408_409.ml
ocaml
************************************************************************ OCaml Migrate Parsetree en Automatique (INRIA). All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ $ $ foreach_field (printf "%s;\n") $ $
Copyright 2017 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the include Migrate_parsetree_408_409_migrate $ open Printf let fields = [ " attribute " ; " attributes " ; " case " ; " cases " ; " class_declaration " ; " class_description " ; " class_expr " ; " class_field " ; " class_signature " ; " class_structure " ; " class_type " ; " class_type_declaration " ; " class_type_field " ; " constructor_declaration " ; " expr " ; " extension " ; " extension_constructor " ; " include_declaration " ; " include_description " ; " label_declaration " ; " location " ; " module_binding " ; " module_declaration " ; " module_expr " ; " module_type " ; " module_type_declaration " ; " open_description " ; " pat " ; " signature " ; " signature_item " ; " structure " ; " structure_item " ; " typ " ; " type_declaration " ; " type_extension " ; " type_kind " ; " value_binding " ; " value_description " ; " with_constraint " ; " payload " ; " binding_op " ; " module_substitution " ; " open_declaration " ; " type_exception " ] let foreach_field f = printf " \n " ; List.iter f fields let fields = [ "attribute"; "attributes"; "case"; "cases"; "class_declaration"; "class_description"; "class_expr"; "class_field"; "class_signature"; "class_structure"; "class_type"; "class_type_declaration"; "class_type_field"; "constructor_declaration"; "expr"; "extension"; "extension_constructor"; "include_declaration"; "include_description"; "label_declaration"; "location"; "module_binding"; "module_declaration"; "module_expr"; "module_type"; "module_type_declaration"; "open_description"; "pat"; "signature"; "signature_item"; "structure"; "structure_item"; "typ"; "type_declaration"; "type_extension"; "type_kind"; "value_binding"; "value_description"; "with_constraint"; "payload"; "binding_op"; "module_substitution"; "open_declaration"; "type_exception" ] let foreach_field f = printf "\n"; List.iter f fields let copy_mapper = fun ({ From.Ast_mapper. attribute; attributes; case; cases; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; constructor_declaration; expr; extension; extension_constructor; include_declaration; include_description; label_declaration; location; module_binding; module_declaration; module_expr; module_type; module_type_declaration; open_description; pat; signature; signature_item; structure; structure_item; typ; type_declaration; type_extension; type_kind; value_binding; value_description; with_constraint; payload; binding_op; module_substitution; open_declaration; type_exception; } as mapper) -> let module Def = Migrate_parsetree_def in let module R = Migrate_parsetree_409_408_migrate in { To.Ast_mapper. $ foreach_field ( fun s - > printf " % s = ( fun _ x - > copy_%s ( % s mapper ( R.copy_%s x)));\n " s s s s ) printf "%s = (fun _ x -> copy_%s (%s mapper (R.copy_%s x)));\n" s s s s) *) attribute = (fun _ x -> copy_attribute (attribute mapper (R.copy_attribute x))); attributes = (fun _ x -> copy_attributes (attributes mapper (R.copy_attributes x))); case = (fun _ x -> copy_case (case mapper (R.copy_case x))); cases = (fun _ x -> copy_cases (cases mapper (R.copy_cases x))); class_declaration = (fun _ x -> copy_class_declaration (class_declaration mapper (R.copy_class_declaration x))); class_description = (fun _ x -> copy_class_description (class_description mapper (R.copy_class_description x))); class_expr = (fun _ x -> copy_class_expr (class_expr mapper (R.copy_class_expr x))); class_field = (fun _ x -> copy_class_field (class_field mapper (R.copy_class_field x))); class_signature = (fun _ x -> copy_class_signature (class_signature mapper (R.copy_class_signature x))); class_structure = (fun _ x -> copy_class_structure (class_structure mapper (R.copy_class_structure x))); class_type = (fun _ x -> copy_class_type (class_type mapper (R.copy_class_type x))); class_type_declaration = (fun _ x -> copy_class_type_declaration (class_type_declaration mapper (R.copy_class_type_declaration x))); class_type_field = (fun _ x -> copy_class_type_field (class_type_field mapper (R.copy_class_type_field x))); constructor_declaration = (fun _ x -> copy_constructor_declaration (constructor_declaration mapper (R.copy_constructor_declaration x))); expr = (fun _ x -> copy_expr (expr mapper (R.copy_expr x))); extension = (fun _ x -> copy_extension (extension mapper (R.copy_extension x))); extension_constructor = (fun _ x -> copy_extension_constructor (extension_constructor mapper (R.copy_extension_constructor x))); include_declaration = (fun _ x -> copy_include_declaration (include_declaration mapper (R.copy_include_declaration x))); include_description = (fun _ x -> copy_include_description (include_description mapper (R.copy_include_description x))); label_declaration = (fun _ x -> copy_label_declaration (label_declaration mapper (R.copy_label_declaration x))); location = (fun _ x -> copy_location (location mapper (R.copy_location x))); module_binding = (fun _ x -> copy_module_binding (module_binding mapper (R.copy_module_binding x))); module_declaration = (fun _ x -> copy_module_declaration (module_declaration mapper (R.copy_module_declaration x))); module_expr = (fun _ x -> copy_module_expr (module_expr mapper (R.copy_module_expr x))); module_type = (fun _ x -> copy_module_type (module_type mapper (R.copy_module_type x))); module_type_declaration = (fun _ x -> copy_module_type_declaration (module_type_declaration mapper (R.copy_module_type_declaration x))); open_description = (fun _ x -> copy_open_description (open_description mapper (R.copy_open_description x))); pat = (fun _ x -> copy_pat (pat mapper (R.copy_pat x))); signature = (fun _ x -> copy_signature (signature mapper (R.copy_signature x))); signature_item = (fun _ x -> copy_signature_item (signature_item mapper (R.copy_signature_item x))); structure = (fun _ x -> copy_structure (structure mapper (R.copy_structure x))); structure_item = (fun _ x -> copy_structure_item (structure_item mapper (R.copy_structure_item x))); typ = (fun _ x -> copy_typ (typ mapper (R.copy_typ x))); type_declaration = (fun _ x -> copy_type_declaration (type_declaration mapper (R.copy_type_declaration x))); type_extension = (fun _ x -> copy_type_extension (type_extension mapper (R.copy_type_extension x))); type_kind = (fun _ x -> copy_type_kind (type_kind mapper (R.copy_type_kind x))); value_binding = (fun _ x -> copy_value_binding (value_binding mapper (R.copy_value_binding x))); value_description = (fun _ x -> copy_value_description (value_description mapper (R.copy_value_description x))); with_constraint = (fun _ x -> copy_with_constraint (with_constraint mapper (R.copy_with_constraint x))); payload = (fun _ x -> copy_payload (payload mapper (R.copy_payload x))); binding_op = (fun _ x -> copy_binding_op (binding_op mapper (R.copy_binding_op x))); module_substitution = (fun _ x -> copy_module_substitution (module_substitution mapper (R.copy_module_substitution x))); open_declaration = (fun _ x -> copy_open_declaration (open_declaration mapper (R.copy_open_declaration x))); type_exception = (fun _ x -> copy_type_exception (type_exception mapper (R.copy_type_exception x))); }
831f7401e56f8ea2afd01f7f23d509fc45594b960e6f9b0849fb2301a5d2679b
reborg/clojure-essential-reference
1.clj
< 1 > < 2 > 3 (s/last-index-of "Bonjure Clojure!" "ju") ; <3> 11
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/StringsandRegularExpressions/index-of%2Clast-index-of/1.clj
clojure
<3>
< 1 > < 2 > 3 11
8429c1345277ed654919cfb6c9ee27288fbaa867f6bf8cf2ff9f4230199e60c8
andorp/bead
LDAP.hs
module Bead.Daemon.LDAP ( LDAPDaemon(..) , LDAPDaemonConfig(..) , startLDAPDaemon , module Bead.Daemon.LDAP.Result ) where import Prelude hiding (log) import Control.Concurrent (forkIO) import Control.Concurrent.Async import Control.Concurrent.STM import Control.Monad (join) import qualified Data.Map as Map import Data.Maybe import System.FilePath ((</>)) import Bead.Controller.Logging import Bead.Daemon.LDAP.Result import Bead.Daemon.LDAP.Query (QuerySettings(..)) import qualified Bead.Daemon.LDAP.Query as Query import qualified Bead.Domain.Entities as Entity type Username = String type Password = String data LDAPDaemon = LDAPDaemon { query :: Username -> IO (IO LDAPResult) -- ^ Queries the given username, and returns a computation that blocks -- until the authentication result is not evaluated. } Configuration for the LDAPDaemon data LDAPDaemonConfig = LDAPDaemonConfig { timeout :: Int , workers :: Int , command :: String , uidKey :: String , nameKey :: String , emailKey :: String } startLDAPDaemon :: Logger -> LDAPDaemonConfig -> IO LDAPDaemon startLDAPDaemon logger config = do queryQueue <- newTChanIO noOfRequests <- newTVarIO (0 :: Int) Every query tries to create an MTVar that blocks until -- the final result is not calculated. let query user = do resultEnvelope <- newEmptyTMVarIO atomically $ do n <- modifyTVar add1 noOfRequests writeTChan queryQueue (user,resultEnvelope) return $ do log logger INFO $ concat ["There are ", show n, " queries waiting in the LDAP queue."] atomically $ readTMVar resultEnvelope let uid_key = uidKey config let name_key = nameKey config let email_key = emailKey config let queryOK attrs = let attrMap = Map.fromList attrs in fromMaybe LDAPAttrMapError $ do uid <- fmap Entity.Uid $ Map.lookup uid_key attrMap name <- Map.lookup name_key attrMap email <- fmap Entity.Email $ Map.lookup email_key attrMap return $! LDAPUser (uid, email, name) let queryInvalid = LDAPInvalidUser let queryError msg = LDAPError msg let attrs = [uid_key, name_key, email_key] let loop daemon_id = do log logger INFO $ concat ["LDAP Daemon ", daemon_id, " is waiting"] join $ atomically $ do modifyTVar sub1 noOfRequests (user,resultEnvelope) <- readTChan queryQueue return $ do let querySettings = QuerySettings { queryTimeout = timeout config , queryCommand = command config } queryResult <- waitCatch =<< async (Query.query querySettings user attrs) log logger INFO $ concat ["LDAP Daemon ", daemon_id, " queries attributes for ", user] atomically $ putTMVar resultEnvelope $ case queryResult of Left someError -> LDAPError $ show someError Right result -> Query.queryResult queryOK queryInvalid queryError result loop daemon_id -- Start the workers sequence_ $ map (forkIO . loop . show) [1 .. workers config] return $! LDAPDaemon query where sub1 x = x - 1 add1 x = x + 1 modifyTVar f var = do x <- fmap f $ readTVar var writeTVar var x return x
null
https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/Daemon/LDAP.hs
haskell
^ Queries the given username, and returns a computation that blocks until the authentication result is not evaluated. the final result is not calculated. Start the workers
module Bead.Daemon.LDAP ( LDAPDaemon(..) , LDAPDaemonConfig(..) , startLDAPDaemon , module Bead.Daemon.LDAP.Result ) where import Prelude hiding (log) import Control.Concurrent (forkIO) import Control.Concurrent.Async import Control.Concurrent.STM import Control.Monad (join) import qualified Data.Map as Map import Data.Maybe import System.FilePath ((</>)) import Bead.Controller.Logging import Bead.Daemon.LDAP.Result import Bead.Daemon.LDAP.Query (QuerySettings(..)) import qualified Bead.Daemon.LDAP.Query as Query import qualified Bead.Domain.Entities as Entity type Username = String type Password = String data LDAPDaemon = LDAPDaemon { query :: Username -> IO (IO LDAPResult) } Configuration for the LDAPDaemon data LDAPDaemonConfig = LDAPDaemonConfig { timeout :: Int , workers :: Int , command :: String , uidKey :: String , nameKey :: String , emailKey :: String } startLDAPDaemon :: Logger -> LDAPDaemonConfig -> IO LDAPDaemon startLDAPDaemon logger config = do queryQueue <- newTChanIO noOfRequests <- newTVarIO (0 :: Int) Every query tries to create an MTVar that blocks until let query user = do resultEnvelope <- newEmptyTMVarIO atomically $ do n <- modifyTVar add1 noOfRequests writeTChan queryQueue (user,resultEnvelope) return $ do log logger INFO $ concat ["There are ", show n, " queries waiting in the LDAP queue."] atomically $ readTMVar resultEnvelope let uid_key = uidKey config let name_key = nameKey config let email_key = emailKey config let queryOK attrs = let attrMap = Map.fromList attrs in fromMaybe LDAPAttrMapError $ do uid <- fmap Entity.Uid $ Map.lookup uid_key attrMap name <- Map.lookup name_key attrMap email <- fmap Entity.Email $ Map.lookup email_key attrMap return $! LDAPUser (uid, email, name) let queryInvalid = LDAPInvalidUser let queryError msg = LDAPError msg let attrs = [uid_key, name_key, email_key] let loop daemon_id = do log logger INFO $ concat ["LDAP Daemon ", daemon_id, " is waiting"] join $ atomically $ do modifyTVar sub1 noOfRequests (user,resultEnvelope) <- readTChan queryQueue return $ do let querySettings = QuerySettings { queryTimeout = timeout config , queryCommand = command config } queryResult <- waitCatch =<< async (Query.query querySettings user attrs) log logger INFO $ concat ["LDAP Daemon ", daemon_id, " queries attributes for ", user] atomically $ putTMVar resultEnvelope $ case queryResult of Left someError -> LDAPError $ show someError Right result -> Query.queryResult queryOK queryInvalid queryError result loop daemon_id sequence_ $ map (forkIO . loop . show) [1 .. workers config] return $! LDAPDaemon query where sub1 x = x - 1 add1 x = x + 1 modifyTVar f var = do x <- fmap f $ readTVar var writeTVar var x return x
1ec457e4f5e7653d60233981b789e3b14d17f262e986433db8563a4a29f12215
GaloisInc/cryptol
Patterns.hs
# Language Safe , RankNTypes , MultiParamTypeClasses # {-# Language FunctionalDependencies #-} {-# Language FlexibleInstances #-} # Language TypeFamilies , UndecidableInstances # {-# Language TypeOperators #-} module Cryptol.Utils.Patterns where import Control.Monad(liftM,liftM2,ap,MonadPlus(..),guard) import qualified Control.Monad.Fail as Fail import Control.Applicative(Alternative(..)) newtype Match b = Match (forall r. r -> (b -> r) -> r) instance Functor Match where fmap = liftM instance Applicative Match where pure a = Match $ \_no yes -> yes a (<*>) = ap instance Monad Match where Match m >>= f = Match $ \no yes -> m no $ \a -> let Match n = f a in n no yes instance Fail.MonadFail Match where fail _ = empty instance Alternative Match where empty = Match $ \no _ -> no Match m <|> Match n = Match $ \no yes -> m (n no yes) yes instance MonadPlus Match where type Pat a b = a -> Match b (|||) :: Pat a b -> Pat a b -> Pat a b p ||| q = \a -> p a <|> q a -- | Check that a value satisfies multiple patterns. -- For example, an "as" pattern is @(__ &&& p)@. (&&&) :: Pat a b -> Pat a c -> Pat a (b,c) p &&& q = \a -> liftM2 (,) (p a) (q a) -- | Match a value, and modify the result. (~>) :: Pat a b -> (b -> c) -> Pat a c p ~> f = \a -> f <$> p a -- | Match a value, and return the given result (~~>) :: Pat a b -> c -> Pat a c p ~~> f = \a -> f <$ p a -- | View pattern. (<~) :: (a -> b) -> Pat b c -> Pat a c f <~ p = \a -> p (f a) -- | Variable pattern. __ :: Pat a a __ = return -- | Constant pattern. succeed :: a -> Pat x a succeed = const . return -- | Predicate pattern checkThat :: (a -> Bool) -> Pat a () checkThat p = \a -> guard (p a) -- | Check for exact value. lit :: Eq a => a -> Pat a () lit x = checkThat (x ==) {-# Inline lit #-} -- | Match a pattern, using the given default if valure. matchDefault :: a -> Match a -> a matchDefault a (Match m) = m a id # Inline matchDefault # -- | Match an irrefutable pattern. Crashes on faliure. match :: Match a -> a match m = matchDefault (error "Pattern match failure.") m # Inline match # matchMaybe :: Match a -> Maybe a matchMaybe (Match m) = m Nothing Just list :: [Pat a b] -> Pat [a] [b] list [] = \a -> case a of [] -> return [] _ -> mzero list (p : ps) = \as -> case as of [] -> mzero x : xs -> do a <- p x bs <- list ps xs return (a : bs) (><) :: Pat a b -> Pat x y -> Pat (a,x) (b,y) p >< q = \(a,x) -> do b <- p a y <- q x return (b,y) class Matches thing pats res | pats -> thing res where matches :: thing -> pats -> Match res instance ( f ~ Pat a a1' , a1 ~ Pat a1' r1 ) => Matches a (f,a1) r1 where matches ty (f,a1) = do a1' <- f ty a1 a1' instance ( op ~ Pat a (a1',a2') , a1 ~ Pat a1' r1 , a2 ~ Pat a2' r2 ) => Matches a (op,a1,a2) (r1,r2) where matches ty (f,a1,a2) = do (a1',a2') <- f ty r1 <- a1 a1' r2 <- a2 a2' return (r1,r2) instance ( op ~ Pat a (a1',a2',a3') , a1 ~ Pat a1' r1 , a2 ~ Pat a2' r2 , a3 ~ Pat a3' r3 ) => Matches a (op,a1,a2,a3) (r1,r2,r3) where matches ty (f,a1,a2,a3) = do (a1',a2',a3') <- f ty r1 <- a1 a1' r2 <- a2 a2' r3 <- a3 a3' return (r1,r2,r3)
null
https://raw.githubusercontent.com/GaloisInc/cryptol/4c1c5fc68120e38e38fe3c93eb787da84c1b24bc/src/Cryptol/Utils/Patterns.hs
haskell
# Language FunctionalDependencies # # Language FlexibleInstances # # Language TypeOperators # | Check that a value satisfies multiple patterns. For example, an "as" pattern is @(__ &&& p)@. | Match a value, and modify the result. | Match a value, and return the given result | View pattern. | Variable pattern. | Constant pattern. | Predicate pattern | Check for exact value. # Inline lit # | Match a pattern, using the given default if valure. | Match an irrefutable pattern. Crashes on faliure.
# Language Safe , RankNTypes , MultiParamTypeClasses # # Language TypeFamilies , UndecidableInstances # module Cryptol.Utils.Patterns where import Control.Monad(liftM,liftM2,ap,MonadPlus(..),guard) import qualified Control.Monad.Fail as Fail import Control.Applicative(Alternative(..)) newtype Match b = Match (forall r. r -> (b -> r) -> r) instance Functor Match where fmap = liftM instance Applicative Match where pure a = Match $ \_no yes -> yes a (<*>) = ap instance Monad Match where Match m >>= f = Match $ \no yes -> m no $ \a -> let Match n = f a in n no yes instance Fail.MonadFail Match where fail _ = empty instance Alternative Match where empty = Match $ \no _ -> no Match m <|> Match n = Match $ \no yes -> m (n no yes) yes instance MonadPlus Match where type Pat a b = a -> Match b (|||) :: Pat a b -> Pat a b -> Pat a b p ||| q = \a -> p a <|> q a (&&&) :: Pat a b -> Pat a c -> Pat a (b,c) p &&& q = \a -> liftM2 (,) (p a) (q a) (~>) :: Pat a b -> (b -> c) -> Pat a c p ~> f = \a -> f <$> p a (~~>) :: Pat a b -> c -> Pat a c p ~~> f = \a -> f <$ p a (<~) :: (a -> b) -> Pat b c -> Pat a c f <~ p = \a -> p (f a) __ :: Pat a a __ = return succeed :: a -> Pat x a succeed = const . return checkThat :: (a -> Bool) -> Pat a () checkThat p = \a -> guard (p a) lit :: Eq a => a -> Pat a () lit x = checkThat (x ==) matchDefault :: a -> Match a -> a matchDefault a (Match m) = m a id # Inline matchDefault # match :: Match a -> a match m = matchDefault (error "Pattern match failure.") m # Inline match # matchMaybe :: Match a -> Maybe a matchMaybe (Match m) = m Nothing Just list :: [Pat a b] -> Pat [a] [b] list [] = \a -> case a of [] -> return [] _ -> mzero list (p : ps) = \as -> case as of [] -> mzero x : xs -> do a <- p x bs <- list ps xs return (a : bs) (><) :: Pat a b -> Pat x y -> Pat (a,x) (b,y) p >< q = \(a,x) -> do b <- p a y <- q x return (b,y) class Matches thing pats res | pats -> thing res where matches :: thing -> pats -> Match res instance ( f ~ Pat a a1' , a1 ~ Pat a1' r1 ) => Matches a (f,a1) r1 where matches ty (f,a1) = do a1' <- f ty a1 a1' instance ( op ~ Pat a (a1',a2') , a1 ~ Pat a1' r1 , a2 ~ Pat a2' r2 ) => Matches a (op,a1,a2) (r1,r2) where matches ty (f,a1,a2) = do (a1',a2') <- f ty r1 <- a1 a1' r2 <- a2 a2' return (r1,r2) instance ( op ~ Pat a (a1',a2',a3') , a1 ~ Pat a1' r1 , a2 ~ Pat a2' r2 , a3 ~ Pat a3' r3 ) => Matches a (op,a1,a2,a3) (r1,r2,r3) where matches ty (f,a1,a2,a3) = do (a1',a2',a3') <- f ty r1 <- a1 a1' r2 <- a2 a2' r3 <- a3 a3' return (r1,r2,r3)
b5dcaf135ada3d87ad9639f21d85060e0c983165b26ac2dc78974b9fa8a1dbf1
SqrtMinusOne/channel-q
starship.scm
(define-module (starship) #:use-module (gnu packages base) #:use-module (gnu packages compression) #:use-module (gnu packages gcc) #:use-module (guix download) #:use-module (guix packages) #:use-module ((guix licenses) #:prefix license:) #:use-module (nonguix build-system binary)) (define-public starship (package (name "starship-bin") (version "1.12.0") (source (origin (method url-fetch) (uri (string-append "" version "/starship-x86_64-unknown-linux-gnu.tar.gz")) (sha256 (base32 "0zq5mn8m3jaqhx1px108izh5ibi23jcwy0wragip8dy1swb3kzr3")))) (build-system binary-build-system) (arguments `(#:install-plan `(("starship" "/bin/")) #:patchelf-plan `(("starship" ("gcc:lib" "glibc"))) #:phases (modify-phases %standard-phases (replace 'unpack (lambda* (#:key inputs #:allow-other-keys) (invoke "tar" "-xvzf" (assoc-ref inputs "source"))))))) (inputs `(("gcc:lib" ,gcc "lib") ("glibc" ,glibc))) (native-inputs `(("gzip" ,gzip))) (synopsis "Starship is the minimal, blazing fast, and extremely customizable prompt for any shell!") (description "Starship is the minimal, blazing fast, and extremely customizable prompt for any shell!") (home-page "") (license license:isc)))
null
https://raw.githubusercontent.com/SqrtMinusOne/channel-q/0531901c54bdf3a0bc40a82412048544853fcf46/starship.scm
scheme
(define-module (starship) #:use-module (gnu packages base) #:use-module (gnu packages compression) #:use-module (gnu packages gcc) #:use-module (guix download) #:use-module (guix packages) #:use-module ((guix licenses) #:prefix license:) #:use-module (nonguix build-system binary)) (define-public starship (package (name "starship-bin") (version "1.12.0") (source (origin (method url-fetch) (uri (string-append "" version "/starship-x86_64-unknown-linux-gnu.tar.gz")) (sha256 (base32 "0zq5mn8m3jaqhx1px108izh5ibi23jcwy0wragip8dy1swb3kzr3")))) (build-system binary-build-system) (arguments `(#:install-plan `(("starship" "/bin/")) #:patchelf-plan `(("starship" ("gcc:lib" "glibc"))) #:phases (modify-phases %standard-phases (replace 'unpack (lambda* (#:key inputs #:allow-other-keys) (invoke "tar" "-xvzf" (assoc-ref inputs "source"))))))) (inputs `(("gcc:lib" ,gcc "lib") ("glibc" ,glibc))) (native-inputs `(("gzip" ,gzip))) (synopsis "Starship is the minimal, blazing fast, and extremely customizable prompt for any shell!") (description "Starship is the minimal, blazing fast, and extremely customizable prompt for any shell!") (home-page "") (license license:isc)))
33c3a8b71c65afefa551b439368ace674a040569e4d78eda1f835b908e792953
FieryCod/holy-lambda
core.cljc
(ns aws-interop-v2.example.core (:gen-class) (:require [fierycod.holy-lambda.response :as hr] [fierycod.holy-lambda.core :as h] [fierycod.holy-lambda.agent :as agent] [fierycod.holy-lambda.native-runtime :as native] [clojure.string :as str] [jsonista.core :as json]) (:import [java.io ByteArrayOutputStream ByteArrayInputStream] [java.time Instant] [java.net HttpURLConnection] ;; AWS API [software.amazon.awssdk.regions Region] [com.amazonaws.xray.interceptors TracingInterceptor] [software.amazon.awssdk.core.client.config ClientOverrideConfiguration] [software.amazon.awssdk.auth.credentials EnvironmentVariableCredentialsProvider] [software.amazon.awssdk.http.urlconnection UrlConnectionHttpClient] [software.amazon.awssdk.core ResponseInputStream SdkBytes] [software.amazon.awssdk.http AbortableInputStream] ;; AWS S3 API ;; -summary.html [software.amazon.awssdk.services.s3 S3Client] [software.amazon.awssdk.services.s3.model S3Object ListObjectsRequest ListObjectsResponse GetObjectAclRequest GetObjectAclResponse])) (def xray-enabled? true) ; cache of re-usable clients using the id/key. best perf to create a client once, not for each request (def cloud-clients (atom {})) (defn aws-client "return an aws client in order of priority: 1. already present in request using the :id i.e. provided by tests etc 2. the :conf client used during native:conf 3. the :default used/re-used for cloud/prod operation" [{:keys [id default-thunk conf request]}] (or (get-in request [:event ::aws-clients id]) (when (get-in request [:event ::native-conf?]) conf) (or (get @cloud-clients id) (let [client (default-thunk)] (swap! cloud-clients assoc id client) client)))) (defn common-client-config [client {:keys [region x-ray?]}] (-> client (cond-> region (.region region) x-ray? (.overrideConfiguration (-> (ClientOverrideConfiguration/builder) (.addExecutionInterceptor (TracingInterceptor.)) (.build)))) (.credentialsProvider (EnvironmentVariableCredentialsProvider/create)) (.httpClientBuilder (UrlConnectionHttpClient/builder)))) (defn s3-client [opts] (-> (S3Client/builder) (common-client-config opts) (.build))) (defn s3-object [key size] (-> (S3Object/builder) (.key key) (.size size) (.build))) (defn mock-s3-client [xfm] (reify S3Client (^ListObjectsResponse listObjects [^S3Client client ^ListObjectsRequest request] (-> (ListObjectsResponse/builder) (xfm :list) (.build))) (^GetObjectAclResponse getObjectAcl [^S3Client client ^GetObjectAclRequest request] (-> (GetObjectAclResponse/builder) (xfm :acl) (.build))))) (defn s3-list-objects [client {:keys [bucket]}] (let [request (-> (ListObjectsRequest/builder) (.bucket bucket) (.build))] (.listObjects client request))) (defn s3-get-acl [client {:keys [bucket key]}] (let [request (-> (GetObjectAclRequest/builder) (.bucket bucket) (.key key) (.build))] (.getObjectAcl client request))) (h/deflambda ExampleLambda "handles 2 uris: one to list an s3 bucket, the second to display the ACL/permissions for an s3 object" [{:keys [event ctx] :as request}] (let [{:keys [envs]} event bucket (get envs "S3_BUCKET") s3-client (aws-client {:id :s3 ; you could have N s3 clients e.g. different regions :default-thunk (fn [] (s3-client {:x-ray? xray-enabled?})) ; used in AWS cloud :conf (mock-s3-client (fn [v _] v)) ; used during native:conf payloads :request request})] allow requests to control logging of full request . Note : this could record your AWS keys in cloudwatch (when (some-> event :queryStringParameters (str/includes? "LOG")) (println (json/write-value-as-string event)) (println (json/write-value-as-string ctx))) (cond ; list page (= (:path request) "/list") (let [s3-list-response (s3-list-objects s3-client {:bucket bucket})] (hr/html (str "<h2>All Objects</h2>\n" (->> (.contents s3-list-response) (map (fn [obj] (str "<p><a href='/obj/" (.key obj) "'>" (.key obj) " : " (.size obj) "</a></p>"))) (str/join "\n"))))) ; object perms page (some-> request :path (str/starts-with? "/obj")) (let [s3-acl-response (s3-get-acl s3-client {:bucket bucket :key "TODO"})] (hr/html (str "<h2>" (subs (:path request) 5 (count (:path request))) "</h2>\n" (->> (.grants s3-acl-response) (map (fn [grant] (str "<p>" (.permissionAsString grant) "</p>"))) (str/join "\n")))))))) (native/entrypoint [#'ExampleLambda]) native : conf forms i.e. exercise all code paths that must be captured by for inclusion during native : executable (def bucket-name "hltaskstest") (agent/in-context ; safe s3 request i.e. no side effects (-> (s3-client {#_#_:region Region/AP_SOUTHEAST_2}) (s3-list-objects {:bucket bucket-name}) (.contents) count (->> (println "s3 bucket count:")))) (agent/in-context ; safe s3 request with x-ray enabled to sample x-ray init blocks. need all classes from this added to runtime init list ; -lambda-xray/deployment/src/main/java/io/quarkus/amazon/lambda/xray/XrayBuildStep.java ;; (try ;; (-> {#_#_:region Region/AP_SOUTHEAST_2 ;; :x-ray? true} ;; s3-client ;; (s3-list-objects {:bucket bucket-name})) ;; (catch Exception e ;; (println (.getMessage e)))) )
null
https://raw.githubusercontent.com/FieryCod/holy-lambda/93e786be70505f6734c6f8c45c7a7703c149f482/examples/bb/native/aws-interop-v2.example/src/aws_interop_v2/example/core.cljc
clojure
AWS API AWS S3 API -summary.html cache of re-usable clients using the id/key. best perf to create a client once, not for each request you could have N s3 clients e.g. different regions used in AWS cloud used during native:conf payloads list page object perms page safe s3 request i.e. no side effects safe s3 request with x-ray enabled to sample x-ray init blocks. need all classes from this added to runtime init list -lambda-xray/deployment/src/main/java/io/quarkus/amazon/lambda/xray/XrayBuildStep.java (try (-> {#_#_:region Region/AP_SOUTHEAST_2 :x-ray? true} s3-client (s3-list-objects {:bucket bucket-name})) (catch Exception e (println (.getMessage e))))
(ns aws-interop-v2.example.core (:gen-class) (:require [fierycod.holy-lambda.response :as hr] [fierycod.holy-lambda.core :as h] [fierycod.holy-lambda.agent :as agent] [fierycod.holy-lambda.native-runtime :as native] [clojure.string :as str] [jsonista.core :as json]) (:import [java.io ByteArrayOutputStream ByteArrayInputStream] [java.time Instant] [java.net HttpURLConnection] [software.amazon.awssdk.regions Region] [com.amazonaws.xray.interceptors TracingInterceptor] [software.amazon.awssdk.core.client.config ClientOverrideConfiguration] [software.amazon.awssdk.auth.credentials EnvironmentVariableCredentialsProvider] [software.amazon.awssdk.http.urlconnection UrlConnectionHttpClient] [software.amazon.awssdk.core ResponseInputStream SdkBytes] [software.amazon.awssdk.http AbortableInputStream] [software.amazon.awssdk.services.s3 S3Client] [software.amazon.awssdk.services.s3.model S3Object ListObjectsRequest ListObjectsResponse GetObjectAclRequest GetObjectAclResponse])) (def xray-enabled? true) (def cloud-clients (atom {})) (defn aws-client "return an aws client in order of priority: 1. already present in request using the :id i.e. provided by tests etc 2. the :conf client used during native:conf 3. the :default used/re-used for cloud/prod operation" [{:keys [id default-thunk conf request]}] (or (get-in request [:event ::aws-clients id]) (when (get-in request [:event ::native-conf?]) conf) (or (get @cloud-clients id) (let [client (default-thunk)] (swap! cloud-clients assoc id client) client)))) (defn common-client-config [client {:keys [region x-ray?]}] (-> client (cond-> region (.region region) x-ray? (.overrideConfiguration (-> (ClientOverrideConfiguration/builder) (.addExecutionInterceptor (TracingInterceptor.)) (.build)))) (.credentialsProvider (EnvironmentVariableCredentialsProvider/create)) (.httpClientBuilder (UrlConnectionHttpClient/builder)))) (defn s3-client [opts] (-> (S3Client/builder) (common-client-config opts) (.build))) (defn s3-object [key size] (-> (S3Object/builder) (.key key) (.size size) (.build))) (defn mock-s3-client [xfm] (reify S3Client (^ListObjectsResponse listObjects [^S3Client client ^ListObjectsRequest request] (-> (ListObjectsResponse/builder) (xfm :list) (.build))) (^GetObjectAclResponse getObjectAcl [^S3Client client ^GetObjectAclRequest request] (-> (GetObjectAclResponse/builder) (xfm :acl) (.build))))) (defn s3-list-objects [client {:keys [bucket]}] (let [request (-> (ListObjectsRequest/builder) (.bucket bucket) (.build))] (.listObjects client request))) (defn s3-get-acl [client {:keys [bucket key]}] (let [request (-> (GetObjectAclRequest/builder) (.bucket bucket) (.key key) (.build))] (.getObjectAcl client request))) (h/deflambda ExampleLambda "handles 2 uris: one to list an s3 bucket, the second to display the ACL/permissions for an s3 object" [{:keys [event ctx] :as request}] (let [{:keys [envs]} event bucket (get envs "S3_BUCKET") :request request})] allow requests to control logging of full request . Note : this could record your AWS keys in cloudwatch (when (some-> event :queryStringParameters (str/includes? "LOG")) (println (json/write-value-as-string event)) (println (json/write-value-as-string ctx))) (cond (= (:path request) "/list") (let [s3-list-response (s3-list-objects s3-client {:bucket bucket})] (hr/html (str "<h2>All Objects</h2>\n" (->> (.contents s3-list-response) (map (fn [obj] (str "<p><a href='/obj/" (.key obj) "'>" (.key obj) " : " (.size obj) "</a></p>"))) (str/join "\n"))))) (some-> request :path (str/starts-with? "/obj")) (let [s3-acl-response (s3-get-acl s3-client {:bucket bucket :key "TODO"})] (hr/html (str "<h2>" (subs (:path request) 5 (count (:path request))) "</h2>\n" (->> (.grants s3-acl-response) (map (fn [grant] (str "<p>" (.permissionAsString grant) "</p>"))) (str/join "\n")))))))) (native/entrypoint [#'ExampleLambda]) native : conf forms i.e. exercise all code paths that must be captured by for inclusion during native : executable (def bucket-name "hltaskstest") (agent/in-context (-> (s3-client {#_#_:region Region/AP_SOUTHEAST_2}) (s3-list-objects {:bucket bucket-name}) (.contents) count (->> (println "s3 bucket count:")))) (agent/in-context )
75a4a5c74313a2d3a03f169d36c68ab8aaa612a25e6a7aeabc8dd3995b31b003
theodormoroianu/SecondYearCourses
LambdaChurch_20210415164419.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) churchNil :: Term churchNil = lams ["agg", "init"] (v "init") churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164419.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda note that it's the same as churchFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) churchNil :: Term churchNil = lams ["agg", "init"] (v "init") churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
07d9d467342ed097b308ba846971c1e87006bd1a8c79635546063a5cbb73a7ae
aryx/fork-efuns
utils.mli
(***********************************************************************) (* *) (* ____ *) (* *) Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt (* *) Copyright 1999 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . (* *) (***********************************************************************) val count_char_sub : string -> int -> int -> char -> int * int val count_char : string -> char -> int * int val list_nth : int -> 'a list -> 'a val mem_assq : 'a -> ('a * 'b) list -> bool val removeq : 'a -> ('a * 'b) list -> ('a * 'b) list val list_removeq : 'a list -> 'a -> 'a list val remove_assocq : 'a -> ('a * 'b) list -> ('a * 'b) list val list_remove : 'a list -> 'a -> 'a list val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list val file_list : string -> string list val string_ncmp : string -> string -> int -> bool val completion : string list -> string -> string list val common_suffix : string list -> string -> string * int val read_string : in_channel -> string val list_of_hash : ('a, 'b) Hashtbl.t -> ('a * 'b) list val find_in_path : string list -> string -> string val string_to_path : string -> string list val path_to_string : string list -> string val hash_add_assoc : ('a, 'b) Hashtbl.t -> ('a * 'b) list -> unit val user : string val homedir : string val known_dirs : (string * string) list ref val check_prefix : string -> string -> string val replace_prefix : string -> (string * string) list -> string val filename_to_string : string -> string val string_to_filename : string -> string val exns : (exn -> string) list ref val register_exn : (exn -> string) -> unit val printexn : exn -> string val catchexn : string -> (unit -> unit) -> unit val vcatchexn : string -> (unit -> 'a) -> 'a option format_to_string : ( ' a - > ' b ) - > ' a - > string val do_and_format : ('a -> 'b) -> 'a -> string * 'b val format_to_string : ('a -> 'b) -> 'a -> string val is_directory : string -> bool val is_link : string -> bool val list_dir : string -> string list val load_directory : string -> string val normal_name : string -> string -> string val to_regexp_string : string -> string val hashtbl_mem : ('a, 'b) Hashtbl.t -> 'a -> bool : : string - > string val list_dir_normal : string -> string list
null
https://raw.githubusercontent.com/aryx/fork-efuns/8f2f8f66879d45e26ecdca0033f9c92aec2b783d/commons/utils.mli
ocaml
********************************************************************* ____ *********************************************************************
Fabrice Le Fessant , projet Para / SOR , INRIA Rocquencourt Copyright 1999 Institut National de Recherche en Informatique et Automatique . Distributed only by permission . val count_char_sub : string -> int -> int -> char -> int * int val count_char : string -> char -> int * int val list_nth : int -> 'a list -> 'a val mem_assq : 'a -> ('a * 'b) list -> bool val removeq : 'a -> ('a * 'b) list -> ('a * 'b) list val list_removeq : 'a list -> 'a -> 'a list val remove_assocq : 'a -> ('a * 'b) list -> ('a * 'b) list val list_remove : 'a list -> 'a -> 'a list val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list val file_list : string -> string list val string_ncmp : string -> string -> int -> bool val completion : string list -> string -> string list val common_suffix : string list -> string -> string * int val read_string : in_channel -> string val list_of_hash : ('a, 'b) Hashtbl.t -> ('a * 'b) list val find_in_path : string list -> string -> string val string_to_path : string -> string list val path_to_string : string list -> string val hash_add_assoc : ('a, 'b) Hashtbl.t -> ('a * 'b) list -> unit val user : string val homedir : string val known_dirs : (string * string) list ref val check_prefix : string -> string -> string val replace_prefix : string -> (string * string) list -> string val filename_to_string : string -> string val string_to_filename : string -> string val exns : (exn -> string) list ref val register_exn : (exn -> string) -> unit val printexn : exn -> string val catchexn : string -> (unit -> unit) -> unit val vcatchexn : string -> (unit -> 'a) -> 'a option format_to_string : ( ' a - > ' b ) - > ' a - > string val do_and_format : ('a -> 'b) -> 'a -> string * 'b val format_to_string : ('a -> 'b) -> 'a -> string val is_directory : string -> bool val is_link : string -> bool val list_dir : string -> string list val load_directory : string -> string val normal_name : string -> string -> string val to_regexp_string : string -> string val hashtbl_mem : ('a, 'b) Hashtbl.t -> 'a -> bool : : string - > string val list_dir_normal : string -> string list
917e3f2e4dae652fae8c306aae719c667f1b43e80a4c3f497e1c2c56487235dc
blynn/compiler
e4096.hs
infixl 9 !!; infixr 9 .; infixl 7 * , / , %; infixl 6 + , -; infixr 5 ++; infixl 4 <*>; infix 4 == , <=; infixl 3 &&; infixl 2 ||; infixl 1 >> , >>=; infixr 0 $; foreign import ccall "putchar" putChar :: Int -> IO Int; class Eq a where { (==) :: a -> a -> Bool }; instance Eq Int where { (==) = intEq }; class Ord a where { (<=) :: a -> a -> Bool }; instance Ord Int where { (<=) = intLE }; class Functor f where { fmap :: (a -> b) -> f a -> f b }; class Applicative f where { pure :: a -> f a ; (<*>) :: f (a -> b) -> f a -> f b }; class Monad m where { return :: a -> m a ; (>>=) :: m a -> (a -> m b) -> m b }; (>>) f g = f >>= \_ -> g; ($) f x = f x; (.) f g x = f (g x); flip f x y = f y x; flst xs n c = case xs of { [] -> n; h:t -> c h t }; foldr c n l = flst l n (\h t -> c h(foldr c n t)); (++) = flip (foldr (:)); concat = foldr (++) []; map = flip (foldr . ((:) .)) []; head (h:_) = h; tail (_:t) = t; repeat x = x : repeat x; mkdigit n | n <= 9 = chr (n + ord '0'); norm c (d:(e:x)) = let { e'x' = norm (c+1) (e:x); e' = head e'x'; x' = tail e'x' } in if e % c + 10 <= c then d + e / c: e' % c : x' else d + e' / c : e' % c : x'; convert x = let { x' = norm 2 (0:map (10*) x) } in mkdigit (head x'):convert (tail x'); edigits = "2." ++ convert (repeat 1); instance Applicative IO where { pure = ioPure ; (<*>) f x = ioBind f \g -> ioBind x \y -> ioPure (g y) }; instance Monad IO where { return = ioPure ; (>>=) = ioBind }; instance Functor IO where { fmap f x = ioPure f <*> x }; mapM_ f = foldr ((>>) . f) (pure ()); putStr = mapM_ $ putChar . ord; take 0 _ = []; take n (h:t) = h:take (n - 1) t; main = putStr $ take 4096 edigits;
null
https://raw.githubusercontent.com/blynn/compiler/b9fe455ad4ee4fbabe77f2f5c3c9aaa53cffa85b/e4096.hs
haskell
infixl 9 !!; infixr 9 .; infixl 7 * , / , %; infixl 6 + , -; infixr 5 ++; infixl 4 <*>; infix 4 == , <=; infixl 3 &&; infixl 2 ||; infixl 1 >> , >>=; infixr 0 $; foreign import ccall "putchar" putChar :: Int -> IO Int; class Eq a where { (==) :: a -> a -> Bool }; instance Eq Int where { (==) = intEq }; class Ord a where { (<=) :: a -> a -> Bool }; instance Ord Int where { (<=) = intLE }; class Functor f where { fmap :: (a -> b) -> f a -> f b }; class Applicative f where { pure :: a -> f a ; (<*>) :: f (a -> b) -> f a -> f b }; class Monad m where { return :: a -> m a ; (>>=) :: m a -> (a -> m b) -> m b }; (>>) f g = f >>= \_ -> g; ($) f x = f x; (.) f g x = f (g x); flip f x y = f y x; flst xs n c = case xs of { [] -> n; h:t -> c h t }; foldr c n l = flst l n (\h t -> c h(foldr c n t)); (++) = flip (foldr (:)); concat = foldr (++) []; map = flip (foldr . ((:) .)) []; head (h:_) = h; tail (_:t) = t; repeat x = x : repeat x; mkdigit n | n <= 9 = chr (n + ord '0'); norm c (d:(e:x)) = let { e'x' = norm (c+1) (e:x); e' = head e'x'; x' = tail e'x' } in if e % c + 10 <= c then d + e / c: e' % c : x' else d + e' / c : e' % c : x'; convert x = let { x' = norm 2 (0:map (10*) x) } in mkdigit (head x'):convert (tail x'); edigits = "2." ++ convert (repeat 1); instance Applicative IO where { pure = ioPure ; (<*>) f x = ioBind f \g -> ioBind x \y -> ioPure (g y) }; instance Monad IO where { return = ioPure ; (>>=) = ioBind }; instance Functor IO where { fmap f x = ioPure f <*> x }; mapM_ f = foldr ((>>) . f) (pure ()); putStr = mapM_ $ putChar . ord; take 0 _ = []; take n (h:t) = h:take (n - 1) t; main = putStr $ take 4096 edigits;
517c9d4b6cae648e773673807ec034452d47ed66083c0c5a1d777d53f9e816f7
locusmath/locus
object.clj
(ns locus.polynomial.fractional.object (:refer-clojure :exclude [+ - * /]) (:require [locus.set.logic.core.set :refer :all :exclude [add]] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.additive.base.core.protocols :refer :all] [locus.additive.base.generic.arithmetic :refer :all] [locus.additive.ring.core.object :refer :all] [locus.additive.semiring.core.object :refer :all] [locus.ab.vector.rset :refer :all] [locus.polynomial.core.object :refer :all]) (:import (locus.polynomial.core.object Polynomial))) ; Elements of the fields of fractions of polynomial rings (deftype RationalExpression [numerator denominator]) (defn numerator-polynomial [^RationalExpression expr] (.numerator expr)) (defn denominator-polynomial [^RationalExpression expr] (.denominator expr)) Generic conversion routines (defmulti to-rational-expression type) (defmethod to-rational-expression RationalExpression [expr] expr) (defmethod to-rational-expression Polynomial [expr] (RationalExpression. expr (one-polynomial (ring-of-coefficients expr)))) ; Negation (defmethod negate RationalExpression [^RationalExpression expr] (RationalExpression. (- (numerator-polynomial expr)) (denominator-polynomial expr))) (defmethod reciprocal Polynomial [^Polynomial polynomial] (RationalExpression. (one-polynomial (ring-of-coefficients polynomial)) polynomial)) (defmethod reciprocal RationalExpression [^RationalExpression expr] (RationalExpression. (.denominator expr) (.numerator expr))) (defmethod multiply [RationalExpression RationalExpression] [a b] (RationalExpression. (* (numerator-polynomial a) (numerator-polynomial b)) (* (denominator-polynomial a) (denominator-polynomial b)))) (defmethod add [RationalExpression RationalExpression] [a b] (RationalExpression. (+ (* (numerator-polynomial a) (denominator-polynomial b)) (* (numerator-polynomial b) (denominator-polynomial a))) (* (denominator-polynomial a) (denominator-polynomial b)))) ; Ontology of rational expressions (defn rational-expression? [expr] (= (type expr) RationalExpression))
null
https://raw.githubusercontent.com/locusmath/locus/12061072ccfe6a28f87eb8bd4489397dcf4b93d8/src/clojure/locus/polynomial/fractional/object.clj
clojure
Elements of the fields of fractions of polynomial rings Negation Ontology of rational expressions
(ns locus.polynomial.fractional.object (:refer-clojure :exclude [+ - * /]) (:require [locus.set.logic.core.set :refer :all :exclude [add]] [locus.set.mapping.general.core.object :refer :all] [locus.set.logic.structure.protocols :refer :all] [locus.set.quiver.structure.core.protocols :refer :all] [locus.set.copresheaf.structure.core.protocols :refer :all] [locus.algebra.commutative.semigroup.object :refer :all] [locus.algebra.semigroup.core.object :refer :all] [locus.algebra.semigroup.monoid.object :refer :all] [locus.algebra.group.core.object :refer :all] [locus.additive.base.core.protocols :refer :all] [locus.additive.base.generic.arithmetic :refer :all] [locus.additive.ring.core.object :refer :all] [locus.additive.semiring.core.object :refer :all] [locus.ab.vector.rset :refer :all] [locus.polynomial.core.object :refer :all]) (:import (locus.polynomial.core.object Polynomial))) (deftype RationalExpression [numerator denominator]) (defn numerator-polynomial [^RationalExpression expr] (.numerator expr)) (defn denominator-polynomial [^RationalExpression expr] (.denominator expr)) Generic conversion routines (defmulti to-rational-expression type) (defmethod to-rational-expression RationalExpression [expr] expr) (defmethod to-rational-expression Polynomial [expr] (RationalExpression. expr (one-polynomial (ring-of-coefficients expr)))) (defmethod negate RationalExpression [^RationalExpression expr] (RationalExpression. (- (numerator-polynomial expr)) (denominator-polynomial expr))) (defmethod reciprocal Polynomial [^Polynomial polynomial] (RationalExpression. (one-polynomial (ring-of-coefficients polynomial)) polynomial)) (defmethod reciprocal RationalExpression [^RationalExpression expr] (RationalExpression. (.denominator expr) (.numerator expr))) (defmethod multiply [RationalExpression RationalExpression] [a b] (RationalExpression. (* (numerator-polynomial a) (numerator-polynomial b)) (* (denominator-polynomial a) (denominator-polynomial b)))) (defmethod add [RationalExpression RationalExpression] [a b] (RationalExpression. (+ (* (numerator-polynomial a) (denominator-polynomial b)) (* (numerator-polynomial b) (denominator-polynomial a))) (* (denominator-polynomial a) (denominator-polynomial b)))) (defn rational-expression? [expr] (= (type expr) RationalExpression))
120974eea633caa6eb81aa892cd19920a5acc144eb3927b48437d69946cf8209
cedlemo/OCaml-GI-ctypes-bindings-generator
Entry_buffer_private.ml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Entry_buffer_private"
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Entry_buffer_private.ml
ocaml
open Ctypes open Foreign type t let t_typ : t structure typ = structure "Entry_buffer_private"
93e03aa0ba31ebfdd20dc369ad9549a728b9257340049e004448003efd95a1a4
Dean177/reason-standard
ArrayOcamlSyntaxSpecificTest.ml
open Standard open AlcoJest let suite = suite "Array - OCaml Syntax" (fun () -> let animals = [|"Bear"; "Wolf"|] in describe ".()" (fun () -> test "regular array syntax is the equivalent to Array.get" (fun () -> expect animals.(0) |> toEqual Eq.string "Bear")) ; describe ".?()" (fun () -> test "in bounds index returns Some" (fun () -> expect (Array.( .?() ) animals 1) |> toEqual Eq.(option string) (Some "Wolf")) ; test "out of bounds index returns None" (fun () -> expect (Array.( .?() ) animals 3) |> toEqual Eq.(option string) None)))
null
https://raw.githubusercontent.com/Dean177/reason-standard/74ed165c988eb4a4ea54339e829ff1d59b186d15/native/test/ArrayOcamlSyntaxSpecificTest.ml
ocaml
open Standard open AlcoJest let suite = suite "Array - OCaml Syntax" (fun () -> let animals = [|"Bear"; "Wolf"|] in describe ".()" (fun () -> test "regular array syntax is the equivalent to Array.get" (fun () -> expect animals.(0) |> toEqual Eq.string "Bear")) ; describe ".?()" (fun () -> test "in bounds index returns Some" (fun () -> expect (Array.( .?() ) animals 1) |> toEqual Eq.(option string) (Some "Wolf")) ; test "out of bounds index returns None" (fun () -> expect (Array.( .?() ) animals 3) |> toEqual Eq.(option string) None)))
9a8c5a73665927b53f74d19bdf31a964fad7dee8ccd5210dc58c696629d5b40c
haskell-CI/hackage-matrix-builder
Job.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE StrictData # -- | Copyright : © 2018 SPDX - License - Identifier : GPL-3.0 - or - later -- module Job ( JobStep(..), runStep , Task, newTask, runTask, cancelTask -- * internal utilities , runProc' ) where import Prelude.Local import Util.WebSvc import qualified Data.Text as T import qualified Data.Text.Encoding as T -- import qualified Data.Text.IO as T import System.IO import qualified System.IO.Streams as Streams import qualified System . IO.Streams . List as Streams import Control.Concurrent.Async import qualified Data.Map.Strict as Map import System.IO.Streams.Process import System.Process data JobStep = JobStep { jsExitCode :: Int , jsLog :: Text , jsStart :: UTCTime , jsDuration :: NominalDiffTime } deriving (Eq,Generic,Show) instance ToJSON JobStep where { toJSON = myToJSON; toEncoding = myToEncoding } instance FromJSON JobStep where { parseJSON = myParseJSON } instance NFData JobStep runStep :: FilePath -> [Text] -> IO JobStep runStep exe args = do !jsStart <- getCurrentTime (jsLog,jsExitCode) <- runProc' exe args !jsDuration <- (`diffUTCTime` jsStart) <$> getCurrentTime pure $! JobStep{..} runProc' :: FilePath -> [Text] -> IO (Text, Int) runProc' exe args = do -- TODO: use exception safe variant (s,ph) <- runProc exe (map T.unpack args) !bs <- T.decodeUtf8 <$> is2bs s !rc <- ec2int <$> waitForProcess ph pure (bs,rc) is2bs :: InputStream ByteString -> IO ByteString is2bs s = mconcat <$> Streams.toList s merges stdout / stderr runProc :: FilePath -> [String] -> IO (InputStream ByteString, ProcessHandle) runProc exe args = do (rend, wend) <- createPipe nullHandle <- openFile "/dev/null" ReadMode -- TODO: are filedescriptors properly closed on process termination? env' <- case args of ("fetch":_:_) -> do -- FIXME/TODO: temporary hack until there's `cabal new-fetch` env0 <- Map.fromList <$> getEnvironment let path_val = "/home/matrixbot/bin:/home/matrixbot/.local/bin:/opt/ghc/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin" pure $ Just (Map.toList (Map.insert "PATH" path_val env0)) _ -> pure Nothing let cp = (proc exe args) { std_in = UseHandle nullHandle , std_err = UseHandle wend , std_out = UseHandle wend , close_fds = True , create_group = True , env = env' } (Nothing, Nothing, Nothing, ph) <- createProcess cp sOutErr <- Streams.handleToInputStream rend >>= Streams.atEndOfInput (hClose rend) >>= Streams.lockingInputStream return (sOutErr,ph) ec2int :: ExitCode -> Int ec2int ExitSuccess = 0 ec2int (ExitFailure i) = i data Task a = TaskReady | TaskRunning (Async a) runTask :: MVar (Task a) -> IO a -> IO a runTask task go = do act <- modifyMVar task $ \case TaskReady -> do act' <- async go pure (TaskRunning act', act') TaskRunning act' -> pure (TaskRunning act', act') wait act cancelTask :: MVar (Task a) -> IO () cancelTask task = do mact <- modifyMVar task $ \t0 -> case t0 of TaskReady -> pure (t0, Nothing) TaskRunning act' -> do pure (t0, Just act') maybe (pure ()) cancel mact newTask :: IO (MVar (Task a)) newTask = newMVar TaskReady default values used by ' proc ' proc : : FilePath - > [ String ] - > CreateProcess proc cmd args = CreateProcess { cmdspec = RawCommand cmd args , cwd = Nothing , env = Nothing , = Inherit , std_out = Inherit , std_err = Inherit , close_fds = False , create_group = False , delegate_ctlc = False , detach_console = False , create_new_console = False , new_session = False , child_group = Nothing , = Nothing } proc :: FilePath -> [String] -> CreateProcess proc cmd args = CreateProcess { cmdspec = RawCommand cmd args, cwd = Nothing, env = Nothing, std_in = Inherit, std_out = Inherit, std_err = Inherit, close_fds = False, create_group = False, delegate_ctlc = False, detach_console = False, create_new_console = False, new_session = False, child_group = Nothing, child_user = Nothing } -}
null
https://raw.githubusercontent.com/haskell-CI/hackage-matrix-builder/bb813e9e4cf0d08352f33004c00ede987f45da56/src-lib/Job.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE OverloadedStrings # | * internal utilities import qualified Data.Text.IO as T TODO: use exception safe variant TODO: are filedescriptors properly closed on process termination? FIXME/TODO: temporary hack until there's `cabal new-fetch`
# LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE StrictData # Copyright : © 2018 SPDX - License - Identifier : GPL-3.0 - or - later module Job ( JobStep(..), runStep , Task, newTask, runTask, cancelTask , runProc' ) where import Prelude.Local import Util.WebSvc import qualified Data.Text as T import qualified Data.Text.Encoding as T import System.IO import qualified System.IO.Streams as Streams import qualified System . IO.Streams . List as Streams import Control.Concurrent.Async import qualified Data.Map.Strict as Map import System.IO.Streams.Process import System.Process data JobStep = JobStep { jsExitCode :: Int , jsLog :: Text , jsStart :: UTCTime , jsDuration :: NominalDiffTime } deriving (Eq,Generic,Show) instance ToJSON JobStep where { toJSON = myToJSON; toEncoding = myToEncoding } instance FromJSON JobStep where { parseJSON = myParseJSON } instance NFData JobStep runStep :: FilePath -> [Text] -> IO JobStep runStep exe args = do !jsStart <- getCurrentTime (jsLog,jsExitCode) <- runProc' exe args !jsDuration <- (`diffUTCTime` jsStart) <$> getCurrentTime pure $! JobStep{..} runProc' :: FilePath -> [Text] -> IO (Text, Int) runProc' exe args = do (s,ph) <- runProc exe (map T.unpack args) !bs <- T.decodeUtf8 <$> is2bs s !rc <- ec2int <$> waitForProcess ph pure (bs,rc) is2bs :: InputStream ByteString -> IO ByteString is2bs s = mconcat <$> Streams.toList s merges stdout / stderr runProc :: FilePath -> [String] -> IO (InputStream ByteString, ProcessHandle) runProc exe args = do (rend, wend) <- createPipe env' <- case args of ("fetch":_:_) -> do env0 <- Map.fromList <$> getEnvironment let path_val = "/home/matrixbot/bin:/home/matrixbot/.local/bin:/opt/ghc/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin" pure $ Just (Map.toList (Map.insert "PATH" path_val env0)) _ -> pure Nothing let cp = (proc exe args) { std_in = UseHandle nullHandle , std_err = UseHandle wend , std_out = UseHandle wend , close_fds = True , create_group = True , env = env' } (Nothing, Nothing, Nothing, ph) <- createProcess cp sOutErr <- Streams.handleToInputStream rend >>= Streams.atEndOfInput (hClose rend) >>= Streams.lockingInputStream return (sOutErr,ph) ec2int :: ExitCode -> Int ec2int ExitSuccess = 0 ec2int (ExitFailure i) = i data Task a = TaskReady | TaskRunning (Async a) runTask :: MVar (Task a) -> IO a -> IO a runTask task go = do act <- modifyMVar task $ \case TaskReady -> do act' <- async go pure (TaskRunning act', act') TaskRunning act' -> pure (TaskRunning act', act') wait act cancelTask :: MVar (Task a) -> IO () cancelTask task = do mact <- modifyMVar task $ \t0 -> case t0 of TaskReady -> pure (t0, Nothing) TaskRunning act' -> do pure (t0, Just act') maybe (pure ()) cancel mact newTask :: IO (MVar (Task a)) newTask = newMVar TaskReady default values used by ' proc ' proc : : FilePath - > [ String ] - > CreateProcess proc cmd args = CreateProcess { cmdspec = RawCommand cmd args , cwd = Nothing , env = Nothing , = Inherit , std_out = Inherit , std_err = Inherit , close_fds = False , create_group = False , delegate_ctlc = False , detach_console = False , create_new_console = False , new_session = False , child_group = Nothing , = Nothing } proc :: FilePath -> [String] -> CreateProcess proc cmd args = CreateProcess { cmdspec = RawCommand cmd args, cwd = Nothing, env = Nothing, std_in = Inherit, std_out = Inherit, std_err = Inherit, close_fds = False, create_group = False, delegate_ctlc = False, detach_console = False, create_new_console = False, new_session = False, child_group = Nothing, child_user = Nothing } -}
f396e8fe3b0de83af5369e2b155726834b55e4f6bf14016693ae908f03f6241f
archimag/rulisp
rulisp.lisp
;;;; rulisp.lisp ;;;; This file is part of the rulisp application , released under GNU Affero General Public License , Version 3.0 ;;;; See file COPYING for details. ;;;; Author : < > (in-package #:rulisp) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; compute login ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun compute-user-login-name () (labels ((find-upper-module (module) (let ((parent (restas::module-parent module))) (if parent (find-upper-module parent) module)))) (let ((rulisp-module (find-upper-module restas:*module*))) (restas::with-module (gethash '-auth- (slot-value rulisp-module 'restas::children)) (restas.simple-auth::compute-user-login-name))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rulisp templates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *resources-dir* (merge-pathnames "resources/" (asdf:component-pathname (asdf:find-system '#:rulisp)))) (closure-template:compile-template :common-lisp-backend (merge-pathnames "rulisp.tmpl" *resources-dir*))) (defparameter *mainmenu* `(("Главная" main) ("Статьи" -articles-.main-wiki-page) ("Планета" -planet-.planet-main) ("Форум" -forum-.list-forums) ("Сервисы" tools-list) ("Practical Common Lisp" -pcl-.pcl-main) ("Wiki" -wiki-.main-wiki-page) ("Поиск" google-search))) (defun rulisp-finalize-page (&key title css js content) (rulisp.view:main-frame (list :title title :css (iter (for item in css) (collect (format nil "/css/~A" item))) :js js :gecko-png "/image/gecko.png" :user (compute-user-login-name) :main-menu (iter (for item in *mainmenu*) (collect (list :href (apply #'restas:genurl (second item) (cddr item)) :name (first item)))) :content content :callback (hunchentoot:request-uri*)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; routes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (restas:define-route main ("") (rulisp-finalize-page :title "Русскоязычное сообщество Common Lisp разработчиков" :css '("style.css") :content (alexandria:read-file-into-string (merge-pathnames "index.html" *resources-dir*)))) (restas:define-route tools-list ("apps/") (rulisp-finalize-page :title "Инструменты" :css '("style.css") :content (rulisp.view:tools))) (restas:define-route google-search ("search") (rulisp-finalize-page :title "Поиск по сайту Lisper.ru" :css '("style.css") :content (rulisp.view:google-search))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; modules ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defclass rulisp-drawer () ()) (defmethod restas:render-object ((designer rulisp-drawer) (code (eql hunchentoot:+http-not-found+))) (rulisp-finalize-page :title "Not Found" :css '("style.css") :content (rulisp.view:not-found-content (list :href (hunchentoot:request-uri*))))) pcl (restas:mount-module -pcl- (#:rulisp.pcl) (:url "pcl")) ;; ;;;; auth (restas:mount-module -auth- (#:restas.simple-auth) (restas.simple-auth:*datastore* *rulisp-db-storage*) (restas.simple-auth:*noreply-email* *noreply-mail-account*) (restas.simple-auth:*cookie-cipher-key* *cookie-cipher-key*) (restas.simple-auth:*finalize-page* (lambda (content) (rulisp-finalize-page :title (getf content :title) :css '("style.css") :content (getf content :body))))) ;;;; forum (restas:mount-module -forum- (#:restas.forum) (:url "forum") (:render-method (lambda (obj) (rulisp-finalize-page :title (getf obj :title) :content (restas:render-object (find-package '#:restas.forum.view) obj) :css '("style.css" "jquery.wysiwyg.css" "forum.css" "colorize.css" ) :js (getf obj :js)))) (restas.forum:*site-name* "Lisper.ru") (restas.forum:*storage* *rulisp-db-storage*) (restas.forum:*user-name-function* #'compute-user-login-name)) ;;;; format (defclass pastebin-drawer (restas.colorize::drawer) ()) (defmethod restas.colorize::finalize-page ((drawer pastebin-drawer) data) (rulisp-finalize-page :title (getf data :title) :css '("style.css" "colorize.css") :content (concatenate 'string (getf data :menu) (getf data :content)))) (restas:mount-module -format- (#:restas.colorize) (:url "apps/format/") (:render-method (make-instance 'pastebin-drawer)) (restas.colorize:*max-on-page* 15) (restas.colorize:*storage* *rulisp-db-storage*) (restas.colorize:*colorize-user-function* #'compute-user-login-name)) ;;;; jscl (restas:mount-module -jscl- (#:rulisp.jscl) (:url "apps/jscl/")) ;;;; wiki (defclass drawer (dokuwiki-drawer) ()) (defmethod restas.wiki:finalize-page ((drawer drawer) content) (rulisp-finalize-page :title (getf content :title) :css '("style.css" "wiki.css" "colorize.css") :content (concatenate 'string (restas.wiki.view:show-page-menu (getf content :menu-links)) (getf content :content)))) (restas:mount-module -wiki- (#:restas.wiki) (:url "wiki") (:render-method (make-instance 'drawer)) (restas.wiki:*storage* (make-instance 'restas.wiki:file-storage :dir *wiki-dir*)) (restas.wiki:*wiki-user-function* #'compute-user-login-name)) ;;;; articles (restas:mount-module -articles- (#:restas.wiki) (:url "articles") (:render-method (make-instance 'drawer)) (restas.wiki:*index-page-title* "Статьи") (restas.wiki:*storage* (make-instance 'restas.wiki:file-storage :dir #P"/var/rulisp/articles/")) (restas.wiki:*wiki-user-function* #'(lambda () (find (compute-user-login-name) '("archimag" "dmitry_vk") :test #'string=)))) Russian Lisp Planet (restas:mount-module -planet- (#:restas.planet) (:url "planet") (restas.planet:*suggest-mail* "") (restas.planet:*feeds* (merge-pathnames "planet-feeds.lisp" *rulisp-path*)) (restas.planet:*name* "Russian Lisp Planet") (restas.planet:*cache-dir* (merge-pathnames "planet/" *cachedir*)) (restas.planet:*template* (lambda (data) (rulisp-finalize-page :title "Russian Lisp Planet" :css '("style.css" "planet.css" "colorize.css") :content (restas.planet.view:feed-html-body data))))) ;;;; static files (eval-when (:compile-toplevel :load-toplevel :execute) (closure-template:ensure-ttable-package '#:rulisp.directory-publisher.view :prototype (closure-template:package-ttable '#:restas.directory-publisher.view)) (let ((ttable (closure-template:package-ttable '#:rulisp.directory-publisher.view))) (flet ((rulisp-autoindex (data out) (write-string (rulisp-finalize-page :title (getf data :title) :css '("style.css" "autoindex.css") :content (restas.directory-publisher.view:autoindex-content data)) out))) (closure-template:ttable-register-template ttable "AUTOINDEX" #'rulisp-autoindex :supersede t) ;;(closure-template:ttable-sync-package ttable '#:rulisp.directory-publisher.view) ))) (defmacro defstatic (resource) (let* ((module-name (make-symbol (format nil "-STATIC-~a" resource))) (resource-string (string-downcase (symbol-name resource))) (path (format nil "static/~(~s~)/" resource))) `(restas:mount-module ,module-name (#:restas.directory-publisher) (:url ,resource-string) (restas.directory-publisher:*directory* (merge-pathnames ,path *resources-dir*))))) (defstatic css) (defstatic image) (defstatic js) (defstatic fonts) ;;;; not found page (restas:define-route not-found ("*any") (:render-method (make-instance 'rulisp-drawer)) (declare (ignore any)) hunchentoot:+http-not-found+)
null
https://raw.githubusercontent.com/archimag/rulisp/2af0d92066572c4665d14dc3ee001c0c5ff84e84/src/rulisp.lisp
lisp
rulisp.lisp See file COPYING for details. compute login rulisp templates routes modules ;;;; auth forum format jscl wiki articles static files (closure-template:ttable-sync-package ttable '#:rulisp.directory-publisher.view) not found page
This file is part of the rulisp application , released under GNU Affero General Public License , Version 3.0 Author : < > (in-package #:rulisp) (defun compute-user-login-name () (labels ((find-upper-module (module) (let ((parent (restas::module-parent module))) (if parent (find-upper-module parent) module)))) (let ((rulisp-module (find-upper-module restas:*module*))) (restas::with-module (gethash '-auth- (slot-value rulisp-module 'restas::children)) (restas.simple-auth::compute-user-login-name))))) (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *resources-dir* (merge-pathnames "resources/" (asdf:component-pathname (asdf:find-system '#:rulisp)))) (closure-template:compile-template :common-lisp-backend (merge-pathnames "rulisp.tmpl" *resources-dir*))) (defparameter *mainmenu* `(("Главная" main) ("Статьи" -articles-.main-wiki-page) ("Планета" -planet-.planet-main) ("Форум" -forum-.list-forums) ("Сервисы" tools-list) ("Practical Common Lisp" -pcl-.pcl-main) ("Wiki" -wiki-.main-wiki-page) ("Поиск" google-search))) (defun rulisp-finalize-page (&key title css js content) (rulisp.view:main-frame (list :title title :css (iter (for item in css) (collect (format nil "/css/~A" item))) :js js :gecko-png "/image/gecko.png" :user (compute-user-login-name) :main-menu (iter (for item in *mainmenu*) (collect (list :href (apply #'restas:genurl (second item) (cddr item)) :name (first item)))) :content content :callback (hunchentoot:request-uri*)))) (restas:define-route main ("") (rulisp-finalize-page :title "Русскоязычное сообщество Common Lisp разработчиков" :css '("style.css") :content (alexandria:read-file-into-string (merge-pathnames "index.html" *resources-dir*)))) (restas:define-route tools-list ("apps/") (rulisp-finalize-page :title "Инструменты" :css '("style.css") :content (rulisp.view:tools))) (restas:define-route google-search ("search") (rulisp-finalize-page :title "Поиск по сайту Lisper.ru" :css '("style.css") :content (rulisp.view:google-search))) (defclass rulisp-drawer () ()) (defmethod restas:render-object ((designer rulisp-drawer) (code (eql hunchentoot:+http-not-found+))) (rulisp-finalize-page :title "Not Found" :css '("style.css") :content (rulisp.view:not-found-content (list :href (hunchentoot:request-uri*))))) pcl (restas:mount-module -pcl- (#:rulisp.pcl) (:url "pcl")) (restas:mount-module -auth- (#:restas.simple-auth) (restas.simple-auth:*datastore* *rulisp-db-storage*) (restas.simple-auth:*noreply-email* *noreply-mail-account*) (restas.simple-auth:*cookie-cipher-key* *cookie-cipher-key*) (restas.simple-auth:*finalize-page* (lambda (content) (rulisp-finalize-page :title (getf content :title) :css '("style.css") :content (getf content :body))))) (restas:mount-module -forum- (#:restas.forum) (:url "forum") (:render-method (lambda (obj) (rulisp-finalize-page :title (getf obj :title) :content (restas:render-object (find-package '#:restas.forum.view) obj) :css '("style.css" "jquery.wysiwyg.css" "forum.css" "colorize.css" ) :js (getf obj :js)))) (restas.forum:*site-name* "Lisper.ru") (restas.forum:*storage* *rulisp-db-storage*) (restas.forum:*user-name-function* #'compute-user-login-name)) (defclass pastebin-drawer (restas.colorize::drawer) ()) (defmethod restas.colorize::finalize-page ((drawer pastebin-drawer) data) (rulisp-finalize-page :title (getf data :title) :css '("style.css" "colorize.css") :content (concatenate 'string (getf data :menu) (getf data :content)))) (restas:mount-module -format- (#:restas.colorize) (:url "apps/format/") (:render-method (make-instance 'pastebin-drawer)) (restas.colorize:*max-on-page* 15) (restas.colorize:*storage* *rulisp-db-storage*) (restas.colorize:*colorize-user-function* #'compute-user-login-name)) (restas:mount-module -jscl- (#:rulisp.jscl) (:url "apps/jscl/")) (defclass drawer (dokuwiki-drawer) ()) (defmethod restas.wiki:finalize-page ((drawer drawer) content) (rulisp-finalize-page :title (getf content :title) :css '("style.css" "wiki.css" "colorize.css") :content (concatenate 'string (restas.wiki.view:show-page-menu (getf content :menu-links)) (getf content :content)))) (restas:mount-module -wiki- (#:restas.wiki) (:url "wiki") (:render-method (make-instance 'drawer)) (restas.wiki:*storage* (make-instance 'restas.wiki:file-storage :dir *wiki-dir*)) (restas.wiki:*wiki-user-function* #'compute-user-login-name)) (restas:mount-module -articles- (#:restas.wiki) (:url "articles") (:render-method (make-instance 'drawer)) (restas.wiki:*index-page-title* "Статьи") (restas.wiki:*storage* (make-instance 'restas.wiki:file-storage :dir #P"/var/rulisp/articles/")) (restas.wiki:*wiki-user-function* #'(lambda () (find (compute-user-login-name) '("archimag" "dmitry_vk") :test #'string=)))) Russian Lisp Planet (restas:mount-module -planet- (#:restas.planet) (:url "planet") (restas.planet:*suggest-mail* "") (restas.planet:*feeds* (merge-pathnames "planet-feeds.lisp" *rulisp-path*)) (restas.planet:*name* "Russian Lisp Planet") (restas.planet:*cache-dir* (merge-pathnames "planet/" *cachedir*)) (restas.planet:*template* (lambda (data) (rulisp-finalize-page :title "Russian Lisp Planet" :css '("style.css" "planet.css" "colorize.css") :content (restas.planet.view:feed-html-body data))))) (eval-when (:compile-toplevel :load-toplevel :execute) (closure-template:ensure-ttable-package '#:rulisp.directory-publisher.view :prototype (closure-template:package-ttable '#:restas.directory-publisher.view)) (let ((ttable (closure-template:package-ttable '#:rulisp.directory-publisher.view))) (flet ((rulisp-autoindex (data out) (write-string (rulisp-finalize-page :title (getf data :title) :css '("style.css" "autoindex.css") :content (restas.directory-publisher.view:autoindex-content data)) out))) (closure-template:ttable-register-template ttable "AUTOINDEX" #'rulisp-autoindex :supersede t) ))) (defmacro defstatic (resource) (let* ((module-name (make-symbol (format nil "-STATIC-~a" resource))) (resource-string (string-downcase (symbol-name resource))) (path (format nil "static/~(~s~)/" resource))) `(restas:mount-module ,module-name (#:restas.directory-publisher) (:url ,resource-string) (restas.directory-publisher:*directory* (merge-pathnames ,path *resources-dir*))))) (defstatic css) (defstatic image) (defstatic js) (defstatic fonts) (restas:define-route not-found ("*any") (:render-method (make-instance 'rulisp-drawer)) (declare (ignore any)) hunchentoot:+http-not-found+)
195b3b9791d730376020aa9d79cf11e054393933920f137a606c94ba31c524b7
tolysz/ghcjs-stack
Message.hs
{-# LANGUAGE BangPatterns #-} module Distribution.Client.Dependency.Modular.Message ( Message(..), showMessages ) where import qualified Data.List as L import Prelude hiding (pi) from Cabal import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.Tree ( FailReason(..), POption(..) ) import Distribution.Client.Dependency.Types ( ConstraintSource(..), showConstraintSource, Progress(..) ) data Message = Enter -- ^ increase indentation level | Leave -- ^ decrease indentation level | TryP QPN POption | TryF QFN Bool | TryS QSN Bool | Next (Goal QPN) | Success | Failure (ConflictSet QPN) FailReason -- | Transforms the structured message type to actual messages (strings). -- -- Takes an additional relevance predicate. The predicate gets a stack of goal -- variables and can decide whether messages regarding these goals are relevant. -- You can plug in 'const True' if you're interested in a full trace. If you -- want a slice of the trace concerning a particular conflict set, then plug in -- a predicate returning 'True' on the empty stack and if the head is in the -- conflict set. -- The second argument indicates if the level numbers should be shown . This is -- recommended for any trace that involves backtracking, because only the level numbers will allow to keep track of backjumps . showMessages :: ([Var QPN] -> Bool) -> Bool -> Progress Message a b -> Progress String a b showMessages p sl = go [] 0 where -- The stack 'v' represents variables that are currently assigned by the -- solver. 'go' pushes a variable for a recursive call when it encounters ' TryP ' , ' TryF ' , or ' TryS ' and pops a variable when it encounters ' Leave ' . -- When 'go' processes a package goal, or a package goal followed by a -- 'Failure', it calls 'atLevel' with the goal variable at the head of the -- stack so that the predicate can also select messages relating to package -- goal choices. go :: [Var QPN] -> Int -> Progress Message a b -> Progress String a b go !_ !_ (Done x) = Done x go !_ !_ (Fail x) = Fail x -- complex patterns go !v !l (Step (TryP qpn i) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = goPReject v l qpn [i] c fr ms go !v !l (Step (TryF qfn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (F qfn) v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms) go !v !l (Step (TryS qsn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (S qsn) v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms) go !v !l (Step (Next (Goal (P qpn) gr)) (Step (TryP qpn' i) ms@(Step Enter (Step (Next _) _)))) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGR gr) (go (add (P qpn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Fail _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms -- the previous case potentially arises in the error output, because we remove the backjump itself if we cut the log after the first error go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Step (Failure _c Backjump) _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms go !v !l (Step (Next (Goal (P qpn) gr)) (Step (Failure c fr) ms)) = let v' = add (P qpn) v in (atLevel v' l $ showPackageGoal qpn gr) $ (atLevel v' l $ showFailure c fr) (go v l ms) go !v !l (Step (Failure c Backjump) ms@(Step Leave (Step (Failure c' Backjump) _))) | c == c' = go v l ms -- standard display go !v !l (Step Enter ms) = go v (l+1) ms go !v !l (Step Leave ms) = go (drop 1 v) (l-1) ms go !v !l (Step (TryP qpn i) ms) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn i) (go (add (P qpn) v) l ms) go !v !l (Step (TryF qfn b) ms) = (atLevel (add (F qfn) v) l $ "trying: " ++ showQFNBool qfn b) (go (add (F qfn) v) l ms) go !v !l (Step (TryS qsn b) ms) = (atLevel (add (S qsn) v) l $ "trying: " ++ showQSNBool qsn b) (go (add (S qsn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms) = (atLevel (add (P qpn) v) l $ showPackageGoal qpn gr) (go v l ms) go !v !l (Step (Next _) ms) = go v l ms -- ignore flag goals in the log go !v !l (Step (Success) ms) = (atLevel v l $ "done") (go v l ms) go !v !l (Step (Failure c fr) ms) = (atLevel v l $ showFailure c fr) (go v l ms) showPackageGoal :: QPN -> QGoalReason -> String showPackageGoal qpn gr = "next goal: " ++ showQPN qpn ++ showGR gr showFailure :: ConflictSet QPN -> FailReason -> String showFailure c fr = "fail" ++ showFR c fr add :: Var QPN -> [Var QPN] -> [Var QPN] add v vs = simplifyVar v : vs -- special handler for many subsequent package rejections goPReject :: [Var QPN] -> Int -> QPN -> [POption] -> ConflictSet QPN -> FailReason -> Progress Message a b -> Progress String a b goPReject v l qpn is c fr (Step (TryP qpn' i) (Step Enter (Step (Failure _ fr') (Step Leave ms)))) | qpn == qpn' && fr == fr' = goPReject v l qpn (i : is) c fr ms goPReject v l qpn is c fr ms = (atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms) -- write a message, but only if it's relevant; we can also enable or disable the display of the current level atLevel :: [Var QPN] -> Int -> String -> Progress String a b -> Progress String a b atLevel v l x xs | sl && p v = let s = show l in Step ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) xs | p v = Step x xs | otherwise = xs showQPNPOpt :: QPN -> POption -> String showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) = case linkedTo of Consistent with prior to POption Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i) showGR :: QGoalReason -> String showGR UserGoal = " (user goal)" showGR (PDependency pi) = " (dependency of " ++ showPI pi ++ ")" showGR (FDependency qfn b) = " (dependency of " ++ showQFNBool qfn b ++ ")" showGR (SDependency qsn) = " (dependency of " ++ showQSNBool qsn True ++ ")" showFR :: ConflictSet QPN -> FailReason -> String showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)" showFR _ (Conflicting ds) = " (conflict: " ++ L.intercalate ", " (map showDep ds) ++ ")" showFR _ CannotInstall = " (only already installed instances can be used)" showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)" showFR _ Shadowed = " (shadowed by another installed package with same version)" showFR _ Broken = " (package is broken)" showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")" showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)" showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)" showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)" showFR _ ManualFlag = " (manual flag can only be changed explicitly)" showFR c Backjump = " (backjumping, conflict set: " ++ showCS c ++ ")" showFR _ MultipleInstances = " (multiple instances)" showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showCS c ++ ")" showFR c CyclicDependencies = " (cyclic dependencies; conflict set: " ++ showCS c ++ ")" -- The following are internal failures. They should not occur. In the -- interest of not crashing unnecessarily, we still just print an error -- message though. showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")" showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")" showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)" constraintSource :: ConstraintSource -> String constraintSource src = "constraint from " ++ showConstraintSource src
null
https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal-next/cabal-install/Distribution/Client/Dependency/Modular/Message.hs
haskell
# LANGUAGE BangPatterns # ^ increase indentation level ^ decrease indentation level | Transforms the structured message type to actual messages (strings). Takes an additional relevance predicate. The predicate gets a stack of goal variables and can decide whether messages regarding these goals are relevant. You can plug in 'const True' if you're interested in a full trace. If you want a slice of the trace concerning a particular conflict set, then plug in a predicate returning 'True' on the empty stack and if the head is in the conflict set. recommended for any trace that involves backtracking, because only the level The stack 'v' represents variables that are currently assigned by the solver. 'go' pushes a variable for a recursive call when it encounters When 'go' processes a package goal, or a package goal followed by a 'Failure', it calls 'atLevel' with the goal variable at the head of the stack so that the predicate can also select messages relating to package goal choices. complex patterns the previous case potentially arises in the error output, because we remove the backjump itself standard display ignore flag goals in the log special handler for many subsequent package rejections write a message, but only if it's relevant; we can also enable or disable the display of the current level The following are internal failures. They should not occur. In the interest of not crashing unnecessarily, we still just print an error message though.
module Distribution.Client.Dependency.Modular.Message ( Message(..), showMessages ) where import qualified Data.List as L import Prelude hiding (pi) from Cabal import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Package import Distribution.Client.Dependency.Modular.Tree ( FailReason(..), POption(..) ) import Distribution.Client.Dependency.Types ( ConstraintSource(..), showConstraintSource, Progress(..) ) data Message = | TryP QPN POption | TryF QFN Bool | TryS QSN Bool | Next (Goal QPN) | Success | Failure (ConflictSet QPN) FailReason The second argument indicates if the level numbers should be shown . This is numbers will allow to keep track of backjumps . showMessages :: ([Var QPN] -> Bool) -> Bool -> Progress Message a b -> Progress String a b showMessages p sl = go [] 0 where ' TryP ' , ' TryF ' , or ' TryS ' and pops a variable when it encounters ' Leave ' . go :: [Var QPN] -> Int -> Progress Message a b -> Progress String a b go !_ !_ (Done x) = Done x go !_ !_ (Fail x) = Fail x go !v !l (Step (TryP qpn i) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = goPReject v l qpn [i] c fr ms go !v !l (Step (TryF qfn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (F qfn) v) l $ "rejecting: " ++ showQFNBool qfn b ++ showFR c fr) (go v l ms) go !v !l (Step (TryS qsn b) (Step Enter (Step (Failure c fr) (Step Leave ms)))) = (atLevel (add (S qsn) v) l $ "rejecting: " ++ showQSNBool qsn b ++ showFR c fr) (go v l ms) go !v !l (Step (Next (Goal (P qpn) gr)) (Step (TryP qpn' i) ms@(Step Enter (Step (Next _) _)))) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn' i ++ showGR gr) (go (add (P qpn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Fail _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms if we cut the log after the first error go !v !l (Step (Next (Goal (P qpn) gr)) ms@(Step (Failure _c Backjump) _)) = (atLevel (add (P qpn) v) l $ "unknown package: " ++ showQPN qpn ++ showGR gr) $ go v l ms go !v !l (Step (Next (Goal (P qpn) gr)) (Step (Failure c fr) ms)) = let v' = add (P qpn) v in (atLevel v' l $ showPackageGoal qpn gr) $ (atLevel v' l $ showFailure c fr) (go v l ms) go !v !l (Step (Failure c Backjump) ms@(Step Leave (Step (Failure c' Backjump) _))) | c == c' = go v l ms go !v !l (Step Enter ms) = go v (l+1) ms go !v !l (Step Leave ms) = go (drop 1 v) (l-1) ms go !v !l (Step (TryP qpn i) ms) = (atLevel (add (P qpn) v) l $ "trying: " ++ showQPNPOpt qpn i) (go (add (P qpn) v) l ms) go !v !l (Step (TryF qfn b) ms) = (atLevel (add (F qfn) v) l $ "trying: " ++ showQFNBool qfn b) (go (add (F qfn) v) l ms) go !v !l (Step (TryS qsn b) ms) = (atLevel (add (S qsn) v) l $ "trying: " ++ showQSNBool qsn b) (go (add (S qsn) v) l ms) go !v !l (Step (Next (Goal (P qpn) gr)) ms) = (atLevel (add (P qpn) v) l $ showPackageGoal qpn gr) (go v l ms) go !v !l (Step (Success) ms) = (atLevel v l $ "done") (go v l ms) go !v !l (Step (Failure c fr) ms) = (atLevel v l $ showFailure c fr) (go v l ms) showPackageGoal :: QPN -> QGoalReason -> String showPackageGoal qpn gr = "next goal: " ++ showQPN qpn ++ showGR gr showFailure :: ConflictSet QPN -> FailReason -> String showFailure c fr = "fail" ++ showFR c fr add :: Var QPN -> [Var QPN] -> [Var QPN] add v vs = simplifyVar v : vs goPReject :: [Var QPN] -> Int -> QPN -> [POption] -> ConflictSet QPN -> FailReason -> Progress Message a b -> Progress String a b goPReject v l qpn is c fr (Step (TryP qpn' i) (Step Enter (Step (Failure _ fr') (Step Leave ms)))) | qpn == qpn' && fr == fr' = goPReject v l qpn (i : is) c fr ms goPReject v l qpn is c fr ms = (atLevel (P qpn : v) l $ "rejecting: " ++ L.intercalate ", " (map (showQPNPOpt qpn) (reverse is)) ++ showFR c fr) (go v l ms) atLevel :: [Var QPN] -> Int -> String -> Progress String a b -> Progress String a b atLevel v l x xs | sl && p v = let s = show l in Step ("[" ++ replicate (3 - length s) '_' ++ s ++ "] " ++ x) xs | p v = Step x xs | otherwise = xs showQPNPOpt :: QPN -> POption -> String showQPNPOpt qpn@(Q _pp pn) (POption i linkedTo) = case linkedTo of Consistent with prior to POption Just pp' -> showQPN qpn ++ "~>" ++ showPI (PI (Q pp' pn) i) showGR :: QGoalReason -> String showGR UserGoal = " (user goal)" showGR (PDependency pi) = " (dependency of " ++ showPI pi ++ ")" showGR (FDependency qfn b) = " (dependency of " ++ showQFNBool qfn b ++ ")" showGR (SDependency qsn) = " (dependency of " ++ showQSNBool qsn True ++ ")" showFR :: ConflictSet QPN -> FailReason -> String showFR _ InconsistentInitialConstraints = " (inconsistent initial constraints)" showFR _ (Conflicting ds) = " (conflict: " ++ L.intercalate ", " (map showDep ds) ++ ")" showFR _ CannotInstall = " (only already installed instances can be used)" showFR _ CannotReinstall = " (avoiding to reinstall a package with same version but new dependencies)" showFR _ Shadowed = " (shadowed by another installed package with same version)" showFR _ Broken = " (package is broken)" showFR _ (GlobalConstraintVersion vr src) = " (" ++ constraintSource src ++ " requires " ++ display vr ++ ")" showFR _ (GlobalConstraintInstalled src) = " (" ++ constraintSource src ++ " requires installed instance)" showFR _ (GlobalConstraintSource src) = " (" ++ constraintSource src ++ " requires source instance)" showFR _ (GlobalConstraintFlag src) = " (" ++ constraintSource src ++ " requires opposite flag selection)" showFR _ ManualFlag = " (manual flag can only be changed explicitly)" showFR c Backjump = " (backjumping, conflict set: " ++ showCS c ++ ")" showFR _ MultipleInstances = " (multiple instances)" showFR c (DependenciesNotLinked msg) = " (dependencies not linked: " ++ msg ++ "; conflict set: " ++ showCS c ++ ")" showFR c CyclicDependencies = " (cyclic dependencies; conflict set: " ++ showCS c ++ ")" showFR _ (MalformedFlagChoice qfn) = " (INTERNAL ERROR: MALFORMED FLAG CHOICE: " ++ showQFN qfn ++ ")" showFR _ (MalformedStanzaChoice qsn) = " (INTERNAL ERROR: MALFORMED STANZA CHOICE: " ++ showQSN qsn ++ ")" showFR _ EmptyGoalChoice = " (INTERNAL ERROR: EMPTY GOAL CHOICE)" constraintSource :: ConstraintSource -> String constraintSource src = "constraint from " ++ showConstraintSource src
fe5c22bc069b8d6d3bc8be10736508aa89e9ab611d79ad159a53b51e3c716d1a
cardmagic/lucash
ccp.scm
;;; Char->char partial maps -*- Scheme -*- Copyright ( C ) 1998 by . ;;; CCPs are an efficient data structure for doing simple string transforms, ;;; similar to the kinds of things you would do with the tr(1) program. ;;; This code is tuned for a 7- or 8 - bit character type . Large , 16 - bit ;;; character types would need a more sophisticated data structure, tuned ;;; for sparseness. I would suggest something like this: ( define - record ccp ;;; domain ; The domain char-set ;;; map ; Sorted vector of (char . string) pairs ;;; ; specifying the map. i d ? ) ; If true , mappings not specified by MAP are ;;; ; identity mapping. If false, MAP must ; specify a mapping for every char in DOMAIN . ;;; ;;; A (char . string) elements in MAP specifies a mapping for the contiguous sequence of L chars beginning with ( in the sequence of the underlying char type representation ) , where L is the length of STRING . These MAP elements are sorted by , so that binary search can be used to get from an input ;;; character C to the right MAP element quickly. ;;; ;;; This representation should be reasonably compact for standard mappings on, ;;; say, a Unicode CCP. An implementation might wish to have a cache field in the record for storing the full 8 kb bitset when performing ccp - map ;;; operations. Or, an implementation might want to store the Latin-1 subset ;;; of the map in a dense format, and keep the remainder in a sparse format. AKA 256 . (define-record ccp domain ; The domain char-set dshared? ; Is the domain value shared or linear? 256 - elt string mshared?) ; Is the map string shared or linear? ;;; Accessors and setters that manage the linear bookkeeping ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (ccp-domain ccp) (set-ccp:dshared? ccp #t) (ccp:domain ccp)) CCP is a linear ccp . PROC is a domain->domain function ; it must be ;;; linear in its parameter and result. ;;; Updates the domain of the CCP with PROC , returns the resulting CCP ; reuses the old one to construct the new one . (define (restrict-linear-ccp-domain ccp proc) (let ((new-d (proc (if (ccp:dshared? ccp) (begin (set-ccp:dshared? ccp #f) (char-set-copy (ccp:domain ccp))) (ccp:domain ccp))))) (set-ccp:domain ccp new-d) ccp)) CCP is a linear CCP . PROC is a domain domain function . ;;; It is passed a linear domain and cmap string. It may side-effect the cmap string , and returns the resulting updated domain . We return the resulting CCP , reusing the parameter to construct it . (define (linear-update-ccp ccp proc) (let* ((cmap (if (ccp:mshared? ccp) (begin (set-ccp:mshared? ccp #f) (string-copy (ccp:map ccp))) (ccp:map ccp))) (new-d (proc (if (ccp:dshared? ccp) (begin (set-ccp:dshared? ccp #f) (char-set-copy (ccp:domain ccp))) (ccp:domain ccp)) cmap))) (set-ccp:domain ccp new-d) ccp)) Return CCP 's map field , and mark it as shared . CCP functions that restrict a ccp 's domain share map strings , so they use this guy . (define (ccp:map/shared ccp) (set-ccp:mshared? ccp #t) (ccp:map ccp)) (define (ccp-copy ccp) (make-ccp (char-set-copy (ccp:domain ccp)) #f (string-copy (ccp:map ccp)) #f)) ;;; N-ary equality relation for partial maps (define (ccp= ccp1 . rest) (let ((domain (ccp:domain ccp1)) (cmap (ccp:map ccp1))) (every (lambda (ccp2) (and (char-set= domain (ccp:domain ccp2)) (let ((cmap2 (ccp:map ccp2))) (char-set-every (lambda (c) (let ((i (char->ascii c))) (char=? (string-ref cmap i) (string-ref cmap2 i)))) domain)))) rest))) ;;; N-ary subset relation for partial maps (define (ccp<= ccp1 . rest) (let lp ((domain1 (ccp:domain ccp1)) (cmap1 (ccp:map ccp1)) (rest rest)) (or (not (pair? rest)) (let* ((ccp2 (car rest)) (domain2 (ccp:domain ccp2)) (cmap2 (ccp:map ccp2)) (rest (cdr rest))) (and (char-set<= domain1 domain2) (let ((cmap2 (ccp:map ccp2))) (char-set-every (lambda (c) (let ((i (char->ascii c))) (char=? (string-ref cmap1 i) (string-ref cmap2 i)))) domain1)) (lp domain2 cmap2 rest)))))) CCP iterators ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (ccp-fold kons knil ccp) (let ((cmap (ccp:map ccp))) (char-set-fold (lambda (c v) (kons c (string-ref cmap (char->ascii c)) v)) knil (ccp:domain ccp)))) (define (ccp-for-each proc ccp) (let ((cmap (ccp:map ccp))) (char-set-for-each (lambda (c) (proc c (string-ref cmap (char->ascii c)))) (ccp:domain ccp)))) (define (ccp->alist ccp) (ccp-fold (lambda (from to alist) (cons (cons from to) alist)) '() ccp)) CCP - RESTRICT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Restrict a ccp 's domain . (define (ccp-restrict ccp cset) (make-ccp (char-set-intersection cset (ccp:domain ccp)) #f (ccp:map/shared ccp) #t)) (define (ccp-restrict! ccp cset) (restrict-linear-ccp-domain ccp (lambda (d) (char-set-intersection! d cset)))) CCP - ADJOIN ccp from - char1 to - char1 ... CCP - DELETE ccp char1 ... ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Add & delete mappings to / from a ccp . (define (ccp-delete ccp . chars) (make-ccp (apply char-set-delete (ccp:domain ccp) chars) #f (ccp:map/shared ccp) #t)) (define (ccp-delete! ccp . chars) (restrict-linear-ccp-domain ccp (lambda (d) (apply char-set-delete! d chars)))) (define (ccp-adjoin ccp . chars) (let ((cmap (string-copy (ccp:map ccp)))) (make-ccp (install-ccp-adjoin! cmap (char-set-copy (ccp:domain ccp)) chars) #f cmap #f))) (define (ccp-adjoin! ccp . chars) (linear-update-ccp ccp (lambda (d cmap) (install-ccp-adjoin! cmap d chars)))) (define (install-ccp-adjoin! cmap domain chars) (let lp ((chars chars) (d domain)) (if (pair? chars) (let ((from (car chars)) (to (cadr chars)) (chars (cddr chars))) (string-set! cmap (char->ascii from) to) (lp chars (char-set-adjoin! d from))) d))) CCP - EXTEND ccp1 ... CCP - EXTEND ! ccp1 ccp2 ... ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Extend ccp1 with ccp2 , etc . (define (ccp-extend . ccps) (if (pair? ccps) (let ((ccp0 (car ccps)) (ccps (cdr ccps))) (if (pair? ccps) . The FOLD installs each ccp in CCPS into CMAP and produces ;; the new domain. (make-ccp (fold (lambda (ccp d) (install-ccp-extension! cmap d ccp)) (char-set-copy (ccp:domain ccp0)) ccps) #f cmap #f)) Only 1 parameter ccp:0)) ; 0 parameters (define (ccp-extend! ccp0 . ccps) (linear-update-ccp ccp0 (lambda (domain cmap) (fold (lambda (ccp d) (install-ccp-extension! cmap d ccp)) domain ccps)))) Side - effect CMAP , linear - update and return DOMAIN . (define (install-ccp-extension! cmap domain ccp) (let ((cmap1 (ccp:map ccp)) (domain1 (ccp:domain ccp))) (char-set-for-each (lambda (c) (let ((i (char->ascii c))) (string-set! cmap i (string-ref cmap1 i)))) domain1) (char-set-union! domain domain1))) ;;; Compose the CCPs. 0-ary case: (ccp-compose) = ccp:1. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; For each character C-IN in the original domain, we push it ;;; through the pipeline of CCPs. If we ever land outside the domain of a ccp , we punt C - IN . If we push it all the way ;;; through, we add C-IN to our result domain, and add the mapping ;;; into the cmap we are assembling. ;;; ;;; Looping this way avoids building up intermediate temporary CCPs . If CCP 's were small bitsets , we might be better off ;;; slicing the double-nested loops the other way around. (define (ccp-compose . ccps) (cond ((not (pair? ccps)) ccp:1) ; 0 args => ccp:1 1 arg (else (let* ((v (list->vector ccps)) (vlen-2 (- (vector-length v) 2)) (cmap (make-string num-chars)) (d1 (ccp:domain (vector-ref v (+ vlen-2 1)))) (d (char-set-fold (lambda (c-in d) (let lp ((c c-in) (i vlen-2)) (if (>= i 0) (let ((ccp (vector-ref v i))) (if (char-set-contains? (ccp:domain ccp) c) (lp (string-ref (ccp:map ccp) (char->ascii c)) (- i 1)) Lose : remove c - in from d. (char-set-delete! d c-in))) ;; Win: C-IN -> C (begin (string-set! cmap (char->ascii c-in) c) d)))) (char-set-copy d1) d1))) (make-ccp d #f cmap #f))))) ;;; ALIST->CPP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (alist->ccp cc-alist . maybe-base-ccp) (let ((base (:optional maybe-base-ccp ccp:0))) (if (pair? cc-alist) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-alist! cmap (char-set-copy (ccp:domain base)) cc-alist) #f cmap #f)) base))) (define (alist->ccp! alist base) (linear-update-ccp base (lambda (d cmap) (install-ccp-alist! cmap d alist)))) Side - effect CMAP , linear - update and return DOMAIN . (define (install-ccp-alist! cmap domain alist) (fold (lambda (from/to d) (let ((from (car from/to)) (to (cdr from/to))) (string-set! cmap (char->ascii from) to) (char-set-adjoin! domain from))) domain alist)) ;;; PROC->CCP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (proc->ccp proc [domain base-ccp]) (define (proc->ccp proc . args) (let-optionals args ((proc-domain char-set:full) (base ccp:0)) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-proc! cmap (char-set-copy (ccp:domain base)) proc proc-domain) #f cmap #f)))) (define (proc->ccp! proc proc-domain base) (linear-update-ccp base (lambda (d cmap) (install-ccp-proc! cmap d proc proc-domain)))) (define (install-ccp-proc! cmap domain proc proc-domain) (char-set-for-each (lambda (c) (string-set! cmap (char->ascii c) (proc c))) proc-domain) (char-set-union! domain proc-domain)) ;;; CONSTANT-CCP ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; (constant-ccp char [domain base-ccp]) Extend BASE - CCP with the a map taking every char in DOMAIN to . ;;; DOMAIN defaults to char-set:full. BASE-CCP defaults to CCP:0. (define (constant-ccp char . args) (let-optionals args ((char-domain char-set:full) (base ccp:0)) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-constant-ccp! cmap (char-set-copy (ccp:domain base)) char char-domain) #f cmap #f)))) (define (constant-ccp! char char-domain base) (linear-update-ccp base (lambda (d cmap) (install-constant-ccp! cmap d char char-domain)))) Install the constant mapping into CMAP0 by side - effect , linear - update & return DOMAIN0 with the constant - mapping 's domain . (define (install-constant-ccp! cmap0 domain0 char char-domain) (char-set-for-each (lambda (c) (string-set! cmap0 (char->ascii c) char)) char-domain) (char-set-union! domain0 char-domain)) CCP / MAPPINGS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ( ccp / mappings from1 to1 from2 to2 ... ) - > ccp ( extend - ccp / mappings base - ccp from1 to1 from2 to2 ... ) - > ccp ( extend - ccp / mappings ! base - ccp from1 to1 from2 to2 ... ) - > ccp ;;; Each FROM element is either a string or a (lo-char . hi-char) range. ;;; Each TO element is either a string or a lo-char. Strings are replicated ;;; to match the length of the corresponding FROM element. CCP / MAPPINGS 's base CCP is CCP:0 ;;; ;;; Tedious code. Internal utility . Install the FROM->TO mapping pair into DOMAIN & CMAP by side - effect . ;;; Return the new domain. (define (install-ccp-mapping-pair! cmap domain from to) Tedium -- four possibilities here : , , ;; range->str, range->lo-char. (if (string? from) (if (string? to) " abc " - > " ABC " (let ((len1 (string-length from)) (len2 (string-length to))) (let lp2 ((i (- len1 1)) (j (modulo (- len2 1) len1)) (d domain)) (if (>= i 0) (let ((c (string-ref from i))) (string-set! cmap (char->ascii c) (string-ref to i)) (lp2 (- i 1) (- (if (> j 0) j len2) 1) (char-set-adjoin! d c))) d))) " abc " - > # \A (let lp2 ((i (- (string-length from) 1)) (j (char->ascii to)) (d domain)) (if (>= i 0) (let ((c (string-ref from i))) (string-set! cmap (char->ascii c) (ascii->char j)) (lp2 (- i 1) (- j 1) (char-set-adjoin! d c))) d))) (let ((from-start (char->ascii (car from))) (from-end (char->ascii (cdr from)))) (if (string? to) (let ((len2-1 (- (string-length to) 1))) ( # \a . # \c ) - > " ABC " (let lp2 ((i from-start) (j 0) (d domain)) (if (<= i from-end) (let ((c (string-ref to j))) (string-set! cmap i c) (lp2 (+ i 1) (if (= j len2-1) 0 (+ j 1)) (char-set-adjoin! d c))) d))) ( # \a . # \c ) - > # \A (do ((i from-start (+ i 1)) (j (char->ascii to) (+ j 1)) (d domain (begin (string-set! cmap i (ascii->char j)) (char-set-adjoin d (ascii->char i))))) ((> i from-end) d)))))) Internal utility -- side - effects CMAP ; linear - updates & returns DOMAIN . (define (install-mapping-pairs cmap domain args) (let lp ((domain domain) (args args)) (if (pair? args) (lp (install-ccp-mapping-pair! cmap domain (car args) (cadr args)) (cddr args)) domain))) (define (ccp/mappings . args) (let ((cmap (make-string num-chars))) (make-ccp (install-mapping-pairs (make-string num-chars) (char-set-copy char-set:empty) args) #f cmap #f))) (define (extend-ccp/mappings base . args) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-mapping-pairs cmap (char-set-copy (ccp:domain base)) args) #f cmap #f))) (define (extend-ccp/mappings! base . args) (linear-update-ccp base (lambda (d cmap) (install-mapping-pairs cmap d args)))) CONSTRUCT - CCP ! ccp elt ... ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The kitchen-sink constructor; static typing be damned. ELTS are interpreted as follows : ( lo - char . hi - char ) to - string|lo - char ; ccp / range from - string to - string|lo - char ; ccp / range ;;; ccp ; ccp-extend ;;; alist ; alist->ccp domain char ; ccp - constant ;;; domain proc ; proc->ccp (define (construct-ccp! ccp . elts) (linear-update-ccp ccp (lambda (d cmap) (install-ccp-construct! cmap d elts)))) (define (construct-ccp base . elts) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-construct! cmap (char-set-copy (ccp:domain base)) elts) #f cmap #f))) Install the mappings into CMAP by side - effect , ;;; linear-update & return DOMAIN with the final domain. (define (install-ccp-construct! cmap domain elts) (let lp ((d domain) (elts elts)) ;(format #t "d=~s elts=~s\n" d elts) (if (not (pair? elts)) d (let ((elt (car elts)) (elts (cdr elts))) (cond ((pair? elt) ELT is an alist . (lp (install-ccp-alist! cmap d elt) elts)) ELT is ( lo - char . hi - char ) range . (lp (install-ccp-mapping-pair! cmap d elt (car elts)) (cdr elts))) (else (error "Illegal elt to construct-ccp" elt)))) ((string? elt) (lp (install-ccp-mapping-pair! cmap d elt (car elts)) (cdr elts))) ((ccp? elt) (lp (install-ccp-extension! cmap d elt) elts)) ((char-set? elt) (let ((elt2 (car elts)) (elts (cdr elts))) (lp (cond ((char? elt2) (install-constant-ccp! cmap d elt2 elt)) ((procedure? elt2) (install-ccp-proc! cmap d elt2 elt)) (else (error "Illegal elt-pair to construct-ccp" elt elt2))) elts))) (else (error "Illegal elt to construct-ccp" elt))))))) CCP unfold (define (ccp-unfold p f g seed) (let lp ((seed seed) (ccp (ccp-copy ccp:0))) (if (p seed) ccp (lp (g seed) (receive (from to) (f seed) (lp (g seed) (ccp-adjoin! ccp from to))))))) ;;; Using CCPs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; TR ccp string [start end] -> string CCP - MAP ccp string [ start end ] - > string CCP - MAP ! ccp string [ start end ] - > undefined CCP - APP > char or false If a char in S is not in CCP 's domain , it is dropped from the result . ;;; You can use this to map and delete chars from a string. (define (tr ccp s . maybe-start+end) (let-optionals maybe-start+end ((start 0) (end (string-length s))) ;; Count up the chars in S that are in the domain, ;; and allocate the answer string ANS: (let* ((len (- end start)) (domain (ccp:domain ccp)) (ans-len (string-fold (lambda (c numchars) (if (char-set-contains? domain c) (+ numchars 1) numchars)) 0 s start end)) (ans (make-string ans-len))) Apply the map , installing the resulting chars into ANS : (string-fold (lambda (c i) (cond ((ccp-app ccp c) => (lambda (c) (string-set! ans i c) (+ i 1))) (else i))) ; Not in domain -- drop it. 0 s start end) ans))) (define (ccp-map ccp s . maybe-start+end) (apply string-map (lambda (c) (ccp-app ccp c)) s maybe-start+end)) (define (ccp-map! ccp s . maybe-start+end) (apply string-map! (lambda (c) (ccp-app ccp c)) s maybe-start+end)) (define (ccp-app ccp char) (and (char-set-contains? (ccp:domain ccp) char) (string-ref (ccp:map ccp) (char->ascii char)))) ;;; Primitive CCPs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define id-cmap (let ((m (make-string num-chars))) (do ((i (- num-chars 1) (- i 1))) ((< i 0)) (string-set! m i (ascii->char i))) m)) (define ccp:0 (make-ccp char-set:empty #t id-cmap #t)) (define ccp:1 (make-ccp char-set:full #t id-cmap #t)) (define ccp:upcase (proc->ccp char-upcase char-set:full)) (define ccp:downcase (proc->ccp char-downcase char-set:full))
null
https://raw.githubusercontent.com/cardmagic/lucash/0452d410430d12140c14948f7f583624f819cdad/reference/scsh-0.6.6/scsh/lib/ccp.scm
scheme
Char->char partial maps -*- Scheme -*- CCPs are an efficient data structure for doing simple string transforms, similar to the kinds of things you would do with the tr(1) program. character types would need a more sophisticated data structure, tuned for sparseness. I would suggest something like this: domain ; The domain char-set map ; Sorted vector of (char . string) pairs ; specifying the map. If true , mappings not specified by MAP are ; identity mapping. If false, MAP must specify a mapping for every char in DOMAIN . A (char . string) elements in MAP specifies a mapping for the contiguous character C to the right MAP element quickly. This representation should be reasonably compact for standard mappings on, say, a Unicode CCP. An implementation might wish to have a cache field operations. Or, an implementation might want to store the Latin-1 subset of the map in a dense format, and keep the remainder in a sparse format. The domain char-set Is the domain value shared or linear? Is the map string shared or linear? Accessors and setters that manage the linear bookkeeping it must be linear in its parameter and result. reuses the old one to construct the new one . It is passed a linear domain and cmap string. It may side-effect N-ary equality relation for partial maps N-ary subset relation for partial maps the new domain. 0 parameters Compose the CCPs. 0-ary case: (ccp-compose) = ccp:1. For each character C-IN in the original domain, we push it through the pipeline of CCPs. If we ever land outside the through, we add C-IN to our result domain, and add the mapping into the cmap we are assembling. Looping this way avoids building up intermediate temporary slicing the double-nested loops the other way around. 0 args => ccp:1 Win: C-IN -> C ALIST->CPP PROC->CCP (proc->ccp proc [domain base-ccp]) CONSTANT-CCP (constant-ccp char [domain base-ccp]) DOMAIN defaults to char-set:full. BASE-CCP defaults to CCP:0. Each FROM element is either a string or a (lo-char . hi-char) range. Each TO element is either a string or a lo-char. Strings are replicated to match the length of the corresponding FROM element. Tedious code. Return the new domain. range->str, range->lo-char. linear - updates & returns DOMAIN . The kitchen-sink constructor; static typing be damned. ccp / range ccp / range ccp ; ccp-extend alist ; alist->ccp ccp - constant domain proc ; proc->ccp linear-update & return DOMAIN with the final domain. (format #t "d=~s elts=~s\n" d elts) Using CCPs TR ccp string [start end] -> string You can use this to map and delete chars from a string. Count up the chars in S that are in the domain, and allocate the answer string ANS: Not in domain -- drop it. Primitive CCPs
Copyright ( C ) 1998 by . This code is tuned for a 7- or 8 - bit character type . Large , 16 - bit ( define - record ccp sequence of L chars beginning with ( in the sequence of the underlying char type representation ) , where L is the length of STRING . These MAP elements are sorted by , so that binary search can be used to get from an input in the record for storing the full 8 kb bitset when performing ccp - map AKA 256 . (define-record ccp 256 - elt string (define (ccp-domain ccp) (set-ccp:dshared? ccp #t) (ccp:domain ccp)) Updates the domain of the CCP with PROC , returns the resulting (define (restrict-linear-ccp-domain ccp proc) (let ((new-d (proc (if (ccp:dshared? ccp) (begin (set-ccp:dshared? ccp #f) (char-set-copy (ccp:domain ccp))) (ccp:domain ccp))))) (set-ccp:domain ccp new-d) ccp)) CCP is a linear CCP . PROC is a domain domain function . the cmap string , and returns the resulting updated domain . We return the resulting CCP , reusing the parameter to construct it . (define (linear-update-ccp ccp proc) (let* ((cmap (if (ccp:mshared? ccp) (begin (set-ccp:mshared? ccp #f) (string-copy (ccp:map ccp))) (ccp:map ccp))) (new-d (proc (if (ccp:dshared? ccp) (begin (set-ccp:dshared? ccp #f) (char-set-copy (ccp:domain ccp))) (ccp:domain ccp)) cmap))) (set-ccp:domain ccp new-d) ccp)) Return CCP 's map field , and mark it as shared . CCP functions that restrict a ccp 's domain share map strings , so they use this guy . (define (ccp:map/shared ccp) (set-ccp:mshared? ccp #t) (ccp:map ccp)) (define (ccp-copy ccp) (make-ccp (char-set-copy (ccp:domain ccp)) #f (string-copy (ccp:map ccp)) #f)) (define (ccp= ccp1 . rest) (let ((domain (ccp:domain ccp1)) (cmap (ccp:map ccp1))) (every (lambda (ccp2) (and (char-set= domain (ccp:domain ccp2)) (let ((cmap2 (ccp:map ccp2))) (char-set-every (lambda (c) (let ((i (char->ascii c))) (char=? (string-ref cmap i) (string-ref cmap2 i)))) domain)))) rest))) (define (ccp<= ccp1 . rest) (let lp ((domain1 (ccp:domain ccp1)) (cmap1 (ccp:map ccp1)) (rest rest)) (or (not (pair? rest)) (let* ((ccp2 (car rest)) (domain2 (ccp:domain ccp2)) (cmap2 (ccp:map ccp2)) (rest (cdr rest))) (and (char-set<= domain1 domain2) (let ((cmap2 (ccp:map ccp2))) (char-set-every (lambda (c) (let ((i (char->ascii c))) (char=? (string-ref cmap1 i) (string-ref cmap2 i)))) domain1)) (lp domain2 cmap2 rest)))))) CCP iterators (define (ccp-fold kons knil ccp) (let ((cmap (ccp:map ccp))) (char-set-fold (lambda (c v) (kons c (string-ref cmap (char->ascii c)) v)) knil (ccp:domain ccp)))) (define (ccp-for-each proc ccp) (let ((cmap (ccp:map ccp))) (char-set-for-each (lambda (c) (proc c (string-ref cmap (char->ascii c)))) (ccp:domain ccp)))) (define (ccp->alist ccp) (ccp-fold (lambda (from to alist) (cons (cons from to) alist)) '() ccp)) CCP - RESTRICT Restrict a ccp 's domain . (define (ccp-restrict ccp cset) (make-ccp (char-set-intersection cset (ccp:domain ccp)) #f (ccp:map/shared ccp) #t)) (define (ccp-restrict! ccp cset) (restrict-linear-ccp-domain ccp (lambda (d) (char-set-intersection! d cset)))) CCP - ADJOIN ccp from - char1 to - char1 ... CCP - DELETE ccp char1 ... Add & delete mappings to / from a ccp . (define (ccp-delete ccp . chars) (make-ccp (apply char-set-delete (ccp:domain ccp) chars) #f (ccp:map/shared ccp) #t)) (define (ccp-delete! ccp . chars) (restrict-linear-ccp-domain ccp (lambda (d) (apply char-set-delete! d chars)))) (define (ccp-adjoin ccp . chars) (let ((cmap (string-copy (ccp:map ccp)))) (make-ccp (install-ccp-adjoin! cmap (char-set-copy (ccp:domain ccp)) chars) #f cmap #f))) (define (ccp-adjoin! ccp . chars) (linear-update-ccp ccp (lambda (d cmap) (install-ccp-adjoin! cmap d chars)))) (define (install-ccp-adjoin! cmap domain chars) (let lp ((chars chars) (d domain)) (if (pair? chars) (let ((from (car chars)) (to (cadr chars)) (chars (cddr chars))) (string-set! cmap (char->ascii from) to) (lp chars (char-set-adjoin! d from))) d))) CCP - EXTEND ccp1 ... CCP - EXTEND ! ccp1 ccp2 ... Extend ccp1 with ccp2 , etc . (define (ccp-extend . ccps) (if (pair? ccps) (let ((ccp0 (car ccps)) (ccps (cdr ccps))) (if (pair? ccps) . The FOLD installs each ccp in CCPS into CMAP and produces (make-ccp (fold (lambda (ccp d) (install-ccp-extension! cmap d ccp)) (char-set-copy (ccp:domain ccp0)) ccps) #f cmap #f)) Only 1 parameter (define (ccp-extend! ccp0 . ccps) (linear-update-ccp ccp0 (lambda (domain cmap) (fold (lambda (ccp d) (install-ccp-extension! cmap d ccp)) domain ccps)))) Side - effect CMAP , linear - update and return DOMAIN . (define (install-ccp-extension! cmap domain ccp) (let ((cmap1 (ccp:map ccp)) (domain1 (ccp:domain ccp))) (char-set-for-each (lambda (c) (let ((i (char->ascii c))) (string-set! cmap i (string-ref cmap1 i)))) domain1) (char-set-union! domain domain1))) domain of a ccp , we punt C - IN . If we push it all the way CCPs . If CCP 's were small bitsets , we might be better off (define (ccp-compose . ccps) 1 arg (else (let* ((v (list->vector ccps)) (vlen-2 (- (vector-length v) 2)) (cmap (make-string num-chars)) (d1 (ccp:domain (vector-ref v (+ vlen-2 1)))) (d (char-set-fold (lambda (c-in d) (let lp ((c c-in) (i vlen-2)) (if (>= i 0) (let ((ccp (vector-ref v i))) (if (char-set-contains? (ccp:domain ccp) c) (lp (string-ref (ccp:map ccp) (char->ascii c)) (- i 1)) Lose : remove c - in from d. (char-set-delete! d c-in))) (begin (string-set! cmap (char->ascii c-in) c) d)))) (char-set-copy d1) d1))) (make-ccp d #f cmap #f))))) (define (alist->ccp cc-alist . maybe-base-ccp) (let ((base (:optional maybe-base-ccp ccp:0))) (if (pair? cc-alist) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-alist! cmap (char-set-copy (ccp:domain base)) cc-alist) #f cmap #f)) base))) (define (alist->ccp! alist base) (linear-update-ccp base (lambda (d cmap) (install-ccp-alist! cmap d alist)))) Side - effect CMAP , linear - update and return DOMAIN . (define (install-ccp-alist! cmap domain alist) (fold (lambda (from/to d) (let ((from (car from/to)) (to (cdr from/to))) (string-set! cmap (char->ascii from) to) (char-set-adjoin! domain from))) domain alist)) (define (proc->ccp proc . args) (let-optionals args ((proc-domain char-set:full) (base ccp:0)) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-proc! cmap (char-set-copy (ccp:domain base)) proc proc-domain) #f cmap #f)))) (define (proc->ccp! proc proc-domain base) (linear-update-ccp base (lambda (d cmap) (install-ccp-proc! cmap d proc proc-domain)))) (define (install-ccp-proc! cmap domain proc proc-domain) (char-set-for-each (lambda (c) (string-set! cmap (char->ascii c) (proc c))) proc-domain) (char-set-union! domain proc-domain)) Extend BASE - CCP with the a map taking every char in DOMAIN to . (define (constant-ccp char . args) (let-optionals args ((char-domain char-set:full) (base ccp:0)) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-constant-ccp! cmap (char-set-copy (ccp:domain base)) char char-domain) #f cmap #f)))) (define (constant-ccp! char char-domain base) (linear-update-ccp base (lambda (d cmap) (install-constant-ccp! cmap d char char-domain)))) Install the constant mapping into CMAP0 by side - effect , linear - update & return DOMAIN0 with the constant - mapping 's domain . (define (install-constant-ccp! cmap0 domain0 char char-domain) (char-set-for-each (lambda (c) (string-set! cmap0 (char->ascii c) char)) char-domain) (char-set-union! domain0 char-domain)) CCP / MAPPINGS ( ccp / mappings from1 to1 from2 to2 ... ) - > ccp ( extend - ccp / mappings base - ccp from1 to1 from2 to2 ... ) - > ccp ( extend - ccp / mappings ! base - ccp from1 to1 from2 to2 ... ) - > ccp CCP / MAPPINGS 's base CCP is CCP:0 Internal utility . Install the FROM->TO mapping pair into DOMAIN & CMAP by side - effect . (define (install-ccp-mapping-pair! cmap domain from to) Tedium -- four possibilities here : , , (if (string? from) (if (string? to) " abc " - > " ABC " (let ((len1 (string-length from)) (len2 (string-length to))) (let lp2 ((i (- len1 1)) (j (modulo (- len2 1) len1)) (d domain)) (if (>= i 0) (let ((c (string-ref from i))) (string-set! cmap (char->ascii c) (string-ref to i)) (lp2 (- i 1) (- (if (> j 0) j len2) 1) (char-set-adjoin! d c))) d))) " abc " - > # \A (let lp2 ((i (- (string-length from) 1)) (j (char->ascii to)) (d domain)) (if (>= i 0) (let ((c (string-ref from i))) (string-set! cmap (char->ascii c) (ascii->char j)) (lp2 (- i 1) (- j 1) (char-set-adjoin! d c))) d))) (let ((from-start (char->ascii (car from))) (from-end (char->ascii (cdr from)))) (if (string? to) (let ((len2-1 (- (string-length to) 1))) ( # \a . # \c ) - > " ABC " (let lp2 ((i from-start) (j 0) (d domain)) (if (<= i from-end) (let ((c (string-ref to j))) (string-set! cmap i c) (lp2 (+ i 1) (if (= j len2-1) 0 (+ j 1)) (char-set-adjoin! d c))) d))) ( # \a . # \c ) - > # \A (do ((i from-start (+ i 1)) (j (char->ascii to) (+ j 1)) (d domain (begin (string-set! cmap i (ascii->char j)) (char-set-adjoin d (ascii->char i))))) ((> i from-end) d)))))) (define (install-mapping-pairs cmap domain args) (let lp ((domain domain) (args args)) (if (pair? args) (lp (install-ccp-mapping-pair! cmap domain (car args) (cadr args)) (cddr args)) domain))) (define (ccp/mappings . args) (let ((cmap (make-string num-chars))) (make-ccp (install-mapping-pairs (make-string num-chars) (char-set-copy char-set:empty) args) #f cmap #f))) (define (extend-ccp/mappings base . args) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-mapping-pairs cmap (char-set-copy (ccp:domain base)) args) #f cmap #f))) (define (extend-ccp/mappings! base . args) (linear-update-ccp base (lambda (d cmap) (install-mapping-pairs cmap d args)))) CONSTRUCT - CCP ! ccp elt ... ELTS are interpreted as follows : (define (construct-ccp! ccp . elts) (linear-update-ccp ccp (lambda (d cmap) (install-ccp-construct! cmap d elts)))) (define (construct-ccp base . elts) (let ((cmap (string-copy (ccp:map base)))) (make-ccp (install-ccp-construct! cmap (char-set-copy (ccp:domain base)) elts) #f cmap #f))) Install the mappings into CMAP by side - effect , (define (install-ccp-construct! cmap domain elts) (let lp ((d domain) (elts elts)) (if (not (pair? elts)) d (let ((elt (car elts)) (elts (cdr elts))) (cond ((pair? elt) ELT is an alist . (lp (install-ccp-alist! cmap d elt) elts)) ELT is ( lo - char . hi - char ) range . (lp (install-ccp-mapping-pair! cmap d elt (car elts)) (cdr elts))) (else (error "Illegal elt to construct-ccp" elt)))) ((string? elt) (lp (install-ccp-mapping-pair! cmap d elt (car elts)) (cdr elts))) ((ccp? elt) (lp (install-ccp-extension! cmap d elt) elts)) ((char-set? elt) (let ((elt2 (car elts)) (elts (cdr elts))) (lp (cond ((char? elt2) (install-constant-ccp! cmap d elt2 elt)) ((procedure? elt2) (install-ccp-proc! cmap d elt2 elt)) (else (error "Illegal elt-pair to construct-ccp" elt elt2))) elts))) (else (error "Illegal elt to construct-ccp" elt))))))) CCP unfold (define (ccp-unfold p f g seed) (let lp ((seed seed) (ccp (ccp-copy ccp:0))) (if (p seed) ccp (lp (g seed) (receive (from to) (f seed) (lp (g seed) (ccp-adjoin! ccp from to))))))) CCP - MAP ccp string [ start end ] - > string CCP - MAP ! ccp string [ start end ] - > undefined CCP - APP > char or false If a char in S is not in CCP 's domain , it is dropped from the result . (define (tr ccp s . maybe-start+end) (let-optionals maybe-start+end ((start 0) (end (string-length s))) (let* ((len (- end start)) (domain (ccp:domain ccp)) (ans-len (string-fold (lambda (c numchars) (if (char-set-contains? domain c) (+ numchars 1) numchars)) 0 s start end)) (ans (make-string ans-len))) Apply the map , installing the resulting chars into ANS : (string-fold (lambda (c i) (cond ((ccp-app ccp c) => (lambda (c) (string-set! ans i c) (+ i 1))) 0 s start end) ans))) (define (ccp-map ccp s . maybe-start+end) (apply string-map (lambda (c) (ccp-app ccp c)) s maybe-start+end)) (define (ccp-map! ccp s . maybe-start+end) (apply string-map! (lambda (c) (ccp-app ccp c)) s maybe-start+end)) (define (ccp-app ccp char) (and (char-set-contains? (ccp:domain ccp) char) (string-ref (ccp:map ccp) (char->ascii char)))) (define id-cmap (let ((m (make-string num-chars))) (do ((i (- num-chars 1) (- i 1))) ((< i 0)) (string-set! m i (ascii->char i))) m)) (define ccp:0 (make-ccp char-set:empty #t id-cmap #t)) (define ccp:1 (make-ccp char-set:full #t id-cmap #t)) (define ccp:upcase (proc->ccp char-upcase char-set:full)) (define ccp:downcase (proc->ccp char-downcase char-set:full))
4ad9adb6874a8117e0ba4ca06c7290a99fe8021a1c48f5be08e49a97d9978371
bos/llvm
Optimize.hs
does not export its functions @createStandardFunctionPasses@ and @createStandardModulePasses@ via its C interface and interfacing to C - C++ wrappers is not very portable . Thus we reimplement these functions from @opt.cpp@ and @StandardPasses.h@ in Haskell . However this way we risk inconsistencies between ' optimizeModule ' and the @opt@ shell command . LLVM does not export its functions @createStandardFunctionPasses@ and @createStandardModulePasses@ via its C interface and interfacing to C-C++ wrappers is not very portable. Thus we reimplement these functions from @opt.cpp@ and @StandardPasses.h@ in Haskell. However this way we risk inconsistencies between 'optimizeModule' and the @opt@ shell command. -} module LLVM.Util.Optimize(optimizeModule) where import LLVM.Core.Util(Module, withModule) import qualified LLVM.FFI.Core as FFI import qualified LLVM.FFI.Support as FFI import LLVM.FFI.Transforms.Scalar import Control.Exception (bracket) {- | Result tells whether the module was modified by any of the passes. -} optimizeModule :: Int -> Module -> IO Bool optimizeModule optLevel mdl = withModule mdl $ \ m -> {- Core.Util.createPassManager would provide a finalizer for us, but I think it is better here to immediately dispose the manager when we need it no longer. -} bracket FFI.createPassManager FFI.disposePassManager $ \ passes -> Note on to 2.8 ( at least ): As far as I understand , if we do not set target data , then the optimizer will only perform machine independent optimizations . If we set target data ( e.g. an empty layout string obtained from a module without ' target data ' specification . ) we risk that the optimizer switches to a wrong layout ( e.g. to 64 bit pointers on a 32 bit machine for empty layout string ) and thus generates corrupt code . Currently it seems to be safer to disable machine dependent optimization completely . -- Pass the module target data to the pass manager . target < - FFI.getDataLayout m > > = createTargetData addTargetData target passes Note on LLVM-2.6 to 2.8 (at least): As far as I understand, if we do not set target data, then the optimizer will only perform machine independent optimizations. If we set target data (e.g. an empty layout string obtained from a module without 'target data' specification.) we risk that the optimizer switches to a wrong layout (e.g. to 64 bit pointers on a 32 bit machine for empty layout string) and thus generates corrupt code. Currently it seems to be safer to disable machine dependent optimization completely. -- Pass the module target data to the pass manager. target <- FFI.getDataLayout m >>= createTargetData addTargetData target passes -} opt.cpp does not use a FunctionPassManager for function optimization , but a module PassManager . Thus we do it the same way . I assume that we would need a FunctionPassManager only if we wanted to apply individual optimizations to functions . fPasses < - FFI.createFunctionPassManager mp opt.cpp does not use a FunctionPassManager for function optimization, but a module PassManager. Thus we do it the same way. I assume that we would need a FunctionPassManager only if we wanted to apply individual optimizations to functions. fPasses <- FFI.createFunctionPassManager mp -} bracket FFI.createPassManager FFI.disposePassManager $ \ fPasses -> do -- add module target data? -- tools/opt/opt.cpp: AddStandardCompilePasses addVerifierPass passes addOptimizationPasses passes fPasses optLevel if we wanted to do so , we could loop through all functions and optimize them . initializeFunctionPassManager fPasses runFunctionPassManager fPasses fcn initializeFunctionPassManager fPasses runFunctionPassManager fPasses fcn -} functionsModified <- FFI.runPassManager fPasses m moduleModified <- FFI.runPassManager passes m return $ toEnum (fromIntegral moduleModified) || toEnum (fromIntegral functionsModified) -- tools/opt/opt.cpp: AddOptimizationPasses addOptimizationPasses :: FFI.PassManagerRef -> FFI.PassManagerRef -> Int -> IO () addOptimizationPasses passes fPasses optLevel = do createStandardFunctionPasses fPasses optLevel createStandardModulePasses passes optLevel True True (optLevel > 1) True True True createStandardFunctionPasses :: FFI.PassManagerRef -> Int -> IO () createStandardFunctionPasses fPasses optLevel = FFI.createStandardFunctionPasses fPasses (fromIntegral optLevel) -- llvm/Support/StandardPasses.h: createStandardModulePasses createStandardModulePasses :: FFI.PassManagerRef -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> IO () createStandardModulePasses passes optLevel optSize unitAtATime unrollLoops simplifyLibCalls haveExceptions inliningPass = FFI.createStandardModulePasses passes (fromIntegral optLevel) (f optSize) (f unitAtATime) (f unrollLoops) (f simplifyLibCalls) (f haveExceptions) (f (not inliningPass)) where f True = 1 f _ = 0 ToDo : Function that adds passes according to a list of opt - options . This would simplify to get consistent behaviour between opt and optimizeModule . -adce addAggressiveDCEPass -deadargelim -deadtypeelim addDeadTypeEliminationPass -dse addFunctionAttrsPass -globalopt addGlobalOptimizerPass -indvars addIndVarSimplifyPass -instcombine addInstructionCombiningPass -ipsccp addIPSCCPPass -jump - threading addJumpThreadingPass -licm addLoopDeletionPass -loop - rotate addLoopRotatePass -memcpyopt -prune - eh addPruneEHPass -reassociate addReassociatePass -scalarrepl addScalarReplAggregatesPass -sccp addSCCPPass -simplifycfg addCFGSimplificationPass -simplify - libcalls addSimplifyLibCallsPass -strip - dead - prototypes addStripDeadPrototypesPass -tailcallelim addVerifierPass ToDo: Function that adds passes according to a list of opt-options. This would simplify to get consistent behaviour between opt and optimizeModule. -adce addAggressiveDCEPass -deadargelim addDeadArgEliminationPass -deadtypeelim addDeadTypeEliminationPass -dse addDeadStoreEliminationPass -functionattrs addFunctionAttrsPass -globalopt addGlobalOptimizerPass -indvars addIndVarSimplifyPass -instcombine addInstructionCombiningPass -ipsccp addIPSCCPPass -jump-threading addJumpThreadingPass -licm addLICMPass -loop-deletion addLoopDeletionPass -loop-rotate addLoopRotatePass -memcpyopt addMemCpyOptPass -prune-eh addPruneEHPass -reassociate addReassociatePass -scalarrepl addScalarReplAggregatesPass -sccp addSCCPPass -simplifycfg addCFGSimplificationPass -simplify-libcalls addSimplifyLibCallsPass -strip-dead-prototypes addStripDeadPrototypesPass -tailcallelim addTailCallEliminationPass -verify addVerifierPass -}
null
https://raw.githubusercontent.com/bos/llvm/819b94d048c9d7787ce41cd7c71b84424e894f64/LLVM/Util/Optimize.hs
haskell
| Result tells whether the module was modified by any of the passes. Core.Util.createPassManager would provide a finalizer for us, but I think it is better here to immediately dispose the manager when we need it no longer. Pass the module target data to the pass manager . Pass the module target data to the pass manager. add module target data? tools/opt/opt.cpp: AddStandardCompilePasses tools/opt/opt.cpp: AddOptimizationPasses llvm/Support/StandardPasses.h: createStandardModulePasses
does not export its functions @createStandardFunctionPasses@ and @createStandardModulePasses@ via its C interface and interfacing to C - C++ wrappers is not very portable . Thus we reimplement these functions from @opt.cpp@ and @StandardPasses.h@ in Haskell . However this way we risk inconsistencies between ' optimizeModule ' and the @opt@ shell command . LLVM does not export its functions @createStandardFunctionPasses@ and @createStandardModulePasses@ via its C interface and interfacing to C-C++ wrappers is not very portable. Thus we reimplement these functions from @opt.cpp@ and @StandardPasses.h@ in Haskell. However this way we risk inconsistencies between 'optimizeModule' and the @opt@ shell command. -} module LLVM.Util.Optimize(optimizeModule) where import LLVM.Core.Util(Module, withModule) import qualified LLVM.FFI.Core as FFI import qualified LLVM.FFI.Support as FFI import LLVM.FFI.Transforms.Scalar import Control.Exception (bracket) optimizeModule :: Int -> Module -> IO Bool optimizeModule optLevel mdl = withModule mdl $ \ m -> bracket FFI.createPassManager FFI.disposePassManager $ \ passes -> Note on to 2.8 ( at least ): As far as I understand , if we do not set target data , then the optimizer will only perform machine independent optimizations . If we set target data ( e.g. an empty layout string obtained from a module without ' target data ' specification . ) we risk that the optimizer switches to a wrong layout ( e.g. to 64 bit pointers on a 32 bit machine for empty layout string ) and thus generates corrupt code . Currently it seems to be safer to disable machine dependent optimization completely . target < - FFI.getDataLayout m > > = createTargetData addTargetData target passes Note on LLVM-2.6 to 2.8 (at least): As far as I understand, if we do not set target data, then the optimizer will only perform machine independent optimizations. If we set target data (e.g. an empty layout string obtained from a module without 'target data' specification.) we risk that the optimizer switches to a wrong layout (e.g. to 64 bit pointers on a 32 bit machine for empty layout string) and thus generates corrupt code. Currently it seems to be safer to disable machine dependent optimization completely. target <- FFI.getDataLayout m >>= createTargetData addTargetData target passes -} opt.cpp does not use a FunctionPassManager for function optimization , but a module PassManager . Thus we do it the same way . I assume that we would need a FunctionPassManager only if we wanted to apply individual optimizations to functions . fPasses < - FFI.createFunctionPassManager mp opt.cpp does not use a FunctionPassManager for function optimization, but a module PassManager. Thus we do it the same way. I assume that we would need a FunctionPassManager only if we wanted to apply individual optimizations to functions. fPasses <- FFI.createFunctionPassManager mp -} bracket FFI.createPassManager FFI.disposePassManager $ \ fPasses -> do addVerifierPass passes addOptimizationPasses passes fPasses optLevel if we wanted to do so , we could loop through all functions and optimize them . initializeFunctionPassManager fPasses runFunctionPassManager fPasses fcn initializeFunctionPassManager fPasses runFunctionPassManager fPasses fcn -} functionsModified <- FFI.runPassManager fPasses m moduleModified <- FFI.runPassManager passes m return $ toEnum (fromIntegral moduleModified) || toEnum (fromIntegral functionsModified) addOptimizationPasses :: FFI.PassManagerRef -> FFI.PassManagerRef -> Int -> IO () addOptimizationPasses passes fPasses optLevel = do createStandardFunctionPasses fPasses optLevel createStandardModulePasses passes optLevel True True (optLevel > 1) True True True createStandardFunctionPasses :: FFI.PassManagerRef -> Int -> IO () createStandardFunctionPasses fPasses optLevel = FFI.createStandardFunctionPasses fPasses (fromIntegral optLevel) createStandardModulePasses :: FFI.PassManagerRef -> Int -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> IO () createStandardModulePasses passes optLevel optSize unitAtATime unrollLoops simplifyLibCalls haveExceptions inliningPass = FFI.createStandardModulePasses passes (fromIntegral optLevel) (f optSize) (f unitAtATime) (f unrollLoops) (f simplifyLibCalls) (f haveExceptions) (f (not inliningPass)) where f True = 1 f _ = 0 ToDo : Function that adds passes according to a list of opt - options . This would simplify to get consistent behaviour between opt and optimizeModule . -adce addAggressiveDCEPass -deadargelim -deadtypeelim addDeadTypeEliminationPass -dse addFunctionAttrsPass -globalopt addGlobalOptimizerPass -indvars addIndVarSimplifyPass -instcombine addInstructionCombiningPass -ipsccp addIPSCCPPass -jump - threading addJumpThreadingPass -licm addLoopDeletionPass -loop - rotate addLoopRotatePass -memcpyopt -prune - eh addPruneEHPass -reassociate addReassociatePass -scalarrepl addScalarReplAggregatesPass -sccp addSCCPPass -simplifycfg addCFGSimplificationPass -simplify - libcalls addSimplifyLibCallsPass -strip - dead - prototypes addStripDeadPrototypesPass -tailcallelim addVerifierPass ToDo: Function that adds passes according to a list of opt-options. This would simplify to get consistent behaviour between opt and optimizeModule. -adce addAggressiveDCEPass -deadargelim addDeadArgEliminationPass -deadtypeelim addDeadTypeEliminationPass -dse addDeadStoreEliminationPass -functionattrs addFunctionAttrsPass -globalopt addGlobalOptimizerPass -indvars addIndVarSimplifyPass -instcombine addInstructionCombiningPass -ipsccp addIPSCCPPass -jump-threading addJumpThreadingPass -licm addLICMPass -loop-deletion addLoopDeletionPass -loop-rotate addLoopRotatePass -memcpyopt addMemCpyOptPass -prune-eh addPruneEHPass -reassociate addReassociatePass -scalarrepl addScalarReplAggregatesPass -sccp addSCCPPass -simplifycfg addCFGSimplificationPass -simplify-libcalls addSimplifyLibCallsPass -strip-dead-prototypes addStripDeadPrototypesPass -tailcallelim addTailCallEliminationPass -verify addVerifierPass -}
7b444e9d9c68330d49c293a57ee6114683705cdf26e5bcb0bf6f76da9118d9ef
elnewfie/lslforge
SerializationInstances.hs
{-# OPTIONS_GHC -XTemplateHaskell -XScopedTypeVariables #-} module Language.Lsl.Internal.SerializationInstances where import Language.Lsl.Internal.SerializationGenerator $(deriveJavaRepTups [2..10]) $(deriveJavaRep ''Either) $(deriveJavaRep ''Maybe)
null
https://raw.githubusercontent.com/elnewfie/lslforge/27eb84231c53fffba6bdb0db67bde81c1c12dbb9/lslforge/haskell/src/Language/Lsl/Internal/SerializationInstances.hs
haskell
# OPTIONS_GHC -XTemplateHaskell -XScopedTypeVariables #
module Language.Lsl.Internal.SerializationInstances where import Language.Lsl.Internal.SerializationGenerator $(deriveJavaRepTups [2..10]) $(deriveJavaRep ''Either) $(deriveJavaRep ''Maybe)
6fd30149d42ce4bf2f50d5fba291142552d8e20d1f089eb840c47d6c193b622f
esl/escalus
escalus_rpc.erl
%% @doc This module should not exist as it has nothing to do with XMPP nor is it needed by Escalus itself . %% The module contains RPC helpers which used to rely on Common Test , %% but do not do so anymore. -module(escalus_rpc). %% Public -export([call/6]). %% %% Public %% %% @doc Emulate `ct_rpc:call/6' but do not rely on Common Test. %% `call/6' takes a `Cookie' as the last parameter, %% so that nodes with different cookies can be easily called. %% However, this function is not safe (and neither is the original `ct_rpc:call/6') %% in a concurrent environment as it gets/sets the cookie with ` erlang : get_cookie/0 ' and ` erlang : ' . %% Interleaving these calls in concurrent processes is prone to race conditions. call(Node, Module, Function, Args, TimeOut, Cookie) -> call_with_cookie_match(Node, Module, Function, Args, TimeOut, Cookie). %% Internal %% Copied from ct_rpc and renamed . call_with_cookie_match(Node, Module, Function, Args, TimeOut, Cookie) when is_atom(Node) -> Cookie0 = set_the_cookie(Cookie), Result = case rpc:call(Node, Module, Function, Args, TimeOut) of {badrpc, Reason} -> error({badrpc, Reason}, [Node, Module, Function, Args, TimeOut, Cookie]); R -> R end, _ = set_the_cookie(Cookie0), Result. Copied from ct_rpc . set_the_cookie([]) -> []; set_the_cookie(Cookie) -> Cookie0 = erlang:get_cookie(), erlang:set_cookie(node(),Cookie), Cookie0.
null
https://raw.githubusercontent.com/esl/escalus/ac5e813ac96c0cdb5d5ac738d63d992f5f948585/src/escalus_rpc.erl
erlang
@doc This module should not exist as it has nothing to do with XMPP but do not do so anymore. Public Public @doc Emulate `ct_rpc:call/6' but do not rely on Common Test. `call/6' takes a `Cookie' as the last parameter, so that nodes with different cookies can be easily called. However, this function is not safe (and neither is the original `ct_rpc:call/6') in a concurrent environment as it gets/sets the cookie Interleaving these calls in concurrent processes is prone to race conditions.
nor is it needed by Escalus itself . The module contains RPC helpers which used to rely on Common Test , -module(escalus_rpc). -export([call/6]). with ` erlang : get_cookie/0 ' and ` erlang : ' . call(Node, Module, Function, Args, TimeOut, Cookie) -> call_with_cookie_match(Node, Module, Function, Args, TimeOut, Cookie). Internal Copied from ct_rpc and renamed . call_with_cookie_match(Node, Module, Function, Args, TimeOut, Cookie) when is_atom(Node) -> Cookie0 = set_the_cookie(Cookie), Result = case rpc:call(Node, Module, Function, Args, TimeOut) of {badrpc, Reason} -> error({badrpc, Reason}, [Node, Module, Function, Args, TimeOut, Cookie]); R -> R end, _ = set_the_cookie(Cookie0), Result. Copied from ct_rpc . set_the_cookie([]) -> []; set_the_cookie(Cookie) -> Cookie0 = erlang:get_cookie(), erlang:set_cookie(node(),Cookie), Cookie0.
f66d6c80ccdaefd9f9c9a281f1c9e32abc1cb3c66f9d71567edb47493c8ab68e
finnishtransportagency/harja
yksikkohintaiset_tyot.cljs
(ns harja.views.urakka.toteumat.yksikkohintaiset-tyot "Urakan 'Toteumat' välilehden Yksikköhintaist työt osio" (:require [reagent.core :refer [atom]] [harja.ui.grid :as grid] [harja.ui.grid.gridin-muokkaus :as gridin-muokkaus] [harja.ui.ikonit :as ikonit] [harja.ui.yleiset :refer [ajax-loader linkki livi-pudotusvalikko]] [harja.ui.viesti :as viesti] [harja.ui.komponentti :as komp] [harja.tiedot.navigaatio :as nav] [harja.tiedot.urakka :as u] [harja.tiedot.urakka.toteumat :as toteumat] [harja.views.urakka.valinnat :as valinnat] [harja.pvm :as pvm] [harja.ui.lomake :refer [lomake]] [harja.loki :refer [log logt tarkkaile!]] [cljs.core.async :refer [<! >! chan]] [harja.ui.protokollat :refer [Haku hae]] [harja.domain.skeema :refer [+tyotyypit+]] [harja.fmt :as fmt] [harja.tiedot.urakka.urakan-toimenpiteet :as urakan-toimenpiteet] [harja.tiedot.urakka.toteumat.yksikkohintaiset-tyot :as tiedot] [harja.views.kartta :as kartta] [harja.tiedot.kartta :as kartta-tiedot] [harja.asiakas.kommunikaatio :as k] [harja.tiedot.urakka :as u] [harja.ui.napit :as napit] [cljs-time.core :as t] [reagent.core :as r] [harja.domain.oikeudet :as oikeudet] [harja.ui.yleiset :as yleiset] [harja.ui.valinnat :as ui-valinnat] [harja.ui.kentat :refer [tee-kentta]] [harja.domain.tierekisteri :as tierekisteri]) (:require-macros [cljs.core.async.macros :refer [go]] [reagent.ratom :refer [reaction run!]])) (defn- rivi-tehtavaksi [rivi] {:toimenpidekoodi (:tehtava rivi) :maara (:maara rivi) :tehtava-id (:tehtava-id rivi) :poistettu (:poistettu rivi)}) (defn- lomakkeen-toteuma-lahetettavaksi [lomakkeen-toteuma lomakkeen-tehtavat] (assoc lomakkeen-toteuma :tyyppi :yksikkohintainen :urakka-id (:id @nav/valittu-urakka) :sopimus-id (first @u/valittu-sopimusnumero) :tehtavat (mapv rivi-tehtavaksi (gridin-muokkaus/filteroi-uudet-poistetut lomakkeen-tehtavat)) :toimenpide-id (:tpi_id @u/valittu-toimenpideinstanssi) :hoitokausi-aloituspvm (first @u/valittu-hoitokausi) :hoitokausi-lopetuspvm (second @u/valittu-hoitokausi))) (defn nayta-toteuma-lomakkeessa [urakka-id toteuma-id] (go (let [toteuma (<! (toteumat/hae-urakan-toteuma urakka-id toteuma-id))] (log "toteuma: " (pr-str toteuma)) (if-not (k/virhe? toteuma) (let [lomake-tiedot {:toteuma-id (:id toteuma) :tehtavat (zipmap (iterate inc 1) (mapv (fn [tehtava] (let [[_ _ emo tehtava-urakassa] (urakan-toimenpiteet/tehtava-urakassa (:tpk-id tehtava) @u/urakan-toimenpiteet-ja-tehtavat) tpi (some #(when (= (:t3_koodi %) (:koodi emo)) %) @u/urakan-toimenpideinstanssit)] (log "Tehtava urakassa: " (pr-str tehtava-urakassa)) (log "Toteuman 4. tason tehtävän 3. tason emo selvitetty: " (pr-str emo)) (log "Toteuman 4. tason tehtävän toimenpideinstanssi selvitetty: " (pr-str tpi)) {:tehtava {:id (:tpk-id tehtava)} :maara (:maara tehtava) :tehtava-id (:tehtava-id tehtava) :toimenpideinstanssi (:tpi_id tpi) :yksikko (:yksikko tehtava-urakassa)})) (:tehtavat toteuma))) :alkanut (:alkanut toteuma) :reitti (:reitti toteuma) :tr (:tr toteuma) :paattynyt (:paattynyt toteuma) :lisatieto (:lisatieto toteuma) :suorittajan-nimi (:nimi (:suorittaja toteuma)) :suorittajan-ytunnus (:ytunnus (:suorittaja toteuma)) :jarjestelman-lisaama (:jarjestelmanlisaama toteuma) :luoja (:kayttajanimi toteuma) :organisaatio (:organisaatio toteuma)}] (nav/aseta-valittu-valilehti! :urakat :toteumat) (nav/aseta-valittu-valilehti! :toteumat :yksikkohintaiset-tyot) (reset! tiedot/valittu-yksikkohintainen-toteuma lomake-tiedot)))))) (defn tallenna-toteuma "Ottaa lomakkeen ja tehtävät siinä muodossa kuin ne ovat lomake-komponentissa ja muodostaa palvelimelle lähetettävän payloadin." [lomakkeen-toteuma lomakkeen-tehtavat] (let [lahetettava-toteuma (lomakkeen-toteuma-lahetettavaksi lomakkeen-toteuma lomakkeen-tehtavat)] (log "Tallennetaan toteuma: " (pr-str lahetettava-toteuma)) (toteumat/tallenna-toteuma-ja-yksikkohintaiset-tehtavat lahetettava-toteuma))) (defn- nelostason-tehtava [tehtava] (nth tehtava 3)) (defn- tehtavan-tiedot [tehtava urakan-hoitokauden-yks-hint-tyot] (first (filter (fn [tiedot] (= (:tehtavan_id tiedot) (:id (nelostason-tehtava tehtava)))) urakan-hoitokauden-yks-hint-tyot))) (defn- tyo-hoitokaudella? [tyo] (pvm/sama-pvm? (:alkupvm tyo) (first @u/valittu-hoitokausi))) (defn- valintakasittelija [vain-suunnitellut? t] (let [urakan-tpi-tehtavat (urakan-toimenpiteet/toimenpideinstanssin-tehtavat (:toimenpideinstanssi t) @u/urakan-toimenpideinstanssit @u/urakan-toimenpiteet-ja-tehtavat) urakan-hoitokauden-yks-hint-tyot (filter tyo-hoitokaudella? @u/urakan-yks-hint-tyot) suunnitellut-tehtavat (filter (fn [tehtava] (> (:yksikkohinta (tehtavan-tiedot tehtava urakan-hoitokauden-yks-hint-tyot)) 0)) urakan-tpi-tehtavat)] (sort-by #(:nimi (get % 3)) (if vain-suunnitellut? suunnitellut-tehtavat urakan-tpi-tehtavat)))) (defn tehtavat-ja-maarat [tehtavat jarjestelman-lisaama-toteuma? tehtavat-virheet] (let [nelostason-tehtavat (map nelostason-tehtava @u/urakan-toimenpiteet-ja-tehtavat) toimenpideinstanssit @u/urakan-toimenpideinstanssit voi-muokata? (not jarjestelman-lisaama-toteuma?)] [grid/muokkaus-grid {:tyhja "Ei töitä." :voi-muokata? voi-muokata? :muutos #(reset! tehtavat-virheet (grid/hae-virheet %))} [{:otsikko "Toimenpide" :nimi :toimenpideinstanssi :tyyppi :valinta :fmt #(:tpi_nimi (urakan-toimenpiteet/toimenpideinstanssi-idlla % toimenpideinstanssit)) :valinta-arvo :tpi_id :valinta-nayta #(if % (:tpi_nimi %) "- Valitse toimenpide -") :valinnat toimenpideinstanssit :leveys 30 :validoi [[:ei-tyhja "Valitse työ"]] :aseta #(assoc %1 :toimenpideinstanssi %2 :tehtava nil)} {:otsikko "Tehtävä" :nimi :tehtava :tyyppi :valinta :valinta-arvo #(:id (nth % 3)) :valinta-nayta #(if % (:nimi (nth % 3)) "- Valitse tehtävä -") :valinnat-fn (partial valintakasittelija voi-muokata?) :leveys 45 :jos-tyhja "Toimenpiteelle ei ole suunniteltu yhtään tehtävää." :validoi [[:ei-tyhja "Valitse tehtävä"]] :aseta (fn [rivi arvo] (assoc rivi :tehtava arvo :yksikko (:yksikko (urakan-toimenpiteet/tehtava-idlla arvo nelostason-tehtavat))))} {:otsikko "Määrä" :nimi :maara :tyyppi :positiivinen-numero :leveys 25 :validoi [[:ei-tyhja "Anna määrä"]] :tasaa :oikea} {:otsikko "Yks." :nimi :yksikko :tyyppi :string :muokattava? (constantly false) :leveys 15}] tehtavat])) (defn yksikkohintainen-toteumalomake "Valmiin kohteen tietoja tarkasteltaessa tiedot annetaan valittu-yksikkohintainen-toteuma atomille. Lomakkeen käsittelyn ajaksi tiedot haetaan tästä atomista kahteen eri atomiin käsittelyn ajaksi: yksikköhintaiset tehtävät ovat omassa ja muut tiedot omassa atomissa. Kun lomake tallennetaan, tiedot yhdistetään näistä atomeista yhdeksi kokonaisuudeksi." [] (let [lomake-toteuma (atom @tiedot/valittu-yksikkohintainen-toteuma) lomake-tehtavat (atom (into {} (map (fn [[id tehtava]] [id (assoc tehtava :tehtava (:id (:tehtava tehtava)))]) (:tehtavat @tiedot/valittu-yksikkohintainen-toteuma)))) tehtavat-virheet (atom nil) jarjestelman-lisaama-toteuma? (true? (:jarjestelman-lisaama @lomake-toteuma)) valmis-tallennettavaksi? (reaction (and (not jarjestelman-lisaama-toteuma?) (not (nil? (:alkanut @lomake-toteuma))) (not (nil? (:paattynyt @lomake-toteuma))) (not (pvm/ennen? (:paattynyt @lomake-toteuma) (:alkanut @lomake-toteuma))) (not (empty? (filter #(not (true? (:poistettu %))) (vals @lomake-tehtavat)))) (empty? @tehtavat-virheet)))] (log "Lomake-toteuma: " (pr-str @lomake-toteuma)) (log "Lomake tehtävät: " (pr-str @lomake-tehtavat)) (komp/luo (fn [ur] [:div.toteuman-tiedot [napit/takaisin "Takaisin toteumaluetteloon" #(reset! tiedot/valittu-yksikkohintainen-toteuma nil)] [lomake {:otsikko (if (:toteuma-id @tiedot/valittu-yksikkohintainen-toteuma) (if jarjestelman-lisaama-toteuma? "Tarkastele toteumaa" "Muokkaa toteumaa") "Luo uusi toteuma") :voi-muokata? (and (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) (not jarjestelman-lisaama-toteuma?)) :muokkaa! (fn [uusi] (log "Muokataan toteumaa: " (pr-str uusi)) (reset! lomake-toteuma uusi)) :footer (when (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) [harja.ui.napit/palvelinkutsu-nappi "Tallenna toteuma" #(tallenna-toteuma @lomake-toteuma @lomake-tehtavat) {:luokka "nappi-ensisijainen" :disabled (or (false? @valmis-tallennettavaksi?) (not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)))) :kun-onnistuu (fn [vastaus] (log "Tehtävät tallennettu, vastaus: " (pr-str vastaus)) (reset! tiedot/yks-hint-tehtavien-summat (:tehtavien-summat vastaus)) (reset! lomake-tehtavat nil) (reset! lomake-toteuma nil) (reset! tiedot/valittu-yksikkohintainen-toteuma nil))}])} [(when jarjestelman-lisaama-toteuma? {:otsikko "Lähde" :nimi :luoja :tyyppi :string :hae (fn [rivi] (str "Järjestelmä (" (:luoja rivi) " / " (:organisaatio rivi) ")")) :muokattava? (constantly false) :vihje toteumat/ilmoitus-jarjestelman-luoma-toteuma}) {:otsikko "Sopimus" :nimi :sopimus :hae (fn [_] (second @u/valittu-sopimusnumero)) :muokattava? (constantly false)} {:otsikko "Aloitus" :nimi :alkanut :pakollinen? true :tyyppi :pvm :uusi-rivi? true :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :aseta (fn [rivi arvo] (assoc rivi :alkanut arvo :paattynyt arvo)) :validoi [[:ei-tyhja "Valitse päivämäärä"]] :huomauta [[:urakan-aikana-ja-hoitokaudella]]} {:otsikko "Lopetus" :nimi :paattynyt :pakollinen? true :tyyppi :pvm :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :validoi [[:ei-tyhja "Valitse päivämäärä"] [:pvm-kentan-jalkeen :alkanut "Lopetuksen pitää olla aloituksen jälkeen"]]} {:otsikko "Suorittaja" :nimi :suorittajan-nimi :pituus-max 256 :tyyppi :string :muokattava? (constantly (not jarjestelman-lisaama-toteuma?))} {:otsikko "Suorittajan Y-tunnus" :nimi :suorittajan-ytunnus :pituus-max 256 :tyyppi :string :muokattava? (constantly (not jarjestelman-lisaama-toteuma?))} {:otsikko "Tehtävät" :nimi :tehtavat :pakollinen? true :uusi-rivi? true :palstoja 2 :tyyppi :komponentti :vihje "Voit syöttää toteumia tehtäville, joille on syötetty hinta yksikköhintaisten töiden suunnitteluosiossa." :komponentti (fn [_] [tehtavat-ja-maarat lomake-tehtavat jarjestelman-lisaama-toteuma? tehtavat-virheet])} (when-not jarjestelman-lisaama-toteuma? {:tyyppi :tierekisteriosoite :nimi :tr :pakollinen? false :sijainti (r/wrap (:reitti @lomake-toteuma) #(swap! lomake-toteuma assoc :reitti %))}) {:otsikko "Lisätieto" :nimi :lisatieto :pituus-max 256 :tyyppi :text :uusi-rivi? true :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :koko [80 :auto] :palstoja 2}] @lomake-toteuma] (when-not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) oikeudet/ilmoitus-ei-oikeutta-muokata-toteumaa)])))) (defn yksiloidyt-tehtavat [rivi tehtavien-summat] (let [urakka-id (:id @nav/valittu-urakka) [sopimus-id _] @u/valittu-sopimusnumero aikavali [(first @u/valittu-aikavali) (second @u/valittu-aikavali)] toteutuneet-tehtavat (atom nil) tallenna (reaction (if (or (not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka))) (nil? @toteutuneet-tehtavat) (every? :jarjestelmanlisaama @toteutuneet-tehtavat)) :ei-mahdollinen #(go (let [vastaus (<! (toteumat/paivita-yk-hint-toteumien-tehtavat urakka-id sopimus-id aikavali :yksikkohintainen % (:tpi_id @u/valittu-toimenpideinstanssi)))] (log "Tehtävät tallennettu: " (pr-str vastaus)) (reset! toteutuneet-tehtavat (:tehtavat vastaus)) (reset! tehtavien-summat (:tehtavien-summat vastaus))))))] (go (reset! toteutuneet-tehtavat (<! (toteumat/hae-urakan-toteutuneet-tehtavat-toimenpidekoodilla urakka-id sopimus-id aikavali :yksikkohintainen (:tpk_id rivi))))) (fn [toteuma-rivi] [:div [grid/grid {:otsikko (str "Yksilöidyt tehtävät: " (:nimi toteuma-rivi)) :tyhja (if (nil? @toteutuneet-tehtavat) [ajax-loader "Haetaan..."] "Toteumia ei löydy") :tallenna @tallenna :voi-lisata? false :esta-poistaminen? (fn [rivi] (:jarjestelmanlisaama rivi)) :esta-poistaminen-tooltip (fn [_] "Järjestelmän lisäämää kohdetta ei voi poistaa.") :max-rivimaara 300 :max-rivimaaran-ylitys-viesti "Liikaa hakutuloksia, rajaa hakua" :tunniste :tehtava_id} [{:otsikko "Päivämäärä" :nimi :alkanut :muokattava? (constantly false) :tyyppi :pvm :hae (comp pvm/pvm :alkanut) :leveys 12} {:otsikko "Määrä" :nimi :maara :validoi [[:ei-tyhja "Anna määrä"]] :muokattava? (fn [rivi] (not (:jarjestelmanlisaama rivi))) :tyyppi :positiivinen-numero :leveys 15 :tasaa :oikea :fmt fmt/desimaaliluku-opt} {:otsikko "Suorittaja" :nimi :suorittajan_nimi :muokattava? (constantly false) :tyyppi :string :leveys 20} {:otsikko "TR-osoite" :nimi :tr :leveys 20 :fmt tierekisteri/tierekisteriosoite-tekstina :tyyppi :tierekisteriosoite :muokattava? (constantly false)} {:otsikko "Lisätieto" :nimi :lisatieto :muokattava? (constantly false) :tyyppi :string :leveys 20} {:otsikko "Tarkastele koko toteumaa" :nimi :tarkastele-toteumaa :muokattava? (constantly false) :tyyppi :komponentti :leveys 20 :komponentti (fn [rivi] [:button.nappi-toissijainen.nappi-grid {:on-click #(nayta-toteuma-lomakkeessa @nav/valittu-urakka-id (:toteuma_id rivi))} (ikonit/eye-open) " Toteuma"])}] (when-let [toteutuneet-tehtavat @toteutuneet-tehtavat] (sort-by :alkanut t/after? toteutuneet-tehtavat))]]))) (defn- aikavali-joka-vaihtuu-hoitokaudesta ([valittu-aikavali-atom] (aikavali-joka-vaihtuu-hoitokaudesta valittu-aikavali-atom nil)) ([valittu-aikavali-atom {:keys [nayta-otsikko? aikavalin-rajoitus aloitusaika-pakota-suunta paattymisaika-pakota-suunta lomake?]}] [:span {:class (if lomake? "label-ja-aikavali-lomake" "label-ja-aikavali")} (when (and (not lomake?) (or (nil? nayta-otsikko?) (true? nayta-otsikko?))) [:span.alasvedon-otsikko "Aikaväli"]) [:div.aikavali-valinnat [tee-kentta {:tyyppi :pvm :pakota-suunta aloitusaika-pakota-suunta} (r/wrap (first @valittu-aikavali-atom) (fn [uusi-arvo] (let [uusi-arvo (pvm/paivan-alussa-opt uusi-arvo)] (if-not aikavalin-rajoitus (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [uusi-arvo (second %)] :alku)) (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [uusi-arvo (second %)] aikavalin-rajoitus :alku)))) (log "Uusi aikaväli: " (pr-str @valittu-aikavali-atom))))] [:div.pvm-valiviiva-wrap [:span.pvm-valiviiva " \u2014 "]] [tee-kentta {:tyyppi :pvm :pakota-suunta paattymisaika-pakota-suunta} (r/wrap (second @valittu-aikavali-atom) (fn [uusi-arvo] (let [uusi-arvo (pvm/paivan-lopussa-opt uusi-arvo)] (if-not aikavalin-rajoitus (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [(first %) uusi-arvo] :loppu)) (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [(first %) uusi-arvo] aikavalin-rajoitus :loppu)))) (log "Uusi aikaväli: " (pr-str @valittu-aikavali-atom))))]]])) (defn yksikkohintaisten-toteumalistaus "Yksikköhintaisten töiden toteumat tehtävittäin" [] (komp/luo (fn [] [:div [valinnat/urakan-sopimus @nav/valittu-urakka] [valinnat/urakan-hoitokausi @nav/valittu-urakka] [valinnat/urakan-toimenpide+kaikki @nav/valittu-urakka] [aikavali-joka-vaihtuu-hoitokaudesta u/yksikkohintaiset-aikavali] [valinnat/urakan-yksikkohintainen-tehtava+kaikki] (let [oikeus? (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka))] (yleiset/wrap-if (not oikeus?) [yleiset/tooltip {} :% (oikeudet/oikeuden-puute-kuvaus :kirjoitus oikeudet/urakat-toteumat-yksikkohintaisettyot)] [napit/uusi "Lisää toteuma" #(reset! tiedot/valittu-yksikkohintainen-toteuma (tiedot/uusi-yksikkohintainen-toteuma)) {:disabled (not oikeus?)}])) [grid/grid {:otsikko (str "Yksikköhintaisten töiden toteumat") :tunniste :tpk_id :tyhja (if (nil? @tiedot/yks-hint-tyot-tehtavittain) [ajax-loader "Haetaan yksikköhintaisten töiden toteumia..."] "Ei yksikköhintaisten töiden toteumia") :luokat ["toteumat-paasisalto"] :vetolaatikot (into {} (map (juxt :tpk_id (fn [rivi] [yksiloidyt-tehtavat rivi tiedot/yks-hint-tehtavien-summat])) @tiedot/yks-hint-tyot-tehtavittain))} [{:tyyppi :vetolaatikon-tila :leveys 5} {:otsikko "Tehtävä" :nimi :nimi :muokattava? (constantly false) :tyyppi :string :leveys 25} {:otsikko "Yksikkö" :nimi :yksikko :muokattava? (constantly false) :tyyppi :string :leveys 10} {:otsikko "Yksikkö\u00ADhinta" :nimi :yksikkohinta :muokattava? (constantly false) :tyyppi :numero :leveys 10 :tasaa :oikea :fmt fmt/euro-opt} {:otsikko "Suunni\u00ADteltu määrä" :nimi :hoitokauden-suunniteltu-maara :muokattava? (constantly false) :tyyppi :numero :leveys 10 :fmt #(fmt/pyorista-ehka-kolmeen %) :tasaa :oikea} {:otsikko "Toteutu\u00ADnut määrä" :nimi :maara :muokattava? (constantly false) :tyyppi :numero :leveys 10 :fmt #(fmt/pyorista-ehka-kolmeen %) :tasaa :oikea} {:otsikko "Suunni\u00ADtellut kustan\u00ADnukset" :nimi :hoitokauden-suunnitellut-kustannukset :fmt fmt/euro-opt :tasaa :oikea :muokattava? (constantly false) :tyyppi :numero :leveys 10} {:otsikko "Toteutu\u00ADneet kustan\u00ADnukset" :nimi :hoitokauden-toteutuneet-kustannukset :fmt fmt/euro-opt :tasaa :oikea :muokattava? (constantly false) :tyyppi :numero :leveys 10} {:otsikko "Budjettia jäljellä" :nimi :kustannuserotus :muokattava? (constantly false) :tyyppi :komponentti :tasaa :oikea :komponentti (fn [rivi] (if (>= (:kustannuserotus rivi) 0) [:span.kustannuserotus.kustannuserotus-positiivinen (fmt/euro-opt (:kustannuserotus rivi))] [:span.kustannuserotus.kustannuserotus-negatiivinen (fmt/euro-opt (:kustannuserotus rivi))])) :leveys 10}] @tiedot/yks-hint-tyot-tehtavittain]]))) (defn yksikkohintaisten-toteumat [] (komp/luo (komp/lippu tiedot/yksikkohintaiset-tyot-nakymassa? tiedot/karttataso-yksikkohintainen-toteuma) (komp/sisaan-ulos #(do (kartta-tiedot/kasittele-infopaneelin-linkit! {:toteuma {:toiminto (fn [{id :id :as klikattu-toteuma}] (nayta-toteuma-lomakkeessa @nav/valittu-urakka-id id)) :teksti "Valitse toteuma"}})) #(kartta-tiedot/kasittele-infopaneelin-linkit! nil)) (fn [] [:span [kartta/kartan-paikka] (if @tiedot/valittu-yksikkohintainen-toteuma [yksikkohintainen-toteumalomake] [yksikkohintaisten-toteumalistaus])])))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/d2c3efc456f459e72943c97c369d5391b57f5536/src/cljs/harja/views/urakka/toteumat/yksikkohintaiset_tyot.cljs
clojure
(ns harja.views.urakka.toteumat.yksikkohintaiset-tyot "Urakan 'Toteumat' välilehden Yksikköhintaist työt osio" (:require [reagent.core :refer [atom]] [harja.ui.grid :as grid] [harja.ui.grid.gridin-muokkaus :as gridin-muokkaus] [harja.ui.ikonit :as ikonit] [harja.ui.yleiset :refer [ajax-loader linkki livi-pudotusvalikko]] [harja.ui.viesti :as viesti] [harja.ui.komponentti :as komp] [harja.tiedot.navigaatio :as nav] [harja.tiedot.urakka :as u] [harja.tiedot.urakka.toteumat :as toteumat] [harja.views.urakka.valinnat :as valinnat] [harja.pvm :as pvm] [harja.ui.lomake :refer [lomake]] [harja.loki :refer [log logt tarkkaile!]] [cljs.core.async :refer [<! >! chan]] [harja.ui.protokollat :refer [Haku hae]] [harja.domain.skeema :refer [+tyotyypit+]] [harja.fmt :as fmt] [harja.tiedot.urakka.urakan-toimenpiteet :as urakan-toimenpiteet] [harja.tiedot.urakka.toteumat.yksikkohintaiset-tyot :as tiedot] [harja.views.kartta :as kartta] [harja.tiedot.kartta :as kartta-tiedot] [harja.asiakas.kommunikaatio :as k] [harja.tiedot.urakka :as u] [harja.ui.napit :as napit] [cljs-time.core :as t] [reagent.core :as r] [harja.domain.oikeudet :as oikeudet] [harja.ui.yleiset :as yleiset] [harja.ui.valinnat :as ui-valinnat] [harja.ui.kentat :refer [tee-kentta]] [harja.domain.tierekisteri :as tierekisteri]) (:require-macros [cljs.core.async.macros :refer [go]] [reagent.ratom :refer [reaction run!]])) (defn- rivi-tehtavaksi [rivi] {:toimenpidekoodi (:tehtava rivi) :maara (:maara rivi) :tehtava-id (:tehtava-id rivi) :poistettu (:poistettu rivi)}) (defn- lomakkeen-toteuma-lahetettavaksi [lomakkeen-toteuma lomakkeen-tehtavat] (assoc lomakkeen-toteuma :tyyppi :yksikkohintainen :urakka-id (:id @nav/valittu-urakka) :sopimus-id (first @u/valittu-sopimusnumero) :tehtavat (mapv rivi-tehtavaksi (gridin-muokkaus/filteroi-uudet-poistetut lomakkeen-tehtavat)) :toimenpide-id (:tpi_id @u/valittu-toimenpideinstanssi) :hoitokausi-aloituspvm (first @u/valittu-hoitokausi) :hoitokausi-lopetuspvm (second @u/valittu-hoitokausi))) (defn nayta-toteuma-lomakkeessa [urakka-id toteuma-id] (go (let [toteuma (<! (toteumat/hae-urakan-toteuma urakka-id toteuma-id))] (log "toteuma: " (pr-str toteuma)) (if-not (k/virhe? toteuma) (let [lomake-tiedot {:toteuma-id (:id toteuma) :tehtavat (zipmap (iterate inc 1) (mapv (fn [tehtava] (let [[_ _ emo tehtava-urakassa] (urakan-toimenpiteet/tehtava-urakassa (:tpk-id tehtava) @u/urakan-toimenpiteet-ja-tehtavat) tpi (some #(when (= (:t3_koodi %) (:koodi emo)) %) @u/urakan-toimenpideinstanssit)] (log "Tehtava urakassa: " (pr-str tehtava-urakassa)) (log "Toteuman 4. tason tehtävän 3. tason emo selvitetty: " (pr-str emo)) (log "Toteuman 4. tason tehtävän toimenpideinstanssi selvitetty: " (pr-str tpi)) {:tehtava {:id (:tpk-id tehtava)} :maara (:maara tehtava) :tehtava-id (:tehtava-id tehtava) :toimenpideinstanssi (:tpi_id tpi) :yksikko (:yksikko tehtava-urakassa)})) (:tehtavat toteuma))) :alkanut (:alkanut toteuma) :reitti (:reitti toteuma) :tr (:tr toteuma) :paattynyt (:paattynyt toteuma) :lisatieto (:lisatieto toteuma) :suorittajan-nimi (:nimi (:suorittaja toteuma)) :suorittajan-ytunnus (:ytunnus (:suorittaja toteuma)) :jarjestelman-lisaama (:jarjestelmanlisaama toteuma) :luoja (:kayttajanimi toteuma) :organisaatio (:organisaatio toteuma)}] (nav/aseta-valittu-valilehti! :urakat :toteumat) (nav/aseta-valittu-valilehti! :toteumat :yksikkohintaiset-tyot) (reset! tiedot/valittu-yksikkohintainen-toteuma lomake-tiedot)))))) (defn tallenna-toteuma "Ottaa lomakkeen ja tehtävät siinä muodossa kuin ne ovat lomake-komponentissa ja muodostaa palvelimelle lähetettävän payloadin." [lomakkeen-toteuma lomakkeen-tehtavat] (let [lahetettava-toteuma (lomakkeen-toteuma-lahetettavaksi lomakkeen-toteuma lomakkeen-tehtavat)] (log "Tallennetaan toteuma: " (pr-str lahetettava-toteuma)) (toteumat/tallenna-toteuma-ja-yksikkohintaiset-tehtavat lahetettava-toteuma))) (defn- nelostason-tehtava [tehtava] (nth tehtava 3)) (defn- tehtavan-tiedot [tehtava urakan-hoitokauden-yks-hint-tyot] (first (filter (fn [tiedot] (= (:tehtavan_id tiedot) (:id (nelostason-tehtava tehtava)))) urakan-hoitokauden-yks-hint-tyot))) (defn- tyo-hoitokaudella? [tyo] (pvm/sama-pvm? (:alkupvm tyo) (first @u/valittu-hoitokausi))) (defn- valintakasittelija [vain-suunnitellut? t] (let [urakan-tpi-tehtavat (urakan-toimenpiteet/toimenpideinstanssin-tehtavat (:toimenpideinstanssi t) @u/urakan-toimenpideinstanssit @u/urakan-toimenpiteet-ja-tehtavat) urakan-hoitokauden-yks-hint-tyot (filter tyo-hoitokaudella? @u/urakan-yks-hint-tyot) suunnitellut-tehtavat (filter (fn [tehtava] (> (:yksikkohinta (tehtavan-tiedot tehtava urakan-hoitokauden-yks-hint-tyot)) 0)) urakan-tpi-tehtavat)] (sort-by #(:nimi (get % 3)) (if vain-suunnitellut? suunnitellut-tehtavat urakan-tpi-tehtavat)))) (defn tehtavat-ja-maarat [tehtavat jarjestelman-lisaama-toteuma? tehtavat-virheet] (let [nelostason-tehtavat (map nelostason-tehtava @u/urakan-toimenpiteet-ja-tehtavat) toimenpideinstanssit @u/urakan-toimenpideinstanssit voi-muokata? (not jarjestelman-lisaama-toteuma?)] [grid/muokkaus-grid {:tyhja "Ei töitä." :voi-muokata? voi-muokata? :muutos #(reset! tehtavat-virheet (grid/hae-virheet %))} [{:otsikko "Toimenpide" :nimi :toimenpideinstanssi :tyyppi :valinta :fmt #(:tpi_nimi (urakan-toimenpiteet/toimenpideinstanssi-idlla % toimenpideinstanssit)) :valinta-arvo :tpi_id :valinta-nayta #(if % (:tpi_nimi %) "- Valitse toimenpide -") :valinnat toimenpideinstanssit :leveys 30 :validoi [[:ei-tyhja "Valitse työ"]] :aseta #(assoc %1 :toimenpideinstanssi %2 :tehtava nil)} {:otsikko "Tehtävä" :nimi :tehtava :tyyppi :valinta :valinta-arvo #(:id (nth % 3)) :valinta-nayta #(if % (:nimi (nth % 3)) "- Valitse tehtävä -") :valinnat-fn (partial valintakasittelija voi-muokata?) :leveys 45 :jos-tyhja "Toimenpiteelle ei ole suunniteltu yhtään tehtävää." :validoi [[:ei-tyhja "Valitse tehtävä"]] :aseta (fn [rivi arvo] (assoc rivi :tehtava arvo :yksikko (:yksikko (urakan-toimenpiteet/tehtava-idlla arvo nelostason-tehtavat))))} {:otsikko "Määrä" :nimi :maara :tyyppi :positiivinen-numero :leveys 25 :validoi [[:ei-tyhja "Anna määrä"]] :tasaa :oikea} {:otsikko "Yks." :nimi :yksikko :tyyppi :string :muokattava? (constantly false) :leveys 15}] tehtavat])) (defn yksikkohintainen-toteumalomake "Valmiin kohteen tietoja tarkasteltaessa tiedot annetaan valittu-yksikkohintainen-toteuma atomille. Lomakkeen käsittelyn ajaksi tiedot haetaan tästä atomista kahteen eri atomiin käsittelyn ajaksi: yksikköhintaiset tehtävät ovat omassa ja muut tiedot omassa atomissa. Kun lomake tallennetaan, tiedot yhdistetään näistä atomeista yhdeksi kokonaisuudeksi." [] (let [lomake-toteuma (atom @tiedot/valittu-yksikkohintainen-toteuma) lomake-tehtavat (atom (into {} (map (fn [[id tehtava]] [id (assoc tehtava :tehtava (:id (:tehtava tehtava)))]) (:tehtavat @tiedot/valittu-yksikkohintainen-toteuma)))) tehtavat-virheet (atom nil) jarjestelman-lisaama-toteuma? (true? (:jarjestelman-lisaama @lomake-toteuma)) valmis-tallennettavaksi? (reaction (and (not jarjestelman-lisaama-toteuma?) (not (nil? (:alkanut @lomake-toteuma))) (not (nil? (:paattynyt @lomake-toteuma))) (not (pvm/ennen? (:paattynyt @lomake-toteuma) (:alkanut @lomake-toteuma))) (not (empty? (filter #(not (true? (:poistettu %))) (vals @lomake-tehtavat)))) (empty? @tehtavat-virheet)))] (log "Lomake-toteuma: " (pr-str @lomake-toteuma)) (log "Lomake tehtävät: " (pr-str @lomake-tehtavat)) (komp/luo (fn [ur] [:div.toteuman-tiedot [napit/takaisin "Takaisin toteumaluetteloon" #(reset! tiedot/valittu-yksikkohintainen-toteuma nil)] [lomake {:otsikko (if (:toteuma-id @tiedot/valittu-yksikkohintainen-toteuma) (if jarjestelman-lisaama-toteuma? "Tarkastele toteumaa" "Muokkaa toteumaa") "Luo uusi toteuma") :voi-muokata? (and (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) (not jarjestelman-lisaama-toteuma?)) :muokkaa! (fn [uusi] (log "Muokataan toteumaa: " (pr-str uusi)) (reset! lomake-toteuma uusi)) :footer (when (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) [harja.ui.napit/palvelinkutsu-nappi "Tallenna toteuma" #(tallenna-toteuma @lomake-toteuma @lomake-tehtavat) {:luokka "nappi-ensisijainen" :disabled (or (false? @valmis-tallennettavaksi?) (not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)))) :kun-onnistuu (fn [vastaus] (log "Tehtävät tallennettu, vastaus: " (pr-str vastaus)) (reset! tiedot/yks-hint-tehtavien-summat (:tehtavien-summat vastaus)) (reset! lomake-tehtavat nil) (reset! lomake-toteuma nil) (reset! tiedot/valittu-yksikkohintainen-toteuma nil))}])} [(when jarjestelman-lisaama-toteuma? {:otsikko "Lähde" :nimi :luoja :tyyppi :string :hae (fn [rivi] (str "Järjestelmä (" (:luoja rivi) " / " (:organisaatio rivi) ")")) :muokattava? (constantly false) :vihje toteumat/ilmoitus-jarjestelman-luoma-toteuma}) {:otsikko "Sopimus" :nimi :sopimus :hae (fn [_] (second @u/valittu-sopimusnumero)) :muokattava? (constantly false)} {:otsikko "Aloitus" :nimi :alkanut :pakollinen? true :tyyppi :pvm :uusi-rivi? true :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :aseta (fn [rivi arvo] (assoc rivi :alkanut arvo :paattynyt arvo)) :validoi [[:ei-tyhja "Valitse päivämäärä"]] :huomauta [[:urakan-aikana-ja-hoitokaudella]]} {:otsikko "Lopetus" :nimi :paattynyt :pakollinen? true :tyyppi :pvm :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :validoi [[:ei-tyhja "Valitse päivämäärä"] [:pvm-kentan-jalkeen :alkanut "Lopetuksen pitää olla aloituksen jälkeen"]]} {:otsikko "Suorittaja" :nimi :suorittajan-nimi :pituus-max 256 :tyyppi :string :muokattava? (constantly (not jarjestelman-lisaama-toteuma?))} {:otsikko "Suorittajan Y-tunnus" :nimi :suorittajan-ytunnus :pituus-max 256 :tyyppi :string :muokattava? (constantly (not jarjestelman-lisaama-toteuma?))} {:otsikko "Tehtävät" :nimi :tehtavat :pakollinen? true :uusi-rivi? true :palstoja 2 :tyyppi :komponentti :vihje "Voit syöttää toteumia tehtäville, joille on syötetty hinta yksikköhintaisten töiden suunnitteluosiossa." :komponentti (fn [_] [tehtavat-ja-maarat lomake-tehtavat jarjestelman-lisaama-toteuma? tehtavat-virheet])} (when-not jarjestelman-lisaama-toteuma? {:tyyppi :tierekisteriosoite :nimi :tr :pakollinen? false :sijainti (r/wrap (:reitti @lomake-toteuma) #(swap! lomake-toteuma assoc :reitti %))}) {:otsikko "Lisätieto" :nimi :lisatieto :pituus-max 256 :tyyppi :text :uusi-rivi? true :muokattava? (constantly (not jarjestelman-lisaama-toteuma?)) :koko [80 :auto] :palstoja 2}] @lomake-toteuma] (when-not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka)) oikeudet/ilmoitus-ei-oikeutta-muokata-toteumaa)])))) (defn yksiloidyt-tehtavat [rivi tehtavien-summat] (let [urakka-id (:id @nav/valittu-urakka) [sopimus-id _] @u/valittu-sopimusnumero aikavali [(first @u/valittu-aikavali) (second @u/valittu-aikavali)] toteutuneet-tehtavat (atom nil) tallenna (reaction (if (or (not (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka))) (nil? @toteutuneet-tehtavat) (every? :jarjestelmanlisaama @toteutuneet-tehtavat)) :ei-mahdollinen #(go (let [vastaus (<! (toteumat/paivita-yk-hint-toteumien-tehtavat urakka-id sopimus-id aikavali :yksikkohintainen % (:tpi_id @u/valittu-toimenpideinstanssi)))] (log "Tehtävät tallennettu: " (pr-str vastaus)) (reset! toteutuneet-tehtavat (:tehtavat vastaus)) (reset! tehtavien-summat (:tehtavien-summat vastaus))))))] (go (reset! toteutuneet-tehtavat (<! (toteumat/hae-urakan-toteutuneet-tehtavat-toimenpidekoodilla urakka-id sopimus-id aikavali :yksikkohintainen (:tpk_id rivi))))) (fn [toteuma-rivi] [:div [grid/grid {:otsikko (str "Yksilöidyt tehtävät: " (:nimi toteuma-rivi)) :tyhja (if (nil? @toteutuneet-tehtavat) [ajax-loader "Haetaan..."] "Toteumia ei löydy") :tallenna @tallenna :voi-lisata? false :esta-poistaminen? (fn [rivi] (:jarjestelmanlisaama rivi)) :esta-poistaminen-tooltip (fn [_] "Järjestelmän lisäämää kohdetta ei voi poistaa.") :max-rivimaara 300 :max-rivimaaran-ylitys-viesti "Liikaa hakutuloksia, rajaa hakua" :tunniste :tehtava_id} [{:otsikko "Päivämäärä" :nimi :alkanut :muokattava? (constantly false) :tyyppi :pvm :hae (comp pvm/pvm :alkanut) :leveys 12} {:otsikko "Määrä" :nimi :maara :validoi [[:ei-tyhja "Anna määrä"]] :muokattava? (fn [rivi] (not (:jarjestelmanlisaama rivi))) :tyyppi :positiivinen-numero :leveys 15 :tasaa :oikea :fmt fmt/desimaaliluku-opt} {:otsikko "Suorittaja" :nimi :suorittajan_nimi :muokattava? (constantly false) :tyyppi :string :leveys 20} {:otsikko "TR-osoite" :nimi :tr :leveys 20 :fmt tierekisteri/tierekisteriosoite-tekstina :tyyppi :tierekisteriosoite :muokattava? (constantly false)} {:otsikko "Lisätieto" :nimi :lisatieto :muokattava? (constantly false) :tyyppi :string :leveys 20} {:otsikko "Tarkastele koko toteumaa" :nimi :tarkastele-toteumaa :muokattava? (constantly false) :tyyppi :komponentti :leveys 20 :komponentti (fn [rivi] [:button.nappi-toissijainen.nappi-grid {:on-click #(nayta-toteuma-lomakkeessa @nav/valittu-urakka-id (:toteuma_id rivi))} (ikonit/eye-open) " Toteuma"])}] (when-let [toteutuneet-tehtavat @toteutuneet-tehtavat] (sort-by :alkanut t/after? toteutuneet-tehtavat))]]))) (defn- aikavali-joka-vaihtuu-hoitokaudesta ([valittu-aikavali-atom] (aikavali-joka-vaihtuu-hoitokaudesta valittu-aikavali-atom nil)) ([valittu-aikavali-atom {:keys [nayta-otsikko? aikavalin-rajoitus aloitusaika-pakota-suunta paattymisaika-pakota-suunta lomake?]}] [:span {:class (if lomake? "label-ja-aikavali-lomake" "label-ja-aikavali")} (when (and (not lomake?) (or (nil? nayta-otsikko?) (true? nayta-otsikko?))) [:span.alasvedon-otsikko "Aikaväli"]) [:div.aikavali-valinnat [tee-kentta {:tyyppi :pvm :pakota-suunta aloitusaika-pakota-suunta} (r/wrap (first @valittu-aikavali-atom) (fn [uusi-arvo] (let [uusi-arvo (pvm/paivan-alussa-opt uusi-arvo)] (if-not aikavalin-rajoitus (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [uusi-arvo (second %)] :alku)) (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [uusi-arvo (second %)] aikavalin-rajoitus :alku)))) (log "Uusi aikaväli: " (pr-str @valittu-aikavali-atom))))] [:div.pvm-valiviiva-wrap [:span.pvm-valiviiva " \u2014 "]] [tee-kentta {:tyyppi :pvm :pakota-suunta paattymisaika-pakota-suunta} (r/wrap (second @valittu-aikavali-atom) (fn [uusi-arvo] (let [uusi-arvo (pvm/paivan-lopussa-opt uusi-arvo)] (if-not aikavalin-rajoitus (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [(first %) uusi-arvo] :loppu)) (swap! valittu-aikavali-atom #(pvm/varmista-aikavali-opt [(first %) uusi-arvo] aikavalin-rajoitus :loppu)))) (log "Uusi aikaväli: " (pr-str @valittu-aikavali-atom))))]]])) (defn yksikkohintaisten-toteumalistaus "Yksikköhintaisten töiden toteumat tehtävittäin" [] (komp/luo (fn [] [:div [valinnat/urakan-sopimus @nav/valittu-urakka] [valinnat/urakan-hoitokausi @nav/valittu-urakka] [valinnat/urakan-toimenpide+kaikki @nav/valittu-urakka] [aikavali-joka-vaihtuu-hoitokaudesta u/yksikkohintaiset-aikavali] [valinnat/urakan-yksikkohintainen-tehtava+kaikki] (let [oikeus? (oikeudet/voi-kirjoittaa? oikeudet/urakat-toteumat-yksikkohintaisettyot (:id @nav/valittu-urakka))] (yleiset/wrap-if (not oikeus?) [yleiset/tooltip {} :% (oikeudet/oikeuden-puute-kuvaus :kirjoitus oikeudet/urakat-toteumat-yksikkohintaisettyot)] [napit/uusi "Lisää toteuma" #(reset! tiedot/valittu-yksikkohintainen-toteuma (tiedot/uusi-yksikkohintainen-toteuma)) {:disabled (not oikeus?)}])) [grid/grid {:otsikko (str "Yksikköhintaisten töiden toteumat") :tunniste :tpk_id :tyhja (if (nil? @tiedot/yks-hint-tyot-tehtavittain) [ajax-loader "Haetaan yksikköhintaisten töiden toteumia..."] "Ei yksikköhintaisten töiden toteumia") :luokat ["toteumat-paasisalto"] :vetolaatikot (into {} (map (juxt :tpk_id (fn [rivi] [yksiloidyt-tehtavat rivi tiedot/yks-hint-tehtavien-summat])) @tiedot/yks-hint-tyot-tehtavittain))} [{:tyyppi :vetolaatikon-tila :leveys 5} {:otsikko "Tehtävä" :nimi :nimi :muokattava? (constantly false) :tyyppi :string :leveys 25} {:otsikko "Yksikkö" :nimi :yksikko :muokattava? (constantly false) :tyyppi :string :leveys 10} {:otsikko "Yksikkö\u00ADhinta" :nimi :yksikkohinta :muokattava? (constantly false) :tyyppi :numero :leveys 10 :tasaa :oikea :fmt fmt/euro-opt} {:otsikko "Suunni\u00ADteltu määrä" :nimi :hoitokauden-suunniteltu-maara :muokattava? (constantly false) :tyyppi :numero :leveys 10 :fmt #(fmt/pyorista-ehka-kolmeen %) :tasaa :oikea} {:otsikko "Toteutu\u00ADnut määrä" :nimi :maara :muokattava? (constantly false) :tyyppi :numero :leveys 10 :fmt #(fmt/pyorista-ehka-kolmeen %) :tasaa :oikea} {:otsikko "Suunni\u00ADtellut kustan\u00ADnukset" :nimi :hoitokauden-suunnitellut-kustannukset :fmt fmt/euro-opt :tasaa :oikea :muokattava? (constantly false) :tyyppi :numero :leveys 10} {:otsikko "Toteutu\u00ADneet kustan\u00ADnukset" :nimi :hoitokauden-toteutuneet-kustannukset :fmt fmt/euro-opt :tasaa :oikea :muokattava? (constantly false) :tyyppi :numero :leveys 10} {:otsikko "Budjettia jäljellä" :nimi :kustannuserotus :muokattava? (constantly false) :tyyppi :komponentti :tasaa :oikea :komponentti (fn [rivi] (if (>= (:kustannuserotus rivi) 0) [:span.kustannuserotus.kustannuserotus-positiivinen (fmt/euro-opt (:kustannuserotus rivi))] [:span.kustannuserotus.kustannuserotus-negatiivinen (fmt/euro-opt (:kustannuserotus rivi))])) :leveys 10}] @tiedot/yks-hint-tyot-tehtavittain]]))) (defn yksikkohintaisten-toteumat [] (komp/luo (komp/lippu tiedot/yksikkohintaiset-tyot-nakymassa? tiedot/karttataso-yksikkohintainen-toteuma) (komp/sisaan-ulos #(do (kartta-tiedot/kasittele-infopaneelin-linkit! {:toteuma {:toiminto (fn [{id :id :as klikattu-toteuma}] (nayta-toteuma-lomakkeessa @nav/valittu-urakka-id id)) :teksti "Valitse toteuma"}})) #(kartta-tiedot/kasittele-infopaneelin-linkit! nil)) (fn [] [:span [kartta/kartan-paikka] (if @tiedot/valittu-yksikkohintainen-toteuma [yksikkohintainen-toteumalomake] [yksikkohintaisten-toteumalistaus])])))
7c1e7945215d3dbac3d3169f36a81b6715823bf3c0d5faaff7bfb236ca8b6a00
fpco/schoolofhaskell.com
Exception.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # {-# LANGUAGE RankNTypes #-} module Azure.BlobStorage.Exception where import Azure.BlobStorage.Request import Azure.BlobStorage.Types import Azure.BlobStorage.Util import Control.Exception import Control.Monad.Reader hiding (forM) import Control.Monad.Trans.Resource import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Encoding (decodeUtf8) import Network.HTTP.Conduit import Network.HTTP.Types import Text.XML as XML import Text.XML.Cursor ((&/), ($/), element) import qualified Text.XML.Cursor as Cursor import Prelude checkErrorCode :: MonadThrow m => ByteString -> CheckStatus m checkErrorCode = checkXmlErrorCode . checkErrorCode' checkErrorCode' :: MonadThrow m => ByteString -> Int -> Text -> Cursor.Cursor -> m () checkErrorCode' sig status code cursor = do let whenStatus s c = when (status == s && code == c) whenStatus 404 "BlobNotFound" $ throwM BlobNotFound whenStatus 404 "ContainerNotFound" $ throwM ContainerNotFound whenStatus 409 "ContainerAlreadyExists" $ throwM ContainerAlreadyExists whenStatus 403 "AuthenticationFailed" $ do case cursor $/ element "AuthenticationErrorDetail" &/ Cursor.content of [d] -> do let msig = Text.stripPrefix "The MAC signature found in the HTTP request '" d >>= return . snd . Text.break (== '\'') >>= Text.stripPrefix "' is not the same as any computed signature. Server used following string to sign: '" >>= return . fst . Text.break (== '\'') case msig of Nothing -> return () Just (unescapeText -> serverSig) -> let clientSig = decodeUtf8 sig in if clientSig == serverSig then throwM AccountKeyWrong else throwM $ SignatureMismatch { ours = clientSig , theirs = serverSig } _ -> return () checkXmlErrorCode :: MonadThrow m => (Int -> Text -> Cursor.Cursor -> m ()) -> CheckStatus m checkXmlErrorCode f res consumeBody = do Parse the XML exceptions from error codes . This intentionally omits handling of 400 ( bad request ) errors , as the error contents likely is n't the XML format we expect ( e.g. HTML instead ) . when (code > 400) $ do body <- consumeBody let invalidXml err = throwM $ InvalidErrorXml err $ case mfallback >>= fromException of Nothing -> Nothing Just (StatusCodeException s hs cj) -> let hs' = ("X-Response-Body-Start", BS.take 1024 body) : hs in Just $ StatusCodeException s hs' cj Just ex -> Just ex case XML.parseLBS def (LBS.fromChunks [body]) of Right (element "Error" . Cursor.fromDocument -> [cursor]) -> do case cursor $/ element "Code" &/ Cursor.content of [errorCode] -> f code errorCode cursor _ -> invalidXml "Expected <Code> element inside <Error>" Right _ -> invalidXml "Expected <Error> element" Left err -> invalidXml (Text.pack (show err)) Fallback on the default status checking from the default request . maybe (return ()) throwM mfallback where code = statusCode (responseStatus res) mfallback = checkStatus def (responseStatus res) (responseHeaders res) (responseCookieJar res) -- | Throw an exception if the status doesn't indicate the blob was -- successfully created. checkCreated :: MonadThrow m => ByteString -> CheckStatus m checkCreated sig res consumeBody = if responseStatus res == Status 201 "Created" then return () else do checkErrorCode sig res consumeBody throwM BlobNotCreated
null
https://raw.githubusercontent.com/fpco/schoolofhaskell.com/15ec1a03cb9d593ee9c0d167dc522afe45ba4f8e/src/Azure/BlobStorage/Exception.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # | Throw an exception if the status doesn't indicate the blob was successfully created.
# LANGUAGE ViewPatterns # module Azure.BlobStorage.Exception where import Azure.BlobStorage.Request import Azure.BlobStorage.Types import Azure.BlobStorage.Util import Control.Exception import Control.Monad.Reader hiding (forM) import Control.Monad.Trans.Resource import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Encoding (decodeUtf8) import Network.HTTP.Conduit import Network.HTTP.Types import Text.XML as XML import Text.XML.Cursor ((&/), ($/), element) import qualified Text.XML.Cursor as Cursor import Prelude checkErrorCode :: MonadThrow m => ByteString -> CheckStatus m checkErrorCode = checkXmlErrorCode . checkErrorCode' checkErrorCode' :: MonadThrow m => ByteString -> Int -> Text -> Cursor.Cursor -> m () checkErrorCode' sig status code cursor = do let whenStatus s c = when (status == s && code == c) whenStatus 404 "BlobNotFound" $ throwM BlobNotFound whenStatus 404 "ContainerNotFound" $ throwM ContainerNotFound whenStatus 409 "ContainerAlreadyExists" $ throwM ContainerAlreadyExists whenStatus 403 "AuthenticationFailed" $ do case cursor $/ element "AuthenticationErrorDetail" &/ Cursor.content of [d] -> do let msig = Text.stripPrefix "The MAC signature found in the HTTP request '" d >>= return . snd . Text.break (== '\'') >>= Text.stripPrefix "' is not the same as any computed signature. Server used following string to sign: '" >>= return . fst . Text.break (== '\'') case msig of Nothing -> return () Just (unescapeText -> serverSig) -> let clientSig = decodeUtf8 sig in if clientSig == serverSig then throwM AccountKeyWrong else throwM $ SignatureMismatch { ours = clientSig , theirs = serverSig } _ -> return () checkXmlErrorCode :: MonadThrow m => (Int -> Text -> Cursor.Cursor -> m ()) -> CheckStatus m checkXmlErrorCode f res consumeBody = do Parse the XML exceptions from error codes . This intentionally omits handling of 400 ( bad request ) errors , as the error contents likely is n't the XML format we expect ( e.g. HTML instead ) . when (code > 400) $ do body <- consumeBody let invalidXml err = throwM $ InvalidErrorXml err $ case mfallback >>= fromException of Nothing -> Nothing Just (StatusCodeException s hs cj) -> let hs' = ("X-Response-Body-Start", BS.take 1024 body) : hs in Just $ StatusCodeException s hs' cj Just ex -> Just ex case XML.parseLBS def (LBS.fromChunks [body]) of Right (element "Error" . Cursor.fromDocument -> [cursor]) -> do case cursor $/ element "Code" &/ Cursor.content of [errorCode] -> f code errorCode cursor _ -> invalidXml "Expected <Code> element inside <Error>" Right _ -> invalidXml "Expected <Error> element" Left err -> invalidXml (Text.pack (show err)) Fallback on the default status checking from the default request . maybe (return ()) throwM mfallback where code = statusCode (responseStatus res) mfallback = checkStatus def (responseStatus res) (responseHeaders res) (responseCookieJar res) checkCreated :: MonadThrow m => ByteString -> CheckStatus m checkCreated sig res consumeBody = if responseStatus res == Status 201 "Created" then return () else do checkErrorCode sig res consumeBody throwM BlobNotCreated
8ee7a5a44699b758954b6cc81cc310fea347b4f28f374736b5139080965a6348
johnstonskj/simple-oauth2
main.rkt
#lang racket/base ;; ;; simple-oauth2 - oauth2. ;; Simple OAuth2 client and server implementation ;; Copyright ( c ) 2019 ( ) . ;; Racket Style Guide: -lang.org/style/index.html (require oauth2/private/logging) (provide OAUTH-SPEC-VERSION OAUTH-RFC OAUTH-DISPLAY-NAME (except-out (struct-out client) make-client) (rename-out [create-client make-client]) (struct-out token) (struct-out exn:fail:http) make-exn:fail:http (struct-out exn:fail:oauth2) make-exn:fail:oauth2 exn:fail:oauth2-error-description (all-from-out oauth2/private/logging)) ;; ---------- Requirements (require racket/bool racket/string net/url oauth2/private/http) ;; ---------- Implementation (define OAUTH-SPEC-VERSION 2.0) (define OAUTH-RFC 6749) (define OAUTH-DISPLAY-NAME (format "RFC~a: OAuth ~a (~a)" OAUTH-RFC OAUTH-SPEC-VERSION OAUTH-RFC)) ;; Useful to put this into the log nice and early. (log-oauth2-info "simple-oauth2 package, implementing ~a." OAUTH-DISPLAY-NAME) (define-struct client ;; Using #:prefab to allow these to be serialized using read/write. (service-name authorization-uri token-uri revoke-uri introspect-uri id secret) #:prefab) (define (create-client service-name id secret authorization-uri token-uri #:revoke [revoke-uri #f] #:introspect [introspect-uri #f]) (unless (non-empty-string? service-name) (error "service name must be a non-empty string")) (unless (validate-url authorization-uri) (error "authorization URL is invalid: " authorization-uri)) (unless (validate-url token-uri) (error "token URL is invalid: " token-uri)) (unless (or (false? revoke-uri) (validate-url revoke-uri)) (error "revoke URL is invalid: " revoke-uri)) (unless (or (false? introspect-uri) (validate-url introspect-uri)) (error "introspection URL is invalid: " introspect-uri)) (make-client service-name authorization-uri token-uri (if (string? revoke-uri) revoke-uri #f) (if (string? introspect-uri) introspect-uri #f) id secret)) (define-struct token (access-token type refresh-token audience scopes expires) #:prefab) (struct exn:fail:http exn:fail (code headers body) #:transparent) (define (make-exn:fail:http code message headers body continuations) (exn:fail:http (if (symbol? message) (error-message message) message) continuations (if (symbol? code) (error-code code) code) headers body)) (struct exn:fail:oauth2 exn:fail (error error-uri state) #:transparent) (define (make-exn:fail:oauth2 error error-description error-uri state continuations) (exn:fail:oauth2 error-description continuations error error-uri state)) (define (exn:fail:oauth2-error-description exn) (exn-message exn)) ;; ---------- Internal Procedures (define (validate-url url) (cond [(non-empty-string? url) (define parsed (string->url url)) (and (and (string? (url-scheme parsed)) (string-prefix? (url-scheme parsed) "http")) (non-empty-string? (url-host parsed)) (url-path-absolute? parsed))] [else #f])) ;; ---------- Internal Tests (module+ test (require rackunit) (define valid-url "") (define not-valid-url "this is not a url, honestly") ;; create-client (check-true (client? (create-client "service name" "id" "secret" valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "" "id" "secret" valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" not-valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url not-valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url valid-url #:revoke not-valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url valid-url #:introspect not-valid-url))) ;; validate-url (check-true (validate-url valid-url)) (check-true (validate-url "")) (check-true (validate-url "")) (check-false (validate-url "ftp")) (check-false (validate-url not-valid-url)) (check-false (validate-url "file")) (check-false (validate-url "/path")) (check-false (validate-url "?query")))
null
https://raw.githubusercontent.com/johnstonskj/simple-oauth2/b8cb40511f64dcb274e17957e6fc9ab4c8a6cbea/main.rkt
racket
simple-oauth2 - oauth2. Simple OAuth2 client and server implementation Racket Style Guide: -lang.org/style/index.html ---------- Requirements ---------- Implementation Useful to put this into the log nice and early. Using #:prefab to allow these to be serialized using read/write. ---------- Internal Procedures ---------- Internal Tests create-client validate-url
#lang racket/base Copyright ( c ) 2019 ( ) . (require oauth2/private/logging) (provide OAUTH-SPEC-VERSION OAUTH-RFC OAUTH-DISPLAY-NAME (except-out (struct-out client) make-client) (rename-out [create-client make-client]) (struct-out token) (struct-out exn:fail:http) make-exn:fail:http (struct-out exn:fail:oauth2) make-exn:fail:oauth2 exn:fail:oauth2-error-description (all-from-out oauth2/private/logging)) (require racket/bool racket/string net/url oauth2/private/http) (define OAUTH-SPEC-VERSION 2.0) (define OAUTH-RFC 6749) (define OAUTH-DISPLAY-NAME (format "RFC~a: OAuth ~a (~a)" OAUTH-RFC OAUTH-SPEC-VERSION OAUTH-RFC)) (log-oauth2-info "simple-oauth2 package, implementing ~a." OAUTH-DISPLAY-NAME) (define-struct client (service-name authorization-uri token-uri revoke-uri introspect-uri id secret) #:prefab) (define (create-client service-name id secret authorization-uri token-uri #:revoke [revoke-uri #f] #:introspect [introspect-uri #f]) (unless (non-empty-string? service-name) (error "service name must be a non-empty string")) (unless (validate-url authorization-uri) (error "authorization URL is invalid: " authorization-uri)) (unless (validate-url token-uri) (error "token URL is invalid: " token-uri)) (unless (or (false? revoke-uri) (validate-url revoke-uri)) (error "revoke URL is invalid: " revoke-uri)) (unless (or (false? introspect-uri) (validate-url introspect-uri)) (error "introspection URL is invalid: " introspect-uri)) (make-client service-name authorization-uri token-uri (if (string? revoke-uri) revoke-uri #f) (if (string? introspect-uri) introspect-uri #f) id secret)) (define-struct token (access-token type refresh-token audience scopes expires) #:prefab) (struct exn:fail:http exn:fail (code headers body) #:transparent) (define (make-exn:fail:http code message headers body continuations) (exn:fail:http (if (symbol? message) (error-message message) message) continuations (if (symbol? code) (error-code code) code) headers body)) (struct exn:fail:oauth2 exn:fail (error error-uri state) #:transparent) (define (make-exn:fail:oauth2 error error-description error-uri state continuations) (exn:fail:oauth2 error-description continuations error error-uri state)) (define (exn:fail:oauth2-error-description exn) (exn-message exn)) (define (validate-url url) (cond [(non-empty-string? url) (define parsed (string->url url)) (and (and (string? (url-scheme parsed)) (string-prefix? (url-scheme parsed) "http")) (non-empty-string? (url-host parsed)) (url-path-absolute? parsed))] [else #f])) (module+ test (require rackunit) (define valid-url "") (define not-valid-url "this is not a url, honestly") (check-true (client? (create-client "service name" "id" "secret" valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "" "id" "secret" valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" not-valid-url valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url not-valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url valid-url #:revoke not-valid-url))) (check-exn exn:fail? (λ () (create-client "service name" "id" "secret" valid-url valid-url #:introspect not-valid-url))) (check-true (validate-url valid-url)) (check-true (validate-url "")) (check-true (validate-url "")) (check-false (validate-url "ftp")) (check-false (validate-url not-valid-url)) (check-false (validate-url "file")) (check-false (validate-url "/path")) (check-false (validate-url "?query")))