_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
14e75a8396b4cdc42fc82c3d92d5b7e69eb4f1e5381f27d2ce18a346421dc401
oscaro/clj-gcloud-common
dsl_test.clj
(ns clj-gcloud.dsl-test (:require [clj-gcloud.dsl :as sut] [clojure.test :refer [deftest is]])) (deftest kw->field-name-test (is (= "tableId" (sut/kw->field-name :table-id)))) (deftest kw->enum-str-test (is (= "CREATE_IF_NEEDED" (sut/kw->enum-str :create-if-needed)))) (deftest dsl->google-json-map-test (is (= {"key" {"aKey" "string" "bLongerKey" 1 "type" "THIS_IS_AN_ENUM" "anotherKey" {"nested" "VALUE"}}} (sut/dsl->google-json-map {:key {:a-key "string" :b-longer-key 1 :type :this-is-an-enum :another-key {:nested :value}}}))))
null
https://raw.githubusercontent.com/oscaro/clj-gcloud-common/fe1709759e2633cc968652b4c27d78bf6ef0243b/test/clj_gcloud/dsl_test.clj
clojure
(ns clj-gcloud.dsl-test (:require [clj-gcloud.dsl :as sut] [clojure.test :refer [deftest is]])) (deftest kw->field-name-test (is (= "tableId" (sut/kw->field-name :table-id)))) (deftest kw->enum-str-test (is (= "CREATE_IF_NEEDED" (sut/kw->enum-str :create-if-needed)))) (deftest dsl->google-json-map-test (is (= {"key" {"aKey" "string" "bLongerKey" 1 "type" "THIS_IS_AN_ENUM" "anotherKey" {"nested" "VALUE"}}} (sut/dsl->google-json-map {:key {:a-key "string" :b-longer-key 1 :type :this-is-an-enum :another-key {:nested :value}}}))))
1b75cbf33cc80dea999a0cf0cca38959df79af0e2bb897d36e0fdb51d21458c5
dyzsr/ocaml-selectml
nativeint.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Processor - native integers . This module provides operations on the type [ nativeint ] of signed 32 - bit integers ( on 32 - bit platforms ) or signed 64 - bit integers ( on 64 - bit platforms ) . This integer type has exactly the same width as that of a pointer type in the C compiler . All arithmetic operations over [ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending on the word size of the architecture . Performance notice : values of type [ nativeint ] occupy more memory space than values of type [ int ] , and arithmetic operations on [ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ] only when the application requires the extra bit of precision over the [ int ] type . Literals for native integers are suffixed by n : { [ let zero : nativeint = 0n let one : nativeint = 1n let m_one : nativeint = -1n ] } This module provides operations on the type [nativeint] of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over [nativeint] are taken modulo 2{^32} or 2{^64} depending on the word size of the architecture. Performance notice: values of type [nativeint] occupy more memory space than values of type [int], and arithmetic operations on [nativeint] are generally slower than those on [int]. Use [nativeint] only when the application requires the extra bit of precision over the [int] type. Literals for native integers are suffixed by n: {[ let zero: nativeint = 0n let one: nativeint = 1n let m_one: nativeint = -1n ]} *) val zero : nativeint (** The native integer 0.*) val one : nativeint * The native integer 1 . val minus_one : nativeint (** The native integer -1.*) external neg : nativeint -> nativeint = "%nativeint_neg" (** Unary negation. *) external add : nativeint -> nativeint -> nativeint = "%nativeint_add" (** Addition. *) external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub" (** Subtraction. *) external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul" (** Multiplication. *) external div : nativeint -> nativeint -> nativeint = "%nativeint_div" * Integer division . This division rounds the real quotient of its arguments towards zero , as specified for { ! Stdlib.(/ ) } . @raise Division_by_zero if the second argument is zero . its arguments towards zero, as specified for {!Stdlib.(/)}. @raise Division_by_zero if the second argument is zero. *) val unsigned_div : nativeint -> nativeint -> nativeint * Same as { ! div } , except that arguments and result are interpreted as { e unsigned } native integers . @since 4.08.0 unsigned} native integers. @since 4.08.0 *) external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod" * Integer remainder . If [ y ] is not zero , the result of [ x y ] satisfies the following properties : [ Nativeint.zero < = x y < Nativeint.abs y ] and [ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y ) ( x y ) ] . If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] . of [Nativeint.rem x y] satisfies the following properties: [Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and [x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y) (Nativeint.rem x y)]. If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *) val unsigned_rem : nativeint -> nativeint -> nativeint * Same as { ! rem } , except that arguments and result are interpreted as { e unsigned } native integers . @since 4.08.0 unsigned} native integers. @since 4.08.0 *) val succ : nativeint -> nativeint (** Successor. [Nativeint.succ x] is [Nativeint.add x Nativeint.one]. *) val pred : nativeint -> nativeint * Predecessor . [ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] . [Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *) val abs : nativeint -> nativeint (** Return the absolute value of its argument. *) val size : int * The size in bits of a native integer . This is equal to [ 32 ] on a 32 - bit platform and to [ 64 ] on a 64 - bit platform . on a 32-bit platform and to [64] on a 64-bit platform. *) val max_int : nativeint * The greatest representable native integer , either 2{^31 } - 1 on a 32 - bit platform , or 2{^63 } - 1 on a 64 - bit platform . either 2{^31} - 1 on a 32-bit platform, or 2{^63} - 1 on a 64-bit platform. *) val min_int : nativeint * The smallest representable native integer , either -2{^31 } on a 32 - bit platform , or -2{^63 } on a 64 - bit platform . either -2{^31} on a 32-bit platform, or -2{^63} on a 64-bit platform. *) external logand : nativeint -> nativeint -> nativeint = "%nativeint_and" (** Bitwise logical and. *) external logor : nativeint -> nativeint -> nativeint = "%nativeint_or" (** Bitwise logical or. *) external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor" (** Bitwise logical exclusive or. *) val lognot : nativeint -> nativeint (** Bitwise logical negation. *) external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl" * [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] , where [ bitsize ] is [ 32 ] on a 32 - bit platform and [ 64 ] on a 64 - bit platform . The result is unspecified if [y < 0] or [y >= bitsize], where [bitsize] is [32] on a 32-bit platform and [64] on a 64-bit platform. *) external shift_right : nativeint -> int -> nativeint = "%nativeint_asr" * [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an arithmetic shift : the sign bit of [ x ] is replicated and inserted in the vacated bits . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] . This is an arithmetic shift: the sign bit of [x] is replicated and inserted in the vacated bits. The result is unspecified if [y < 0] or [y >= bitsize]. *) external shift_right_logical : nativeint -> int -> nativeint = "%nativeint_lsr" * [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a logical shift : zeroes are inserted in the vacated bits regardless of the sign of [ x ] . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] . by [y] bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of [x]. The result is unspecified if [y < 0] or [y >= bitsize]. *) external of_int : int -> nativeint = "%nativeint_of_int" (** Convert the given integer (type [int]) to a native integer (type [nativeint]). *) external to_int : nativeint -> int = "%nativeint_to_int" (** Convert the given native integer (type [nativeint]) to an integer (type [int]). The high-order bit is lost during the conversion. *) val unsigned_to_int : nativeint -> int option * Same as { ! to_int } , but interprets the argument as an { e unsigned } integer . Returns [ None ] if the unsigned value of the argument can not fit into an [ int ] . @since 4.08.0 Returns [None] if the unsigned value of the argument cannot fit into an [int]. @since 4.08.0 *) external of_float : float -> nativeint = "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed" [@@unboxed] [@@noalloc] (** Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[{!Nativeint.min_int}, {!Nativeint.max_int}\], no exception is raised, and an unspecified, platform-dependent integer is returned. *) external to_float : nativeint -> float = "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed" [@@unboxed] [@@noalloc] (** Convert the given native integer to a floating-point number. *) external of_int32 : int32 -> nativeint = "%nativeint_of_int32" * Convert the given 32 - bit integer ( type [ int32 ] ) to a native integer . to a native integer. *) external to_int32 : nativeint -> int32 = "%nativeint_to_int32" * Convert the given native integer to a 32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms , the 64 - bit native integer is taken modulo 2{^32 } , i.e. the top 32 bits are lost . On 32 - bit platforms , the conversion is exact . 32-bit integer (type [int32]). On 64-bit platforms, the 64-bit native integer is taken modulo 2{^32}, i.e. the top 32 bits are lost. On 32-bit platforms, the conversion is exact. *) external of_string : string -> nativeint = "caml_nativeint_of_string" * Convert the given string to a native integer . The string is read in decimal ( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively . The [ 0u ] prefix reads the input as an unsigned integer in the range [ [ 0 , 2*Nativeint.max_int+1 ] ] . If the input exceeds { ! Nativeint.max_int } it is converted to the signed integer [ + input - Nativeint.max_int - 1 ] . @raise Failure if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ nativeint ] . The string is read in decimal (by default, or if the string begins with [0u]) or in hexadecimal, octal or binary if the string begins with [0x], [0o] or [0b] respectively. The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*Nativeint.max_int+1]]. If the input exceeds {!Nativeint.max_int} it is converted to the signed integer [Int64.min_int + input - Nativeint.max_int - 1]. @raise Failure if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [nativeint]. *) val of_string_opt: string -> nativeint option * Same as [ of_string ] , but return [ None ] instead of raising . @since 4.05 @since 4.05 *) val to_string : nativeint -> string (** Return the string representation of its argument, in decimal. *) type t = nativeint (** An alias for the type of native integers. *) val compare: t -> t -> int * The comparison function for native integers , with the same specification as { ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ] allows the module [ Nativeint ] to be passed as argument to the functors { ! Set . Make } and { ! Map . Make } . {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [Nativeint] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val unsigned_compare: t -> t -> int * Same as { ! compare } , except that arguments are interpreted as { e unsigned } native integers . @since 4.08.0 native integers. @since 4.08.0 *) val equal: t -> t -> bool * The equal function for native ints . @since 4.03.0 @since 4.03.0 *) val min: t -> t -> t * Return the smaller of the two arguments . @since 4.13.0 @since 4.13.0 *) val max: t -> t -> t * Return the greater of the two arguments . @since 4.13.0 @since 4.13.0 *) (**/**) * { 1 Deprecated functions } external format : string -> nativeint -> string = "caml_nativeint_format" [@@ocaml.deprecated "Use Printf.sprintf with a [%n...] format instead."] (** [Nativeint.format fmt n] return the string representation of the native integer [n] in the format specified by [fmt]. [fmt] is a [Printf]-style format consisting of exactly one [%d], [%i], [%u], [%x], [%X] or [%o] conversion specification. This function is deprecated; use {!Printf.sprintf} with a [%nx] format instead. *)
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/stdlib/nativeint.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * The native integer 0. * The native integer -1. * Unary negation. * Addition. * Subtraction. * Multiplication. * Successor. [Nativeint.succ x] is [Nativeint.add x Nativeint.one]. * Return the absolute value of its argument. * Bitwise logical and. * Bitwise logical or. * Bitwise logical exclusive or. * Bitwise logical negation. * Convert the given integer (type [int]) to a native integer (type [nativeint]). * Convert the given native integer (type [nativeint]) to an integer (type [int]). The high-order bit is lost during the conversion. * Convert the given floating-point number to a native integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[{!Nativeint.min_int}, {!Nativeint.max_int}\], no exception is raised, and an unspecified, platform-dependent integer is returned. * Convert the given native integer to a floating-point number. * Return the string representation of its argument, in decimal. * An alias for the type of native integers. */* * [Nativeint.format fmt n] return the string representation of the native integer [n] in the format specified by [fmt]. [fmt] is a [Printf]-style format consisting of exactly one [%d], [%i], [%u], [%x], [%X] or [%o] conversion specification. This function is deprecated; use {!Printf.sprintf} with a [%nx] format instead.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * Processor - native integers . This module provides operations on the type [ nativeint ] of signed 32 - bit integers ( on 32 - bit platforms ) or signed 64 - bit integers ( on 64 - bit platforms ) . This integer type has exactly the same width as that of a pointer type in the C compiler . All arithmetic operations over [ nativeint ] are taken modulo 2{^32 } or 2{^64 } depending on the word size of the architecture . Performance notice : values of type [ nativeint ] occupy more memory space than values of type [ int ] , and arithmetic operations on [ nativeint ] are generally slower than those on [ int ] . Use [ nativeint ] only when the application requires the extra bit of precision over the [ int ] type . Literals for native integers are suffixed by n : { [ let zero : nativeint = 0n let one : nativeint = 1n let m_one : nativeint = -1n ] } This module provides operations on the type [nativeint] of signed 32-bit integers (on 32-bit platforms) or signed 64-bit integers (on 64-bit platforms). This integer type has exactly the same width as that of a pointer type in the C compiler. All arithmetic operations over [nativeint] are taken modulo 2{^32} or 2{^64} depending on the word size of the architecture. Performance notice: values of type [nativeint] occupy more memory space than values of type [int], and arithmetic operations on [nativeint] are generally slower than those on [int]. Use [nativeint] only when the application requires the extra bit of precision over the [int] type. Literals for native integers are suffixed by n: {[ let zero: nativeint = 0n let one: nativeint = 1n let m_one: nativeint = -1n ]} *) val zero : nativeint val one : nativeint * The native integer 1 . val minus_one : nativeint external neg : nativeint -> nativeint = "%nativeint_neg" external add : nativeint -> nativeint -> nativeint = "%nativeint_add" external sub : nativeint -> nativeint -> nativeint = "%nativeint_sub" external mul : nativeint -> nativeint -> nativeint = "%nativeint_mul" external div : nativeint -> nativeint -> nativeint = "%nativeint_div" * Integer division . This division rounds the real quotient of its arguments towards zero , as specified for { ! Stdlib.(/ ) } . @raise Division_by_zero if the second argument is zero . its arguments towards zero, as specified for {!Stdlib.(/)}. @raise Division_by_zero if the second argument is zero. *) val unsigned_div : nativeint -> nativeint -> nativeint * Same as { ! div } , except that arguments and result are interpreted as { e unsigned } native integers . @since 4.08.0 unsigned} native integers. @since 4.08.0 *) external rem : nativeint -> nativeint -> nativeint = "%nativeint_mod" * Integer remainder . If [ y ] is not zero , the result of [ x y ] satisfies the following properties : [ Nativeint.zero < = x y < Nativeint.abs y ] and [ x = Nativeint.add ( Nativeint.mul ( Nativeint.div x y ) y ) ( x y ) ] . If [ y = 0 ] , [ x y ] raises [ Division_by_zero ] . of [Nativeint.rem x y] satisfies the following properties: [Nativeint.zero <= Nativeint.rem x y < Nativeint.abs y] and [x = Nativeint.add (Nativeint.mul (Nativeint.div x y) y) (Nativeint.rem x y)]. If [y = 0], [Nativeint.rem x y] raises [Division_by_zero]. *) val unsigned_rem : nativeint -> nativeint -> nativeint * Same as { ! rem } , except that arguments and result are interpreted as { e unsigned } native integers . @since 4.08.0 unsigned} native integers. @since 4.08.0 *) val succ : nativeint -> nativeint val pred : nativeint -> nativeint * Predecessor . [ Nativeint.pred x ] is [ Nativeint.sub x Nativeint.one ] . [Nativeint.pred x] is [Nativeint.sub x Nativeint.one]. *) val abs : nativeint -> nativeint val size : int * The size in bits of a native integer . This is equal to [ 32 ] on a 32 - bit platform and to [ 64 ] on a 64 - bit platform . on a 32-bit platform and to [64] on a 64-bit platform. *) val max_int : nativeint * The greatest representable native integer , either 2{^31 } - 1 on a 32 - bit platform , or 2{^63 } - 1 on a 64 - bit platform . either 2{^31} - 1 on a 32-bit platform, or 2{^63} - 1 on a 64-bit platform. *) val min_int : nativeint * The smallest representable native integer , either -2{^31 } on a 32 - bit platform , or -2{^63 } on a 64 - bit platform . either -2{^31} on a 32-bit platform, or -2{^63} on a 64-bit platform. *) external logand : nativeint -> nativeint -> nativeint = "%nativeint_and" external logor : nativeint -> nativeint -> nativeint = "%nativeint_or" external logxor : nativeint -> nativeint -> nativeint = "%nativeint_xor" val lognot : nativeint -> nativeint external shift_left : nativeint -> int -> nativeint = "%nativeint_lsl" * [ Nativeint.shift_left x y ] shifts [ x ] to the left by [ y ] bits . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] , where [ bitsize ] is [ 32 ] on a 32 - bit platform and [ 64 ] on a 64 - bit platform . The result is unspecified if [y < 0] or [y >= bitsize], where [bitsize] is [32] on a 32-bit platform and [64] on a 64-bit platform. *) external shift_right : nativeint -> int -> nativeint = "%nativeint_asr" * [ Nativeint.shift_right x y ] shifts [ x ] to the right by [ y ] bits . This is an arithmetic shift : the sign bit of [ x ] is replicated and inserted in the vacated bits . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] . This is an arithmetic shift: the sign bit of [x] is replicated and inserted in the vacated bits. The result is unspecified if [y < 0] or [y >= bitsize]. *) external shift_right_logical : nativeint -> int -> nativeint = "%nativeint_lsr" * [ Nativeint.shift_right_logical x y ] shifts [ x ] to the right by [ y ] bits . This is a logical shift : zeroes are inserted in the vacated bits regardless of the sign of [ x ] . The result is unspecified if [ y < 0 ] or [ y > = bitsize ] . by [y] bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of [x]. The result is unspecified if [y < 0] or [y >= bitsize]. *) external of_int : int -> nativeint = "%nativeint_of_int" external to_int : nativeint -> int = "%nativeint_to_int" val unsigned_to_int : nativeint -> int option * Same as { ! to_int } , but interprets the argument as an { e unsigned } integer . Returns [ None ] if the unsigned value of the argument can not fit into an [ int ] . @since 4.08.0 Returns [None] if the unsigned value of the argument cannot fit into an [int]. @since 4.08.0 *) external of_float : float -> nativeint = "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed" [@@unboxed] [@@noalloc] external to_float : nativeint -> float = "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed" [@@unboxed] [@@noalloc] external of_int32 : int32 -> nativeint = "%nativeint_of_int32" * Convert the given 32 - bit integer ( type [ int32 ] ) to a native integer . to a native integer. *) external to_int32 : nativeint -> int32 = "%nativeint_to_int32" * Convert the given native integer to a 32 - bit integer ( type [ int32 ] ) . On 64 - bit platforms , the 64 - bit native integer is taken modulo 2{^32 } , i.e. the top 32 bits are lost . On 32 - bit platforms , the conversion is exact . 32-bit integer (type [int32]). On 64-bit platforms, the 64-bit native integer is taken modulo 2{^32}, i.e. the top 32 bits are lost. On 32-bit platforms, the conversion is exact. *) external of_string : string -> nativeint = "caml_nativeint_of_string" * Convert the given string to a native integer . The string is read in decimal ( by default , or if the string begins with [ 0u ] ) or in hexadecimal , octal or binary if the string begins with [ 0x ] , [ 0o ] or [ 0b ] respectively . The [ 0u ] prefix reads the input as an unsigned integer in the range [ [ 0 , 2*Nativeint.max_int+1 ] ] . If the input exceeds { ! Nativeint.max_int } it is converted to the signed integer [ + input - Nativeint.max_int - 1 ] . @raise Failure if the given string is not a valid representation of an integer , or if the integer represented exceeds the range of integers representable in type [ nativeint ] . The string is read in decimal (by default, or if the string begins with [0u]) or in hexadecimal, octal or binary if the string begins with [0x], [0o] or [0b] respectively. The [0u] prefix reads the input as an unsigned integer in the range [[0, 2*Nativeint.max_int+1]]. If the input exceeds {!Nativeint.max_int} it is converted to the signed integer [Int64.min_int + input - Nativeint.max_int - 1]. @raise Failure if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type [nativeint]. *) val of_string_opt: string -> nativeint option * Same as [ of_string ] , but return [ None ] instead of raising . @since 4.05 @since 4.05 *) val to_string : nativeint -> string type t = nativeint val compare: t -> t -> int * The comparison function for native integers , with the same specification as { ! Stdlib.compare } . Along with the type [ t ] , this function [ compare ] allows the module [ Nativeint ] to be passed as argument to the functors { ! Set . Make } and { ! Map . Make } . {!Stdlib.compare}. Along with the type [t], this function [compare] allows the module [Nativeint] to be passed as argument to the functors {!Set.Make} and {!Map.Make}. *) val unsigned_compare: t -> t -> int * Same as { ! compare } , except that arguments are interpreted as { e unsigned } native integers . @since 4.08.0 native integers. @since 4.08.0 *) val equal: t -> t -> bool * The equal function for native ints . @since 4.03.0 @since 4.03.0 *) val min: t -> t -> t * Return the smaller of the two arguments . @since 4.13.0 @since 4.13.0 *) val max: t -> t -> t * Return the greater of the two arguments . @since 4.13.0 @since 4.13.0 *) * { 1 Deprecated functions } external format : string -> nativeint -> string = "caml_nativeint_format" [@@ocaml.deprecated "Use Printf.sprintf with a [%n...] format instead."]
cb2d30f9a76eb29506b47fed49d7c3d262b5b924b9f87b2d98ae9b380982fa6f
lojic/LearningRacket
day20.rkt
#lang racket (require "../advent.rkt") (require "../circular-queue.rkt") (define in (file->list "./day20.txt")) (define (solve n in) (let* ([ q (list->queue in) ] [ len (length in) ] [ digits (get-references q) ]) (for ([ _ (in-range n) ]) (for ([ digit (in-list digits) ]) (mix! digit len))) (for/sum ([ n '(1000 2000 3000) ]) (queue-val (iterate queue-next (queue-memv 0 q) n))))) (define (get-references q) (let loop ([ current (queue-next q) ][ result (list q) ]) (if (queue-eq? current q) (reverse result) (loop (queue-next current) (cons current result))))) (define (mix! digit len) (let ([ val (modulo (queue-val digit) (sub1 len)) ]) (when (not (zero? val)) (let ([ pos (cond [ (positive? val) (iterate queue-next digit val) ] [ else (iterate queue-previous digit (add1 (abs val))) ]) ]) (queue-remove-n! digit 1) (queue-insert-queue! pos digit))))) (time (check-equal? (solve 1 in) 4151)) (time (check-equal? (solve 10 (map (λ (n) (* n 811589153)) in)) 7848878698663))
null
https://raw.githubusercontent.com/lojic/LearningRacket/d96e6e832dc2e9002fe6849501a72a575594a7c0/advent-of-code-2022/day20/day20.rkt
racket
#lang racket (require "../advent.rkt") (require "../circular-queue.rkt") (define in (file->list "./day20.txt")) (define (solve n in) (let* ([ q (list->queue in) ] [ len (length in) ] [ digits (get-references q) ]) (for ([ _ (in-range n) ]) (for ([ digit (in-list digits) ]) (mix! digit len))) (for/sum ([ n '(1000 2000 3000) ]) (queue-val (iterate queue-next (queue-memv 0 q) n))))) (define (get-references q) (let loop ([ current (queue-next q) ][ result (list q) ]) (if (queue-eq? current q) (reverse result) (loop (queue-next current) (cons current result))))) (define (mix! digit len) (let ([ val (modulo (queue-val digit) (sub1 len)) ]) (when (not (zero? val)) (let ([ pos (cond [ (positive? val) (iterate queue-next digit val) ] [ else (iterate queue-previous digit (add1 (abs val))) ]) ]) (queue-remove-n! digit 1) (queue-insert-queue! pos digit))))) (time (check-equal? (solve 1 in) 4151)) (time (check-equal? (solve 10 (map (λ (n) (* n 811589153)) in)) 7848878698663))
907d13b66e54fcda1cd83146917bbd4535e6ca4754681ac96958e5dd6ef550f6
skeuchel/needle
Core.hs
# LANGUAGE ExistentialQuantification # # LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # module KnotCore.DeBruijn.Core where import KnotCore.Syntax import Control.Applicative import Data.Maybe import Data.Traversable (traverse) -- _ _ -- | \| |__ _ _ __ ___ ___ | . ` / _ ` | ' \/ -_|_- < -- |_|\_\__,_|_|_|_\___/__/ -- Representation of heterogeneous variable lists. This is a list -- representing a list of variables from all namespaces in the -- specifications. Unfortunately this is not modular for now. data HVarlistVar = HVLV { hvarlistVarRoot :: NameRoot, hvarlistVarSuffix :: Suffix } deriving (Eq,Ord,Show) -- Representation of a cutoff variable. Cutoffs always belong to a -- single namespace. data CutoffVar = CV { cutoffVarRoot :: NameRoot, cutoffVarSuffix :: Suffix, cutoffVarNamespace :: NamespaceTypeName } deriving (Eq,Ord,Show) -- Representation of an index variable. Cutoffs always belong to a -- single namespace. data IndexVar = IndexVar { indexVarRoot :: NameRoot, indexVarSuffix :: Suffix, indexVarNamespace :: NamespaceTypeName, indexVarSort :: SortTypeName } deriving (Eq,Ord,Show) toIndex :: EnvM m => FreeVariable -> m IndexVar toIndex (FV nr suff ntn) = do Just stn <- lookupNamespaceSort ntn return $ IndexVar nr suff ntn stn -- Representation of a trace of a namespace. data TraceVar = TV { traceVarRoot :: NameRoot, traceVarSuffix :: Suffix, traceVarNamespace :: NamespaceTypeName } deriving (Eq,Ord,Show) -- Representation of an term variable. data TermVar = TermVar { termVarRoot :: NameRoot, termVarSuffix :: Suffix, termVarSort :: SortTypeName } deriving (Eq,Ord,Show) -------------------------------------------------------------------------------- Symbolic Data -------------------------------------------------------------------------------- data HVarlist = HV0 | HVS NamespaceTypeName HVarlist | HVVar HVarlistVar | HVCall FunName STerm | HVAppend HVarlist HVarlist | HVDomainEnv ETerm deriving (Eq,Ord,Show) data Cutoff = C0 NamespaceTypeName | CS Cutoff | CS' NamespaceTypeName Cutoff | CVar CutoffVar | CWeaken Cutoff HVarlist deriving (Eq,Ord,Show) data Index = I0 NamespaceTypeName SortTypeName | IS Index | IVar IndexVar | IWeaken Index HVarlist | IShift Cutoff Index | IShift' Cutoff Index deriving (Eq,Ord,Show) data Trace = T0 NamespaceTypeName | TS NamespaceTypeName Trace | TVar TraceVar | TWeaken Trace HVarlist deriving (Eq,Ord,Show) data STerm = SVar SortVariable | SCtorVar SortTypeName CtorName Index | SCtorReg SortTypeName CtorName [Field 'WMV] | SShift Cutoff STerm | SShift' Cutoff STerm | SSubst Trace STerm STerm | SSubst' Trace STerm STerm | SSubstIndex Trace STerm Index | SWeaken STerm HVarlist deriving (Eq,Ord,Show) data Field (w :: WithMV) = FieldSort STerm | FieldEnv ETerm | (w ~ 'WMV) => FieldIndex Index deriving instance Eq (Field w) deriving instance Ord (Field w) deriving instance Show (Field w) fieldDeclToField :: EnvM m => FieldDecl w -> Maybe (m (Field w)) fieldDeclToField (FieldDeclSort _ sv _) = Just (pure (FieldSort (SVar sv))) fieldDeclsToFields :: EnvM m => [FieldDecl w] -> m [Field w] fieldDeclsToFields = sequenceA . mapMaybe fieldDeclToField shiftField :: Cutoff -> Field w -> Field w shiftField c (FieldSort st) = FieldSort (SShift' c st) substField :: Trace -> STerm -> Field w -> Field w substField x t (FieldSort st) = FieldSort (SSubst' x t st) weakenField :: Field w -> HVarlist -> Field w weakenField (FieldSort st) h = FieldSort (SWeaken st h) data ETerm = EVar EnvVariable | ENil EnvTypeName | ECons ETerm NamespaceTypeName [Field 'WOMV] | EAppend ETerm ETerm | EShift Cutoff ETerm | EShift' Cutoff ETerm | ESubst Trace STerm ETerm | ESubst' Trace STerm ETerm | EWeaken ETerm HVarlist | ECall FunName JudgementVariable EnvTypeName deriving (Eq,Ord,Show) data Lookup = Lookup ETerm Index [Field 'WOMV] deriving (Eq,Ord,Show) data InsertEnv = InsertEnv Cutoff ETerm ETerm deriving (Eq,Ord,Show) data InsertEnvHyp = InsertEnvHyp Hypothesis InsertEnv deriving (Eq,Ord,Show) data InsertEnvTerm = InsertEnvVar InsertEnvHyp | InsertEnvCons NamespaceTypeName [Field 'WOMV] InsertEnvTerm | InsertEnvWeaken InsertEnvTerm ETerm deriving (Eq,Ord,Show) data SubstEnv = SubstEnv ETerm [Field 'WOMV] STerm Trace ETerm ETerm deriving (Eq,Ord,Show) data SubstEnvHyp = SubstEnvHyp Hypothesis SubstEnv deriving (Eq,Ord,Show) data SubstEnvTerm = SubstEnvVar SubstEnvHyp | SubstEnvCons NamespaceTypeName [Field 'WOMV] SubstEnvTerm | SubstEnvWeaken SubstEnvTerm ETerm deriving (Eq,Ord,Show) data JudgementEnv = JudgementEnvTerm ETerm | JudgementEnvUnderscore | JudgementEnvNothing deriving (Eq,Ord,Show) data Prop = PEqTerm STerm STerm | forall w. PEqField (Field w) (Field w) | PAnd [Prop] | PJudgement RelationTypeName JudgementEnv [Field 'WOMV] [ETerm] | PEqHvl HVarlist HVarlist data WellFormedIndex = WfIndex HVarlist Index deriving (Eq,Ord,Show) data WellFormedSort = WfSort HVarlist STerm deriving (Eq,Ord,Show) data WellFormedSortHyp = WellFormedSortHyp { wfsHyp :: Hypothesis , wfsType :: WellFormedSort } deriving (Eq,Ord,Show) data WellFormedIndexHyp = WellFormedIndexHyp { wfiHyp :: Hypothesis , wfiType :: WellFormedIndex } deriving (Eq,Ord,Show) data WellFormedHyp = WellFormedHypSort WellFormedSortHyp | WellFormedHypIndex WellFormedIndexHyp deriving (Eq,Ord,Show) data WellFormedSortTerm = WellFormedSortVar WellFormedSortHyp | WellFormedSortShift InsertHvlTerm WellFormedSortTerm | WellFormedSortSubst WellFormedSortTerm SubstHvlTerm WellFormedSortTerm | WellFormedSortJudgement Int SortTypeName JudgementVariable RelationTypeName ETerm [Field 'WOMV] [ETerm] deriving (Eq,Ord,Show) data WellFormedIndexTerm = WellFormedIndexVar WellFormedIndexHyp | WellFormedIndexShift InsertHvlTerm WellFormedIndexTerm | WellFormedIndexSubst WellFormedSortTerm SubstHvlTerm WellFormedIndexTerm deriving (Eq,Ord,Show) data InsertHvlTerm = InsertHvlEnv { insertHvlEnv :: InsertEnvTerm } | InsertHvlWeaken { insertHvlRec :: InsertHvlTerm , insertHvlWeaken :: HVarlist } deriving (Eq,Ord,Show) data SubstHvlTerm = SubstHvlEnv { substHvlEnv :: SubstEnvTerm } | SubstHvlWeaken { substHvlRec :: SubstHvlTerm , substHvlWeaken :: HVarlist } deriving (Eq,Ord,Show) data WellFormedFormula = WfFormHyp WellFormedHyp | WfShift WellFormedFormula deriving (Eq,Ord,Show) data HVarlistInsertion = HVarlistInsertion Cutoff HVarlist HVarlist deriving (Eq,Ord,Show) data SubstHvl = SubstHvl HVarlist Trace HVarlist HVarlist deriving (Eq,Ord,Show) data SubHvl = SubHvl [NamespaceTypeName] HVarlist deriving (Eq,Ord,Show) -------------------------------------------------------------------------------- -- Typenames -------------------------------------------------------------------------------- instance TypeNameOf CutoffVar NamespaceTypeName where typeNameOf = cutoffVarNamespace instance TypeNameOf IndexVar NamespaceTypeName where typeNameOf = indexVarNamespace instance TypeNameOf TermVar SortTypeName where typeNameOf = termVarSort instance TypeNameOf TraceVar NamespaceTypeName where typeNameOf = traceVarNamespace class SortOf a where sortOf :: a -> SortTypeName -- instance TypeNameOf a SortTypeName => SortOf a where -- sortOf = typeNameOf instance SortOf SortVariable where sortOf (SV _ _ stn) = stn instance SortOf IndexVar where sortOf (IndexVar _ _ _ stn) = stn instance TypeNameOf Cutoff NamespaceTypeName where typeNameOf (C0 ntn) = ntn typeNameOf (CS c) = typeNameOf c typeNameOf (CS' _ c) = typeNameOf c typeNameOf (CVar cv) = typeNameOf cv typeNameOf (CWeaken c _) = typeNameOf c instance TypeNameOf Trace NamespaceTypeName where typeNameOf (T0 ntn) = ntn typeNameOf (TS _ x) = typeNameOf x typeNameOf (TVar xv) = typeNameOf xv typeNameOf (TWeaken x _) = typeNameOf x instance TypeNameOf Index NamespaceTypeName where typeNameOf (I0 ntn _) = ntn typeNameOf (IS i) = typeNameOf i typeNameOf (IVar iv) = typeNameOf iv typeNameOf (IWeaken i _) = typeNameOf i typeNameOf (IShift _ i) = typeNameOf i typeNameOf (IShift' _ i) = typeNameOf i instance TypeNameOf WellFormedIndex NamespaceTypeName where typeNameOf (WfIndex _ i) = typeNameOf i instance TypeNameOf WellFormedSort SortTypeName where typeNameOf (WfSort _ s) = typeNameOf s instance SortOf Index where sortOf (I0 _ stn) = stn sortOf (IS i) = sortOf i sortOf (IVar iv) = sortOf iv sortOf (IWeaken i _) = sortOf i sortOf (IShift _ i) = sortOf i sortOf (IShift' _ i) = sortOf i instance SortOf STerm where sortOf (SVar sv) = sortOf sv sortOf (SCtorVar stn _ _) = stn sortOf (SCtorReg stn _ _) = stn sortOf (SShift _ t) = sortOf t sortOf (SShift' _ t) = sortOf t sortOf (SSubst _ _ t) = sortOf t sortOf (SSubst' _ _ t) = sortOf t sortOf (SSubstIndex _ _ i) = sortOf i sortOf (SWeaken t _) = sortOf t instance TypeNameOf STerm SortTypeName where typeNameOf = sortOf instance TypeNameOf ETerm EnvTypeName where typeNameOf (EVar ev) = typeNameOf ev typeNameOf (ENil etn) = etn typeNameOf (ECons et _ _) = typeNameOf et typeNameOf (EAppend et _) = typeNameOf et typeNameOf (EShift _ et) = typeNameOf et typeNameOf (EShift' _ et) = typeNameOf et typeNameOf (ESubst _ _ et) = typeNameOf et typeNameOf (ESubst' _ _ et) = typeNameOf et typeNameOf (EWeaken et _) = typeNameOf et instance TypeNameOf InsertEnvHyp (NamespaceTypeName, EnvTypeName) where typeNameOf (InsertEnvHyp _ (InsertEnv cv ev _)) = (typeNameOf cv, typeNameOf ev) instance TypeNameOf InsertEnvTerm (NamespaceTypeName, EnvTypeName) where typeNameOf (InsertEnvVar hyp) = typeNameOf hyp typeNameOf (InsertEnvCons _ _ iet) = typeNameOf iet typeNameOf (InsertEnvWeaken iet _) = typeNameOf iet instance TypeNameOf SubstEnvHyp (NamespaceTypeName, EnvTypeName) where typeNameOf (SubstEnvHyp _ (SubstEnv et0 _ _ x _ _)) = (typeNameOf x, typeNameOf et0) instance TypeNameOf SubstEnvTerm (NamespaceTypeName, EnvTypeName) where typeNameOf (SubstEnvVar hyp) = typeNameOf hyp typeNameOf (SubstEnvCons _ _ set) = typeNameOf set typeNameOf (SubstEnvWeaken set _) = typeNameOf set instance TypeNameOf InsertHvlTerm NamespaceTypeName where typeNameOf (InsertHvlEnv ins) = fst (typeNameOf ins) typeNameOf (InsertHvlWeaken rec _) = typeNameOf rec instance TypeNameOf SubstHvlTerm NamespaceTypeName where typeNameOf (SubstHvlEnv sub) = fst (typeNameOf sub) typeNameOf (SubstHvlWeaken rec _) = typeNameOf rec instance TypeNameOf WellFormedIndexHyp NamespaceTypeName where typeNameOf (WellFormedIndexHyp _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedIndexTerm NamespaceTypeName where typeNameOf (WellFormedIndexVar hyp) = typeNameOf hyp typeNameOf (WellFormedIndexShift _ wfi) = typeNameOf wfi typeNameOf (WellFormedIndexSubst _ _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedSortHyp SortTypeName where typeNameOf (WellFormedSortHyp _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedSortTerm SortTypeName where typeNameOf (WellFormedSortVar hyp) = typeNameOf hyp typeNameOf (WellFormedSortShift _ wfi) = typeNameOf wfi typeNameOf (WellFormedSortSubst _ _ wfi) = typeNameOf wfi typeNameOf (WellFormedSortJudgement _ stn _ _ _ _ _) = stn instance SortOf WellFormedIndex where sortOf (WfIndex _ i) = sortOf i instance SortOf WellFormedSort where sortOf (WfSort _ s) = sortOf s symbolicTermToSTerm :: EnvM m => SymbolicTerm -> m STerm symbolicTermToSTerm (SymSubtree _ sv) = pure (SVar sv) symbolicTermToSTerm (SymCtorVarFree _ cn mv) = do stn <- lookupCtorType cn SCtorVar stn cn . IVar <$> toIndex mv symbolicTermToSTerm (SymCtorVarBound _ cn mv _ diff) = do stn <- lookupCtorType cn let ntn = typeNameOf mv pure (SCtorVar stn cn (IWeaken (I0 ntn stn) (evalBindSpec HV0 diff))) symbolicTermToSTerm (SymCtorReg _ cn sfs) = do stn <- lookupCtorType cn SCtorReg stn cn . catMaybes <$> traverse symbolicFieldToField sfs symbolicTermToSTerm (SymWeaken _ _ st diff) = SWeaken <$> symbolicTermToSTerm st <*> pure (evalBindSpec HV0 diff) symbolicTermToSTerm (SymSubst _ mv st1 st2) = SSubst <$> pure (T0 (typeNameOf mv)) <*> symbolicTermToSTerm st1 <*> symbolicTermToSTerm st2 symbolicFieldToField :: EnvM m => SymbolicField w -> m (Maybe (Field w)) symbolicFieldToField (SymFieldSort _ _ st) = Just . FieldSort <$> symbolicTermToSTerm st symbolicFieldToField (SymFieldEnv{}) = error "NOT IMPLEMENTED" symbolicFieldToField (SymFieldBinding{}) = pure Nothing symbolicFieldToField (SymFieldReferenceFree{}) = error "NOT IMPLEMENTED" symbolicFieldToField (SymFieldReferenceBound{}) = error "NOT IMPLEMENTED" symbolicEnvToETerm :: EnvM m => SymbolicEnv -> m ETerm symbolicEnvToETerm _se = case _se of SymEnvVar ev -> pure (EVar ev) SymEnvNil etn -> pure (ENil etn) SymEnvCons ntn se sts -> ECons <$> symbolicEnvToETerm se <*> pure ntn <*> (catMaybes <$> traverse symbolicFieldToField sts) SymEnvAppend l r -> EAppend <$> symbolicEnvToETerm l <*> symbolicEnvToETerm r SymEnvCall fn jv - > ECall fn jv < $ > lookupRelationOutput fn ( typeNameOf jv ) -- ___ _ _ _ -- | __|_ ____ _| |_ _ __ _| |_(_)___ _ _ -- | _|\ V / _` | | || / _` | _| / _ \ ' \ -- |___|\_/\__,_|_|\_,_\__,_|\__|_\___/_||_| evalBindSpecItem :: BindSpecItem -> HVarlist evalBindSpecItem (BsiBinding mv) = HVS (typeNameOf mv) HV0 evalBindSpecItem (BsiCall fn sn) = HVCall fn (SVar sn) evalBindSpec :: HVarlist -> BindSpec -> HVarlist evalBindSpec h Nil = h evalBindSpec h (bs :. bsi) = HVAppend (evalBindSpec h bs) (evalBindSpecItem bsi)
null
https://raw.githubusercontent.com/skeuchel/needle/25f46005d37571c1585805487a47950dcd588269/src/KnotCore/DeBruijn/Core.hs
haskell
# LANGUAGE GADTs # _ _ | \| |__ _ _ __ ___ ___ |_|\_\__,_|_|_|_\___/__/ Representation of heterogeneous variable lists. This is a list representing a list of variables from all namespaces in the specifications. Unfortunately this is not modular for now. Representation of a cutoff variable. Cutoffs always belong to a single namespace. Representation of an index variable. Cutoffs always belong to a single namespace. Representation of a trace of a namespace. Representation of an term variable. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Typenames ------------------------------------------------------------------------------ instance TypeNameOf a SortTypeName => SortOf a where sortOf = typeNameOf ___ _ _ _ | __|_ ____ _| |_ _ __ _| |_(_)___ _ _ | _|\ V / _` | | || / _` | _| / _ \ ' \ |___|\_/\__,_|_|\_,_\__,_|\__|_\___/_||_|
# LANGUAGE ExistentialQuantification # # LANGUAGE DataKinds # # LANGUAGE FlexibleInstances # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # module KnotCore.DeBruijn.Core where import KnotCore.Syntax import Control.Applicative import Data.Maybe import Data.Traversable (traverse) | . ` / _ ` | ' \/ -_|_- < data HVarlistVar = HVLV { hvarlistVarRoot :: NameRoot, hvarlistVarSuffix :: Suffix } deriving (Eq,Ord,Show) data CutoffVar = CV { cutoffVarRoot :: NameRoot, cutoffVarSuffix :: Suffix, cutoffVarNamespace :: NamespaceTypeName } deriving (Eq,Ord,Show) data IndexVar = IndexVar { indexVarRoot :: NameRoot, indexVarSuffix :: Suffix, indexVarNamespace :: NamespaceTypeName, indexVarSort :: SortTypeName } deriving (Eq,Ord,Show) toIndex :: EnvM m => FreeVariable -> m IndexVar toIndex (FV nr suff ntn) = do Just stn <- lookupNamespaceSort ntn return $ IndexVar nr suff ntn stn data TraceVar = TV { traceVarRoot :: NameRoot, traceVarSuffix :: Suffix, traceVarNamespace :: NamespaceTypeName } deriving (Eq,Ord,Show) data TermVar = TermVar { termVarRoot :: NameRoot, termVarSuffix :: Suffix, termVarSort :: SortTypeName } deriving (Eq,Ord,Show) Symbolic Data data HVarlist = HV0 | HVS NamespaceTypeName HVarlist | HVVar HVarlistVar | HVCall FunName STerm | HVAppend HVarlist HVarlist | HVDomainEnv ETerm deriving (Eq,Ord,Show) data Cutoff = C0 NamespaceTypeName | CS Cutoff | CS' NamespaceTypeName Cutoff | CVar CutoffVar | CWeaken Cutoff HVarlist deriving (Eq,Ord,Show) data Index = I0 NamespaceTypeName SortTypeName | IS Index | IVar IndexVar | IWeaken Index HVarlist | IShift Cutoff Index | IShift' Cutoff Index deriving (Eq,Ord,Show) data Trace = T0 NamespaceTypeName | TS NamespaceTypeName Trace | TVar TraceVar | TWeaken Trace HVarlist deriving (Eq,Ord,Show) data STerm = SVar SortVariable | SCtorVar SortTypeName CtorName Index | SCtorReg SortTypeName CtorName [Field 'WMV] | SShift Cutoff STerm | SShift' Cutoff STerm | SSubst Trace STerm STerm | SSubst' Trace STerm STerm | SSubstIndex Trace STerm Index | SWeaken STerm HVarlist deriving (Eq,Ord,Show) data Field (w :: WithMV) = FieldSort STerm | FieldEnv ETerm | (w ~ 'WMV) => FieldIndex Index deriving instance Eq (Field w) deriving instance Ord (Field w) deriving instance Show (Field w) fieldDeclToField :: EnvM m => FieldDecl w -> Maybe (m (Field w)) fieldDeclToField (FieldDeclSort _ sv _) = Just (pure (FieldSort (SVar sv))) fieldDeclsToFields :: EnvM m => [FieldDecl w] -> m [Field w] fieldDeclsToFields = sequenceA . mapMaybe fieldDeclToField shiftField :: Cutoff -> Field w -> Field w shiftField c (FieldSort st) = FieldSort (SShift' c st) substField :: Trace -> STerm -> Field w -> Field w substField x t (FieldSort st) = FieldSort (SSubst' x t st) weakenField :: Field w -> HVarlist -> Field w weakenField (FieldSort st) h = FieldSort (SWeaken st h) data ETerm = EVar EnvVariable | ENil EnvTypeName | ECons ETerm NamespaceTypeName [Field 'WOMV] | EAppend ETerm ETerm | EShift Cutoff ETerm | EShift' Cutoff ETerm | ESubst Trace STerm ETerm | ESubst' Trace STerm ETerm | EWeaken ETerm HVarlist | ECall FunName JudgementVariable EnvTypeName deriving (Eq,Ord,Show) data Lookup = Lookup ETerm Index [Field 'WOMV] deriving (Eq,Ord,Show) data InsertEnv = InsertEnv Cutoff ETerm ETerm deriving (Eq,Ord,Show) data InsertEnvHyp = InsertEnvHyp Hypothesis InsertEnv deriving (Eq,Ord,Show) data InsertEnvTerm = InsertEnvVar InsertEnvHyp | InsertEnvCons NamespaceTypeName [Field 'WOMV] InsertEnvTerm | InsertEnvWeaken InsertEnvTerm ETerm deriving (Eq,Ord,Show) data SubstEnv = SubstEnv ETerm [Field 'WOMV] STerm Trace ETerm ETerm deriving (Eq,Ord,Show) data SubstEnvHyp = SubstEnvHyp Hypothesis SubstEnv deriving (Eq,Ord,Show) data SubstEnvTerm = SubstEnvVar SubstEnvHyp | SubstEnvCons NamespaceTypeName [Field 'WOMV] SubstEnvTerm | SubstEnvWeaken SubstEnvTerm ETerm deriving (Eq,Ord,Show) data JudgementEnv = JudgementEnvTerm ETerm | JudgementEnvUnderscore | JudgementEnvNothing deriving (Eq,Ord,Show) data Prop = PEqTerm STerm STerm | forall w. PEqField (Field w) (Field w) | PAnd [Prop] | PJudgement RelationTypeName JudgementEnv [Field 'WOMV] [ETerm] | PEqHvl HVarlist HVarlist data WellFormedIndex = WfIndex HVarlist Index deriving (Eq,Ord,Show) data WellFormedSort = WfSort HVarlist STerm deriving (Eq,Ord,Show) data WellFormedSortHyp = WellFormedSortHyp { wfsHyp :: Hypothesis , wfsType :: WellFormedSort } deriving (Eq,Ord,Show) data WellFormedIndexHyp = WellFormedIndexHyp { wfiHyp :: Hypothesis , wfiType :: WellFormedIndex } deriving (Eq,Ord,Show) data WellFormedHyp = WellFormedHypSort WellFormedSortHyp | WellFormedHypIndex WellFormedIndexHyp deriving (Eq,Ord,Show) data WellFormedSortTerm = WellFormedSortVar WellFormedSortHyp | WellFormedSortShift InsertHvlTerm WellFormedSortTerm | WellFormedSortSubst WellFormedSortTerm SubstHvlTerm WellFormedSortTerm | WellFormedSortJudgement Int SortTypeName JudgementVariable RelationTypeName ETerm [Field 'WOMV] [ETerm] deriving (Eq,Ord,Show) data WellFormedIndexTerm = WellFormedIndexVar WellFormedIndexHyp | WellFormedIndexShift InsertHvlTerm WellFormedIndexTerm | WellFormedIndexSubst WellFormedSortTerm SubstHvlTerm WellFormedIndexTerm deriving (Eq,Ord,Show) data InsertHvlTerm = InsertHvlEnv { insertHvlEnv :: InsertEnvTerm } | InsertHvlWeaken { insertHvlRec :: InsertHvlTerm , insertHvlWeaken :: HVarlist } deriving (Eq,Ord,Show) data SubstHvlTerm = SubstHvlEnv { substHvlEnv :: SubstEnvTerm } | SubstHvlWeaken { substHvlRec :: SubstHvlTerm , substHvlWeaken :: HVarlist } deriving (Eq,Ord,Show) data WellFormedFormula = WfFormHyp WellFormedHyp | WfShift WellFormedFormula deriving (Eq,Ord,Show) data HVarlistInsertion = HVarlistInsertion Cutoff HVarlist HVarlist deriving (Eq,Ord,Show) data SubstHvl = SubstHvl HVarlist Trace HVarlist HVarlist deriving (Eq,Ord,Show) data SubHvl = SubHvl [NamespaceTypeName] HVarlist deriving (Eq,Ord,Show) instance TypeNameOf CutoffVar NamespaceTypeName where typeNameOf = cutoffVarNamespace instance TypeNameOf IndexVar NamespaceTypeName where typeNameOf = indexVarNamespace instance TypeNameOf TermVar SortTypeName where typeNameOf = termVarSort instance TypeNameOf TraceVar NamespaceTypeName where typeNameOf = traceVarNamespace class SortOf a where sortOf :: a -> SortTypeName instance SortOf SortVariable where sortOf (SV _ _ stn) = stn instance SortOf IndexVar where sortOf (IndexVar _ _ _ stn) = stn instance TypeNameOf Cutoff NamespaceTypeName where typeNameOf (C0 ntn) = ntn typeNameOf (CS c) = typeNameOf c typeNameOf (CS' _ c) = typeNameOf c typeNameOf (CVar cv) = typeNameOf cv typeNameOf (CWeaken c _) = typeNameOf c instance TypeNameOf Trace NamespaceTypeName where typeNameOf (T0 ntn) = ntn typeNameOf (TS _ x) = typeNameOf x typeNameOf (TVar xv) = typeNameOf xv typeNameOf (TWeaken x _) = typeNameOf x instance TypeNameOf Index NamespaceTypeName where typeNameOf (I0 ntn _) = ntn typeNameOf (IS i) = typeNameOf i typeNameOf (IVar iv) = typeNameOf iv typeNameOf (IWeaken i _) = typeNameOf i typeNameOf (IShift _ i) = typeNameOf i typeNameOf (IShift' _ i) = typeNameOf i instance TypeNameOf WellFormedIndex NamespaceTypeName where typeNameOf (WfIndex _ i) = typeNameOf i instance TypeNameOf WellFormedSort SortTypeName where typeNameOf (WfSort _ s) = typeNameOf s instance SortOf Index where sortOf (I0 _ stn) = stn sortOf (IS i) = sortOf i sortOf (IVar iv) = sortOf iv sortOf (IWeaken i _) = sortOf i sortOf (IShift _ i) = sortOf i sortOf (IShift' _ i) = sortOf i instance SortOf STerm where sortOf (SVar sv) = sortOf sv sortOf (SCtorVar stn _ _) = stn sortOf (SCtorReg stn _ _) = stn sortOf (SShift _ t) = sortOf t sortOf (SShift' _ t) = sortOf t sortOf (SSubst _ _ t) = sortOf t sortOf (SSubst' _ _ t) = sortOf t sortOf (SSubstIndex _ _ i) = sortOf i sortOf (SWeaken t _) = sortOf t instance TypeNameOf STerm SortTypeName where typeNameOf = sortOf instance TypeNameOf ETerm EnvTypeName where typeNameOf (EVar ev) = typeNameOf ev typeNameOf (ENil etn) = etn typeNameOf (ECons et _ _) = typeNameOf et typeNameOf (EAppend et _) = typeNameOf et typeNameOf (EShift _ et) = typeNameOf et typeNameOf (EShift' _ et) = typeNameOf et typeNameOf (ESubst _ _ et) = typeNameOf et typeNameOf (ESubst' _ _ et) = typeNameOf et typeNameOf (EWeaken et _) = typeNameOf et instance TypeNameOf InsertEnvHyp (NamespaceTypeName, EnvTypeName) where typeNameOf (InsertEnvHyp _ (InsertEnv cv ev _)) = (typeNameOf cv, typeNameOf ev) instance TypeNameOf InsertEnvTerm (NamespaceTypeName, EnvTypeName) where typeNameOf (InsertEnvVar hyp) = typeNameOf hyp typeNameOf (InsertEnvCons _ _ iet) = typeNameOf iet typeNameOf (InsertEnvWeaken iet _) = typeNameOf iet instance TypeNameOf SubstEnvHyp (NamespaceTypeName, EnvTypeName) where typeNameOf (SubstEnvHyp _ (SubstEnv et0 _ _ x _ _)) = (typeNameOf x, typeNameOf et0) instance TypeNameOf SubstEnvTerm (NamespaceTypeName, EnvTypeName) where typeNameOf (SubstEnvVar hyp) = typeNameOf hyp typeNameOf (SubstEnvCons _ _ set) = typeNameOf set typeNameOf (SubstEnvWeaken set _) = typeNameOf set instance TypeNameOf InsertHvlTerm NamespaceTypeName where typeNameOf (InsertHvlEnv ins) = fst (typeNameOf ins) typeNameOf (InsertHvlWeaken rec _) = typeNameOf rec instance TypeNameOf SubstHvlTerm NamespaceTypeName where typeNameOf (SubstHvlEnv sub) = fst (typeNameOf sub) typeNameOf (SubstHvlWeaken rec _) = typeNameOf rec instance TypeNameOf WellFormedIndexHyp NamespaceTypeName where typeNameOf (WellFormedIndexHyp _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedIndexTerm NamespaceTypeName where typeNameOf (WellFormedIndexVar hyp) = typeNameOf hyp typeNameOf (WellFormedIndexShift _ wfi) = typeNameOf wfi typeNameOf (WellFormedIndexSubst _ _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedSortHyp SortTypeName where typeNameOf (WellFormedSortHyp _ wfi) = typeNameOf wfi instance TypeNameOf WellFormedSortTerm SortTypeName where typeNameOf (WellFormedSortVar hyp) = typeNameOf hyp typeNameOf (WellFormedSortShift _ wfi) = typeNameOf wfi typeNameOf (WellFormedSortSubst _ _ wfi) = typeNameOf wfi typeNameOf (WellFormedSortJudgement _ stn _ _ _ _ _) = stn instance SortOf WellFormedIndex where sortOf (WfIndex _ i) = sortOf i instance SortOf WellFormedSort where sortOf (WfSort _ s) = sortOf s symbolicTermToSTerm :: EnvM m => SymbolicTerm -> m STerm symbolicTermToSTerm (SymSubtree _ sv) = pure (SVar sv) symbolicTermToSTerm (SymCtorVarFree _ cn mv) = do stn <- lookupCtorType cn SCtorVar stn cn . IVar <$> toIndex mv symbolicTermToSTerm (SymCtorVarBound _ cn mv _ diff) = do stn <- lookupCtorType cn let ntn = typeNameOf mv pure (SCtorVar stn cn (IWeaken (I0 ntn stn) (evalBindSpec HV0 diff))) symbolicTermToSTerm (SymCtorReg _ cn sfs) = do stn <- lookupCtorType cn SCtorReg stn cn . catMaybes <$> traverse symbolicFieldToField sfs symbolicTermToSTerm (SymWeaken _ _ st diff) = SWeaken <$> symbolicTermToSTerm st <*> pure (evalBindSpec HV0 diff) symbolicTermToSTerm (SymSubst _ mv st1 st2) = SSubst <$> pure (T0 (typeNameOf mv)) <*> symbolicTermToSTerm st1 <*> symbolicTermToSTerm st2 symbolicFieldToField :: EnvM m => SymbolicField w -> m (Maybe (Field w)) symbolicFieldToField (SymFieldSort _ _ st) = Just . FieldSort <$> symbolicTermToSTerm st symbolicFieldToField (SymFieldEnv{}) = error "NOT IMPLEMENTED" symbolicFieldToField (SymFieldBinding{}) = pure Nothing symbolicFieldToField (SymFieldReferenceFree{}) = error "NOT IMPLEMENTED" symbolicFieldToField (SymFieldReferenceBound{}) = error "NOT IMPLEMENTED" symbolicEnvToETerm :: EnvM m => SymbolicEnv -> m ETerm symbolicEnvToETerm _se = case _se of SymEnvVar ev -> pure (EVar ev) SymEnvNil etn -> pure (ENil etn) SymEnvCons ntn se sts -> ECons <$> symbolicEnvToETerm se <*> pure ntn <*> (catMaybes <$> traverse symbolicFieldToField sts) SymEnvAppend l r -> EAppend <$> symbolicEnvToETerm l <*> symbolicEnvToETerm r SymEnvCall fn jv - > ECall fn jv < $ > lookupRelationOutput fn ( typeNameOf jv ) evalBindSpecItem :: BindSpecItem -> HVarlist evalBindSpecItem (BsiBinding mv) = HVS (typeNameOf mv) HV0 evalBindSpecItem (BsiCall fn sn) = HVCall fn (SVar sn) evalBindSpec :: HVarlist -> BindSpec -> HVarlist evalBindSpec h Nil = h evalBindSpec h (bs :. bsi) = HVAppend (evalBindSpec h bs) (evalBindSpecItem bsi)
674e0874baaad52e68808cdd4eee3a50f1ae3a29ced5a73376d7a8a098e669bc
cryptomeme/nario
Player.hs
-- Player (nario) module Player ( Player(..), PlayerType(..), newPlayer, updatePlayer, renderPlayer, playerGetCoin, addScore, getScrollPos, getPlayerX, getPlayerY, getPlayerVY, getPlayerHitRect, getPlayerCoin, getPlayerScore, getPlayerType, setPlayerType, setPlayerDamage, stampPlayer ) where import Multimedia . SDL ( blitSurface , pt ) import Data.Bits ((.&.)) import Util import AppUtil (KeyProc, padPressed, padPressing, PadBtn(..), cellCrd, KeyState(..), getImageSurface, Rect(..), putimg) import Const import Images import Field import Event import Actor (ActorWrapper(..)) import Actor.Shot import Mixer walkVx = one * 4 `div` 2 runVx = one * 11 `div` 4 acc = one `div` 32 acc2 = one `div` 14 jumpVy = -12 * gravity jumpVy2 = -13 * gravity scrollMinX = 5 * chrSize + 6 scrollMaxX = 8 * chrSize gravity2 = one `div` 6 -- Aを長押ししたときの重力 stampVy = -8 * gravity undeadFrame = frameRate * 2 -- Type of player data PlayerType = SmallNario | SuperNario | FireNario deriving (Eq) State data PlayerState = Normal | Dead deriving (Eq) -- Structure data Player = Player { pltype :: PlayerType, plstate :: PlayerState, x :: Int, y :: Int, vx :: Int, vy :: Int, scrx :: Int, stand :: Bool, undeadCount :: Int, coin :: Int, score :: Int, lr :: Int, pat :: Int, anm :: Int } newPlayer = Player { pltype = SmallNario, plstate = Normal, x = 3 * chrSize * one, y = 13 * chrSize * one, vx = 0, vy = 0, scrx = 0, stand = False, undeadCount = 0, coin = 0, score = 0, lr = 1, pat = 0, anm = 0 } patStop = 0 patWalk = 1 walkPatNum = 3 patJump = patWalk + walkPatNum patSlip = patJump + 1 patSit = patSlip + 1 patShot = patSit + 1 patDead = patShot + 2 imgTableSmall = [ [ImgNarioLStand, ImgNarioLWalk1, ImgNarioLWalk2, ImgNarioLWalk3, ImgNarioLJump, ImgNarioLSlip, ImgNarioLStand], [ImgNarioRStand, ImgNarioRWalk1, ImgNarioRWalk2, ImgNarioRWalk3, ImgNarioRJump, ImgNarioRSlip, ImgNarioRStand] ] imgTableSuper = [ [ImgSNarioLStand, ImgSNarioLWalk1, ImgSNarioLWalk2, ImgSNarioLWalk3, ImgSNarioLJump, ImgSNarioLSlip, ImgSNarioLSit], [ImgSNarioRStand, ImgSNarioRWalk1, ImgSNarioRWalk2, ImgSNarioRWalk3, ImgSNarioRJump, ImgSNarioRSlip, ImgSNarioRSit] ] imgTableFire = [ [ImgFNarioLStand, ImgFNarioLWalk1, ImgFNarioLWalk2, ImgFNarioLWalk3, ImgFNarioLJump, ImgFNarioLSlip, ImgFNarioLSit, ImgFNarioLShot], [ImgFNarioRStand, ImgFNarioRWalk1, ImgFNarioRWalk2, ImgFNarioRWalk3, ImgFNarioRJump, ImgFNarioRSlip, ImgFNarioRSit, ImgFNarioRShot] ] -- Move horizontal moveX :: KeyProc -> Player -> Player moveX kp self = if stand self then self' { lr = lr', pat = pat', anm = anm' } else self' where axtmp = if padd then 0 else (-padl + padr) * nowacc ax = if sgn (axtmp * vx self) < 0 then axtmp * 2 else axtmp vx' | ax /= 0 = rangeadd (vx self) ax (-maxspd) maxspd | stand self = friction (vx self) acc | otherwise = vx self x' = max xmin $ (x self) + vx' padd = if padPressing kp PadD then True else False padl = if padPressing kp PadL then 1 else 0 padr = if padPressing kp PadR then 1 else 0 maxspd | not $ stand self = walkVx `div` 2 | padPressing kp PadB = runVx | otherwise = walkVx nowacc | padPressing kp PadB = acc2 | otherwise = acc xmin = (scrx self + chrSize `div` 2) * one self' = self { x = x', vx = vx' } lr' = case (-padl + padr) of 0 -> lr self -1 -> 0 1 -> 1 pat' | padd && pltype self /= SmallNario = patSit | vx' == 0 = patStop | vx' > 0 && lr' == 0 = patSlip | vx' < 0 && lr' == 1 = patSlip | otherwise = (anm' `div` anmCnt) + patWalk anm' | vx' == 0 = 0 | otherwise = ((anm self) + (abs vx')) `mod` (walkPatNum * anmCnt) anmCnt = walkVx * 3 -- Check wall for moving horizontal direction checkX :: Field -> Player -> Player checkX fld self | dir == 0 = check (-1) $ check 1 $ self | otherwise = check dir $ self where dir = sgn $ vx self check dx self | isBlock $ fieldRef fld cx cy = self { x = (x self) - dx * one, vx = 0 } | otherwise = self where cx = cellCrd (x self + ofsx dx) cy = cellCrd (y self - chrSize `div` 2 * one) ofsx (-1) = -6 * one ofsx 1 = 5 * one -- Adjust horizontal scroll position scroll :: Player -> Player -> Player scroll opl self = self { scrx = scrx' } where odx = x opl `div` one - scrx opl dx = (max 0 $ vx self) * (scrollMaxX - scrollMinX) `div` runVx + scrollMinX scrx' | d > 0 = scrx self + d | otherwise = scrx self d = x self `div` one - scrx self - (max odx dx) Fall by gravity fall :: Bool -> Player -> Player fall abtn self | stand self = self | otherwise = self { y = y', vy = vy' } where ay | vy self < 0 && abtn = gravity2 | otherwise = gravity vy' = min maxVy $ vy self + ay y' = y self + vy' -- Check for stand on a floor checkFloor :: Field -> Player -> Player checkFloor fld self | stand' = self { stand = stand', y = ystand, vy = 0 } | otherwise = self { stand = stand' } where stand' | vy self >= 0 = isGround (-6) || isGround 5 | otherwise = stand self ystand = (cellCrd $ y self) * (chrSize * one) isGround ofsx = isBlock $ fieldRef fld (cellCrd $ x self + ofsx * one) (cellCrd (y self)) -- Check upper wall checkCeil :: Field -> Player -> (Player, [Event]) checkCeil fld self | stand self || vy self >= 0 || not isCeil = (self, []) | otherwise = (self { y = y', vy = 0 }, [EvHitBlock ImgBlock2 cx cy (pltype self /= SmallNario)]) where yofs = case pltype self of SmallNario -> 14 SuperNario -> 28 FireNario -> 28 ytmp = y self - yofs * one cx = cellCrd $ x self cy = cellCrd ytmp isCeil = isBlock $ fieldRef fld cx cy yground y = (cellCrd y) * (chrSize * one) y' = ((cy + 1) * chrSize + yofs) * one -- Do jump? doJump :: KeyProc -> Player -> (Player, [Event]) doJump kp self | stand self && padPressed kp PadA = (self { vy = vy', stand = False, pat = patJump }, [EvSound SndJump]) | otherwise = (self, []) where vy' = (jumpVy2 - jumpVy) * (abs $ vx self) `div` runVx + jumpVy -- Do shot? shot :: KeyProc -> Player -> (Player, [Event]) shot kp self | canShot && padPressed kp PadB = (shotPl, shotEv) | otherwise = (self, []) where canShot = pltype self == FireNario shotPl = self { pat = patShot } shotEv = [ EvAddActor $ ActorWrapper $ newShot (x self) (y self) (lr self), EvSound SndShot ] -- Update updatePlayer :: KeyProc -> Field -> Player -> (Player, [Event]) updatePlayer kp fld self = case plstate self of Normal -> updateNormal kp fld self' Dead -> updateDead kp fld self' where self' = decUndead self decUndead pl = pl { undeadCount = max 0 $ undeadCount pl - 1 } -- In normal state updateNormal :: KeyProc -> Field -> Player -> (Player, [Event]) updateNormal kp fld self = (self3, ev1 ++ ev2 ++ ev3) where (self1, ev1) = moveY $ scroll self $ checkX fld $ moveX kp self (self2, ev2) = checkCeil fld self1 (self3, ev3) = shot kp self2 moveY = doJump kp . checkFloor fld . fall (padPressing kp PadA) -- In dead state updateDead :: KeyProc -> Field -> Player -> (Player, [Event]) updateDead kp fld self = (fall False self, []) -- Get scroll position getScrollPos :: Player -> Int getScrollPos = scrx -- Get x position getPlayerX :: Player -> Int getPlayerX = x -- Get Y position getPlayerY :: Player -> Int getPlayerY = y -- Get y velocity getPlayerVY :: Player -> Int getPlayerVY = vy -- Get hit rect getPlayerHitRect :: Player -> Rect getPlayerHitRect self = Rect (xx - 6) (yy - 16) (xx + 6) yy where xx = x self `div` one yy = y self `div` one -- Get coin num getPlayerCoin :: Player -> Int getPlayerCoin = coin -- Get score getPlayerScore :: Player -> Int getPlayerScore = score -- Get type getPlayerType :: Player -> PlayerType getPlayerType = pltype -- Set type setPlayerType :: PlayerType -> Player -> Player setPlayerType t self = self { pltype = t } -- Set damage setPlayerDamage :: Player -> Player setPlayerDamage self | undeadCount self > 0 = self | pltype self == SmallNario = self { plstate = Dead, pat = patDead, vy = jumpVy, stand = False } | otherwise = self { pltype = SmallNario, undeadCount = undeadFrame } -- Stamp enemy stampPlayer :: Player -> Player stampPlayer self = self { vy = stampVy } -- Player get a coin playerGetCoin :: Player -> Player playerGetCoin self = self { coin = (coin self + 1) `mod` 100 } -- Add score addScore :: Int -> Player -> Player addScore a self = self { score = score self + a } -- Render renderPlayer sur imgres scrx self = do if undeadCount self == 0 || (undeadCount self .&. 1) /= 0 then putimg sur imgres imgtype sx posy else return () where posy = case pltype self of SmallNario -> sy - chrSize + 1 otherwise -> sy - chrSize * 2 + 1 imgtype | plstate self == Dead = ImgNarioDead | otherwise = imgtbl !! lr self !! pat self imgtbl = case pltype self of SmallNario -> imgTableSmall SuperNario -> imgTableSuper FireNario -> imgTableFire sx = x self `div` one - chrSize `div` 2 - scrx sy = y self `div` one - 8
null
https://raw.githubusercontent.com/cryptomeme/nario/5f1ef10a1530763e1d2f51d280266ba48dae0c26/Player.hs
haskell
Player (nario) Aを長押ししたときの重力 Type of player Structure Move horizontal Check wall for moving horizontal direction Adjust horizontal scroll position Check for stand on a floor Check upper wall Do jump? Do shot? Update In normal state In dead state Get scroll position Get x position Get Y position Get y velocity Get hit rect Get coin num Get score Get type Set type Set damage Stamp enemy Player get a coin Add score Render
module Player ( Player(..), PlayerType(..), newPlayer, updatePlayer, renderPlayer, playerGetCoin, addScore, getScrollPos, getPlayerX, getPlayerY, getPlayerVY, getPlayerHitRect, getPlayerCoin, getPlayerScore, getPlayerType, setPlayerType, setPlayerDamage, stampPlayer ) where import Multimedia . SDL ( blitSurface , pt ) import Data.Bits ((.&.)) import Util import AppUtil (KeyProc, padPressed, padPressing, PadBtn(..), cellCrd, KeyState(..), getImageSurface, Rect(..), putimg) import Const import Images import Field import Event import Actor (ActorWrapper(..)) import Actor.Shot import Mixer walkVx = one * 4 `div` 2 runVx = one * 11 `div` 4 acc = one `div` 32 acc2 = one `div` 14 jumpVy = -12 * gravity jumpVy2 = -13 * gravity scrollMinX = 5 * chrSize + 6 scrollMaxX = 8 * chrSize stampVy = -8 * gravity undeadFrame = frameRate * 2 data PlayerType = SmallNario | SuperNario | FireNario deriving (Eq) State data PlayerState = Normal | Dead deriving (Eq) data Player = Player { pltype :: PlayerType, plstate :: PlayerState, x :: Int, y :: Int, vx :: Int, vy :: Int, scrx :: Int, stand :: Bool, undeadCount :: Int, coin :: Int, score :: Int, lr :: Int, pat :: Int, anm :: Int } newPlayer = Player { pltype = SmallNario, plstate = Normal, x = 3 * chrSize * one, y = 13 * chrSize * one, vx = 0, vy = 0, scrx = 0, stand = False, undeadCount = 0, coin = 0, score = 0, lr = 1, pat = 0, anm = 0 } patStop = 0 patWalk = 1 walkPatNum = 3 patJump = patWalk + walkPatNum patSlip = patJump + 1 patSit = patSlip + 1 patShot = patSit + 1 patDead = patShot + 2 imgTableSmall = [ [ImgNarioLStand, ImgNarioLWalk1, ImgNarioLWalk2, ImgNarioLWalk3, ImgNarioLJump, ImgNarioLSlip, ImgNarioLStand], [ImgNarioRStand, ImgNarioRWalk1, ImgNarioRWalk2, ImgNarioRWalk3, ImgNarioRJump, ImgNarioRSlip, ImgNarioRStand] ] imgTableSuper = [ [ImgSNarioLStand, ImgSNarioLWalk1, ImgSNarioLWalk2, ImgSNarioLWalk3, ImgSNarioLJump, ImgSNarioLSlip, ImgSNarioLSit], [ImgSNarioRStand, ImgSNarioRWalk1, ImgSNarioRWalk2, ImgSNarioRWalk3, ImgSNarioRJump, ImgSNarioRSlip, ImgSNarioRSit] ] imgTableFire = [ [ImgFNarioLStand, ImgFNarioLWalk1, ImgFNarioLWalk2, ImgFNarioLWalk3, ImgFNarioLJump, ImgFNarioLSlip, ImgFNarioLSit, ImgFNarioLShot], [ImgFNarioRStand, ImgFNarioRWalk1, ImgFNarioRWalk2, ImgFNarioRWalk3, ImgFNarioRJump, ImgFNarioRSlip, ImgFNarioRSit, ImgFNarioRShot] ] moveX :: KeyProc -> Player -> Player moveX kp self = if stand self then self' { lr = lr', pat = pat', anm = anm' } else self' where axtmp = if padd then 0 else (-padl + padr) * nowacc ax = if sgn (axtmp * vx self) < 0 then axtmp * 2 else axtmp vx' | ax /= 0 = rangeadd (vx self) ax (-maxspd) maxspd | stand self = friction (vx self) acc | otherwise = vx self x' = max xmin $ (x self) + vx' padd = if padPressing kp PadD then True else False padl = if padPressing kp PadL then 1 else 0 padr = if padPressing kp PadR then 1 else 0 maxspd | not $ stand self = walkVx `div` 2 | padPressing kp PadB = runVx | otherwise = walkVx nowacc | padPressing kp PadB = acc2 | otherwise = acc xmin = (scrx self + chrSize `div` 2) * one self' = self { x = x', vx = vx' } lr' = case (-padl + padr) of 0 -> lr self -1 -> 0 1 -> 1 pat' | padd && pltype self /= SmallNario = patSit | vx' == 0 = patStop | vx' > 0 && lr' == 0 = patSlip | vx' < 0 && lr' == 1 = patSlip | otherwise = (anm' `div` anmCnt) + patWalk anm' | vx' == 0 = 0 | otherwise = ((anm self) + (abs vx')) `mod` (walkPatNum * anmCnt) anmCnt = walkVx * 3 checkX :: Field -> Player -> Player checkX fld self | dir == 0 = check (-1) $ check 1 $ self | otherwise = check dir $ self where dir = sgn $ vx self check dx self | isBlock $ fieldRef fld cx cy = self { x = (x self) - dx * one, vx = 0 } | otherwise = self where cx = cellCrd (x self + ofsx dx) cy = cellCrd (y self - chrSize `div` 2 * one) ofsx (-1) = -6 * one ofsx 1 = 5 * one scroll :: Player -> Player -> Player scroll opl self = self { scrx = scrx' } where odx = x opl `div` one - scrx opl dx = (max 0 $ vx self) * (scrollMaxX - scrollMinX) `div` runVx + scrollMinX scrx' | d > 0 = scrx self + d | otherwise = scrx self d = x self `div` one - scrx self - (max odx dx) Fall by gravity fall :: Bool -> Player -> Player fall abtn self | stand self = self | otherwise = self { y = y', vy = vy' } where ay | vy self < 0 && abtn = gravity2 | otherwise = gravity vy' = min maxVy $ vy self + ay y' = y self + vy' checkFloor :: Field -> Player -> Player checkFloor fld self | stand' = self { stand = stand', y = ystand, vy = 0 } | otherwise = self { stand = stand' } where stand' | vy self >= 0 = isGround (-6) || isGround 5 | otherwise = stand self ystand = (cellCrd $ y self) * (chrSize * one) isGround ofsx = isBlock $ fieldRef fld (cellCrd $ x self + ofsx * one) (cellCrd (y self)) checkCeil :: Field -> Player -> (Player, [Event]) checkCeil fld self | stand self || vy self >= 0 || not isCeil = (self, []) | otherwise = (self { y = y', vy = 0 }, [EvHitBlock ImgBlock2 cx cy (pltype self /= SmallNario)]) where yofs = case pltype self of SmallNario -> 14 SuperNario -> 28 FireNario -> 28 ytmp = y self - yofs * one cx = cellCrd $ x self cy = cellCrd ytmp isCeil = isBlock $ fieldRef fld cx cy yground y = (cellCrd y) * (chrSize * one) y' = ((cy + 1) * chrSize + yofs) * one doJump :: KeyProc -> Player -> (Player, [Event]) doJump kp self | stand self && padPressed kp PadA = (self { vy = vy', stand = False, pat = patJump }, [EvSound SndJump]) | otherwise = (self, []) where vy' = (jumpVy2 - jumpVy) * (abs $ vx self) `div` runVx + jumpVy shot :: KeyProc -> Player -> (Player, [Event]) shot kp self | canShot && padPressed kp PadB = (shotPl, shotEv) | otherwise = (self, []) where canShot = pltype self == FireNario shotPl = self { pat = patShot } shotEv = [ EvAddActor $ ActorWrapper $ newShot (x self) (y self) (lr self), EvSound SndShot ] updatePlayer :: KeyProc -> Field -> Player -> (Player, [Event]) updatePlayer kp fld self = case plstate self of Normal -> updateNormal kp fld self' Dead -> updateDead kp fld self' where self' = decUndead self decUndead pl = pl { undeadCount = max 0 $ undeadCount pl - 1 } updateNormal :: KeyProc -> Field -> Player -> (Player, [Event]) updateNormal kp fld self = (self3, ev1 ++ ev2 ++ ev3) where (self1, ev1) = moveY $ scroll self $ checkX fld $ moveX kp self (self2, ev2) = checkCeil fld self1 (self3, ev3) = shot kp self2 moveY = doJump kp . checkFloor fld . fall (padPressing kp PadA) updateDead :: KeyProc -> Field -> Player -> (Player, [Event]) updateDead kp fld self = (fall False self, []) getScrollPos :: Player -> Int getScrollPos = scrx getPlayerX :: Player -> Int getPlayerX = x getPlayerY :: Player -> Int getPlayerY = y getPlayerVY :: Player -> Int getPlayerVY = vy getPlayerHitRect :: Player -> Rect getPlayerHitRect self = Rect (xx - 6) (yy - 16) (xx + 6) yy where xx = x self `div` one yy = y self `div` one getPlayerCoin :: Player -> Int getPlayerCoin = coin getPlayerScore :: Player -> Int getPlayerScore = score getPlayerType :: Player -> PlayerType getPlayerType = pltype setPlayerType :: PlayerType -> Player -> Player setPlayerType t self = self { pltype = t } setPlayerDamage :: Player -> Player setPlayerDamage self | undeadCount self > 0 = self | pltype self == SmallNario = self { plstate = Dead, pat = patDead, vy = jumpVy, stand = False } | otherwise = self { pltype = SmallNario, undeadCount = undeadFrame } stampPlayer :: Player -> Player stampPlayer self = self { vy = stampVy } playerGetCoin :: Player -> Player playerGetCoin self = self { coin = (coin self + 1) `mod` 100 } addScore :: Int -> Player -> Player addScore a self = self { score = score self + a } renderPlayer sur imgres scrx self = do if undeadCount self == 0 || (undeadCount self .&. 1) /= 0 then putimg sur imgres imgtype sx posy else return () where posy = case pltype self of SmallNario -> sy - chrSize + 1 otherwise -> sy - chrSize * 2 + 1 imgtype | plstate self == Dead = ImgNarioDead | otherwise = imgtbl !! lr self !! pat self imgtbl = case pltype self of SmallNario -> imgTableSmall SuperNario -> imgTableSuper FireNario -> imgTableFire sx = x self `div` one - chrSize `div` 2 - scrx sy = y self `div` one - 8
1828737abae34a2c407f0fecb8e0a4870d40a8d6b6eb289885a58afcde68923a
realworldocaml/book
rule_cache.ml
open Import (* A type isomorphic to [Result], but without the negative connotations associated with the word "error". *) module Result = struct type ('hit, 'miss) t = | Hit of 'hit | Miss of 'miss end module Workspace_local = struct (* Stores information for deciding if a rule needs to be re-executed. *) module Database = struct module Entry = struct type t = { rule_digest : Digest.t ; dynamic_deps_stages : (Action_exec.Dynamic_dep.Set.t * Digest.t) list ; targets_digest : Digest.t } let to_dyn { rule_digest; dynamic_deps_stages; targets_digest } = Dyn.Record [ ("rule_digest", Digest.to_dyn rule_digest) ; ( "dynamic_deps_stages" , Dyn.list (Dyn.pair Action_exec.Dynamic_dep.Set.to_dyn Digest.to_dyn) dynamic_deps_stages ) ; ("targets_digest", Digest.to_dyn targets_digest) ] end Keyed by the first target of the rule . type t = Entry.t Path.Table.t let file = Path.relative Path.build_dir ".db" let to_dyn = Path.Table.to_dyn Entry.to_dyn module P = Dune_util.Persistent.Make (struct type nonrec t = t let name = "INCREMENTAL-DB" let version = 4 let to_dyn = to_dyn end) let needs_dumping = ref false let t = lazy (match P.load file with | Some t -> t (* This mutable table is safe: it's only used by [execute_rule_impl] to decide whether to rebuild a rule or not; [execute_rule_impl] ensures that the targets are produced deterministically. *) | None -> Path.Table.create 1024) let dump () = if !needs_dumping && Path.build_dir_exists () then ( needs_dumping := false; Console.Status_line.with_overlay (Live (fun () -> Pp.hbox (Pp.text "Saving build trace db..."))) ~f:(fun () -> P.dump file (Lazy.force t))) (* CR-someday amokhov: If this happens to be executed after we've cleared the status line and printed some text afterwards, [dump] would overwrite that text by the "Saving..." message. If this hypothetical scenario turns out to be a real problem, we will need to add some synchronisation mechanism to prevent clearing the status line too early. *) let () = at_exit dump let get path = let t = Lazy.force t in Path.Table.find t path let set path e = let t = Lazy.force t in needs_dumping := true; Path.Table.set t path e end let store ~head_target ~rule_digest ~dynamic_deps_stages ~targets_digest = Database.set (Path.build head_target) { rule_digest; dynamic_deps_stages; targets_digest } module Miss_reason = struct type t = | No_previous_record | Rule_changed of Digest.t * Digest.t | Targets_changed | Targets_missing | Dynamic_deps_changed | Always_rerun | Error_while_collecting_directory_targets of Unix_error.Detailed.t let report ~head_target reason = let reason = match reason with | No_previous_record -> "never seen this target before" | Rule_changed (before, after) -> sprintf "rule or dependencies changed: %s -> %s" (Digest.to_string before) (Digest.to_string after) | Targets_missing -> "target missing from build dir" | Targets_changed -> "target changed in build dir" | Always_rerun -> "not trying to use the cache" | Dynamic_deps_changed -> "dynamic dependencies changed" | Error_while_collecting_directory_targets unix_error -> sprintf "error while collecting directory targets: %s" (Unix_error.Detailed.to_string_hum unix_error) in Console.print_user_message (User_message.make [ Pp.hbox (Pp.textf "Workspace-local cache miss: %s: %s" (Path.Build.to_string head_target) reason) ]) end let compute_target_digests (targets : Targets.Validated.t) : (Digest.t Targets.Produced.t, Miss_reason.t) Result.t = match Targets.Produced.of_validated targets with | Error unix_error -> Miss (Error_while_collecting_directory_targets unix_error) | Ok targets -> ( match Targets.Produced.Option.mapi targets ~f:(fun target () -> Cached_digest.build_file ~allow_dirs:true target |> Cached_digest.Digest_result.to_option) with | Some produced_targets -> Hit produced_targets | None -> Miss Targets_missing) let lookup_impl ~rule_digest ~targets ~env ~build_deps = (* [prev_trace] will be [None] if [head_target] was never built before. *) let head_target = Targets.Validated.head targets in let prev_trace = Database.get (Path.build head_target) in let prev_trace_with_produced_targets = match prev_trace with | None -> Result.Miss Miss_reason.No_previous_record | Some prev_trace -> ( match Digest.equal prev_trace.rule_digest rule_digest with | false -> Miss (Rule_changed (prev_trace.rule_digest, rule_digest)) | true -> ( (* [compute_target_digests] returns a [Miss] if not all targets are available in the workspace-local cache. *) match compute_target_digests targets with | Miss reason -> Miss reason | Hit produced_targets -> ( match Digest.equal prev_trace.targets_digest (Targets.Produced.digest produced_targets) with | true -> Hit (prev_trace, produced_targets) | false -> Miss Targets_changed))) in match prev_trace_with_produced_targets with | Result.Miss reason -> Fiber.return (Result.Miss reason) | Hit (prev_trace, produced_targets) -> CR - someday aalekseyev : If there 's a change at one of the last stages , we still re - run all the previous stages , which is a bit of a waste . We could remember what stage needs re - running and only re - run that ( and later stages ) . we still re-run all the previous stages, which is a bit of a waste. We could remember what stage needs re-running and only re-run that (and later stages). *) let rec loop stages = match stages with | [] -> Fiber.return (Result.Hit produced_targets) | (deps, old_digest) :: rest -> ( let deps = Action_exec.Dynamic_dep.Set.to_dep_set deps in let open Fiber.O in let* deps = Memo.run (build_deps deps) in let new_digest = Dep.Facts.digest deps ~env in match Digest.equal old_digest new_digest with | true -> loop rest | false -> Fiber.return (Result.Miss Miss_reason.Dynamic_deps_changed) ) in loop prev_trace.dynamic_deps_stages let lookup ~always_rerun ~rule_digest ~targets ~env ~build_deps : Digest.t Targets.Produced.t option Fiber.t = let open Fiber.O in let+ result = match always_rerun with | true -> Fiber.return (Result.Miss Miss_reason.Always_rerun) | false -> lookup_impl ~rule_digest ~targets ~env ~build_deps in match result with | Hit result -> Some result | Miss reason -> let t = Build_config.get () in if t.cache_debug_flags.workspace_local_cache then Miss_reason.report reason ~head_target:(Targets.Validated.head targets); None end module Shared = struct let shared_cache_key_string_for_log ~rule_digest ~head_target = sprintf "[%s] (%s)" (Digest.to_string rule_digest) (Path.Build.to_string head_target) module Miss_reason = struct type t = | Cache_disabled | Cannot_go_in_shared_cache | Rerunning_for_reproducibility_check | Not_found_in_cache | Error of string let report ~rule_digest ~head_target reason = let reason = match reason with | Cache_disabled -> "cache disabled" | Cannot_go_in_shared_cache -> "can't go in shared cache" | Error exn -> sprintf "error: %s" exn | Rerunning_for_reproducibility_check -> "rerunning for reproducibility check" | Not_found_in_cache -> "not found in cache" in Console.print_user_message (User_message.make [ Pp.hbox (Pp.textf "Shared cache miss %s: %s" (shared_cache_key_string_for_log ~rule_digest ~head_target) reason) ]) end (* CR-someday amokhov: If the cloud cache is enabled, then before attempting to restore artifacts from the shared cache, we should send a download request for [rule_digest] to the cloud. *) let try_to_restore_from_shared_cache ~mode ~rule_digest ~head_target ~target_dir : (Digest.t Targets.Produced.t, Miss_reason.t) Result.t = let key () = shared_cache_key_string_for_log ~rule_digest ~head_target in match Dune_cache.Local.restore_artifacts ~mode ~rule_digest ~target_dir with | Restored res -> (* it's a small departure from the general "debug cache" semantics that we're also printing successes, but it can be useful to see successes too if the goal is to understand when and how the file in the build directory appeared *) let t = Build_config.get () in if t.cache_debug_flags.shared_cache then Log.info [ Pp.textf "cache restore success %s" (key ()) ]; Hit (Targets.Produced.of_file_list_exn res) | Not_found_in_cache -> Miss Not_found_in_cache | Error exn -> Miss (Error (Printexc.to_string exn)) let lookup_impl ~rule_digest ~targets ~target_dir = let t = Build_config.get () in match t.cache_config with | Disabled -> Result.Miss Miss_reason.Cache_disabled | Enabled { storage_mode = mode; reproducibility_check } -> ( match Dune_cache.Config.Reproducibility_check.sample reproducibility_check with | true -> CR - someday amokhov : Here we re - execute the rule , as in Jenga . To make [ check_probability ] more meaningful , we could first make sure that the shared cache actually does contain an entry for [ rule_digest ] . [check_probability] more meaningful, we could first make sure that the shared cache actually does contain an entry for [rule_digest]. *) Miss Rerunning_for_reproducibility_check | false -> try_to_restore_from_shared_cache ~mode ~head_target:(Targets.Validated.head targets) ~rule_digest ~target_dir) let lookup ~can_go_in_shared_cache ~rule_digest ~targets ~target_dir : Digest.t Targets.Produced.t option = let result = match can_go_in_shared_cache with | false -> Result.Miss Miss_reason.Cannot_go_in_shared_cache | true -> lookup_impl ~rule_digest ~targets ~target_dir in match result with | Hit result -> Some result | Miss reason -> let t = Build_config.get () in (match (t.cache_debug_flags.shared_cache, reason) with | true, _ | false, Error _ -> (* Always log errors because they are not expected as a part of normal operation and might indicate a problem. *) Miss_reason.report reason ~rule_digest ~head_target:(Targets.Validated.head targets) | false, _ -> ()); None (* If this function fails to store the rule to the shared cache, it returns [None] because we don't want this to be a catastrophic error. We simply log this incident and continue without saving the rule to the shared cache. *) let try_to_store_to_shared_cache ~mode ~rule_digest ~action ~file_targets : Digest.t Targets.Produced.t option Fiber.t = let open Fiber.O in let hex = Digest.to_string rule_digest in let pp_error msg = let action = Action.for_shell action |> Action_to_sh.pp in Pp.concat [ Pp.textf "cache store error [%s]: %s after executing" hex msg ; Pp.space ; Pp.char '(' ; action ; Pp.char ')' ] in let update_cached_digests ~targets_and_digests = List.iter targets_and_digests ~f:(fun (target, digest) -> Cached_digest.set target digest); Some (Targets.Produced.of_file_list_exn targets_and_digests) in match Path.Build.Map.to_list_map file_targets ~f:(fun target () -> Dune_cache.Local.Target.create target) |> Option.List.all with | None -> Fiber.return None | Some targets -> ( let compute_digest ~executable path = Stdune.Result.try_with (fun () -> Digest.file_with_executable_bit ~executable path) |> Fiber.return in Dune_cache.Local.store_artifacts ~mode ~rule_digest ~compute_digest targets >>| function | Stored targets_and_digests -> (* CR-someday amokhov: Here and in the case below we can inform the cloud daemon that a new cache entry can be uploaded to the cloud. *) Log.info [ Pp.textf "cache store success [%s]" hex ]; update_cached_digests ~targets_and_digests | Already_present targets_and_digests -> Log.info [ Pp.textf "cache store skipped [%s]: already present" hex ]; update_cached_digests ~targets_and_digests | Error (Unix.Unix_error (Unix.EXDEV, "link", file)) -> We can not hardlink accross partitions so we kindly let the user know that they should use copy cache instead . that they should use copy cache instead. *) Log.info [ Pp.concat [ Pp.textf "cache store error [%s]:" hex ; Pp.space ; Pp.textf "cannot link %s between file systems. Use \ (cache-storage-mode copy) instead." file ] ]; None | Error exn -> Log.info [ pp_error (Printexc.to_string exn) ]; None | Will_not_store_due_to_non_determinism sexp -> (* CR-someday amokhov: We should systematically log all warnings. *) Log.info [ pp_error (Sexp.to_string sexp) ]; User_warning.emit [ pp_error (Sexp.to_string sexp) ]; None) let compute_target_digests_or_raise_error exec_params ~loc ~produced_targets : Digest.t Targets.Produced.t = let compute_digest = Remove write permissions on targets . A first theoretical reason is that the build process should be a computational graph and targets should not change state once built . A very practical reason is that enabling the cache will remove write permission because of sharing anyway , so always removing them enables to catch mistakes earlier . the build process should be a computational graph and targets should not change state once built. A very practical reason is that enabling the cache will remove write permission because of hardlink sharing anyway, so always removing them enables to catch mistakes earlier. *) FIXME : searching the dune version for each single target seems way suboptimal . This information could probably be stored in rules directly . suboptimal. This information could probably be stored in rules directly. *) let remove_write_permissions = Execution_parameters.should_remove_write_permissions_on_generated_files exec_params in Cached_digest.refresh ~allow_dirs:true ~remove_write_permissions in match Targets.Produced.Option.mapi produced_targets ~f:(fun target () -> compute_digest target |> Cached_digest.Digest_result.to_option) with | Some result -> result | None -> ( let missing, errors = let process_target target (missing, errors) = let expected_syscall_path = Path.to_string (Path.build target) in match compute_digest target with | Ok (_ : Digest.t) -> (missing, errors) | No_such_file -> (target :: missing, errors) | Broken_symlink -> let error = Pp.verbatim "Broken symbolic link" in (missing, (target, error) :: errors) | Cyclic_symlink -> let error = Pp.verbatim "Cyclic symbolic link" in (missing, (target, error) :: errors) | Unexpected_kind file_kind -> let error = Pp.verbatim (sprintf "Unexpected file kind %S (%s)" (File_kind.to_string file_kind) (File_kind.to_string_hum file_kind)) in (missing, (target, error) :: errors) | Unix_error (error, syscall, arg) -> let unix_error = Unix_error.Detailed.create error ~syscall ~arg in (missing, (target, Unix_error.Detailed.pp unix_error) :: errors) | Error exn -> let error = match exn with | Sys_error msg -> Pp.verbatim (String.drop_prefix_if_exists ~prefix:(expected_syscall_path ^ ": ") msg) | exn -> Pp.verbatim (Printexc.to_string exn) in (missing, (target, error) :: errors) in Path.Build.Map.foldi (Targets.Produced.all_files produced_targets) ~init:([], []) ~f:(fun target () -> process_target target) in match (missing, errors) with | [], [] -> Code_error.raise "compute_target_digests_or_raise_error: spurious target digest \ failure" [ ("targets", Targets.Produced.to_dyn produced_targets) ] | missing, errors -> User_error.raise ~loc ((match missing with | [] -> [] | _ -> [ Pp.textf "Rule failed to generate the following targets:" ; Pp.enumerate ~f:Path.pp (List.rev_map ~f:Path.build missing) ]) @ match errors with | [] -> [] | _ -> [ Pp.textf "Error trying to read targets after a rule was run:" ; Pp.enumerate (List.rev errors) ~f:(fun (target, error) -> Pp.concat ~sep:(Pp.verbatim ": ") [ Path.pp (Path.build target); error ]) ])) let examine_targets_and_store ~can_go_in_shared_cache ~loc ~rule_digest ~execution_parameters ~action ~(produced_targets : unit Targets.Produced.t) : Digest.t Targets.Produced.t Fiber.t = let t = Build_config.get () in match t.cache_config with | Enabled { storage_mode = mode; reproducibility_check = _ } when can_go_in_shared_cache -> ( let open Fiber.O in let+ produced_targets_with_digests = try_to_store_to_shared_cache ~mode ~rule_digest ~file_targets:produced_targets.files ~action in match produced_targets_with_digests with | Some produced_targets_with_digests -> produced_targets_with_digests | None -> compute_target_digests_or_raise_error execution_parameters ~loc ~produced_targets) | _ -> Fiber.return (compute_target_digests_or_raise_error execution_parameters ~loc ~produced_targets) end
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_engine/rule_cache.ml
ocaml
A type isomorphic to [Result], but without the negative connotations associated with the word "error". Stores information for deciding if a rule needs to be re-executed. This mutable table is safe: it's only used by [execute_rule_impl] to decide whether to rebuild a rule or not; [execute_rule_impl] ensures that the targets are produced deterministically. CR-someday amokhov: If this happens to be executed after we've cleared the status line and printed some text afterwards, [dump] would overwrite that text by the "Saving..." message. If this hypothetical scenario turns out to be a real problem, we will need to add some synchronisation mechanism to prevent clearing the status line too early. [prev_trace] will be [None] if [head_target] was never built before. [compute_target_digests] returns a [Miss] if not all targets are available in the workspace-local cache. CR-someday amokhov: If the cloud cache is enabled, then before attempting to restore artifacts from the shared cache, we should send a download request for [rule_digest] to the cloud. it's a small departure from the general "debug cache" semantics that we're also printing successes, but it can be useful to see successes too if the goal is to understand when and how the file in the build directory appeared Always log errors because they are not expected as a part of normal operation and might indicate a problem. If this function fails to store the rule to the shared cache, it returns [None] because we don't want this to be a catastrophic error. We simply log this incident and continue without saving the rule to the shared cache. CR-someday amokhov: Here and in the case below we can inform the cloud daemon that a new cache entry can be uploaded to the cloud. CR-someday amokhov: We should systematically log all warnings.
open Import module Result = struct type ('hit, 'miss) t = | Hit of 'hit | Miss of 'miss end module Workspace_local = struct module Database = struct module Entry = struct type t = { rule_digest : Digest.t ; dynamic_deps_stages : (Action_exec.Dynamic_dep.Set.t * Digest.t) list ; targets_digest : Digest.t } let to_dyn { rule_digest; dynamic_deps_stages; targets_digest } = Dyn.Record [ ("rule_digest", Digest.to_dyn rule_digest) ; ( "dynamic_deps_stages" , Dyn.list (Dyn.pair Action_exec.Dynamic_dep.Set.to_dyn Digest.to_dyn) dynamic_deps_stages ) ; ("targets_digest", Digest.to_dyn targets_digest) ] end Keyed by the first target of the rule . type t = Entry.t Path.Table.t let file = Path.relative Path.build_dir ".db" let to_dyn = Path.Table.to_dyn Entry.to_dyn module P = Dune_util.Persistent.Make (struct type nonrec t = t let name = "INCREMENTAL-DB" let version = 4 let to_dyn = to_dyn end) let needs_dumping = ref false let t = lazy (match P.load file with | Some t -> t | None -> Path.Table.create 1024) let dump () = if !needs_dumping && Path.build_dir_exists () then ( needs_dumping := false; Console.Status_line.with_overlay (Live (fun () -> Pp.hbox (Pp.text "Saving build trace db..."))) ~f:(fun () -> P.dump file (Lazy.force t))) let () = at_exit dump let get path = let t = Lazy.force t in Path.Table.find t path let set path e = let t = Lazy.force t in needs_dumping := true; Path.Table.set t path e end let store ~head_target ~rule_digest ~dynamic_deps_stages ~targets_digest = Database.set (Path.build head_target) { rule_digest; dynamic_deps_stages; targets_digest } module Miss_reason = struct type t = | No_previous_record | Rule_changed of Digest.t * Digest.t | Targets_changed | Targets_missing | Dynamic_deps_changed | Always_rerun | Error_while_collecting_directory_targets of Unix_error.Detailed.t let report ~head_target reason = let reason = match reason with | No_previous_record -> "never seen this target before" | Rule_changed (before, after) -> sprintf "rule or dependencies changed: %s -> %s" (Digest.to_string before) (Digest.to_string after) | Targets_missing -> "target missing from build dir" | Targets_changed -> "target changed in build dir" | Always_rerun -> "not trying to use the cache" | Dynamic_deps_changed -> "dynamic dependencies changed" | Error_while_collecting_directory_targets unix_error -> sprintf "error while collecting directory targets: %s" (Unix_error.Detailed.to_string_hum unix_error) in Console.print_user_message (User_message.make [ Pp.hbox (Pp.textf "Workspace-local cache miss: %s: %s" (Path.Build.to_string head_target) reason) ]) end let compute_target_digests (targets : Targets.Validated.t) : (Digest.t Targets.Produced.t, Miss_reason.t) Result.t = match Targets.Produced.of_validated targets with | Error unix_error -> Miss (Error_while_collecting_directory_targets unix_error) | Ok targets -> ( match Targets.Produced.Option.mapi targets ~f:(fun target () -> Cached_digest.build_file ~allow_dirs:true target |> Cached_digest.Digest_result.to_option) with | Some produced_targets -> Hit produced_targets | None -> Miss Targets_missing) let lookup_impl ~rule_digest ~targets ~env ~build_deps = let head_target = Targets.Validated.head targets in let prev_trace = Database.get (Path.build head_target) in let prev_trace_with_produced_targets = match prev_trace with | None -> Result.Miss Miss_reason.No_previous_record | Some prev_trace -> ( match Digest.equal prev_trace.rule_digest rule_digest with | false -> Miss (Rule_changed (prev_trace.rule_digest, rule_digest)) | true -> ( match compute_target_digests targets with | Miss reason -> Miss reason | Hit produced_targets -> ( match Digest.equal prev_trace.targets_digest (Targets.Produced.digest produced_targets) with | true -> Hit (prev_trace, produced_targets) | false -> Miss Targets_changed))) in match prev_trace_with_produced_targets with | Result.Miss reason -> Fiber.return (Result.Miss reason) | Hit (prev_trace, produced_targets) -> CR - someday aalekseyev : If there 's a change at one of the last stages , we still re - run all the previous stages , which is a bit of a waste . We could remember what stage needs re - running and only re - run that ( and later stages ) . we still re-run all the previous stages, which is a bit of a waste. We could remember what stage needs re-running and only re-run that (and later stages). *) let rec loop stages = match stages with | [] -> Fiber.return (Result.Hit produced_targets) | (deps, old_digest) :: rest -> ( let deps = Action_exec.Dynamic_dep.Set.to_dep_set deps in let open Fiber.O in let* deps = Memo.run (build_deps deps) in let new_digest = Dep.Facts.digest deps ~env in match Digest.equal old_digest new_digest with | true -> loop rest | false -> Fiber.return (Result.Miss Miss_reason.Dynamic_deps_changed) ) in loop prev_trace.dynamic_deps_stages let lookup ~always_rerun ~rule_digest ~targets ~env ~build_deps : Digest.t Targets.Produced.t option Fiber.t = let open Fiber.O in let+ result = match always_rerun with | true -> Fiber.return (Result.Miss Miss_reason.Always_rerun) | false -> lookup_impl ~rule_digest ~targets ~env ~build_deps in match result with | Hit result -> Some result | Miss reason -> let t = Build_config.get () in if t.cache_debug_flags.workspace_local_cache then Miss_reason.report reason ~head_target:(Targets.Validated.head targets); None end module Shared = struct let shared_cache_key_string_for_log ~rule_digest ~head_target = sprintf "[%s] (%s)" (Digest.to_string rule_digest) (Path.Build.to_string head_target) module Miss_reason = struct type t = | Cache_disabled | Cannot_go_in_shared_cache | Rerunning_for_reproducibility_check | Not_found_in_cache | Error of string let report ~rule_digest ~head_target reason = let reason = match reason with | Cache_disabled -> "cache disabled" | Cannot_go_in_shared_cache -> "can't go in shared cache" | Error exn -> sprintf "error: %s" exn | Rerunning_for_reproducibility_check -> "rerunning for reproducibility check" | Not_found_in_cache -> "not found in cache" in Console.print_user_message (User_message.make [ Pp.hbox (Pp.textf "Shared cache miss %s: %s" (shared_cache_key_string_for_log ~rule_digest ~head_target) reason) ]) end let try_to_restore_from_shared_cache ~mode ~rule_digest ~head_target ~target_dir : (Digest.t Targets.Produced.t, Miss_reason.t) Result.t = let key () = shared_cache_key_string_for_log ~rule_digest ~head_target in match Dune_cache.Local.restore_artifacts ~mode ~rule_digest ~target_dir with | Restored res -> let t = Build_config.get () in if t.cache_debug_flags.shared_cache then Log.info [ Pp.textf "cache restore success %s" (key ()) ]; Hit (Targets.Produced.of_file_list_exn res) | Not_found_in_cache -> Miss Not_found_in_cache | Error exn -> Miss (Error (Printexc.to_string exn)) let lookup_impl ~rule_digest ~targets ~target_dir = let t = Build_config.get () in match t.cache_config with | Disabled -> Result.Miss Miss_reason.Cache_disabled | Enabled { storage_mode = mode; reproducibility_check } -> ( match Dune_cache.Config.Reproducibility_check.sample reproducibility_check with | true -> CR - someday amokhov : Here we re - execute the rule , as in Jenga . To make [ check_probability ] more meaningful , we could first make sure that the shared cache actually does contain an entry for [ rule_digest ] . [check_probability] more meaningful, we could first make sure that the shared cache actually does contain an entry for [rule_digest]. *) Miss Rerunning_for_reproducibility_check | false -> try_to_restore_from_shared_cache ~mode ~head_target:(Targets.Validated.head targets) ~rule_digest ~target_dir) let lookup ~can_go_in_shared_cache ~rule_digest ~targets ~target_dir : Digest.t Targets.Produced.t option = let result = match can_go_in_shared_cache with | false -> Result.Miss Miss_reason.Cannot_go_in_shared_cache | true -> lookup_impl ~rule_digest ~targets ~target_dir in match result with | Hit result -> Some result | Miss reason -> let t = Build_config.get () in (match (t.cache_debug_flags.shared_cache, reason) with | true, _ | false, Error _ -> Miss_reason.report reason ~rule_digest ~head_target:(Targets.Validated.head targets) | false, _ -> ()); None let try_to_store_to_shared_cache ~mode ~rule_digest ~action ~file_targets : Digest.t Targets.Produced.t option Fiber.t = let open Fiber.O in let hex = Digest.to_string rule_digest in let pp_error msg = let action = Action.for_shell action |> Action_to_sh.pp in Pp.concat [ Pp.textf "cache store error [%s]: %s after executing" hex msg ; Pp.space ; Pp.char '(' ; action ; Pp.char ')' ] in let update_cached_digests ~targets_and_digests = List.iter targets_and_digests ~f:(fun (target, digest) -> Cached_digest.set target digest); Some (Targets.Produced.of_file_list_exn targets_and_digests) in match Path.Build.Map.to_list_map file_targets ~f:(fun target () -> Dune_cache.Local.Target.create target) |> Option.List.all with | None -> Fiber.return None | Some targets -> ( let compute_digest ~executable path = Stdune.Result.try_with (fun () -> Digest.file_with_executable_bit ~executable path) |> Fiber.return in Dune_cache.Local.store_artifacts ~mode ~rule_digest ~compute_digest targets >>| function | Stored targets_and_digests -> Log.info [ Pp.textf "cache store success [%s]" hex ]; update_cached_digests ~targets_and_digests | Already_present targets_and_digests -> Log.info [ Pp.textf "cache store skipped [%s]: already present" hex ]; update_cached_digests ~targets_and_digests | Error (Unix.Unix_error (Unix.EXDEV, "link", file)) -> We can not hardlink accross partitions so we kindly let the user know that they should use copy cache instead . that they should use copy cache instead. *) Log.info [ Pp.concat [ Pp.textf "cache store error [%s]:" hex ; Pp.space ; Pp.textf "cannot link %s between file systems. Use \ (cache-storage-mode copy) instead." file ] ]; None | Error exn -> Log.info [ pp_error (Printexc.to_string exn) ]; None | Will_not_store_due_to_non_determinism sexp -> Log.info [ pp_error (Sexp.to_string sexp) ]; User_warning.emit [ pp_error (Sexp.to_string sexp) ]; None) let compute_target_digests_or_raise_error exec_params ~loc ~produced_targets : Digest.t Targets.Produced.t = let compute_digest = Remove write permissions on targets . A first theoretical reason is that the build process should be a computational graph and targets should not change state once built . A very practical reason is that enabling the cache will remove write permission because of sharing anyway , so always removing them enables to catch mistakes earlier . the build process should be a computational graph and targets should not change state once built. A very practical reason is that enabling the cache will remove write permission because of hardlink sharing anyway, so always removing them enables to catch mistakes earlier. *) FIXME : searching the dune version for each single target seems way suboptimal . This information could probably be stored in rules directly . suboptimal. This information could probably be stored in rules directly. *) let remove_write_permissions = Execution_parameters.should_remove_write_permissions_on_generated_files exec_params in Cached_digest.refresh ~allow_dirs:true ~remove_write_permissions in match Targets.Produced.Option.mapi produced_targets ~f:(fun target () -> compute_digest target |> Cached_digest.Digest_result.to_option) with | Some result -> result | None -> ( let missing, errors = let process_target target (missing, errors) = let expected_syscall_path = Path.to_string (Path.build target) in match compute_digest target with | Ok (_ : Digest.t) -> (missing, errors) | No_such_file -> (target :: missing, errors) | Broken_symlink -> let error = Pp.verbatim "Broken symbolic link" in (missing, (target, error) :: errors) | Cyclic_symlink -> let error = Pp.verbatim "Cyclic symbolic link" in (missing, (target, error) :: errors) | Unexpected_kind file_kind -> let error = Pp.verbatim (sprintf "Unexpected file kind %S (%s)" (File_kind.to_string file_kind) (File_kind.to_string_hum file_kind)) in (missing, (target, error) :: errors) | Unix_error (error, syscall, arg) -> let unix_error = Unix_error.Detailed.create error ~syscall ~arg in (missing, (target, Unix_error.Detailed.pp unix_error) :: errors) | Error exn -> let error = match exn with | Sys_error msg -> Pp.verbatim (String.drop_prefix_if_exists ~prefix:(expected_syscall_path ^ ": ") msg) | exn -> Pp.verbatim (Printexc.to_string exn) in (missing, (target, error) :: errors) in Path.Build.Map.foldi (Targets.Produced.all_files produced_targets) ~init:([], []) ~f:(fun target () -> process_target target) in match (missing, errors) with | [], [] -> Code_error.raise "compute_target_digests_or_raise_error: spurious target digest \ failure" [ ("targets", Targets.Produced.to_dyn produced_targets) ] | missing, errors -> User_error.raise ~loc ((match missing with | [] -> [] | _ -> [ Pp.textf "Rule failed to generate the following targets:" ; Pp.enumerate ~f:Path.pp (List.rev_map ~f:Path.build missing) ]) @ match errors with | [] -> [] | _ -> [ Pp.textf "Error trying to read targets after a rule was run:" ; Pp.enumerate (List.rev errors) ~f:(fun (target, error) -> Pp.concat ~sep:(Pp.verbatim ": ") [ Path.pp (Path.build target); error ]) ])) let examine_targets_and_store ~can_go_in_shared_cache ~loc ~rule_digest ~execution_parameters ~action ~(produced_targets : unit Targets.Produced.t) : Digest.t Targets.Produced.t Fiber.t = let t = Build_config.get () in match t.cache_config with | Enabled { storage_mode = mode; reproducibility_check = _ } when can_go_in_shared_cache -> ( let open Fiber.O in let+ produced_targets_with_digests = try_to_store_to_shared_cache ~mode ~rule_digest ~file_targets:produced_targets.files ~action in match produced_targets_with_digests with | Some produced_targets_with_digests -> produced_targets_with_digests | None -> compute_target_digests_or_raise_error execution_parameters ~loc ~produced_targets) | _ -> Fiber.return (compute_target_digests_or_raise_error execution_parameters ~loc ~produced_targets) end
aaa8adafb687026b520e238651be7c3edb714a339a408c054398d5422e5f8529
danieljharvey/mimsa
Scheme.hs
# LANGUAGE DerivingStrategies # {-# LANGUAGE OverloadedStrings #-} module Language.Mimsa.Types.Typechecker.Scheme where import qualified Data.Text as T import Language.Mimsa.Core data Scheme = Scheme [TypeIdentifier] MonoType deriving stock (Eq, Ord, Show) instance Printer Scheme where prettyPrint (Scheme vars mt) = varText <> prettyPrint mt where varText = case vars of [] -> "" a -> "[" <> T.intercalate ", " (prettyPrint <$> a) <> "] "
null
https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/compiler/src/Language/Mimsa/Types/Typechecker/Scheme.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DerivingStrategies # module Language.Mimsa.Types.Typechecker.Scheme where import qualified Data.Text as T import Language.Mimsa.Core data Scheme = Scheme [TypeIdentifier] MonoType deriving stock (Eq, Ord, Show) instance Printer Scheme where prettyPrint (Scheme vars mt) = varText <> prettyPrint mt where varText = case vars of [] -> "" a -> "[" <> T.intercalate ", " (prettyPrint <$> a) <> "] "
0ee7db544dd405a630e705576284f8a578bc7a89f29907abe9cbaa5380406c5e
TokTok/hs-toxcore
DhtPacketSpec.hs
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.DHT.DhtPacketSpec where import Test.Hspec import Test.QuickCheck import Data.Binary (Binary) import qualified Data.Binary as Binary (get, put) import qualified Data.Binary.Get as Binary (runGet) import qualified Data.Binary.Put as Binary (runPut) import Data.Proxy (Proxy (..)) import Network.Tox.Crypto.Key (Nonce) import Network.Tox.Crypto.KeyPair (KeyPair (..)) import Network.Tox.DHT.DhtPacket (DhtPacket (..)) import qualified Network.Tox.DHT.DhtPacket as DhtPacket import Network.Tox.EncodingSpec import Network.Tox.NodeInfo.NodeInfo (NodeInfo) encodeAndDecode :: (Binary a, Binary b) => KeyPair -> KeyPair -> Nonce -> a -> Maybe b encodeAndDecode senderKeyPair receiverKeyPair nonce payload = let KeyPair _ receiverPublicKey = receiverKeyPair packet = DhtPacket.encode senderKeyPair receiverPublicKey nonce payload packet' = Binary.runGet Binary.get $ Binary.runPut $ Binary.put packet in DhtPacket.decode receiverKeyPair packet' encodeAndDecodeString :: KeyPair -> KeyPair -> Nonce -> String -> Maybe String encodeAndDecodeString = encodeAndDecode encodeCharAndDecodeString :: KeyPair -> KeyPair -> Nonce -> Char -> Maybe String encodeCharAndDecodeString = encodeAndDecode encodeIntAndDecodeNodeInfo :: KeyPair -> KeyPair -> Nonce -> Int -> Maybe NodeInfo encodeIntAndDecodeNodeInfo = encodeAndDecode spec :: Spec spec = do rpcSpec (Proxy :: Proxy DhtPacket) binarySpec (Proxy :: Proxy DhtPacket) readShowSpec (Proxy :: Proxy DhtPacket) it "encodes and decodes packets" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Just payload it "fails to decode packets with the wrong secret key" $ property $ \senderKeyPair (KeyPair _ receiverPublicKey) badSecretKey nonce payload -> encodeAndDecodeString senderKeyPair (KeyPair badSecretKey receiverPublicKey) nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Partial)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeCharAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Fail)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeIntAndDecodeNodeInfo senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "should decode empty CipherText correctly" $ expectDecoded [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] $ DhtPacket (read "\"0000000000000000000000000000000000000000000000000000000000000000\"") (read "\"000000000000000000000000000000000000000000000000\"") (read "\"00000000000000000000000000000000\"")
null
https://raw.githubusercontent.com/TokTok/hs-toxcore/3ceab5974c36c4c5dbf7518ba733ec2b6084ce5d/test/Network/Tox/DHT/DhtPacketSpec.hs
haskell
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.DHT.DhtPacketSpec where import Test.Hspec import Test.QuickCheck import Data.Binary (Binary) import qualified Data.Binary as Binary (get, put) import qualified Data.Binary.Get as Binary (runGet) import qualified Data.Binary.Put as Binary (runPut) import Data.Proxy (Proxy (..)) import Network.Tox.Crypto.Key (Nonce) import Network.Tox.Crypto.KeyPair (KeyPair (..)) import Network.Tox.DHT.DhtPacket (DhtPacket (..)) import qualified Network.Tox.DHT.DhtPacket as DhtPacket import Network.Tox.EncodingSpec import Network.Tox.NodeInfo.NodeInfo (NodeInfo) encodeAndDecode :: (Binary a, Binary b) => KeyPair -> KeyPair -> Nonce -> a -> Maybe b encodeAndDecode senderKeyPair receiverKeyPair nonce payload = let KeyPair _ receiverPublicKey = receiverKeyPair packet = DhtPacket.encode senderKeyPair receiverPublicKey nonce payload packet' = Binary.runGet Binary.get $ Binary.runPut $ Binary.put packet in DhtPacket.decode receiverKeyPair packet' encodeAndDecodeString :: KeyPair -> KeyPair -> Nonce -> String -> Maybe String encodeAndDecodeString = encodeAndDecode encodeCharAndDecodeString :: KeyPair -> KeyPair -> Nonce -> Char -> Maybe String encodeCharAndDecodeString = encodeAndDecode encodeIntAndDecodeNodeInfo :: KeyPair -> KeyPair -> Nonce -> Int -> Maybe NodeInfo encodeIntAndDecodeNodeInfo = encodeAndDecode spec :: Spec spec = do rpcSpec (Proxy :: Proxy DhtPacket) binarySpec (Proxy :: Proxy DhtPacket) readShowSpec (Proxy :: Proxy DhtPacket) it "encodes and decodes packets" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Just payload it "fails to decode packets with the wrong secret key" $ property $ \senderKeyPair (KeyPair _ receiverPublicKey) badSecretKey nonce payload -> encodeAndDecodeString senderKeyPair (KeyPair badSecretKey receiverPublicKey) nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Partial)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeCharAndDecodeString senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "fails to decode packets with the wrong payload type (Fail)" $ property $ \senderKeyPair receiverKeyPair nonce payload -> encodeIntAndDecodeNodeInfo senderKeyPair receiverKeyPair nonce payload `shouldBe` Nothing it "should decode empty CipherText correctly" $ expectDecoded [ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ] $ DhtPacket (read "\"0000000000000000000000000000000000000000000000000000000000000000\"") (read "\"000000000000000000000000000000000000000000000000\"") (read "\"00000000000000000000000000000000\"")
666f9152be0834bb6779f210192b798e51abf14a5d4733269510b780e83e8851
jawline/c8hardcaml
c8_bin.ml
open Core let () = print_s [%message "currently empty"]
null
https://raw.githubusercontent.com/jawline/c8hardcaml/0b9c315beac69353d7fcb5e9efed275948bccd6a/bin/c8_bin.ml
ocaml
open Core let () = print_s [%message "currently empty"]
3f590bb7aee64588c8963f42ce216c250b63b31a1f1df6c44d0ac2f1268245c7
chrisroman/coc
ast.ml
open Core open Common type id = string [@@deriving sexp] type typed = | Untyped | Typed type term_t = | Id of id | Lambda of (id * term_t * term_t) | App of (term_t * term_t) | Product of (id * term_t * term_t) | Star [@@deriving sexp] type program = | Let of (typed * id * term_t * program) | Term of term_t | Theorem of (id * term_t * term_t * program) let rec string_of_term_t t = match t with | Id id -> id | Lambda (x, m, n) -> Printf.sprintf "(λ%s: %s) %s" x (string_of_term_t m) (string_of_term_t n) | App (m, n) -> Printf.sprintf "(%s %s)" (string_of_term_t m) (string_of_term_t n) | Product (x, m, n) -> Printf.sprintf "[%s: %s] %s" x (string_of_term_t m) (string_of_term_t n) | Star -> "*" let string_of_typed tc = match tc with | Untyped -> " Untyped" | Typed -> "" let rec string_of_program p = match p with | Let (tc, x, t, p') -> Printf.sprintf "let%s %s = %s in \n%s" (string_of_typed tc) x (string_of_term_t t) (string_of_program p') | Term t -> string_of_term_t t | Theorem (x, theorem, proof, prog) -> Printf.sprintf "Theorem %s = %s with \n\tProof %s;\n%s" x (string_of_term_t theorem) (string_of_term_t proof) (string_of_program prog) let rec is_context (term : term_t) : bool = match term with | Star -> true | Product (_, _, n) -> is_context n | _ -> false let assert_context (term : term_t) = m_assert (is_context term) ~msg:(Printf.sprintf "Expected term %s to be a context\n" (string_of_term_t term)) (* If term = [x1:M1]...[xn:Mn]* then we split off just the last element, i.e. * components, i.e. return [x1:M1]...[xn-1:Mn-1]* and (xn, Mn) * If term = [x:M]* then just return * and (x, M) * For consistent naming, we'll say we return a tuple of the "body" and "foot" * of the list *) let rec context_split_bf (term : term_t) : term_t * (id * term_t) = assert_context term; match term with | Product (x, m, Star) -> Star, (x, m) | Product (x, m, n) -> let (hd, tl) = context_split_bf n in Product (x, m, hd), tl | _ -> failwith (Printf.sprintf "Tried to call [context_split_bf] on an empty or invalid context term %s\n" (string_of_term_t term) ) (* If term = [x1:M1]...[xn:Mn]* then return the head and tail * i.e. return (x1, m1) and [x2:M2]...[xn:Mn]* * If term = [x:M]* then just return (x, M) and * *) let context_split_ht (term : term_t) : (id * term_t) * term_t = assert_context term; match term with | Product (x, m, Star) -> (x, m), Star | Product (x, m, n) -> (x, m), n | _ -> failwith (Printf.sprintf "Tried to call [context_split_ht] on an empty or invalid context term %s\n" (string_of_term_t term) ) let rec context_append (context : term_t) (x, m : id * term_t) : term_t = assert_context context; match context with | Star -> Product (x, m, Star) | Product (x', m', n) -> Product (x', m', context_append n (x, m)) | _ -> failwith (Printf.sprintf "Tried to call [context_append] on an invalid context term %s\n" (string_of_term_t context) ) let rec context_contains (context : term_t) (x, p : id * term_t) : bool = assert_context context; match context with | Star -> false | Product (x', m', n) -> (x = x' && p = m') || (context_contains n (x, p)) | _ -> failwith (Printf.sprintf "Tried to call [context_contains] on an invalid context term %s\n" (string_of_term_t context) ) (* Allows shadowing *) let rec context_get_impl (context : term_t) (x : id) (res : term_t option): term_t = match context with | Star -> begin match res with | None -> failwith (Printf.sprintf "Couldn't find %s in %s" x (string_of_term_t context)) | Some r -> r end | Product (x', m, n) -> let res = if x = x' then Some m else res in context_get_impl n x res | _ -> failwith (Printf.sprintf "Tried to call [context_get_impl] on an invalid context term %s\n" (string_of_term_t context) ) let context_get (context : term_t) (x : id) : term_t = assert_context context; context_get_impl context x None (* Return [n/x]term *) let rec subst_term (term : term_t) (n : term_t) (x : id) : term_t = match term with | Star -> Star | Id x' -> if x = x' then n else term | App (m', n') -> App (subst_term m' n x, subst_term n' n x) | Lambda (x', m', n') -> if x' <> x then Lambda (x', subst_term m' n x, subst_term n' n x) else failwith "trying to substitute a bound variable" | Product (x', m', n') -> Product (x', subst_term m' n x, subst_term n' n x) let rec alpha_equiv ?(map = []) (t1 : term_t) (t2 : term_t) : bool = match t1, t2 with | Star, Star -> true | Id x, Id y -> (* TODO: Not sure if the things aren't mapped, then they should be equal *) begin match List.Assoc.find map x ~equal:(=) with | None -> x = y | Some x' -> x' = y end | App (m1, n1), App (m2, n2) -> (alpha_equiv ~map m1 m2) && (alpha_equiv ~map n1 n2) | Lambda (x1, m1, n1), Lambda (x2, m2, n2) | Product (x1, m1, n1), Product (x2, m2, n2) -> let new_map = List.Assoc.add map x1 x2 ~equal:(=) in (alpha_equiv ~map:(new_map) m1 m2) && (alpha_equiv ~map:(new_map) n1 n2) | _ -> false let rec subst_binding (x : id) (t : term_t) (p : program) : program = match p with | Term t' -> Term (subst_term t' t x) | Let (tc, x', t', p') -> Let (tc, x', (subst_term t' t x), (subst_binding x t p')) | Theorem (x', theorem, proof, prog) -> Theorem (x', (subst_term theorem t x), (subst_term proof t x), (subst_binding x t prog))
null
https://raw.githubusercontent.com/chrisroman/coc/95e8c344c0694b4293aad04098c046652bf42652/ast.ml
ocaml
If term = [x1:M1]...[xn:Mn]* then we split off just the last element, i.e. * components, i.e. return [x1:M1]...[xn-1:Mn-1]* and (xn, Mn) * If term = [x:M]* then just return * and (x, M) * For consistent naming, we'll say we return a tuple of the "body" and "foot" * of the list If term = [x1:M1]...[xn:Mn]* then return the head and tail * i.e. return (x1, m1) and [x2:M2]...[xn:Mn]* * If term = [x:M]* then just return (x, M) and * Allows shadowing Return [n/x]term TODO: Not sure if the things aren't mapped, then they should be equal
open Core open Common type id = string [@@deriving sexp] type typed = | Untyped | Typed type term_t = | Id of id | Lambda of (id * term_t * term_t) | App of (term_t * term_t) | Product of (id * term_t * term_t) | Star [@@deriving sexp] type program = | Let of (typed * id * term_t * program) | Term of term_t | Theorem of (id * term_t * term_t * program) let rec string_of_term_t t = match t with | Id id -> id | Lambda (x, m, n) -> Printf.sprintf "(λ%s: %s) %s" x (string_of_term_t m) (string_of_term_t n) | App (m, n) -> Printf.sprintf "(%s %s)" (string_of_term_t m) (string_of_term_t n) | Product (x, m, n) -> Printf.sprintf "[%s: %s] %s" x (string_of_term_t m) (string_of_term_t n) | Star -> "*" let string_of_typed tc = match tc with | Untyped -> " Untyped" | Typed -> "" let rec string_of_program p = match p with | Let (tc, x, t, p') -> Printf.sprintf "let%s %s = %s in \n%s" (string_of_typed tc) x (string_of_term_t t) (string_of_program p') | Term t -> string_of_term_t t | Theorem (x, theorem, proof, prog) -> Printf.sprintf "Theorem %s = %s with \n\tProof %s;\n%s" x (string_of_term_t theorem) (string_of_term_t proof) (string_of_program prog) let rec is_context (term : term_t) : bool = match term with | Star -> true | Product (_, _, n) -> is_context n | _ -> false let assert_context (term : term_t) = m_assert (is_context term) ~msg:(Printf.sprintf "Expected term %s to be a context\n" (string_of_term_t term)) let rec context_split_bf (term : term_t) : term_t * (id * term_t) = assert_context term; match term with | Product (x, m, Star) -> Star, (x, m) | Product (x, m, n) -> let (hd, tl) = context_split_bf n in Product (x, m, hd), tl | _ -> failwith (Printf.sprintf "Tried to call [context_split_bf] on an empty or invalid context term %s\n" (string_of_term_t term) ) let context_split_ht (term : term_t) : (id * term_t) * term_t = assert_context term; match term with | Product (x, m, Star) -> (x, m), Star | Product (x, m, n) -> (x, m), n | _ -> failwith (Printf.sprintf "Tried to call [context_split_ht] on an empty or invalid context term %s\n" (string_of_term_t term) ) let rec context_append (context : term_t) (x, m : id * term_t) : term_t = assert_context context; match context with | Star -> Product (x, m, Star) | Product (x', m', n) -> Product (x', m', context_append n (x, m)) | _ -> failwith (Printf.sprintf "Tried to call [context_append] on an invalid context term %s\n" (string_of_term_t context) ) let rec context_contains (context : term_t) (x, p : id * term_t) : bool = assert_context context; match context with | Star -> false | Product (x', m', n) -> (x = x' && p = m') || (context_contains n (x, p)) | _ -> failwith (Printf.sprintf "Tried to call [context_contains] on an invalid context term %s\n" (string_of_term_t context) ) let rec context_get_impl (context : term_t) (x : id) (res : term_t option): term_t = match context with | Star -> begin match res with | None -> failwith (Printf.sprintf "Couldn't find %s in %s" x (string_of_term_t context)) | Some r -> r end | Product (x', m, n) -> let res = if x = x' then Some m else res in context_get_impl n x res | _ -> failwith (Printf.sprintf "Tried to call [context_get_impl] on an invalid context term %s\n" (string_of_term_t context) ) let context_get (context : term_t) (x : id) : term_t = assert_context context; context_get_impl context x None let rec subst_term (term : term_t) (n : term_t) (x : id) : term_t = match term with | Star -> Star | Id x' -> if x = x' then n else term | App (m', n') -> App (subst_term m' n x, subst_term n' n x) | Lambda (x', m', n') -> if x' <> x then Lambda (x', subst_term m' n x, subst_term n' n x) else failwith "trying to substitute a bound variable" | Product (x', m', n') -> Product (x', subst_term m' n x, subst_term n' n x) let rec alpha_equiv ?(map = []) (t1 : term_t) (t2 : term_t) : bool = match t1, t2 with | Star, Star -> true | Id x, Id y -> begin match List.Assoc.find map x ~equal:(=) with | None -> x = y | Some x' -> x' = y end | App (m1, n1), App (m2, n2) -> (alpha_equiv ~map m1 m2) && (alpha_equiv ~map n1 n2) | Lambda (x1, m1, n1), Lambda (x2, m2, n2) | Product (x1, m1, n1), Product (x2, m2, n2) -> let new_map = List.Assoc.add map x1 x2 ~equal:(=) in (alpha_equiv ~map:(new_map) m1 m2) && (alpha_equiv ~map:(new_map) n1 n2) | _ -> false let rec subst_binding (x : id) (t : term_t) (p : program) : program = match p with | Term t' -> Term (subst_term t' t x) | Let (tc, x', t', p') -> Let (tc, x', (subst_term t' t x), (subst_binding x t p')) | Theorem (x', theorem, proof, prog) -> Theorem (x', (subst_term theorem t x), (subst_term proof t x), (subst_binding x t prog))
5d285b379a6334aa5d813879ff55ceab2d4d28e7a93aa036165d0303c4096c2a
ypyf/fscm
stack.scm
(define stack '()) (define push! (lambda (x) (set! stack (cons x stack)))) (define pop! (lambda () (let ((temp (car stack))) (set! stack (cdr stack)) temp))) (push! 9) (push! 8) (push! 7)
null
https://raw.githubusercontent.com/ypyf/fscm/4e6a31665051d51bbcfc823ac8d85dcc3491a6ef/test/stack.scm
scheme
(define stack '()) (define push! (lambda (x) (set! stack (cons x stack)))) (define pop! (lambda () (let ((temp (car stack))) (set! stack (cdr stack)) temp))) (push! 9) (push! 8) (push! 7)
53eccce642a026264d10e95c3f88ece6a2f06d16714eabde175aa8203936b6c4
typelead/intellij-eta
FileViewProvider.hs
module FFI.Com.IntelliJ.Psi.FileViewProvider where import P data {-# CLASS "com.intellij.psi.FileViewProvider" #-} FileViewProvider = FileViewProvider (Object# FileViewProvider) deriving Class
null
https://raw.githubusercontent.com/typelead/intellij-eta/ee66d621aa0bfdf56d7d287279a9a54e89802cf9/plugin/src/main/eta/FFI/Com/IntelliJ/Psi/FileViewProvider.hs
haskell
# CLASS "com.intellij.psi.FileViewProvider" #
module FFI.Com.IntelliJ.Psi.FileViewProvider where import P FileViewProvider = FileViewProvider (Object# FileViewProvider) deriving Class
e62f6fa7cb44f226c1f2985ee6324397122670f37f6a49b5c22922022383254b
smart-chain-fr/tokenomia
LocalRepository.hs
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE DuplicateRecordFields # # LANGUAGE TupleSections # # LANGUAGE NumericUnderscores # # LANGUAGE NamedFieldPuns # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DerivingStrategies # # LANGUAGE DerivingVia # module Tokenomia.ICO.LocalRepository ( askRoundSettings ) where import Prelude hiding (round,print) import Plutus.V1.Ledger.Ada import Plutus.V1.Ledger.Value import Plutus.V1.Ledger.Interval import Data.List.NonEmpty import Tokenomia.Wallet.ChildAddress.ChildAddressRef import Control.Monad.Reader import Tokenomia.Common.Environment import Tokenomia.Wallet.ChildAddress.LocalRepository as ChildAddress import Tokenomia.ICO.Round.Settings import Tokenomia.Wallet.LocalRepository as Wallet import Tokenomia.Common.Shell.InteractiveMenu ( askMenu, DisplayMenuItem(..) ) import Tokenomia.Common.Shell.Console (printLn) data ICO = ICO { projectName :: String , rounds :: NonEmpty Round} instance DisplayMenuItem ICO where displayMenuItem ICO {..} = projectName data Round = Round { title :: String , settings :: RoundSettings } instance DisplayMenuItem Round where displayMenuItem Round {..} = title askRoundSettings :: ( MonadIO m , MonadReader Environment m) => m RoundSettings askRoundSettings = do printLn "Select Your ICO :" ICO {..} <- getICOs >>= askMenu printLn "Select Your Round :" settings <$> askMenu rounds getICOs :: ( MonadIO m , MonadReader Environment m) => m (NonEmpty ICO) getICOs = do ask >>= \case Testnet {} -> error "no testnet..." Mainnet {} -> do flashSale <- getFlashSaleSettings publicSale <- getPublicSaleSettings return $ ICO { projectName = "CardaShift (Mainnet with CLAP !!!)" , rounds = flashSale :| [publicSale]} :| [] getFlashSaleSettings :: ( MonadIO m , MonadReader Environment m) => m Round getFlashSaleSettings = do Wallet{name= feesWalletName} <- Wallet.fetchById "Cardashift.Fees" fees <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef feesWalletName 0) Wallet{name= exchangeWalletName} <- Wallet.fetchById "Cardashift.Flash.Sale.Exchange" exchange <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef exchangeWalletName 0) investorsWallet <- Wallet.fetchById "Cardashift.Flash.Sale.Investors" Wallet{name= tokenWalletName} <- Wallet.fetchById "Cardashift.Flash.Sale.Tokens" tokens <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef tokenWalletName 0) Wallet{name= nextExchangeWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Exchange" nextExchangeAddress <- ChildAddress.address <$> ChildAddress.fetchById (ChildAddressRef nextExchangeWalletName 0) Wallet{name= collateralWalletName} <- Wallet.fetchById "Global.Collateral" collateral <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef collateralWalletName 0) ask >>= (\case Mainnet {} -> return $ Round { title = "Flash Sale (Mainnet !!!!!)" , settings = RoundSettings { syncSlot = Nothing , maximumAdaPerAddress = adaOf 50_000 , minimumAdaPerFund = adaOf 3 , timeRange = interval 51_73_71_99 52_80_66_55 , kycIntegration = Integration { params = \(ChildAddressIndex index) -> "admin=xR0CE2Vk80fOoD57slc4&from_user=" <> show index <> "&round=1" , url = ""} " 3657151839007cfd06deeb174987957dc9c21cfd3863d384c0d0293a " " 434c41505554 " , investorsWallet = investorsWallet , previousRoundMaybe = Nothing , nextRoundMaybe = Just $ NextRound nextExchangeAddress , tokenRatePerLovelace = 36_000 / 1_000_000 , addresses = RoundAddresses { exchange = exchange , collateral = collateral , tokens = tokens , adaSink = "DdzFFzCqrhsuG7R4n5w9vr2Zo6quuzVbqQbfcDm8BZV29p5T8yTfBnz4Jx3mmgsXCoDtjpCVyB61ttV4MVsVivnQHMKEzFozBHVE8Emq" , fees } }} Testnet {} -> error "No Testnet for Flash Sale anymore") getPublicSaleSettings :: ( MonadIO m , MonadReader Environment m) => m Round getPublicSaleSettings = do Wallet{name= collateralWalletName} <- Wallet.fetchById "Global.Collateral" collateral <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef collateralWalletName 0) Wallet{name= feesWalletName} <- Wallet.fetchById "Cardashift.Fees" fees <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef feesWalletName 0) previousInvestorWalletRound <- Wallet.fetchById "Cardashift.Flash.Sale.Investors" previousExchangeWalletRound <- Wallet.fetchById "Cardashift.Flash.Sale.Exchange" investorsWallet <- Wallet.fetchById "Cardashift.Public.Sale.Investors" Wallet{name= tokenWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Tokens" tokens <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef tokenWalletName 0) Wallet{name= exchangeWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Exchange" exchange <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef exchangeWalletName 0) ask >>= (\case Testnet {} -> error "No Testnet for Public Sale anymore" Mainnet {} -> return $ Round { title = "Public Sale (Mainnet !!!!!)" , settings = RoundSettings { syncSlot = Nothing , maximumAdaPerAddress = adaOf 25_000 , minimumAdaPerFund = adaOf 3 51_80_66_55 , kycIntegration = Integration { params = \(ChildAddressIndex index) -> "admin=xR0CE2Vk80fOoD57slc4&from_user=" <> show index <> "&round=2" , url = ""} , exchangeTokenId = assetClass "db30c7905f598ed0154de14f970de0f61f0cb3943ed82c891968480a" "434c4150" , investorsWallet = investorsWallet , previousRoundMaybe = Just PreviousRound {investorsWallet = previousInvestorWalletRound , exchangeWallet = previousExchangeWalletRound} , nextRoundMaybe = Nothing , tokenRatePerLovelace = 30_000 / 1_000_000 , addresses = RoundAddresses { exchange = exchange , collateral = collateral , tokens = tokens , adaSink = "DdzFFzCqrhsuG7R4n5w9vr2Zo6quuzVbqQbfcDm8BZV29p5T8yTfBnz4Jx3mmgsXCoDtjpCVyB61ttV4MVsVivnQHMKEzFozBHVE8Emq" , fees } }})
null
https://raw.githubusercontent.com/smart-chain-fr/tokenomia/dfb46829f0a88c559eddb3181e5320ed1a33601e/src/Tokenomia/ICO/LocalRepository.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE DuplicateRecordFields # # LANGUAGE TupleSections # # LANGUAGE NumericUnderscores # # LANGUAGE NamedFieldPuns # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DerivingStrategies # # LANGUAGE DerivingVia # module Tokenomia.ICO.LocalRepository ( askRoundSettings ) where import Prelude hiding (round,print) import Plutus.V1.Ledger.Ada import Plutus.V1.Ledger.Value import Plutus.V1.Ledger.Interval import Data.List.NonEmpty import Tokenomia.Wallet.ChildAddress.ChildAddressRef import Control.Monad.Reader import Tokenomia.Common.Environment import Tokenomia.Wallet.ChildAddress.LocalRepository as ChildAddress import Tokenomia.ICO.Round.Settings import Tokenomia.Wallet.LocalRepository as Wallet import Tokenomia.Common.Shell.InteractiveMenu ( askMenu, DisplayMenuItem(..) ) import Tokenomia.Common.Shell.Console (printLn) data ICO = ICO { projectName :: String , rounds :: NonEmpty Round} instance DisplayMenuItem ICO where displayMenuItem ICO {..} = projectName data Round = Round { title :: String , settings :: RoundSettings } instance DisplayMenuItem Round where displayMenuItem Round {..} = title askRoundSettings :: ( MonadIO m , MonadReader Environment m) => m RoundSettings askRoundSettings = do printLn "Select Your ICO :" ICO {..} <- getICOs >>= askMenu printLn "Select Your Round :" settings <$> askMenu rounds getICOs :: ( MonadIO m , MonadReader Environment m) => m (NonEmpty ICO) getICOs = do ask >>= \case Testnet {} -> error "no testnet..." Mainnet {} -> do flashSale <- getFlashSaleSettings publicSale <- getPublicSaleSettings return $ ICO { projectName = "CardaShift (Mainnet with CLAP !!!)" , rounds = flashSale :| [publicSale]} :| [] getFlashSaleSettings :: ( MonadIO m , MonadReader Environment m) => m Round getFlashSaleSettings = do Wallet{name= feesWalletName} <- Wallet.fetchById "Cardashift.Fees" fees <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef feesWalletName 0) Wallet{name= exchangeWalletName} <- Wallet.fetchById "Cardashift.Flash.Sale.Exchange" exchange <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef exchangeWalletName 0) investorsWallet <- Wallet.fetchById "Cardashift.Flash.Sale.Investors" Wallet{name= tokenWalletName} <- Wallet.fetchById "Cardashift.Flash.Sale.Tokens" tokens <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef tokenWalletName 0) Wallet{name= nextExchangeWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Exchange" nextExchangeAddress <- ChildAddress.address <$> ChildAddress.fetchById (ChildAddressRef nextExchangeWalletName 0) Wallet{name= collateralWalletName} <- Wallet.fetchById "Global.Collateral" collateral <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef collateralWalletName 0) ask >>= (\case Mainnet {} -> return $ Round { title = "Flash Sale (Mainnet !!!!!)" , settings = RoundSettings { syncSlot = Nothing , maximumAdaPerAddress = adaOf 50_000 , minimumAdaPerFund = adaOf 3 , timeRange = interval 51_73_71_99 52_80_66_55 , kycIntegration = Integration { params = \(ChildAddressIndex index) -> "admin=xR0CE2Vk80fOoD57slc4&from_user=" <> show index <> "&round=1" , url = ""} " 3657151839007cfd06deeb174987957dc9c21cfd3863d384c0d0293a " " 434c41505554 " , investorsWallet = investorsWallet , previousRoundMaybe = Nothing , nextRoundMaybe = Just $ NextRound nextExchangeAddress , tokenRatePerLovelace = 36_000 / 1_000_000 , addresses = RoundAddresses { exchange = exchange , collateral = collateral , tokens = tokens , adaSink = "DdzFFzCqrhsuG7R4n5w9vr2Zo6quuzVbqQbfcDm8BZV29p5T8yTfBnz4Jx3mmgsXCoDtjpCVyB61ttV4MVsVivnQHMKEzFozBHVE8Emq" , fees } }} Testnet {} -> error "No Testnet for Flash Sale anymore") getPublicSaleSettings :: ( MonadIO m , MonadReader Environment m) => m Round getPublicSaleSettings = do Wallet{name= collateralWalletName} <- Wallet.fetchById "Global.Collateral" collateral <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef collateralWalletName 0) Wallet{name= feesWalletName} <- Wallet.fetchById "Cardashift.Fees" fees <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef feesWalletName 0) previousInvestorWalletRound <- Wallet.fetchById "Cardashift.Flash.Sale.Investors" previousExchangeWalletRound <- Wallet.fetchById "Cardashift.Flash.Sale.Exchange" investorsWallet <- Wallet.fetchById "Cardashift.Public.Sale.Investors" Wallet{name= tokenWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Tokens" tokens <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef tokenWalletName 0) Wallet{name= exchangeWalletName} <- Wallet.fetchById "Cardashift.Public.Sale.Exchange" exchange <- toIndexedAddress <$> ChildAddress.fetchById (ChildAddressRef exchangeWalletName 0) ask >>= (\case Testnet {} -> error "No Testnet for Public Sale anymore" Mainnet {} -> return $ Round { title = "Public Sale (Mainnet !!!!!)" , settings = RoundSettings { syncSlot = Nothing , maximumAdaPerAddress = adaOf 25_000 , minimumAdaPerFund = adaOf 3 51_80_66_55 , kycIntegration = Integration { params = \(ChildAddressIndex index) -> "admin=xR0CE2Vk80fOoD57slc4&from_user=" <> show index <> "&round=2" , url = ""} , exchangeTokenId = assetClass "db30c7905f598ed0154de14f970de0f61f0cb3943ed82c891968480a" "434c4150" , investorsWallet = investorsWallet , previousRoundMaybe = Just PreviousRound {investorsWallet = previousInvestorWalletRound , exchangeWallet = previousExchangeWalletRound} , nextRoundMaybe = Nothing , tokenRatePerLovelace = 30_000 / 1_000_000 , addresses = RoundAddresses { exchange = exchange , collateral = collateral , tokens = tokens , adaSink = "DdzFFzCqrhsuG7R4n5w9vr2Zo6quuzVbqQbfcDm8BZV29p5T8yTfBnz4Jx3mmgsXCoDtjpCVyB61ttV4MVsVivnQHMKEzFozBHVE8Emq" , fees } }})
9fd064a006b5a805655816659f50126f1c9620ce34a6d936239a210d731c5ae5
wangweihao/ProgrammingErlangAnswer
2.erl
在 Erlang shell 里输入一些命令。不要忘了以句号和空白结束命令 1 > X = 999 . 2 > X * 2 . 3 > io : format("hello world ~n " )
null
https://raw.githubusercontent.com/wangweihao/ProgrammingErlangAnswer/b145b5e6a19cb866ce5d2ceeac116d751f6e2b3d/2/2/2.erl
erlang
在 Erlang shell 里输入一些命令。不要忘了以句号和空白结束命令 1 > X = 999 . 2 > X * 2 . 3 > io : format("hello world ~n " )
afcde40bcc514ae8db5b456ae274b617ac1471871e62a6b63ef897a9d3176473
bobzhang/fan
gdefs.ml
(* the [location] and the parsed value *) type 'a cont_parse = Locf.t -> Gaction.t -> 'a Tokenf.parse type entry = { name : string; mutable start : int -> Gaction.t Tokenf.parse ; mutable continue : int -> Gaction.t cont_parse ; mutable levels : level list ; (* sorted list *) mutable freezed : bool;} (* level is the runtime which is not used by the compiler *) and level = { level : int; lassoc : bool ; productions : production list ; (* the raw productions stored in the level*) lsuffix : tree ; lprefix : tree} and asymbol = | Nterm of entry the second argument is the level name | List0 of symbol | List1 of symbol | Try of symbol | Peek of symbol | Self | List0sep of (symbol * symbol) | List1sep of (symbol * symbol) | Token of Tokenf.pattern and symbol = | Nterm of entry the second argument is the level name | List0 of symbol | List0sep of (symbol * symbol) | List1 of symbol | List1sep of (symbol * symbol) | Try of symbol | Peek of symbol | Self | Token of Tokenf.pattern and tree = (* internal struccture *) | Node of node | LocAct of anno_action (* * anno_action list *) | DeadEnd and node = { node : symbol ; son : tree ; brother : tree } and production= { symbols : symbol list; annot : string; fn : Gaction.t } and anno_action = {arity : int ; symbols : symbol list; annot : string; fn : Gaction.t } (** [olevel] is the [processed output] from the Fgram DDSL, the runtime representation is [level], there is a function [Ginsert.level_of_olevel] which converts the processed output into the runtime BOOTSTRAPING *) type label = int option type olevel = { label : label ; lassoc : bool; productions : production list } (* type single_extend_statement = *) type delete_statment = symbol list (* local variables: *) compile - command : " cd .. & & pmake treeparser / gdefs.cmo " (* end: *)
null
https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/treeparser/gdefs.ml
ocaml
the [location] and the parsed value sorted list level is the runtime which is not used by the compiler the raw productions stored in the level internal struccture * anno_action list * [olevel] is the [processed output] from the Fgram DDSL, the runtime representation is [level], there is a function [Ginsert.level_of_olevel] which converts the processed output into the runtime BOOTSTRAPING type single_extend_statement = local variables: end:
type 'a cont_parse = Locf.t -> Gaction.t -> 'a Tokenf.parse type entry = { name : string; mutable start : int -> Gaction.t Tokenf.parse ; mutable continue : int -> Gaction.t cont_parse ; mutable freezed : bool;} and level = { level : int; lassoc : bool ; lsuffix : tree ; lprefix : tree} and asymbol = | Nterm of entry the second argument is the level name | List0 of symbol | List1 of symbol | Try of symbol | Peek of symbol | Self | List0sep of (symbol * symbol) | List1sep of (symbol * symbol) | Token of Tokenf.pattern and symbol = | Nterm of entry the second argument is the level name | List0 of symbol | List0sep of (symbol * symbol) | List1 of symbol | List1sep of (symbol * symbol) | Try of symbol | Peek of symbol | Self | Token of Tokenf.pattern | Node of node | DeadEnd and node = { node : symbol ; son : tree ; brother : tree } and production= { symbols : symbol list; annot : string; fn : Gaction.t } and anno_action = {arity : int ; symbols : symbol list; annot : string; fn : Gaction.t } type label = int option type olevel = { label : label ; lassoc : bool; productions : production list } type delete_statment = symbol list compile - command : " cd .. & & pmake treeparser / gdefs.cmo "
e8a6a79495edd371bea154eb9c95cb2fd836f50f5092fa6ec3bab2ff7566c5d8
cirfi/sicp-my-solutions
1.15.scm
;;; a. 5 ;;; b. space: O(log(n)) ;;; time: O(log(n))
null
https://raw.githubusercontent.com/cirfi/sicp-my-solutions/4b6cc17391aa2c8c033b42b076a663b23aa022de/ch1/1.15.scm
scheme
a. 5 b. space: O(log(n)) time: O(log(n))
712e38ffc2afc9f11ec976f951e1339843c41a334e82da1475e5f3598ba20d3b
tsloughter/kuberl
kuberl_v1_persistent_volume_claim.erl
-module(kuberl_v1_persistent_volume_claim). -export([encode/1]). -export_type([kuberl_v1_persistent_volume_claim/0]). -type kuberl_v1_persistent_volume_claim() :: #{ 'apiVersion' => binary(), 'kind' => binary(), 'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(), 'spec' => kuberl_v1_persistent_volume_claim_spec:kuberl_v1_persistent_volume_claim_spec(), 'status' => kuberl_v1_persistent_volume_claim_status:kuberl_v1_persistent_volume_claim_status() }. encode(#{ 'apiVersion' := ApiVersion, 'kind' := Kind, 'metadata' := Metadata, 'spec' := Spec, 'status' := Status }) -> #{ 'apiVersion' => ApiVersion, 'kind' => Kind, 'metadata' => Metadata, 'spec' => Spec, 'status' => Status }.
null
https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1_persistent_volume_claim.erl
erlang
-module(kuberl_v1_persistent_volume_claim). -export([encode/1]). -export_type([kuberl_v1_persistent_volume_claim/0]). -type kuberl_v1_persistent_volume_claim() :: #{ 'apiVersion' => binary(), 'kind' => binary(), 'metadata' => kuberl_v1_object_meta:kuberl_v1_object_meta(), 'spec' => kuberl_v1_persistent_volume_claim_spec:kuberl_v1_persistent_volume_claim_spec(), 'status' => kuberl_v1_persistent_volume_claim_status:kuberl_v1_persistent_volume_claim_status() }. encode(#{ 'apiVersion' := ApiVersion, 'kind' := Kind, 'metadata' := Metadata, 'spec' := Spec, 'status' := Status }) -> #{ 'apiVersion' => ApiVersion, 'kind' => Kind, 'metadata' => Metadata, 'spec' => Spec, 'status' => Status }.
0af2d8944bc84f4bd4f627ec707e951334318d850e709d29f1d613a0bad702bd
dmbarbour/awelon
Env.hs
-- | environment variables, paths and directories module AO.Env ( getAO_TEMP , getAO_PATH , getRscDir , getJitDir ) where import Control.Applicative import Data.Either import qualified Data.Text as T import qualified Filesystem as FS import qualified Filesystem.Path.CurrentOS as FS import qualified System.Environment as Env import qualified System.IO.Error as Err getEnvDefault :: String -> String -> IO String getEnvDefault var defaultVal = withDefault <$> getVar where withDefault = either (const defaultVal) id getVar = Err.tryIOError (Env.getEnv var) -- (idempotent) obtain (and create) the AO_TEMP directory may raise an IOError based on permissions or similar getAO_TEMP :: IO FS.FilePath getAO_TEMP = getEnvDefault "AO_TEMP" "aotmp" >>= \ d0 -> let fp0 = FS.fromText (T.pack d0) in FS.createTree fp0 >> canonicalizeDirPath fp0 ( idempotent ) obtain ( and create ) the ABC ciphertext resource -- storage directory. This will serve as the primary location for -- resources until we upgrade to a proper database. getRscDir :: IO FS.FilePath getRscDir = getAO_TEMP >>= \ aoTmp -> let rscDir = aoTmp FS.</> FS.fromText (T.pack "rsc") in FS.createDirectory True rscDir >> return rscDir -- | (idempotent) obtain or create the JIT directory getJitDir :: IO FS.FilePath getJitDir = getAO_TEMP >>= \ aoTmp -> let jitDir = aoTmp FS.</> FS.fromText (T.pack "jit") in FS.createDirectory True jitDir >> return jitDir -- | obtain valid filesystem paths from AO_PATH environment variable -- (defaults empty; does not use current path) getAO_PATH :: IO [FS.FilePath] getAO_PATH = getEnvDefault "AO_PATH" "" >>= \ sps -> let paths = FS.splitSearchPathString sps in let canonize = Err.tryIOError . canonicalizeDirPath in rights <$> mapM canonize paths canonizalize + assert isDirectory ( may fail with IOError ) canonicalizeDirPath :: FS.FilePath -> IO FS.FilePath canonicalizeDirPath fp = FS.canonicalizePath fp >>= \ cfp -> FS.isDirectory cfp >>= \ bDir -> if bDir then return cfp else -- success case let emsg = show cfp ++ " is not a directory." in let etype = Err.doesNotExistErrorType in Err.ioError $ Err.mkIOError etype emsg Nothing (Just (show fp))
null
https://raw.githubusercontent.com/dmbarbour/awelon/af9124654dd9462cc4887dccf67b3e33302c7351/hsrc/AO/Env.hs
haskell
| environment variables, paths and directories (idempotent) obtain (and create) the AO_TEMP directory storage directory. This will serve as the primary location for resources until we upgrade to a proper database. | (idempotent) obtain or create the JIT directory | obtain valid filesystem paths from AO_PATH environment variable (defaults empty; does not use current path) success case
module AO.Env ( getAO_TEMP , getAO_PATH , getRscDir , getJitDir ) where import Control.Applicative import Data.Either import qualified Data.Text as T import qualified Filesystem as FS import qualified Filesystem.Path.CurrentOS as FS import qualified System.Environment as Env import qualified System.IO.Error as Err getEnvDefault :: String -> String -> IO String getEnvDefault var defaultVal = withDefault <$> getVar where withDefault = either (const defaultVal) id getVar = Err.tryIOError (Env.getEnv var) may raise an IOError based on permissions or similar getAO_TEMP :: IO FS.FilePath getAO_TEMP = getEnvDefault "AO_TEMP" "aotmp" >>= \ d0 -> let fp0 = FS.fromText (T.pack d0) in FS.createTree fp0 >> canonicalizeDirPath fp0 ( idempotent ) obtain ( and create ) the ABC ciphertext resource getRscDir :: IO FS.FilePath getRscDir = getAO_TEMP >>= \ aoTmp -> let rscDir = aoTmp FS.</> FS.fromText (T.pack "rsc") in FS.createDirectory True rscDir >> return rscDir getJitDir :: IO FS.FilePath getJitDir = getAO_TEMP >>= \ aoTmp -> let jitDir = aoTmp FS.</> FS.fromText (T.pack "jit") in FS.createDirectory True jitDir >> return jitDir getAO_PATH :: IO [FS.FilePath] getAO_PATH = getEnvDefault "AO_PATH" "" >>= \ sps -> let paths = FS.splitSearchPathString sps in let canonize = Err.tryIOError . canonicalizeDirPath in rights <$> mapM canonize paths canonizalize + assert isDirectory ( may fail with IOError ) canonicalizeDirPath :: FS.FilePath -> IO FS.FilePath canonicalizeDirPath fp = FS.canonicalizePath fp >>= \ cfp -> FS.isDirectory cfp >>= \ bDir -> let emsg = show cfp ++ " is not a directory." in let etype = Err.doesNotExistErrorType in Err.ioError $ Err.mkIOError etype emsg Nothing (Just (show fp))
0efcb2071a0a0ba964fa0f5d2075d17397b18ebe23c3709292134e24248873e0
synduce/Synduce
count_negations.ml
* @synduce --no - lifting -n 10 -NB When using args in comments , they must be separated by at least one line from the declarations . type arithop = APlus | AMinus | AGt type boolop = BNot | BAnd | BOr | BEq type term = | TArithBin of arithop * term * term | TBoolBin of boolop * term * term | TArithUn of arithop * term | TBoolUn of boolop * term | TVar of int | TCInt of int | TCBool of bool type op = Plus | Minus | Not | And | Or | Gt | Eq type term2 = | Bin of op * term2 * term2 | Un of op * term2 | Var of int | CInt of int | CBool of bool let rec repr = function | Bin (o, a, b) -> mk_bin a b o | Un (o, x) -> mk_un x o | Var i -> TVar i | CInt i -> TCInt i | CBool b -> TCBool b and mk_bin a b = function | Plus -> TArithBin (APlus, repr a, repr b) | Minus -> TArithBin (AMinus, repr a, repr b) | Not -> TBoolBin (BNot, repr a, repr b) | And -> TBoolBin (BAnd, repr a, repr b) | Or -> TBoolBin (BOr, repr a, repr b) | Gt -> TArithBin (AGt, repr a, repr b) | Eq -> TBoolBin (BEq, repr a, repr b) and mk_un a = function | Plus -> TArithUn (APlus, repr a) | Minus -> TArithUn (AMinus, repr a) | Not -> TBoolUn (BNot, repr a) | And -> TBoolUn (BAnd, repr a) | Or -> TBoolUn (BOr, repr a) | Gt -> TArithUn (AGt, repr a) | Eq -> TBoolUn (BEq, repr a) let rec well_formed_term = function | Bin (op, a, b) -> well_formed_term a && well_formed_term b && is_binary op | Un (op, a) -> well_formed_term a && is_unary op | Var i -> true | CInt i -> true | CBool b -> true and is_binary = function | Plus -> true | Minus -> true | And -> true | Or -> true | Gt -> true | Eq -> true | Not -> false and is_unary = function | Plus -> false | Minus -> false | And -> false | Or -> false | Gt -> false | Eq -> false | Not -> true let rec spec = function | TArithBin (a, b, c) -> spec c + spec b | TBoolBin (a, b, c) -> count a + spec c + spec b | TArithUn (o, a) -> spec a | TBoolUn (o, b) -> spec b + count o | TVar i -> 0 | TCInt i -> 0 | TCBool b -> 0 and count = function BNot -> 1 | BAnd -> 0 | BOr -> 0 | BEq -> 0 (* The constraint on well formedness does nothing in this example. *) let rec target = function | Bin (op, a, b) -> [%synt hbin] (target a) (target b) | Un (op, a) -> [%synt hun] (target a) (bcount op) | Var i -> [%synt var] | CInt i -> [%synt const] | CBool b -> [%synt boolconst] [@@requires well_formed_term] and bcount = function | Plus -> [%synt f_op_plus] | Minus -> [%synt f_op_minus] | And -> [%synt f_op_and] | Or -> [%synt f_op_or] | Gt -> [%synt f_op_gt] | Eq -> [%synt f_op_eq] | Not -> [%synt f_op_not]
null
https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/program/count_negations.ml
ocaml
The constraint on well formedness does nothing in this example.
* @synduce --no - lifting -n 10 -NB When using args in comments , they must be separated by at least one line from the declarations . type arithop = APlus | AMinus | AGt type boolop = BNot | BAnd | BOr | BEq type term = | TArithBin of arithop * term * term | TBoolBin of boolop * term * term | TArithUn of arithop * term | TBoolUn of boolop * term | TVar of int | TCInt of int | TCBool of bool type op = Plus | Minus | Not | And | Or | Gt | Eq type term2 = | Bin of op * term2 * term2 | Un of op * term2 | Var of int | CInt of int | CBool of bool let rec repr = function | Bin (o, a, b) -> mk_bin a b o | Un (o, x) -> mk_un x o | Var i -> TVar i | CInt i -> TCInt i | CBool b -> TCBool b and mk_bin a b = function | Plus -> TArithBin (APlus, repr a, repr b) | Minus -> TArithBin (AMinus, repr a, repr b) | Not -> TBoolBin (BNot, repr a, repr b) | And -> TBoolBin (BAnd, repr a, repr b) | Or -> TBoolBin (BOr, repr a, repr b) | Gt -> TArithBin (AGt, repr a, repr b) | Eq -> TBoolBin (BEq, repr a, repr b) and mk_un a = function | Plus -> TArithUn (APlus, repr a) | Minus -> TArithUn (AMinus, repr a) | Not -> TBoolUn (BNot, repr a) | And -> TBoolUn (BAnd, repr a) | Or -> TBoolUn (BOr, repr a) | Gt -> TArithUn (AGt, repr a) | Eq -> TBoolUn (BEq, repr a) let rec well_formed_term = function | Bin (op, a, b) -> well_formed_term a && well_formed_term b && is_binary op | Un (op, a) -> well_formed_term a && is_unary op | Var i -> true | CInt i -> true | CBool b -> true and is_binary = function | Plus -> true | Minus -> true | And -> true | Or -> true | Gt -> true | Eq -> true | Not -> false and is_unary = function | Plus -> false | Minus -> false | And -> false | Or -> false | Gt -> false | Eq -> false | Not -> true let rec spec = function | TArithBin (a, b, c) -> spec c + spec b | TBoolBin (a, b, c) -> count a + spec c + spec b | TArithUn (o, a) -> spec a | TBoolUn (o, b) -> spec b + count o | TVar i -> 0 | TCInt i -> 0 | TCBool b -> 0 and count = function BNot -> 1 | BAnd -> 0 | BOr -> 0 | BEq -> 0 let rec target = function | Bin (op, a, b) -> [%synt hbin] (target a) (target b) | Un (op, a) -> [%synt hun] (target a) (bcount op) | Var i -> [%synt var] | CInt i -> [%synt const] | CBool b -> [%synt boolconst] [@@requires well_formed_term] and bcount = function | Plus -> [%synt f_op_plus] | Minus -> [%synt f_op_minus] | And -> [%synt f_op_and] | Or -> [%synt f_op_or] | Gt -> [%synt f_op_gt] | Eq -> [%synt f_op_eq] | Not -> [%synt f_op_not]
ea4eaed2907820cc588294e8756b222132bcd53a8e83f69998b303edb815e08e
krtx/ws-ocaml
bytes_ext.mli
(** Bytes functions. *) val encode_int : int -> bytes -> int -> int -> unit (** [encode_int x dst start len] encodes integer [x] into [dst] from [start] with [len] characters in big endian. *) val bytes_of_int : int -> int -> bytes (** [bytes_of_int x n] newly allocate a byte sequence of [n] characters where [x] is encoded in big endian. *) val decode_int : bytes -> int -> int -> int (** [decode_int src start len] decodes [len] characters of [src] starting at [start] as an integer of big endian. *) val int_of_bytes : bytes -> int (** [int_of_bytes bytes] translates [bytes] into an integer. *)
null
https://raw.githubusercontent.com/krtx/ws-ocaml/f3710f1ef36d73440c10d96785c13e08bc638545/lib/bytes_ext.mli
ocaml
* Bytes functions. * [encode_int x dst start len] encodes integer [x] into [dst] from [start] with [len] characters in big endian. * [bytes_of_int x n] newly allocate a byte sequence of [n] characters where [x] is encoded in big endian. * [decode_int src start len] decodes [len] characters of [src] starting at [start] as an integer of big endian. * [int_of_bytes bytes] translates [bytes] into an integer.
val encode_int : int -> bytes -> int -> int -> unit val bytes_of_int : int -> int -> bytes val decode_int : bytes -> int -> int -> int val int_of_bytes : bytes -> int
16e2b5b9a1b18a71c7660fb41972706e4b44874fe8ee054c691c23f3640cca17
melange-re/melange
camlinternalAtomic.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , University of Cambridge , projet Gallinette , INRIA (* *) Copyright 2020 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* 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. *) (* *) (**************************************************************************) The documentation is in atomic.mli . CamlinternalAtomic exists in order to be a dependency of . More precisely , the option modules_before_stdlib used in stdlib / dune does not support the Stdlib _ _ prefix trick . order to be a dependency of Stdlib. More precisely, the option modules_before_stdlib used in stdlib/dune does not support the Stdlib__ prefix trick. *) type !'a t val make : 'a -> 'a t val get : 'a t -> 'a val set : 'a t -> 'a -> unit val exchange : 'a t -> 'a -> 'a val compare_and_set : 'a t -> 'a -> 'a -> bool val fetch_and_add : int t -> int -> int val incr : int t -> unit val decr : int t -> unit
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/stdlib-412/camlinternalAtomic.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
, University of Cambridge , projet Gallinette , INRIA Copyright 2020 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the The documentation is in atomic.mli . CamlinternalAtomic exists in order to be a dependency of . More precisely , the option modules_before_stdlib used in stdlib / dune does not support the Stdlib _ _ prefix trick . order to be a dependency of Stdlib. More precisely, the option modules_before_stdlib used in stdlib/dune does not support the Stdlib__ prefix trick. *) type !'a t val make : 'a -> 'a t val get : 'a t -> 'a val set : 'a t -> 'a -> unit val exchange : 'a t -> 'a -> 'a val compare_and_set : 'a t -> 'a -> 'a -> bool val fetch_and_add : int t -> int -> int val incr : int t -> unit val decr : int t -> unit
ee0dc392ebed2fe91c7ee5f80ed6f3b0c69e53e290b91b297ebf9c8aed7dfa23
nuprl/gradual-typing-performance
sugar-list.rkt
#lang racket/base (provide slice-at break-at slicef-after shifts ) ;; ----------------------------------------------------------------------------- (require (only-in racket/list split-at empty empty? first take-right make-list drop-right take drop) ) ;; ============================================================================= (define slice-at ;; with polymorphic function, use cased typing to simulate optional position arguments (case-lambda [(xs len) (slice-at xs len #f)] [(xs len force?) (define-values (last-list list-of-lists) (for/fold ([current-list '()][list-of-lists '()]) ([x (in-list xs)][i (in-naturals)]) (if (= (modulo (add1 i) len) 0) (values '() (cons (reverse (cons x current-list)) list-of-lists)) (values (cons x current-list) list-of-lists)))) (reverse (if (or (eq? '() last-list) (and force? (not (= len (length last-list))))) list-of-lists (cons (reverse last-list) list-of-lists)))])) (define (break-at xs bps) (let ([bps (if (list? bps) bps (list bps))]) ; coerce bps to list (when (ormap (λ(bp) (>= bp (length xs))) bps) (error 'break-at (format "breakpoint in ~v is greater than or equal to input list length = ~a" bps (length xs)))) ;; easier to do back to front, because then the list index for each item won't change during the recursion cons a zero onto bps ( which may already start with zero ) and then use that as the terminating condition because breaking at zero means we 've reached the start of the list (reverse (let loop ([xs xs][bps (reverse (cons 0 bps))]) (if (= (car bps) 0) (cons xs null) ; return whatever's left, because no more splits are possible (let-values ([(head tail) (split-at xs (car bps))]) (cons tail (loop head (cdr bps))))))))) (define (slicef-after xs pred) (define-values (last-list list-of-lists) (for/fold ([current-list empty][list-of-lists empty]) ([x (in-list xs)]) (if (pred x) (values empty (cons (reverse (cons x current-list)) list-of-lists)) (values (cons x current-list) list-of-lists)))) (reverse (if (empty? last-list) list-of-lists (cons (reverse last-list) list-of-lists)))) (define shifts (case-lambda [(xs how-fars) (shifts xs how-fars #f #f)] [(xs how-fars fill-item) (shifts xs how-fars fill-item #f)] [(xs how-fars fill-item cycle) (map (λ(how-far) (shift xs how-far fill-item cycle)) how-fars)])) (define shift (case-lambda [(xs how-far) (shift xs how-far #f #f)] [(xs how-far fill-item) (shift xs how-far fill-item #f)] [(xs how-far fill-item cycle) (define abs-how-far (abs how-far)) (cond [(> abs-how-far (length xs)) (error 'shift "index is too large for list\nindex: ~a\nlist: ~v" how-far xs)] [(= how-far 0) xs] [(positive? how-far) (define filler (if cycle (take-right xs abs-how-far) (make-list abs-how-far fill-item))) (append filler (drop-right xs abs-how-far))] [else ; how-far is negative (define filler (if cycle (take xs abs-how-far) (make-list abs-how-far fill-item))) (append (drop xs abs-how-far) filler)])]))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/tools/summarize/test/mini-quadMB/untyped/sugar-list.rkt
racket
----------------------------------------------------------------------------- ============================================================================= with polymorphic function, use cased typing to simulate optional position arguments coerce bps to list easier to do back to front, because then the list index for each item won't change during the recursion return whatever's left, because no more splits are possible how-far is negative
#lang racket/base (provide slice-at break-at slicef-after shifts ) (require (only-in racket/list split-at empty empty? first take-right make-list drop-right take drop) ) (define slice-at (case-lambda [(xs len) (slice-at xs len #f)] [(xs len force?) (define-values (last-list list-of-lists) (for/fold ([current-list '()][list-of-lists '()]) ([x (in-list xs)][i (in-naturals)]) (if (= (modulo (add1 i) len) 0) (values '() (cons (reverse (cons x current-list)) list-of-lists)) (values (cons x current-list) list-of-lists)))) (reverse (if (or (eq? '() last-list) (and force? (not (= len (length last-list))))) list-of-lists (cons (reverse last-list) list-of-lists)))])) (define (break-at xs bps) (when (ormap (λ(bp) (>= bp (length xs))) bps) (error 'break-at (format "breakpoint in ~v is greater than or equal to input list length = ~a" bps (length xs)))) cons a zero onto bps ( which may already start with zero ) and then use that as the terminating condition because breaking at zero means we 've reached the start of the list (reverse (let loop ([xs xs][bps (reverse (cons 0 bps))]) (if (= (car bps) 0) (let-values ([(head tail) (split-at xs (car bps))]) (cons tail (loop head (cdr bps))))))))) (define (slicef-after xs pred) (define-values (last-list list-of-lists) (for/fold ([current-list empty][list-of-lists empty]) ([x (in-list xs)]) (if (pred x) (values empty (cons (reverse (cons x current-list)) list-of-lists)) (values (cons x current-list) list-of-lists)))) (reverse (if (empty? last-list) list-of-lists (cons (reverse last-list) list-of-lists)))) (define shifts (case-lambda [(xs how-fars) (shifts xs how-fars #f #f)] [(xs how-fars fill-item) (shifts xs how-fars fill-item #f)] [(xs how-fars fill-item cycle) (map (λ(how-far) (shift xs how-far fill-item cycle)) how-fars)])) (define shift (case-lambda [(xs how-far) (shift xs how-far #f #f)] [(xs how-far fill-item) (shift xs how-far fill-item #f)] [(xs how-far fill-item cycle) (define abs-how-far (abs how-far)) (cond [(> abs-how-far (length xs)) (error 'shift "index is too large for list\nindex: ~a\nlist: ~v" how-far xs)] [(= how-far 0) xs] [(positive? how-far) (define filler (if cycle (take-right xs abs-how-far) (make-list abs-how-far fill-item))) (append filler (drop-right xs abs-how-far))] (define filler (if cycle (take xs abs-how-far) (make-list abs-how-far fill-item))) (append (drop xs abs-how-far) filler)])]))
076c6eadd46a3be99d870b05a6a5a549f332c0c8c4791f22be4bf0eef0c905d1
tsoding/HyperNerd
Migration.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # module Sqlite.Migration ( migrateDatabase , Migration(..) ) where import Data.Foldable import Data.Function import Data.List import Data.String import qualified Data.Text as T import Database.SQLite.Simple import Text.RawString.QQ newtype Migration = Migration { migrationQuery :: Query } instance IsString Migration where fromString = Migration . fromString instance FromRow Migration where fromRow = fromString <$> field instance Eq Migration where (==) = (==) `on` (T.unwords . T.words . fromQuery . migrationQuery) createMigrationTablesIfNeeded :: Connection -> IO () createMigrationTablesIfNeeded conn = execute_ conn [r| CREATE TABLE IF NOT EXISTS Migrations ( id INTEGER PRIMARY KEY, migrationQuery TEXT NOT NULL ) |] filterUnappliedMigrations :: Connection -> [Migration] -> IO [Migration] filterUnappliedMigrations conn migrations = do appliedMigrations <- query_ conn [r| SELECT migrationQuery FROM Migrations |] maybe (error "Inconsistent migrations state! \ \List of already applied migrations \ \is not a prefix of required migrations.") return (stripPrefix appliedMigrations migrations) applyMigration :: Connection -> Migration -> IO () applyMigration conn migration = do execute_ conn $ migrationQuery migration executeNamed conn [r| INSERT INTO Migrations ( migrationQuery ) VALUES ( :migrationQuery ) |] [":migrationQuery" := (fromQuery $ migrationQuery migration :: T.Text)] migrateDatabase :: Connection -> [Migration] -> IO () migrateDatabase conn migrations = do createMigrationTablesIfNeeded conn unappliedMigrations <- filterUnappliedMigrations conn migrations traverse_ (applyMigration conn) unappliedMigrations
null
https://raw.githubusercontent.com/tsoding/HyperNerd/5322580483c5c05179bc455a6f94566d398bccdf/src/Sqlite/Migration.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE QuasiQuotes # module Sqlite.Migration ( migrateDatabase , Migration(..) ) where import Data.Foldable import Data.Function import Data.List import Data.String import qualified Data.Text as T import Database.SQLite.Simple import Text.RawString.QQ newtype Migration = Migration { migrationQuery :: Query } instance IsString Migration where fromString = Migration . fromString instance FromRow Migration where fromRow = fromString <$> field instance Eq Migration where (==) = (==) `on` (T.unwords . T.words . fromQuery . migrationQuery) createMigrationTablesIfNeeded :: Connection -> IO () createMigrationTablesIfNeeded conn = execute_ conn [r| CREATE TABLE IF NOT EXISTS Migrations ( id INTEGER PRIMARY KEY, migrationQuery TEXT NOT NULL ) |] filterUnappliedMigrations :: Connection -> [Migration] -> IO [Migration] filterUnappliedMigrations conn migrations = do appliedMigrations <- query_ conn [r| SELECT migrationQuery FROM Migrations |] maybe (error "Inconsistent migrations state! \ \List of already applied migrations \ \is not a prefix of required migrations.") return (stripPrefix appliedMigrations migrations) applyMigration :: Connection -> Migration -> IO () applyMigration conn migration = do execute_ conn $ migrationQuery migration executeNamed conn [r| INSERT INTO Migrations ( migrationQuery ) VALUES ( :migrationQuery ) |] [":migrationQuery" := (fromQuery $ migrationQuery migration :: T.Text)] migrateDatabase :: Connection -> [Migration] -> IO () migrateDatabase conn migrations = do createMigrationTablesIfNeeded conn unappliedMigrations <- filterUnappliedMigrations conn migrations traverse_ (applyMigration conn) unappliedMigrations
9ffe8610119063b850d4d3e7789932e05baac4e0c13621bf243fcbc50f9e5933
timbod7/haskell-chart
Vectors.hs
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.Chart.Plot.Vectors Copyright : ( c ) < > 2014 -- License : BSD-style (see chart/COPYRIGHT) -- -- Vector plots -- # LANGUAGE CPP # # LANGUAGE TemplateHaskell # module Graphics.Rendering.Chart.Plot.Vectors( PlotVectors(..), VectorStyle(..), plotVectorField, plot_vectors_mapf, plot_vectors_grid, plot_vectors_title, plot_vectors_style, plot_vectors_scale, plot_vectors_values, vector_line_style, vector_head_style, ) where import Control.Lens import Control.Monad #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Data.Tuple import Data.Colour hiding (over) import Data.Colour.Names import Data.Default.Class import Graphics.Rendering.Chart.Axis import Graphics.Rendering.Chart.Drawing import Graphics.Rendering.Chart.Geometry import Graphics.Rendering.Chart.Plot.Types data VectorStyle = VectorStyle { _vector_line_style :: LineStyle , _vector_head_style :: PointStyle } $( makeLenses ''VectorStyle ) data PlotVectors x y = PlotVectors { _plot_vectors_title :: String , _plot_vectors_style :: VectorStyle | Set to 1 ( default ) to normalize the length of vectors to a space -- between them (so that the vectors never overlap on the graph). -- Set to 0 to disable any scaling. Values in between 0 and 1 are also permitted to adjust scaling . , _plot_vectors_scale :: Double -- | Provide a square-tiled regular grid. , _plot_vectors_grid :: [(x,y)] -- | Provide a vector field (R^2 -> R^2) function. , _plot_vectors_mapf :: (x,y) -> (x,y) -- | Provide a prepared list of (start,vector) pairs. , _plot_vectors_values :: [((x,y),(x,y))] } $( makeLenses ''PlotVectors ) mapGrid :: (PlotValue y, PlotValue x) => [(x,y)] -> ((x,y) -> (x,y)) -> [((x,y),(x,y))] mapGrid grid f = zip grid (f <$> grid) plotVectorField :: (PlotValue x, PlotValue y) => PlotVectors x y -> Plot x y plotVectorField pv = Plot { _plot_render = renderPlotVectors pv , _plot_legend = [(_plot_vectors_title pv, renderPlotLegendVectors pv)] , _plot_all_points = (map fst pts, map snd pts) } where pvals = _plot_vectors_values pv mvals = mapGrid (_plot_vectors_grid pv) (_plot_vectors_mapf pv) pts = concatMap (\(a,b) -> [a,b]) (pvals ++ mvals) renderPlotVectors :: (PlotValue x, PlotValue y) => PlotVectors x y -> PointMapFn x y -> BackendProgram () renderPlotVectors pv pmap = do let pvals = _plot_vectors_values pv mvals = mapGrid (_plot_vectors_grid pv) (_plot_vectors_mapf pv) trans = translateToStart <$> (pvals ++ mvals) pvecs = filter (\v -> vlen' v > 0) $ over both (mapXY pmap) <$> trans mgrid = take 2 $ fst <$> pvecs maxLen = maximum $ vlen' <$> pvecs spacing = (!!1) $ (vlen <$> zipWith psub mgrid (reverse mgrid)) ++ [maxLen] sfactor = spacing/maxLen -- Non-adjusted scale factor afactor = sfactor + (1 - sfactor)*(1 - _plot_vectors_scale pv) tails = pscale afactor <$> pvecs -- Paths of arrows' tails angles = (vangle . psub' . swap) <$> pvecs -- Angles of the arrows centers = snd <$> tails -- Where to draw arrow heads mapM_ (drawTail radius) tails zipWithM_ (drawArrowHead radius) centers angles where psub' = uncurry psub vlen' = vlen . psub' pvs = _plot_vectors_style pv radius = _point_radius $ _vector_head_style pvs hs angle = _vector_head_style pvs & point_shape %~ (\(PointShapeArrowHead a) -> PointShapeArrowHead $ a+angle) translateToStart (s@(x,y),(vx,vy)) = (s,(tr x vx,tr y vy)) where tr p t = fromValue $ toValue p + toValue t pscale w v@(s,_) = (s,translateP (vscale w . psub' $ swap v) s) drawTail r v = withLineStyle (_vector_line_style pvs) $ strokePointPath $ (^..each) v' where v' = pscale (1-(3/2)*r/l) v l = vlen' v drawArrowHead r (Point x y) theta = withTranslation (Point (-r*cos theta) (-r*sin theta)) (drawPoint (hs theta) (Point x y)) renderPlotLegendVectors :: (PlotValue x, PlotValue y) => PlotVectors x y -> Rect -> BackendProgram () renderPlotLegendVectors pv (Rect p1 p2) = do let y = (p_y p1 + p_y p2)/2 pv' = plot_vectors_grid .~ [] $ plot_vectors_values .~ [((fromValue $ p_x p1, fromValue y), (fromValue $ p_x p2, fromValue 0))] $ pv renderPlotVectors pv' pmap where pmap (LValue x,LValue y) = Point (toValue x) (toValue y) pmap _ = Point 0 0 instance Default VectorStyle where def = VectorStyle { _vector_line_style = (solidLine lw $ opaque blue) { _line_cap = LineCapSquare } , _vector_head_style = PointStyle (opaque red) transparent lw (2*lw) (PointShapeArrowHead 0) } where lw = 2 instance Default (PlotVectors x y) where def = PlotVectors { _plot_vectors_title = "" , _plot_vectors_style = def , _plot_vectors_scale = 1 , _plot_vectors_grid = [] , _plot_vectors_mapf = id , _plot_vectors_values = [] }
null
https://raw.githubusercontent.com/timbod7/haskell-chart/8c5a823652ea1b4ec2adbced4a92a8161065ead6/chart/Graphics/Rendering/Chart/Plot/Vectors.hs
haskell
--------------------------------------------------------------------------- | Module : Graphics.Rendering.Chart.Plot.Vectors License : BSD-style (see chart/COPYRIGHT) Vector plots between them (so that the vectors never overlap on the graph). Set to 0 to disable any scaling. | Provide a square-tiled regular grid. | Provide a vector field (R^2 -> R^2) function. | Provide a prepared list of (start,vector) pairs. Non-adjusted scale factor Paths of arrows' tails Angles of the arrows Where to draw arrow heads
Copyright : ( c ) < > 2014 # LANGUAGE CPP # # LANGUAGE TemplateHaskell # module Graphics.Rendering.Chart.Plot.Vectors( PlotVectors(..), VectorStyle(..), plotVectorField, plot_vectors_mapf, plot_vectors_grid, plot_vectors_title, plot_vectors_style, plot_vectors_scale, plot_vectors_values, vector_line_style, vector_head_style, ) where import Control.Lens import Control.Monad #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif import Data.Tuple import Data.Colour hiding (over) import Data.Colour.Names import Data.Default.Class import Graphics.Rendering.Chart.Axis import Graphics.Rendering.Chart.Drawing import Graphics.Rendering.Chart.Geometry import Graphics.Rendering.Chart.Plot.Types data VectorStyle = VectorStyle { _vector_line_style :: LineStyle , _vector_head_style :: PointStyle } $( makeLenses ''VectorStyle ) data PlotVectors x y = PlotVectors { _plot_vectors_title :: String , _plot_vectors_style :: VectorStyle | Set to 1 ( default ) to normalize the length of vectors to a space Values in between 0 and 1 are also permitted to adjust scaling . , _plot_vectors_scale :: Double , _plot_vectors_grid :: [(x,y)] , _plot_vectors_mapf :: (x,y) -> (x,y) , _plot_vectors_values :: [((x,y),(x,y))] } $( makeLenses ''PlotVectors ) mapGrid :: (PlotValue y, PlotValue x) => [(x,y)] -> ((x,y) -> (x,y)) -> [((x,y),(x,y))] mapGrid grid f = zip grid (f <$> grid) plotVectorField :: (PlotValue x, PlotValue y) => PlotVectors x y -> Plot x y plotVectorField pv = Plot { _plot_render = renderPlotVectors pv , _plot_legend = [(_plot_vectors_title pv, renderPlotLegendVectors pv)] , _plot_all_points = (map fst pts, map snd pts) } where pvals = _plot_vectors_values pv mvals = mapGrid (_plot_vectors_grid pv) (_plot_vectors_mapf pv) pts = concatMap (\(a,b) -> [a,b]) (pvals ++ mvals) renderPlotVectors :: (PlotValue x, PlotValue y) => PlotVectors x y -> PointMapFn x y -> BackendProgram () renderPlotVectors pv pmap = do let pvals = _plot_vectors_values pv mvals = mapGrid (_plot_vectors_grid pv) (_plot_vectors_mapf pv) trans = translateToStart <$> (pvals ++ mvals) pvecs = filter (\v -> vlen' v > 0) $ over both (mapXY pmap) <$> trans mgrid = take 2 $ fst <$> pvecs maxLen = maximum $ vlen' <$> pvecs spacing = (!!1) $ (vlen <$> zipWith psub mgrid (reverse mgrid)) ++ [maxLen] afactor = sfactor + (1 - sfactor)*(1 - _plot_vectors_scale pv) mapM_ (drawTail radius) tails zipWithM_ (drawArrowHead radius) centers angles where psub' = uncurry psub vlen' = vlen . psub' pvs = _plot_vectors_style pv radius = _point_radius $ _vector_head_style pvs hs angle = _vector_head_style pvs & point_shape %~ (\(PointShapeArrowHead a) -> PointShapeArrowHead $ a+angle) translateToStart (s@(x,y),(vx,vy)) = (s,(tr x vx,tr y vy)) where tr p t = fromValue $ toValue p + toValue t pscale w v@(s,_) = (s,translateP (vscale w . psub' $ swap v) s) drawTail r v = withLineStyle (_vector_line_style pvs) $ strokePointPath $ (^..each) v' where v' = pscale (1-(3/2)*r/l) v l = vlen' v drawArrowHead r (Point x y) theta = withTranslation (Point (-r*cos theta) (-r*sin theta)) (drawPoint (hs theta) (Point x y)) renderPlotLegendVectors :: (PlotValue x, PlotValue y) => PlotVectors x y -> Rect -> BackendProgram () renderPlotLegendVectors pv (Rect p1 p2) = do let y = (p_y p1 + p_y p2)/2 pv' = plot_vectors_grid .~ [] $ plot_vectors_values .~ [((fromValue $ p_x p1, fromValue y), (fromValue $ p_x p2, fromValue 0))] $ pv renderPlotVectors pv' pmap where pmap (LValue x,LValue y) = Point (toValue x) (toValue y) pmap _ = Point 0 0 instance Default VectorStyle where def = VectorStyle { _vector_line_style = (solidLine lw $ opaque blue) { _line_cap = LineCapSquare } , _vector_head_style = PointStyle (opaque red) transparent lw (2*lw) (PointShapeArrowHead 0) } where lw = 2 instance Default (PlotVectors x y) where def = PlotVectors { _plot_vectors_title = "" , _plot_vectors_style = def , _plot_vectors_scale = 1 , _plot_vectors_grid = [] , _plot_vectors_mapf = id , _plot_vectors_values = [] }
270fe6d75470f2e954722357768878ee85d66dd6e7686b56fa2cb094622f345e
mirage/capnp-rpc
db.ml
open Lwt.Infix open Capnp_rpc_lwt open Capnp_rpc_net module File_store = Capnp_rpc_unix.File_store module Store = Store.Make(Capnp.BytesMessage) type loader = [`Logger_beacebd78653e9af] Sturdy_ref.t -> label:string -> Restorer.resolution type t = { store : Store.Reader.SavedService.struct_t File_store.t; loader : loader Lwt.t; make_sturdy : Restorer.Id.t -> Uri.t; } let hash _ = `SHA256 let make_sturdy t = t.make_sturdy let save t ~digest label = let open Store.Builder in let service = SavedService.init_root () in let logger = SavedService.logger_init service in SavedLogger.label_set logger label; File_store.save t.store ~digest @@ SavedService.to_reader service let save_new t ~label = let id = Restorer.Id.generate () in let digest = Restorer.Id.digest (hash t) id in save t ~digest label; id let load t sr digest = match File_store.load t.store ~digest with | None -> Lwt.return Restorer.unknown_service_id | Some saved_service -> let logger = Store.Reader.SavedService.logger_get saved_service in let label = Store.Reader.SavedLogger.label_get logger in let sr = Capnp_rpc_lwt.Sturdy_ref.cast sr in t.loader >|= fun loader -> loader sr ~label let create ~make_sturdy dir = let loader, set_loader = Lwt.wait () in if not (Sys.file_exists dir) then Unix.mkdir dir 0o755; let store = File_store.create dir in {store; loader; make_sturdy}, set_loader
null
https://raw.githubusercontent.com/mirage/capnp-rpc/8a0b6dce373dc2e2d547d85e542962862773f74b/examples/sturdy-refs-4/db.ml
ocaml
open Lwt.Infix open Capnp_rpc_lwt open Capnp_rpc_net module File_store = Capnp_rpc_unix.File_store module Store = Store.Make(Capnp.BytesMessage) type loader = [`Logger_beacebd78653e9af] Sturdy_ref.t -> label:string -> Restorer.resolution type t = { store : Store.Reader.SavedService.struct_t File_store.t; loader : loader Lwt.t; make_sturdy : Restorer.Id.t -> Uri.t; } let hash _ = `SHA256 let make_sturdy t = t.make_sturdy let save t ~digest label = let open Store.Builder in let service = SavedService.init_root () in let logger = SavedService.logger_init service in SavedLogger.label_set logger label; File_store.save t.store ~digest @@ SavedService.to_reader service let save_new t ~label = let id = Restorer.Id.generate () in let digest = Restorer.Id.digest (hash t) id in save t ~digest label; id let load t sr digest = match File_store.load t.store ~digest with | None -> Lwt.return Restorer.unknown_service_id | Some saved_service -> let logger = Store.Reader.SavedService.logger_get saved_service in let label = Store.Reader.SavedLogger.label_get logger in let sr = Capnp_rpc_lwt.Sturdy_ref.cast sr in t.loader >|= fun loader -> loader sr ~label let create ~make_sturdy dir = let loader, set_loader = Lwt.wait () in if not (Sys.file_exists dir) then Unix.mkdir dir 0o755; let store = File_store.create dir in {store; loader; make_sturdy}, set_loader
fff1131e7e68172af89c058f232756cc87399198ab1c395fbc0162588f804227
mhwombat/grid
OctagonalInternal.hs
------------------------------------------------------------------------ -- | -- Module : Math.Geometry.OctGridInternal Copyright : ( c ) 2012 - 2022 -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : portable -- A module containing private @OctGrid@ internals . Most developers should use @OctGrid@ instead . This module is subject to change -- without notice. -- ------------------------------------------------------------------------ {-# LANGUAGE DeriveGeneric #-} # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # module Math.Geometry.Grid.OctagonalInternal where import Prelude hiding (null) import Data.List (nub) import GHC.Generics (Generic) import Math.Geometry.GridInternal data OctDirection = West | Northwest | North | Northeast | East | Southeast | South | Southwest deriving (Read, Show, Eq, Generic) -- | An unbounded grid with octagonal tiles. -- The grid and its indexing scheme are illustrated in the user guide, -- available at <>. data UnboundedOctGrid = UnboundedOctGrid deriving (Read, Show, Eq, Generic) instance Grid UnboundedOctGrid where type Index UnboundedOctGrid = (Int, Int) type Direction UnboundedOctGrid = OctDirection indices _ = undefined neighbours _ (x,y) = [(x-1,y+1), (x,y+1), (x+1,y+1), (x+1,y), (x+1,y-1), (x,y-1), (x-1,y-1), (x-1,y)] distance _ (x1, y1) (x2, y2) = max (abs (x2-x1)) (abs (y2-y1)) contains _ _ = True directionTo _ (x1, y1) (x2, y2) = f1 . f2 . f3 . f4 . f5 . f6 . f7 . f8 $ [] where f1 ds = if dy > abs dx then North:ds else ds f2 ds = if -dy > abs dx then South:ds else ds f3 ds = if dx > abs dy then East:ds else ds f4 ds = if -dx > abs dy then West:ds else ds f5 ds = if dx > 0 && dy > 0 then Northeast:ds else ds f6 ds = if dx > 0 && dy < 0 then Southeast:ds else ds f7 ds = if dx < 0 && dy < 0 then Southwest:ds else ds f8 ds = if dx < 0 && dy > 0 then Northwest:ds else ds dx = x2 - x1 dy = y2 - y1 null _ = False nonNull _ = True -- -- Rectangular grids with octagonal tiles -- -- | A rectangular grid with octagonal tiles. -- The grid and its indexing scheme are illustrated in the user guide, -- available at <>. data RectOctGrid = RectOctGrid (Int, Int) deriving (Read, Show, Eq, Generic) instance Grid RectOctGrid where type Index RectOctGrid = (Int, Int) type Direction RectOctGrid = OctDirection indices (RectOctGrid (r, c)) = [(x,y) | x <- [0..c-1], y <- [0..r-1]] neighbours = neighboursBasedOn UnboundedOctGrid distance = distanceBasedOn UnboundedOctGrid directionTo = directionToBasedOn UnboundedOctGrid contains g (x,y) = 0 <= x && x < c && 0 <= y && y < r where (r,c) = size g instance FiniteGrid RectOctGrid where type Size RectOctGrid = (Int, Int) size (RectOctGrid s) = s maxPossibleDistance g@(RectOctGrid (r,c)) = distance g (0,0) (c-1,r-1) instance BoundedGrid RectOctGrid where tileSideCount _ = 8 boundary g = cartesianIndices . size $ g centre g = cartesianCentre . size $ g {-# DEPRECATED rectOctGrid "Use the RectOctGrid constructor instead." #-} -- | @'rectOctGrid' r c@ produces a rectangular grid with @r@ rows and @c@ columns , using octagonal tiles . If @r@ and @c@ are both -- nonnegative, the resulting grid will have @r*c@ tiles. Otherwise, -- the resulting grid will be null and the list of indices will be -- null. rectOctGrid :: Int -> Int -> RectOctGrid rectOctGrid r c = RectOctGrid (r,c) -- Toroidal grids with octagonal tiles . -- -- | A toroidal grid with octagonal tiles. -- The grid and its indexing scheme are illustrated in the user guide, -- available at <>. data TorOctGrid = TorOctGrid (Int, Int) deriving (Read, Show, Eq, Generic) instance Grid TorOctGrid where type Index TorOctGrid = (Int, Int) type Direction TorOctGrid = OctDirection indices (TorOctGrid (r, c)) = [(x, y) | x <- [0..c-1], y <- [0..r-1]] neighbours = neighboursWrappedBasedOn UnboundedOctGrid neighbour = neighbourWrappedBasedOn UnboundedOctGrid distance = distanceWrappedBasedOn UnboundedOctGrid directionTo = directionToWrappedBasedOn UnboundedOctGrid isAdjacent g a b = distance g a b <= 1 contains _ _ = True instance FiniteGrid TorOctGrid where type Size TorOctGrid = (Int, Int) size (TorOctGrid s) = s maxPossibleDistance g@(TorOctGrid (r,c)) = distance g (0,0) (c `div` 2, r `div` 2) instance WrappedGrid TorOctGrid where normalise g (x,y) = (x `mod` c, y `mod` r) where (r, c) = size g denormalise g a = nub [ (x-c,y+r), (x,y+r), (x+c,y+r), (x-c,y), (x,y), (x+c,y), (x-c,y-r), (x,y-r), (x+c,y-r) ] where (r, c) = size g (x, y) = normalise g a # DEPRECATED torOctGrid " Use the constructor instead . " # -- | @'torOctGrid' r c@ returns a toroidal grid with @r@ rows and @c@ columns , using octagonal tiles . If @r@ and @c@ are -- both nonnegative, the resulting grid will have @r*c@ tiles. Otherwise, -- the resulting grid will be null and the list of indices will be null. torOctGrid :: Int -> Int -> TorOctGrid torOctGrid r c = TorOctGrid (r,c)
null
https://raw.githubusercontent.com/mhwombat/grid/b8c4a928733494f4a410127d6ae007857de921f9/src/Math/Geometry/Grid/OctagonalInternal.hs
haskell
---------------------------------------------------------------------- | Module : Math.Geometry.OctGridInternal License : BSD-style Maintainer : Stability : experimental Portability : portable without notice. ---------------------------------------------------------------------- # LANGUAGE DeriveGeneric # | An unbounded grid with octagonal tiles. The grid and its indexing scheme are illustrated in the user guide, available at <>. Rectangular grids with octagonal tiles | A rectangular grid with octagonal tiles. The grid and its indexing scheme are illustrated in the user guide, available at <>. # DEPRECATED rectOctGrid "Use the RectOctGrid constructor instead." # | @'rectOctGrid' r c@ produces a rectangular grid with @r@ rows nonnegative, the resulting grid will have @r*c@ tiles. Otherwise, the resulting grid will be null and the list of indices will be null. | A toroidal grid with octagonal tiles. The grid and its indexing scheme are illustrated in the user guide, available at <>. | @'torOctGrid' r c@ returns a toroidal grid with @r@ both nonnegative, the resulting grid will have @r*c@ tiles. Otherwise, the resulting grid will be null and the list of indices will be null.
Copyright : ( c ) 2012 - 2022 A module containing private @OctGrid@ internals . Most developers should use @OctGrid@ instead . This module is subject to change # LANGUAGE FlexibleContexts # # LANGUAGE TypeFamilies # module Math.Geometry.Grid.OctagonalInternal where import Prelude hiding (null) import Data.List (nub) import GHC.Generics (Generic) import Math.Geometry.GridInternal data OctDirection = West | Northwest | North | Northeast | East | Southeast | South | Southwest deriving (Read, Show, Eq, Generic) data UnboundedOctGrid = UnboundedOctGrid deriving (Read, Show, Eq, Generic) instance Grid UnboundedOctGrid where type Index UnboundedOctGrid = (Int, Int) type Direction UnboundedOctGrid = OctDirection indices _ = undefined neighbours _ (x,y) = [(x-1,y+1), (x,y+1), (x+1,y+1), (x+1,y), (x+1,y-1), (x,y-1), (x-1,y-1), (x-1,y)] distance _ (x1, y1) (x2, y2) = max (abs (x2-x1)) (abs (y2-y1)) contains _ _ = True directionTo _ (x1, y1) (x2, y2) = f1 . f2 . f3 . f4 . f5 . f6 . f7 . f8 $ [] where f1 ds = if dy > abs dx then North:ds else ds f2 ds = if -dy > abs dx then South:ds else ds f3 ds = if dx > abs dy then East:ds else ds f4 ds = if -dx > abs dy then West:ds else ds f5 ds = if dx > 0 && dy > 0 then Northeast:ds else ds f6 ds = if dx > 0 && dy < 0 then Southeast:ds else ds f7 ds = if dx < 0 && dy < 0 then Southwest:ds else ds f8 ds = if dx < 0 && dy > 0 then Northwest:ds else ds dx = x2 - x1 dy = y2 - y1 null _ = False nonNull _ = True data RectOctGrid = RectOctGrid (Int, Int) deriving (Read, Show, Eq, Generic) instance Grid RectOctGrid where type Index RectOctGrid = (Int, Int) type Direction RectOctGrid = OctDirection indices (RectOctGrid (r, c)) = [(x,y) | x <- [0..c-1], y <- [0..r-1]] neighbours = neighboursBasedOn UnboundedOctGrid distance = distanceBasedOn UnboundedOctGrid directionTo = directionToBasedOn UnboundedOctGrid contains g (x,y) = 0 <= x && x < c && 0 <= y && y < r where (r,c) = size g instance FiniteGrid RectOctGrid where type Size RectOctGrid = (Int, Int) size (RectOctGrid s) = s maxPossibleDistance g@(RectOctGrid (r,c)) = distance g (0,0) (c-1,r-1) instance BoundedGrid RectOctGrid where tileSideCount _ = 8 boundary g = cartesianIndices . size $ g centre g = cartesianCentre . size $ g and @c@ columns , using octagonal tiles . If @r@ and @c@ are both rectOctGrid :: Int -> Int -> RectOctGrid rectOctGrid r c = RectOctGrid (r,c) Toroidal grids with octagonal tiles . data TorOctGrid = TorOctGrid (Int, Int) deriving (Read, Show, Eq, Generic) instance Grid TorOctGrid where type Index TorOctGrid = (Int, Int) type Direction TorOctGrid = OctDirection indices (TorOctGrid (r, c)) = [(x, y) | x <- [0..c-1], y <- [0..r-1]] neighbours = neighboursWrappedBasedOn UnboundedOctGrid neighbour = neighbourWrappedBasedOn UnboundedOctGrid distance = distanceWrappedBasedOn UnboundedOctGrid directionTo = directionToWrappedBasedOn UnboundedOctGrid isAdjacent g a b = distance g a b <= 1 contains _ _ = True instance FiniteGrid TorOctGrid where type Size TorOctGrid = (Int, Int) size (TorOctGrid s) = s maxPossibleDistance g@(TorOctGrid (r,c)) = distance g (0,0) (c `div` 2, r `div` 2) instance WrappedGrid TorOctGrid where normalise g (x,y) = (x `mod` c, y `mod` r) where (r, c) = size g denormalise g a = nub [ (x-c,y+r), (x,y+r), (x+c,y+r), (x-c,y), (x,y), (x+c,y), (x-c,y-r), (x,y-r), (x+c,y-r) ] where (r, c) = size g (x, y) = normalise g a # DEPRECATED torOctGrid " Use the constructor instead . " # rows and @c@ columns , using octagonal tiles . If @r@ and @c@ are torOctGrid :: Int -> Int -> TorOctGrid torOctGrid r c = TorOctGrid (r,c)
097c807c34487ea8f0ded6028a45554a39a8a134b3f37429ec9ab6f6f048d068
IvanIvanov/fp2013
accumulate-tests.scm
;;; This file contains unit tests for the problem listed in the name ;;; of this file. ;;; ;;; To run the tests specify the relative or absolute path to the ;;; ".scm" file with the proposed solution in the (load ...) command ;;; below. Then you can either open the tests and run them in Racket ( with R5RS set as the language ) , or you can run the following ;;; directly from the command line: ;;; ;;; plt-r5rs <the-name-of-this-file> ;;; assuming 's bin directory is included in the PATH environment ;;; variable. ;;; ;;; To inspect the actual test cases that are run - look at the ;;; bottom of the file. ;;; (load "accumulate.scm") ;;; Here be dragons! ;;; ;;; The following definitions create the infrastructure for a very simple ;;; "test framework". As a student you should be just fine in skipping them. (define (__make-counter x) (lambda () (set! x (+ x 1)) x)) (define __test-counter (__make-counter 0)) (define (__test-passed) (display (string-append "Test" (number->string (__test-counter)) " passed!")) (newline)) (define (__test-failed) (display (string-append "Test" (number->string (__test-counter)) " failed!")) (newline)) (define (framework-check expected-value return-value) (if (eq? expected-value return-value) (__test-passed) (__test-failed))) (define (framework-check-aprox expected-value return-value) (let ((epsilon 1e-6)) (if (< (abs (- expected-value return-value)) epsilon) (__test-passed) (__test-failed)))) ;;; Dragons no more! ;;; End of the "test framework" code. ;;; The test cases follow: ;;; Test1 (framework-check 55 (accumulate + 0 '(1 2 3 4 5 6 7 8 9 10))) ;;; Test2 (framework-check 3628800 (accumulate * 1 '(1 2 3 4 5 6 7 8 9 10))) Test3 (framework-check 1 (accumulate * 1 '())) ;;; Test4 (framework-check 0 (accumulate + 0 '())) Test5 (framework-check 7 (accumulate * 1 '(7))) Test6 (framework-check 7 (accumulate + 0 '(7)))
null
https://raw.githubusercontent.com/IvanIvanov/fp2013/2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf/lab1/homework4/accumulate-tests.scm
scheme
This file contains unit tests for the problem listed in the name of this file. To run the tests specify the relative or absolute path to the ".scm" file with the proposed solution in the (load ...) command below. Then you can either open the tests and run them in Racket directly from the command line: plt-r5rs <the-name-of-this-file> variable. To inspect the actual test cases that are run - look at the bottom of the file. Here be dragons! The following definitions create the infrastructure for a very simple "test framework". As a student you should be just fine in skipping them. Dragons no more! End of the "test framework" code. The test cases follow: Test1 Test2 Test4
( with R5RS set as the language ) , or you can run the following assuming 's bin directory is included in the PATH environment (load "accumulate.scm") (define (__make-counter x) (lambda () (set! x (+ x 1)) x)) (define __test-counter (__make-counter 0)) (define (__test-passed) (display (string-append "Test" (number->string (__test-counter)) " passed!")) (newline)) (define (__test-failed) (display (string-append "Test" (number->string (__test-counter)) " failed!")) (newline)) (define (framework-check expected-value return-value) (if (eq? expected-value return-value) (__test-passed) (__test-failed))) (define (framework-check-aprox expected-value return-value) (let ((epsilon 1e-6)) (if (< (abs (- expected-value return-value)) epsilon) (__test-passed) (__test-failed)))) (framework-check 55 (accumulate + 0 '(1 2 3 4 5 6 7 8 9 10))) (framework-check 3628800 (accumulate * 1 '(1 2 3 4 5 6 7 8 9 10))) Test3 (framework-check 1 (accumulate * 1 '())) (framework-check 0 (accumulate + 0 '())) Test5 (framework-check 7 (accumulate * 1 '(7))) Test6 (framework-check 7 (accumulate + 0 '(7)))
ebf86df791110dc80fee7907f2795bdcbf34e78a17cdbc0448b13d95b87108a6
wangsix/VMO_repeated_themes_discovery
converter.lisp
;(in-package :common-lisp-user) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "csv-files" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "humdrum-by-col" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "midi-save" :type "lisp") *lisp-code-root*)) (setq *path&name* (merge-pathnames (make-pathname :directory '(:relative "mozartK282Mvt2" "polyphonic" "repeatedPatterns" "schoenberg" "E")) *music-data-root*)) (setq csv-destination (merge-pathnames (make-pathname :directory '(:relative "csv") :name "sonata04-2" :type "csv") *path&name*)) (setq MIDI-destination (merge-pathnames (make-pathname :directory '(:relative "midi") :name "sonata04-2" :type "mid") *path&name*)) (setq dataset-destination (merge-pathnames (make-pathname :directory '(:relative "lisp") :name "sonata04-2" :type "txt") *path&name*)) (progn (setq *scale* 1000) (setq *anacrusis* -1) (setq dataset (humdrum-file2dataset-by-col (merge-pathnames (make-pathname :directory '(:relative "kern") :name "sonata04-2" :type "krn") *path&name*))) (saveit MIDI-destination (modify-to-check-dataset dataset *scale*)) (write-to-file (mapcar #'(lambda (x) (append (list (+ (first x) *anacrusis*)) (rest x))) dataset) dataset-destination) (dataset2csv dataset-destination csv-destination))
null
https://raw.githubusercontent.com/wangsix/VMO_repeated_themes_discovery/0082b3c55e64ed447c8b68bcb705fd6da8e3541f/JKUPDD-Aug2013/groundTruth/mozartK282Mvt2/polyphonic/repeatedPatterns/schoenberg/E/script/converter.lisp
lisp
(in-package :common-lisp-user)
(load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "csv-files" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "humdrum-by-col" :type "lisp") *lisp-code-root*)) (load (merge-pathnames (make-pathname :directory '(:relative "File conversion") :name "midi-save" :type "lisp") *lisp-code-root*)) (setq *path&name* (merge-pathnames (make-pathname :directory '(:relative "mozartK282Mvt2" "polyphonic" "repeatedPatterns" "schoenberg" "E")) *music-data-root*)) (setq csv-destination (merge-pathnames (make-pathname :directory '(:relative "csv") :name "sonata04-2" :type "csv") *path&name*)) (setq MIDI-destination (merge-pathnames (make-pathname :directory '(:relative "midi") :name "sonata04-2" :type "mid") *path&name*)) (setq dataset-destination (merge-pathnames (make-pathname :directory '(:relative "lisp") :name "sonata04-2" :type "txt") *path&name*)) (progn (setq *scale* 1000) (setq *anacrusis* -1) (setq dataset (humdrum-file2dataset-by-col (merge-pathnames (make-pathname :directory '(:relative "kern") :name "sonata04-2" :type "krn") *path&name*))) (saveit MIDI-destination (modify-to-check-dataset dataset *scale*)) (write-to-file (mapcar #'(lambda (x) (append (list (+ (first x) *anacrusis*)) (rest x))) dataset) dataset-destination) (dataset2csv dataset-destination csv-destination))
50443b2ca76cbaf08272ef6cffc4a832ece6998f63f4c921d9e95136ccb51dbb
clash-lang/clash-compiler
SatWrap.hs
module SatWrap where import Clash.Prelude topEntity:: (SFixed 2 6) -> (SFixed 2 6) -> (SFixed 2 6) topEntity = satAdd SatWrap
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/Fixed/SatWrap.hs
haskell
module SatWrap where import Clash.Prelude topEntity:: (SFixed 2 6) -> (SFixed 2 6) -> (SFixed 2 6) topEntity = satAdd SatWrap
66a51e2e3db01b7c9acc711f5b7739872d6b861d226e4717cf06b6fd401fab3b
CryptoKami/cryptokami-core
SlottingSpec.hs
-- | Specification of Pos.Core.Slotting. module Test.Pos.Core.SlottingSpec ( spec ) where import Universum import Test.Hspec (Expectation, Spec, anyErrorCall, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonNegative (..), Positive (..), Property, (===), (==>)) import Pos.Arbitrary.Core (EoSToIntOverflow (..), UnreasonableEoS (..)) import Pos.Core (EpochOrSlot, HasConfiguration, SlotId (..), flattenSlotId, unflattenSlotId) import Pos.Util.QuickCheck.Property (shouldThrowException, (.=.)) import Test.Pos.Configuration (withDefConfiguration) spec :: Spec spec = withDefConfiguration $ describe "Slotting" $ do describe "SlotId" $ do describe "Ord" $ do prop "is consistent with flatten/unflatten" flattenOrdConsistency describe "flattening" $ do prop "unflattening after flattening returns original SlotId" flattenThenUnflatten describe "EpochOrSlot" $ do prop "succ . pred = id" predThenSucc prop "Using 'pred' with 'minBound :: EpochOrSlot' triggers an exception" predToMinBound prop "pred . succ = id" succThenPred prop "Using 'succ' with 'maxBound :: EpochOrSlot' triggers an exception" succToMaxBound prop "from . toEnum = id @Int" toFromEnum prop "toEnum . fromEnum = id @EpochOrSlot" fromToEnum prop "toEnum . fromEnum = id @EpochOrSlot (with very large, larger than \ \ 'maxReasonableEpoch', epochs" fromToEnumLargeEpoch prop "calling 'fromEnum' with a result greater than 'maxBound :: Int' will raise \ \ an exception" fromEnumOverflow prop "calling 'toEnum' with a negative number will raise an exception" toEnumNegative flattenOrdConsistency :: HasConfiguration => SlotId -> SlotId -> Property flattenOrdConsistency a b = a `compare` b === flattenSlotId a `compare` flattenSlotId b flattenThenUnflatten :: HasConfiguration => SlotId -> Property flattenThenUnflatten si = si === unflattenSlotId (flattenSlotId si) predThenSucc :: HasConfiguration => EpochOrSlot -> Property predThenSucc eos = eos > minBound ==> succ (pred eos) === eos predToMinBound :: HasConfiguration => Expectation predToMinBound = shouldThrowException pred anyErrorCall (minBound :: EpochOrSlot) succThenPred :: HasConfiguration => EpochOrSlot -> Property succThenPred eos = eos < maxBound ==> pred (succ eos) === eos succToMaxBound :: HasConfiguration => Expectation succToMaxBound = shouldThrowException succ anyErrorCall (maxBound :: EpochOrSlot) It is not necessary to check that ' int < fromEnum ( maxBound : : EpochOrSlot ) ' because -- this is not possible with the current implementation of the type. toFromEnum :: HasConfiguration => NonNegative Int -> Property toFromEnum (getNonNegative -> int) = fromEnum (toEnum @EpochOrSlot int) === int fromToEnum :: HasConfiguration => EpochOrSlot -> Property fromToEnum = toEnum . fromEnum .=. identity fromToEnumLargeEpoch :: HasConfiguration => UnreasonableEoS -> Property fromToEnumLargeEpoch (getUnreasonable -> eos) = toEnum (fromEnum eos) === eos fromEnumOverflow :: HasConfiguration => EoSToIntOverflow-> Expectation fromEnumOverflow (getEoS -> eos) = shouldThrowException (fromEnum @EpochOrSlot) anyErrorCall eos toEnumNegative :: HasConfiguration => Positive Int -> Expectation toEnumNegative (negate . getPositive -> int) = shouldThrowException (toEnum @EpochOrSlot) anyErrorCall int
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/lib/test/Test/Pos/Core/SlottingSpec.hs
haskell
| Specification of Pos.Core.Slotting. this is not possible with the current implementation of the type.
module Test.Pos.Core.SlottingSpec ( spec ) where import Universum import Test.Hspec (Expectation, Spec, anyErrorCall, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonNegative (..), Positive (..), Property, (===), (==>)) import Pos.Arbitrary.Core (EoSToIntOverflow (..), UnreasonableEoS (..)) import Pos.Core (EpochOrSlot, HasConfiguration, SlotId (..), flattenSlotId, unflattenSlotId) import Pos.Util.QuickCheck.Property (shouldThrowException, (.=.)) import Test.Pos.Configuration (withDefConfiguration) spec :: Spec spec = withDefConfiguration $ describe "Slotting" $ do describe "SlotId" $ do describe "Ord" $ do prop "is consistent with flatten/unflatten" flattenOrdConsistency describe "flattening" $ do prop "unflattening after flattening returns original SlotId" flattenThenUnflatten describe "EpochOrSlot" $ do prop "succ . pred = id" predThenSucc prop "Using 'pred' with 'minBound :: EpochOrSlot' triggers an exception" predToMinBound prop "pred . succ = id" succThenPred prop "Using 'succ' with 'maxBound :: EpochOrSlot' triggers an exception" succToMaxBound prop "from . toEnum = id @Int" toFromEnum prop "toEnum . fromEnum = id @EpochOrSlot" fromToEnum prop "toEnum . fromEnum = id @EpochOrSlot (with very large, larger than \ \ 'maxReasonableEpoch', epochs" fromToEnumLargeEpoch prop "calling 'fromEnum' with a result greater than 'maxBound :: Int' will raise \ \ an exception" fromEnumOverflow prop "calling 'toEnum' with a negative number will raise an exception" toEnumNegative flattenOrdConsistency :: HasConfiguration => SlotId -> SlotId -> Property flattenOrdConsistency a b = a `compare` b === flattenSlotId a `compare` flattenSlotId b flattenThenUnflatten :: HasConfiguration => SlotId -> Property flattenThenUnflatten si = si === unflattenSlotId (flattenSlotId si) predThenSucc :: HasConfiguration => EpochOrSlot -> Property predThenSucc eos = eos > minBound ==> succ (pred eos) === eos predToMinBound :: HasConfiguration => Expectation predToMinBound = shouldThrowException pred anyErrorCall (minBound :: EpochOrSlot) succThenPred :: HasConfiguration => EpochOrSlot -> Property succThenPred eos = eos < maxBound ==> pred (succ eos) === eos succToMaxBound :: HasConfiguration => Expectation succToMaxBound = shouldThrowException succ anyErrorCall (maxBound :: EpochOrSlot) It is not necessary to check that ' int < fromEnum ( maxBound : : EpochOrSlot ) ' because toFromEnum :: HasConfiguration => NonNegative Int -> Property toFromEnum (getNonNegative -> int) = fromEnum (toEnum @EpochOrSlot int) === int fromToEnum :: HasConfiguration => EpochOrSlot -> Property fromToEnum = toEnum . fromEnum .=. identity fromToEnumLargeEpoch :: HasConfiguration => UnreasonableEoS -> Property fromToEnumLargeEpoch (getUnreasonable -> eos) = toEnum (fromEnum eos) === eos fromEnumOverflow :: HasConfiguration => EoSToIntOverflow-> Expectation fromEnumOverflow (getEoS -> eos) = shouldThrowException (fromEnum @EpochOrSlot) anyErrorCall eos toEnumNegative :: HasConfiguration => Positive Int -> Expectation toEnumNegative (negate . getPositive -> int) = shouldThrowException (toEnum @EpochOrSlot) anyErrorCall int
8d79d8d493e7c646c66012dabb84567bf14f39b2579751deaba9fd9bafd2a1a7
MLstate/opalang
time.ml
Copyright © 2011 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) #<Ifstatic:OCAML_WORD_SIZE 64> type t = int type tm = Unix.tm let infinity = max_int let of_unix_time t = int_of_float (t *. 1000.) let to_unix_time t = float_of_int t /. 1000. let fmi = float_of_int max_int let of_unix_time_inf t = let t1000 = t *. 1000.0 in if t1000 >= fmi then max_int else int_of_float t1000 let adjust_mktime res ms = if res < 0 then res - ms else res + ms let zero = 0 let is_positive t = t > 0 let add t1 t2 = if t1 = infinity || t2 = infinity then infinity else t1 + t2 let difference t1 t2 = if t1 = infinity then zero else if t2 = infinity then infinity else t2 - t1 let milliseconds v = v let in_milliseconds t = t let in_seconds t = float_of_int t /. 1000. let round_to_sec t = t - (t mod 1000) let gmt_msec time = (abs time) mod 1000 let local_msec time = (abs time) mod 1000 #<Else> type t = float type tm = Unix.tm let infinity = infinity let of_unix_time t = t let to_unix_time t = t let of_unix_time_inf t = t let adjust_mktime res ms = (if res < 0. then (-.) else (+.)) res (float_of_int ms /. 1000.) let zero = 0. let is_positive t = t > 0. let add t1 t2 = t1 +. t2 let difference t1 t2 = t2 -. t1 let milliseconds v = float_of_int v /. 1000. let in_milliseconds t = int_of_float (t *. 1000.) let in_seconds t = t let round_to_sec t = floor t let gmt_msec time = int_of_float (snd (modf (abs_float time)) *. 1000.) let local_msec time = gmt_msec time #<End> let now () = of_unix_time (Unix.gettimeofday ()) let process_utime () = of_unix_time (Unix.times ()).Unix.tms_utime let process_stime () = of_unix_time (Unix.times ()).Unix.tms_stime let process_cutime () = of_unix_time (Unix.times ()).Unix.tms_cutime let process_cstime () = of_unix_time (Unix.times ()).Unix.tms_cstime let sleep = Unix.sleep let gmtime t = Unix.gmtime (to_unix_time t) let localtime t = Unix.localtime (to_unix_time t) let gmt_sec time = (gmtime time).Unix.tm_sec let gmt_min time = (gmtime time).Unix.tm_min let gmt_hour time = (gmtime time).Unix.tm_hour let gmt_mday time = (gmtime time).Unix.tm_mday let gmt_mon time = (gmtime time).Unix.tm_mon let gmt_year time = (gmtime time).Unix.tm_year + 1900 let gmt_wday time = (gmtime time).Unix.tm_wday let gmt_yday time = (gmtime time).Unix.tm_yday let gmt_isdst time = (gmtime time).Unix.tm_isdst let local_sec time = (localtime time).Unix.tm_sec let local_min time = (localtime time).Unix.tm_min let local_hour time = (localtime time).Unix.tm_hour let local_mday time = (localtime time).Unix.tm_mday let local_mon time = (localtime time).Unix.tm_mon let local_year time = (localtime time).Unix.tm_year + 1900 let local_wday time = (localtime time).Unix.tm_wday let local_yday time = (localtime time).Unix.tm_yday let local_isdst time = (localtime time).Unix.tm_isdst let local_timezone_offset () = let t = Unix.time() in let gmt = Unix.gmtime(t) in let local = Unix.localtime(t) in let (gmt_s, _) = Unix.mktime(gmt) in let (local_s, _) = Unix.mktime(local) in int_of_float((gmt_s -. local_s) /. 60.0);; let mktime ~year ~month ~day ~h ~min ~sec ~ms = let res = of_unix_time ( fst ( Unix.mktime { Unix.tm_sec = sec ; Unix.tm_min = min ; Unix.tm_hour = h ; Unix.tm_mday = day ; Unix.tm_mon = month ; Unix.tm_year = year - 1900 ; Unix.tm_wday = 0 ; Unix.tm_yday = 0 ; Unix.tm_isdst = false } ) ) in adjust_mktime res ms let bound = Chrono.bound let is_infinite t = t = infinity let is_after t1 t2 = t1 > t2 let is_before t1 t2 = t1 < t2 let seconds v = milliseconds (v * 1000) let seconds_float = of_unix_time let minutes v = seconds (v * 60) let hours v = minutes (v * 60) let days v = hours (v * 24) let max = Pervasives.max let min = Pervasives.min let get_accurate_time = Unix.gettimeofday
null
https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/ocamllib/libbase/time.ml
ocaml
Copyright © 2011 MLstate This file is part of . is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with . If not , see < / > . Copyright © 2011 MLstate This file is part of Opa. Opa is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. Opa is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Opa. If not, see </>. *) #<Ifstatic:OCAML_WORD_SIZE 64> type t = int type tm = Unix.tm let infinity = max_int let of_unix_time t = int_of_float (t *. 1000.) let to_unix_time t = float_of_int t /. 1000. let fmi = float_of_int max_int let of_unix_time_inf t = let t1000 = t *. 1000.0 in if t1000 >= fmi then max_int else int_of_float t1000 let adjust_mktime res ms = if res < 0 then res - ms else res + ms let zero = 0 let is_positive t = t > 0 let add t1 t2 = if t1 = infinity || t2 = infinity then infinity else t1 + t2 let difference t1 t2 = if t1 = infinity then zero else if t2 = infinity then infinity else t2 - t1 let milliseconds v = v let in_milliseconds t = t let in_seconds t = float_of_int t /. 1000. let round_to_sec t = t - (t mod 1000) let gmt_msec time = (abs time) mod 1000 let local_msec time = (abs time) mod 1000 #<Else> type t = float type tm = Unix.tm let infinity = infinity let of_unix_time t = t let to_unix_time t = t let of_unix_time_inf t = t let adjust_mktime res ms = (if res < 0. then (-.) else (+.)) res (float_of_int ms /. 1000.) let zero = 0. let is_positive t = t > 0. let add t1 t2 = t1 +. t2 let difference t1 t2 = t2 -. t1 let milliseconds v = float_of_int v /. 1000. let in_milliseconds t = int_of_float (t *. 1000.) let in_seconds t = t let round_to_sec t = floor t let gmt_msec time = int_of_float (snd (modf (abs_float time)) *. 1000.) let local_msec time = gmt_msec time #<End> let now () = of_unix_time (Unix.gettimeofday ()) let process_utime () = of_unix_time (Unix.times ()).Unix.tms_utime let process_stime () = of_unix_time (Unix.times ()).Unix.tms_stime let process_cutime () = of_unix_time (Unix.times ()).Unix.tms_cutime let process_cstime () = of_unix_time (Unix.times ()).Unix.tms_cstime let sleep = Unix.sleep let gmtime t = Unix.gmtime (to_unix_time t) let localtime t = Unix.localtime (to_unix_time t) let gmt_sec time = (gmtime time).Unix.tm_sec let gmt_min time = (gmtime time).Unix.tm_min let gmt_hour time = (gmtime time).Unix.tm_hour let gmt_mday time = (gmtime time).Unix.tm_mday let gmt_mon time = (gmtime time).Unix.tm_mon let gmt_year time = (gmtime time).Unix.tm_year + 1900 let gmt_wday time = (gmtime time).Unix.tm_wday let gmt_yday time = (gmtime time).Unix.tm_yday let gmt_isdst time = (gmtime time).Unix.tm_isdst let local_sec time = (localtime time).Unix.tm_sec let local_min time = (localtime time).Unix.tm_min let local_hour time = (localtime time).Unix.tm_hour let local_mday time = (localtime time).Unix.tm_mday let local_mon time = (localtime time).Unix.tm_mon let local_year time = (localtime time).Unix.tm_year + 1900 let local_wday time = (localtime time).Unix.tm_wday let local_yday time = (localtime time).Unix.tm_yday let local_isdst time = (localtime time).Unix.tm_isdst let local_timezone_offset () = let t = Unix.time() in let gmt = Unix.gmtime(t) in let local = Unix.localtime(t) in let (gmt_s, _) = Unix.mktime(gmt) in let (local_s, _) = Unix.mktime(local) in int_of_float((gmt_s -. local_s) /. 60.0);; let mktime ~year ~month ~day ~h ~min ~sec ~ms = let res = of_unix_time ( fst ( Unix.mktime { Unix.tm_sec = sec ; Unix.tm_min = min ; Unix.tm_hour = h ; Unix.tm_mday = day ; Unix.tm_mon = month ; Unix.tm_year = year - 1900 ; Unix.tm_wday = 0 ; Unix.tm_yday = 0 ; Unix.tm_isdst = false } ) ) in adjust_mktime res ms let bound = Chrono.bound let is_infinite t = t = infinity let is_after t1 t2 = t1 > t2 let is_before t1 t2 = t1 < t2 let seconds v = milliseconds (v * 1000) let seconds_float = of_unix_time let minutes v = seconds (v * 60) let hours v = minutes (v * 60) let days v = hours (v * 24) let max = Pervasives.max let min = Pervasives.min let get_accurate_time = Unix.gettimeofday
39cfb3697fa9fe3182dbb8b66fde15a69085cd433ca359a0c41432f3f4da7d28
erlang/sourcer
erlang_ls.erl
-module(erlang_ls). -export([main/1]). -define(DEFAULT_TRANSPORT, tcp). -define(DEFAULT_PORT, 9000). main(Args) -> case getopt:parse(cli_options(), Args) of {ok, {Opts, Other}} -> OptsMap = maps:from_list(proplists:unfold(Opts)), run(OptsMap, Other); _Err -> io:format("Error: ~p~n", [_Err]), getopt:usage(cli_options(), "lsp_server") end. cli_options() -> [ {help, $h, "help", undefined, "Show this help"}, {dump, $d, "dump", string, "Dump sourcer db for file or project"}, {format, undefined, "fmt", {atom, raw}, "Format for the dump (default: raw)"}, {out, undefined, "out", {string, standard_io}, "Destination file for the dump (default: standard_io)"}, {transport,$t, "transport",{atom, tcp}, "Transport layer for communication (default: tcp, stdio)"}, {port, $p, "port", integer, "LSP server port"}, {verbose, $v, "verbose", integer, "Verbosity level"}, {indent, $i, "indent", string, "Indent file(s) and exit"}, {stdout, undefined, "stdout", {boolean, false}, "Output to stdout instead of in place"}, {config, undefined, "config", string, "Configuration file"} ]. run(Opts, Other) -> Verbose = maps:get(verbose, Opts, 0), Config = maybe_load_config(maps:get(config, Opts, undefined), Verbose), case Opts of #{help := _} -> getopt:usage(cli_options(), "erlang_ls", "", [ {"", ""}, {"Start LS:", "'erlang_ls -P <nnnn>'"}, {"Indent :", "'erlang_ls -i <files>'"}, {"Dump :", "'erlang_ls -d <files> -fmt <fmt> -out <file>'"} ]), erlang:halt(0); #{dump:=DumpFile, format:=Fmt, out:=Out} -> Out1 = case Out of "standard_io" -> standard_io; _ -> Out end, sourcer_dump:dump(DumpFile, Fmt, Out1); #{indent := Indent, stdout := Stdout} -> IndentConfig = proplists:get_value(indent, Config, []), indent([Indent|Other], IndentConfig, Stdout, Verbose); _ -> ServerConfig = proplists:get_value(server, Config, []), start_server(Opts, ServerConfig) end. start_server(Opts, Config) -> Transport = maps:get(transport, Opts, proplists:get_value(transport, Config, ?DEFAULT_TRANSPORT)), ok = application:load(lsp_server), ok = application:set_env(lsp_server, transport, Transport), case Transport of tcp -> Port = maps:get(port, Opts, proplists:get_value(port, Config, ?DEFAULT_PORT)), ok = application:set_env(lsp_server, port, Port); _ -> ok end, ok = application:set_env(lsp_server, backend, sourcer), case application:ensure_all_started(lsp_server, permanent) of {ok, _R} -> receive stop -> ok end, ok; _Err -> io:format("Startup error: ~p~n", [_Err]), ok end. maybe_load_config(undefined, _Verbose) -> []; maybe_load_config(File, Verbose) -> case file:consult(File) of {ok, Config} -> Config; {error, Reason} -> io:format("Error loading config file: ~ts~n", [File]), Verbose > 0 andalso io:format("Reason ~p~n", [Reason]), erlang:halt(1) end. indent([File|Files], Config, Stdout, Verbose) -> Output = output(Stdout, File), try case file:read_file(File) of {ok, BinSrc} -> Enc = encoding(BinSrc), Src = unicode:characters_to_list(BinSrc, Enc), {ST,Indented} = timer:tc(fun() -> sourcer_indent:all(Src, Config) end), ok = Output(unicode:characters_to_binary(Indented, utf8, Enc)), Verbose > 0 andalso io:format(standard_error, "Indent: ~.6wms ~s~n", [ST div 1000, File]), indent(Files, Config, Stdout, Verbose); {error, Error} -> Str = io_lib:format("Could not read file: ~ts\n Reason: ~p~n", [File, Error]), throw({error,Str}) end catch throw:{error, Desc} -> io:format(standard_error, "~ts", [Desc]), erlang:halt(1); error:What -> io:format(standard_error, "Error could not indent file: ~ts\n", [File]), Verbose > 0 andalso io:format(standard_error, "Error ~p~n", [What]), Verbose > 1 andalso io:format(standard_error, "Stacktrace ~p~n", [erlang:get_stacktrace()]), erlang:halt(1) end; indent([], _, _, _) -> ok. output(false, File) -> fun(C) -> file:write_file(File, C) end; output(true, _) -> fun(C) -> io:format(standard_io, "~s", [C]) end. encoding(Bin) -> case epp:read_encoding_from_binary(Bin) of latin1 -> latin1; _ -> utf8 end.
null
https://raw.githubusercontent.com/erlang/sourcer/27ea9c63998b9e694eb7b654dd05b831b989e69e/apps/erlang_ls/src/erlang_ls.erl
erlang
-module(erlang_ls). -export([main/1]). -define(DEFAULT_TRANSPORT, tcp). -define(DEFAULT_PORT, 9000). main(Args) -> case getopt:parse(cli_options(), Args) of {ok, {Opts, Other}} -> OptsMap = maps:from_list(proplists:unfold(Opts)), run(OptsMap, Other); _Err -> io:format("Error: ~p~n", [_Err]), getopt:usage(cli_options(), "lsp_server") end. cli_options() -> [ {help, $h, "help", undefined, "Show this help"}, {dump, $d, "dump", string, "Dump sourcer db for file or project"}, {format, undefined, "fmt", {atom, raw}, "Format for the dump (default: raw)"}, {out, undefined, "out", {string, standard_io}, "Destination file for the dump (default: standard_io)"}, {transport,$t, "transport",{atom, tcp}, "Transport layer for communication (default: tcp, stdio)"}, {port, $p, "port", integer, "LSP server port"}, {verbose, $v, "verbose", integer, "Verbosity level"}, {indent, $i, "indent", string, "Indent file(s) and exit"}, {stdout, undefined, "stdout", {boolean, false}, "Output to stdout instead of in place"}, {config, undefined, "config", string, "Configuration file"} ]. run(Opts, Other) -> Verbose = maps:get(verbose, Opts, 0), Config = maybe_load_config(maps:get(config, Opts, undefined), Verbose), case Opts of #{help := _} -> getopt:usage(cli_options(), "erlang_ls", "", [ {"", ""}, {"Start LS:", "'erlang_ls -P <nnnn>'"}, {"Indent :", "'erlang_ls -i <files>'"}, {"Dump :", "'erlang_ls -d <files> -fmt <fmt> -out <file>'"} ]), erlang:halt(0); #{dump:=DumpFile, format:=Fmt, out:=Out} -> Out1 = case Out of "standard_io" -> standard_io; _ -> Out end, sourcer_dump:dump(DumpFile, Fmt, Out1); #{indent := Indent, stdout := Stdout} -> IndentConfig = proplists:get_value(indent, Config, []), indent([Indent|Other], IndentConfig, Stdout, Verbose); _ -> ServerConfig = proplists:get_value(server, Config, []), start_server(Opts, ServerConfig) end. start_server(Opts, Config) -> Transport = maps:get(transport, Opts, proplists:get_value(transport, Config, ?DEFAULT_TRANSPORT)), ok = application:load(lsp_server), ok = application:set_env(lsp_server, transport, Transport), case Transport of tcp -> Port = maps:get(port, Opts, proplists:get_value(port, Config, ?DEFAULT_PORT)), ok = application:set_env(lsp_server, port, Port); _ -> ok end, ok = application:set_env(lsp_server, backend, sourcer), case application:ensure_all_started(lsp_server, permanent) of {ok, _R} -> receive stop -> ok end, ok; _Err -> io:format("Startup error: ~p~n", [_Err]), ok end. maybe_load_config(undefined, _Verbose) -> []; maybe_load_config(File, Verbose) -> case file:consult(File) of {ok, Config} -> Config; {error, Reason} -> io:format("Error loading config file: ~ts~n", [File]), Verbose > 0 andalso io:format("Reason ~p~n", [Reason]), erlang:halt(1) end. indent([File|Files], Config, Stdout, Verbose) -> Output = output(Stdout, File), try case file:read_file(File) of {ok, BinSrc} -> Enc = encoding(BinSrc), Src = unicode:characters_to_list(BinSrc, Enc), {ST,Indented} = timer:tc(fun() -> sourcer_indent:all(Src, Config) end), ok = Output(unicode:characters_to_binary(Indented, utf8, Enc)), Verbose > 0 andalso io:format(standard_error, "Indent: ~.6wms ~s~n", [ST div 1000, File]), indent(Files, Config, Stdout, Verbose); {error, Error} -> Str = io_lib:format("Could not read file: ~ts\n Reason: ~p~n", [File, Error]), throw({error,Str}) end catch throw:{error, Desc} -> io:format(standard_error, "~ts", [Desc]), erlang:halt(1); error:What -> io:format(standard_error, "Error could not indent file: ~ts\n", [File]), Verbose > 0 andalso io:format(standard_error, "Error ~p~n", [What]), Verbose > 1 andalso io:format(standard_error, "Stacktrace ~p~n", [erlang:get_stacktrace()]), erlang:halt(1) end; indent([], _, _, _) -> ok. output(false, File) -> fun(C) -> file:write_file(File, C) end; output(true, _) -> fun(C) -> io:format(standard_io, "~s", [C]) end. encoding(Bin) -> case epp:read_encoding_from_binary(Bin) of latin1 -> latin1; _ -> utf8 end.
61c95805eda31473b2944379663b7536ebb8cd8672ed99fdffa80cd2b676d31c
victornicolet/parsynt
STerm.ml
open Base open Lang.Typ open Lang.Term open Lang.TermUtils open Lang.AcTerm open Lang.ResourceModel open Lang.Normalize open Lang.Unfold open SolverForms open Utils module Smt = SmtLib let simplify_conditionals (solver : online_solver) (ct : term) : term = spush solver; let t' = Transform.transform (fun f t -> match t.texpr with | EIte (c, tb, fb) -> ( let c' = f c in match c'.texpr with | EConst (CBool true) -> Some (f tb) | EConst (CBool false) -> Some (f fb) | _ -> ( match check_simple ~solver:(Some solver) (mk_not c) with | Unsat -> Some (f tb) | _ -> ( match check_simple ~solver:(Some solver) c with | Unsat -> Some (f fb) | _ -> spush solver; sassert solver c; let tb' = f tb in spop solver; spush solver; sassert solver (mk_not c); let fb' = f fb in spop solver; Some (simplify_easy (mk_ite c tb' fb')) ) ) ) | _ -> None) ct in spop solver; t' (* ======================================== MCNF helpers ========================= *) (** Rebuild an expression from a multi-way conditional normal form. Requires calls to solver to infer the conditions. *) let rev_conds (m : mcnf) : mcnf = List.map ~f:(fun (c, t) -> (List.rev c, t)) m let simplify_branches_assuming ?(assume = mk_true) (s : online_solver) (vars : VarSet.t) (inp : mcnf) : mcnf = let maybe_assume_term, _, _ = build_smt_term assume in let f_branch hyp_term (ct, e) = let t_to_opt_expr ec = let ot, _, _ = build_smt_term ec in match ot with | Some t -> ( let rc = exec_command s (Smt.mk_simplify (Smt.mk_and (Smt.mk_not hyp_term) t)) in match get_exprs_of_response vars rc with | Ok el -> ( match el with | hd :: _ -> if Terms.(hd = mk_false) then None else Some ec | [] -> Log.error (wrap "No expressions in response."); None ) | Error e -> Log.warning ~level:5 (printer_msg "Error in response. Simplification failed: %a" Smt.pp_smtTerm (Smt.mk_and (Smt.mk_not hyp_term) t)); Log.warning ~level:5 (printer_msg " %a@." Fmt.(list ~sep:sp Sexp.pp) e); None ) | None -> None in (List.filter_map ~f:t_to_opt_expr ct, e) in match maybe_assume_term with | Some hyp_term -> List.map ~f:(f_branch hyp_term) inp | None -> Log.error (printer_msg "This term cannot be translated to smt:@.---> %a.@." Fmt.(box Lang.TermPp.pp_term) assume); failhere Caml.__FILE__ "simplify_branches_assuming" "Failed to write assumption as SMT term." let simplify_conjunction (solver : online_solver) (conj : term list) = let conj = List.map ~f:Lang.AcTerm.simplify_easy conj in if List.exists ~f:has_branching conj then ( spush solver; List.iter ~f:(sassert solver) conj; let conj = List.map ~f:(simplify_conditionals solver) conj in spop solver; List.filter ~f:(fun t -> not (is_true t)) conj ) else conj (* Rebuild an expression tree from the mcnf. To do so, use a solver. *) let expr_of_mcnf solver (t : mcnf) = let split_branches s splitc = List.partition_tf ~f:(fun (bc, _) -> let cnj = mk_conj (splitc :: bc) in is_unsat (check_simple ~solver:(Some s) (mk_not cnj))) in let _, req_decls, vars = decls_of t in let local_solver = match solver with | Some s -> s | None -> let z3 = make_z3_solver () in declare_all z3 req_decls; z3 in let rec aux_f t = match t with | branch0 :: _ -> ( match branch0 with | c0 :: _, _ -> ( let bt, bf = split_branches local_solver c0 t in match (bt, bf) with | [], c -> Log.info ( printer_msg " a@. " pp_mcnf c ) ; aux_f (simplify_branches_assuming ~assume:c0 local_solver vars (rev_conds c)) | _, [] -> failwith "Malformed MCNF." | _ :: _, _ :: _ -> let et = aux_f (simplify_branches_assuming ~assume:c0 local_solver vars bt) in let ef = aux_f (simplify_branches_assuming ~assume:(mk_not c0) local_solver vars bf) in mk_ite c0 et ef ) | [], e -> e ) | [] -> failhere Caml.__FILE__ "expr_of_mcnf" "Unreachable case" in let e = match t with [] -> mk_empty_list | _ -> aux_f t in if is_none solver then close_solver local_solver; e let rec simplify_term ?(solver = None) ?(assume = []) ?(strategy = "default") (t : term) : term = match strategy with | "default" -> if List.length assume > 0 then simplify_mcnf ~solver ~assume ~mcnf:(to_mcnf t) else t | "z3" -> ( match z3_simplify ~solver t with Some x -> x | None -> t ) | "conds" -> simplify_cond ~solver ~assume t | "blast_max" -> rebuild_max (simplify_cond ~solver ~assume (blast_max t)) | _ -> failhere Caml.__FILE__ "simplify_term" "Not a valid strategy." and simplify_mcnf ?(solver = None) ~assume:(assumptions : term list) ~mcnf:(m : mcnf) : term = (* Remove unreachable branches *) let reachable_mcnf _e = let cnd_implied (cnd, _) = is_unsat (check_simple ~solver (mk_not (mk_and (mk_conj assumptions) (mk_conj cnd)))) in List.filter ~f:cnd_implied _e in (* Simplify remaining branch conditions and branch expressions. *) let e_mcnf' _e = let simpl_branch_cond (cnd, __e) = let cnd' = List.filter ~f:(fun c -> not (is_unsat (check_simple ~solver (mk_and (mk_conj assumptions) (mk_not c))))) cnd in (cnd', simplify_term ~solver ~assume:cnd' __e) in if List.is_empty assumptions then _e else List.map ~f:simpl_branch_cond (reachable_mcnf _e) in match List.find m ~f:(fun (cnd, _) -> List.is_empty cnd) with | Some (_, x) -> x | _ -> expr_of_mcnf solver (e_mcnf' m) and simplify_cond ?(solver = None) ~assume:(assumptions : term list) (t : term) : term = match assumptions with | [] -> t | _ -> let leftorright cond = let conj_assumptions = mk_conj assumptions in if check_implication ~solver conj_assumptions ~implies:cond then (true, false) else if check_implication ~solver conj_assumptions ~implies:(mk_not cond) then (false, true) else (false, false) in Transform.transform (fun f _t -> match _t.texpr with | EIte (c, t1, t2) -> ( let c' = f c in match leftorright c' with | true, false -> Some (f t1) | false, true -> Some (f t2) | _ -> Some (mk_ite c' (f t1) (f t2)) ) | _ -> None) t (** Compress a multi-way conditional form. When using the syntactic rules to obtain the mcnf, we will end up with unreachable branches. In compress_mcnf, we use a backend solver to remove these branches. *) let compress_mcnf ~(solver : online_solver) (t : mcnf) : mcnf = let elim_if_unsat terms (condl, term) = match condl with | _ :: _ -> ( let condl = simplify_conjunction solver condl in match check_simple ~solver:(Some solver) (mk_conj condl) with | Sat | Unknown | SExps _ -> let s_term = simplify_term ~solver:(Some solver) ~assume:condl ~strategy:"blast_max" term in terms @ [ (condl, s_term) ] | Error s -> failwith ("Solver error: " ^ s) | Unsat -> terms ) | [] -> [ ([], term) ] in let elim_duplicates t_mcnf ( condl , term ) = let has_equiv ( elt , _ ) = match check_simple ~solver:(Some solver ) ( mk_not ( mk_bin ( mk_conj elt ) Eq ( mk_conj condl ) ) ) with./te | Unsat - > true | _ - > false in if List.exists ~f : has_equiv t_mcnf then t_mcnf else t_mcnf @ [ ( condl , term ) ] in let has_equiv (elt, _) = match check_simple ~solver:(Some solver) (mk_not (mk_bin (mk_conj elt) Eq (mk_conj condl))) with./te | Unsat -> true | _ -> false in if List.exists ~f:has_equiv t_mcnf then t_mcnf else t_mcnf @ [(condl, term)] in *) let no_unsat_branches = List.fold_left ~f:elim_if_unsat ~init:[] t in (* List.fold_left ~f:elim_duplicates ~init:[] no_unsat_branches *) no_unsat_branches let normalize_unfoldings ~solver ~(costly : resource list) unfoldings : normalized_unfolding list = let f s_i = compress_mcnf ~solver (to_mcnf (normalize s_i)) in let couple_branches all_c_mcnfs e_mcnf = let f (c, e) = let conc_state = Map.map ~f:(fun cm -> simplify_mcnf ~solver:(Some solver) ~assume:c ~mcnf:cm) all_c_mcnfs in let computed = Array.of_list (List.map ~f:snd (Map.to_alist conc_state)) in let e' = add_computed_attributes e ~prev:None ~cur:computed in (c, e', computed) in List.map ~f e_mcnf in let per_unfolding u = let from_symb_mcnf, from_init_mcnf, u = let fi i = let s_i = if i > -1 then reduce_exn (mk_mem u.from_symb i) else u.from_symb in normalize_branches_mcnf ~costly (f s_i) in match (u.from_symb.texpr, u.from_init.texpr) with | ETuple els, ETuple elc -> if List.length els = List.length elc then ( Map.of_alist_exn (module Int) (List.mapi ~f:(fun i _ -> (i, fi i)) els), Map.of_alist_exn (module Int) (List.mapi ~f:(fun j e -> (j, f e)) elc), Map.of_alist_exn (module Int) (List.map2_exn ~f:(fun (j, from_symb) (_, from_init) -> (j, { input = u.input; from_init; from_symb })) (List.mapi ~f:(fun j e -> (j, e)) els) (List.mapi ~f:(fun j e -> (j, e)) elc)) ) else failhere Caml.__FILE__ "normalize_unfoldings" "Type mismatch between concrete and symbolic." | _ -> ( Map.of_alist_exn (module Int) [ (0, fi (-1)) ], Map.of_alist_exn (module Int) [ (0, f u.from_init) ], Map.of_alist_exn (module Int) [ (0, u) ] ) in let compress_components = Map.map ~f:(fun m -> compress_mcnf ~solver m) in let from_symb_mcnf = compress_components from_symb_mcnf in let from_init_mcnf = compress_components from_init_mcnf in let from_symb_mcnf = Map.map ~f:(couple_branches from_init_mcnf) from_symb_mcnf in { u; from_symb_mcnf; from_init_mcnf } in List.map ~f:per_unfolding unfoldings let normalize_eqns_unfoldings ~solver ~cinit ~(costly : resource list) (eqns_unfoldings : unfolding IM.t list) : normalized_unfolding list = let term_to_mcnf x = compress_mcnf ~solver (to_mcnf (normalize x)) in let couple_branches all_c_mcnfs e_mcnf = let f (prev, l) (c, e) = let conc_state = Map.map ~f:(fun cm -> simplify_mcnf ~solver:(Some solver) ~assume:c ~mcnf:cm) all_c_mcnfs in let computed = Array.of_list (List.map ~f:snd (Map.to_alist conc_state)) in let e' = add_computed_attributes e ~prev:(Some prev) ~cur:computed in (computed, l @ [ (c, e', prev) ]) in List.fold ~init:(cinit, []) ~f e_mcnf in let per_eqns_unfolding eqnu = let per_unfolding sel ~key:_ ~data:u = let mcnf = normalize_branches_mcnf ~costly (term_to_mcnf (sel u)) in let mcnf = compress_mcnf ~solver mcnf in mcnf in let from_symbs = Map.mapi ~f:(per_unfolding (fun u -> u.from_symb)) eqnu in let from_init_mcnf = Map.mapi ~f:(per_unfolding (fun u -> u.from_init)) eqnu in let from_symb_mcnf = Map.map ~f:(couple_branches from_init_mcnf --> snd) from_symbs in { u = eqnu; from_symb_mcnf; from_init_mcnf } in List.map ~f:per_eqns_unfolding eqns_unfoldings let normalize_soln_unfoldings ~solver ~cinit:_ ~(costly : resource list) (_unfoldings : unfolding list) = let term_to_mcnf x = let n_x, elapsed = timed normalize x in Log.debug ~level:3 (printer_msg "Normalize in %a s." Fmt.float elapsed); let m_x, elapsed = timed to_mcnf n_x in Log.debug ~level:3 (printer_msg "To mcnf in %a s." Fmt.float elapsed); let m_f, elapsed = timed (compress_mcnf ~solver) m_x in Log.debug ~level:3 (printer_msg "Compress in %a s." Fmt.float elapsed); m_f in let to_mcnf t = let m0 = term_to_mcnf t in normalize_branches_mcnf ~costly (compress_mcnf ~solver m0) in let per_unfolding unf = let this_unfolding sel = match (sel unf).texpr with | EStruct fields -> Map.of_alist_exn (module String) (List.map ~f:(fun (a, b) -> (a, to_mcnf b)) fields) | _ -> Map.empty (module String) in let from_symbs = this_unfolding (fun u -> u.from_symb) in let from_init = this_unfolding (fun u -> u.from_init) in Map.iter ~f:(fun mcnf -> Log.debug ~level:3 (printer_msg "@[Mcnf of unfolding:@;@[%a@]@]" pp_mcnf mcnf)) from_symbs; (from_init, from_symbs) in List.map ~f:per_unfolding _unfoldings let norm_cond_unfoldings (t : term) = Log.debug ~level:3 (wrap "Apply norm cond@."); let t = simplify_easy (Transform.apply_top_down_rule not_rule t) in rebuild_tree_AC ACES.compare (to_ac t) * Find a condition such that forall cond in cpos , cond = > c. If possible , this condition should be minimal . If possible, this condition should be minimal. *) let splitting_condition ~(solver : online_solver) (e : mcnf) (sube : int list) : term = let epos = List.(filteri ~f:(fun i _ -> mem sube i ~equal:( = ))) e in let eneg = List.(filteri ~f:(fun i _ -> not (mem sube i ~equal:( = )))) e in let check_valid_split s = List.for_all epos ~f:(fun (cnd, _) -> is_unsat (check_simple ~solver:(Some solver) (mk_and (mk_not s) (mk_conj cnd)))) && List.for_all eneg ~f:(fun (cnd, _) -> is_unsat (check_simple ~solver:(Some solver) (mk_and s (mk_conj cnd)))) in let conjs = unique_conjuncts e in let num_conjs = List.length conjs in let split_level i = let allk = List.(concat (map ~f:cond_possibilities (ListTools.k_combinations i conjs))) in let allsplits = List.(map ~f:mk_conj allk @ map ~f:mk_disj allk) in List.find ~f:check_valid_split allsplits in let rec find_split k = if k > num_conjs then mk_false else match split_level k with Some split -> split | None -> find_split (k + 1) in find_split 1
null
https://raw.githubusercontent.com/victornicolet/parsynt/d3f530923c0c75537b92c2930eb882921f38268c/src/solve/STerm.ml
ocaml
======================================== MCNF helpers ========================= * Rebuild an expression from a multi-way conditional normal form. Requires calls to solver to infer the conditions. Rebuild an expression tree from the mcnf. To do so, use a solver. Remove unreachable branches Simplify remaining branch conditions and branch expressions. * Compress a multi-way conditional form. When using the syntactic rules to obtain the mcnf, we will end up with unreachable branches. In compress_mcnf, we use a backend solver to remove these branches. List.fold_left ~f:elim_duplicates ~init:[] no_unsat_branches
open Base open Lang.Typ open Lang.Term open Lang.TermUtils open Lang.AcTerm open Lang.ResourceModel open Lang.Normalize open Lang.Unfold open SolverForms open Utils module Smt = SmtLib let simplify_conditionals (solver : online_solver) (ct : term) : term = spush solver; let t' = Transform.transform (fun f t -> match t.texpr with | EIte (c, tb, fb) -> ( let c' = f c in match c'.texpr with | EConst (CBool true) -> Some (f tb) | EConst (CBool false) -> Some (f fb) | _ -> ( match check_simple ~solver:(Some solver) (mk_not c) with | Unsat -> Some (f tb) | _ -> ( match check_simple ~solver:(Some solver) c with | Unsat -> Some (f fb) | _ -> spush solver; sassert solver c; let tb' = f tb in spop solver; spush solver; sassert solver (mk_not c); let fb' = f fb in spop solver; Some (simplify_easy (mk_ite c tb' fb')) ) ) ) | _ -> None) ct in spop solver; t' let rev_conds (m : mcnf) : mcnf = List.map ~f:(fun (c, t) -> (List.rev c, t)) m let simplify_branches_assuming ?(assume = mk_true) (s : online_solver) (vars : VarSet.t) (inp : mcnf) : mcnf = let maybe_assume_term, _, _ = build_smt_term assume in let f_branch hyp_term (ct, e) = let t_to_opt_expr ec = let ot, _, _ = build_smt_term ec in match ot with | Some t -> ( let rc = exec_command s (Smt.mk_simplify (Smt.mk_and (Smt.mk_not hyp_term) t)) in match get_exprs_of_response vars rc with | Ok el -> ( match el with | hd :: _ -> if Terms.(hd = mk_false) then None else Some ec | [] -> Log.error (wrap "No expressions in response."); None ) | Error e -> Log.warning ~level:5 (printer_msg "Error in response. Simplification failed: %a" Smt.pp_smtTerm (Smt.mk_and (Smt.mk_not hyp_term) t)); Log.warning ~level:5 (printer_msg " %a@." Fmt.(list ~sep:sp Sexp.pp) e); None ) | None -> None in (List.filter_map ~f:t_to_opt_expr ct, e) in match maybe_assume_term with | Some hyp_term -> List.map ~f:(f_branch hyp_term) inp | None -> Log.error (printer_msg "This term cannot be translated to smt:@.---> %a.@." Fmt.(box Lang.TermPp.pp_term) assume); failhere Caml.__FILE__ "simplify_branches_assuming" "Failed to write assumption as SMT term." let simplify_conjunction (solver : online_solver) (conj : term list) = let conj = List.map ~f:Lang.AcTerm.simplify_easy conj in if List.exists ~f:has_branching conj then ( spush solver; List.iter ~f:(sassert solver) conj; let conj = List.map ~f:(simplify_conditionals solver) conj in spop solver; List.filter ~f:(fun t -> not (is_true t)) conj ) else conj let expr_of_mcnf solver (t : mcnf) = let split_branches s splitc = List.partition_tf ~f:(fun (bc, _) -> let cnj = mk_conj (splitc :: bc) in is_unsat (check_simple ~solver:(Some s) (mk_not cnj))) in let _, req_decls, vars = decls_of t in let local_solver = match solver with | Some s -> s | None -> let z3 = make_z3_solver () in declare_all z3 req_decls; z3 in let rec aux_f t = match t with | branch0 :: _ -> ( match branch0 with | c0 :: _, _ -> ( let bt, bf = split_branches local_solver c0 t in match (bt, bf) with | [], c -> Log.info ( printer_msg " a@. " pp_mcnf c ) ; aux_f (simplify_branches_assuming ~assume:c0 local_solver vars (rev_conds c)) | _, [] -> failwith "Malformed MCNF." | _ :: _, _ :: _ -> let et = aux_f (simplify_branches_assuming ~assume:c0 local_solver vars bt) in let ef = aux_f (simplify_branches_assuming ~assume:(mk_not c0) local_solver vars bf) in mk_ite c0 et ef ) | [], e -> e ) | [] -> failhere Caml.__FILE__ "expr_of_mcnf" "Unreachable case" in let e = match t with [] -> mk_empty_list | _ -> aux_f t in if is_none solver then close_solver local_solver; e let rec simplify_term ?(solver = None) ?(assume = []) ?(strategy = "default") (t : term) : term = match strategy with | "default" -> if List.length assume > 0 then simplify_mcnf ~solver ~assume ~mcnf:(to_mcnf t) else t | "z3" -> ( match z3_simplify ~solver t with Some x -> x | None -> t ) | "conds" -> simplify_cond ~solver ~assume t | "blast_max" -> rebuild_max (simplify_cond ~solver ~assume (blast_max t)) | _ -> failhere Caml.__FILE__ "simplify_term" "Not a valid strategy." and simplify_mcnf ?(solver = None) ~assume:(assumptions : term list) ~mcnf:(m : mcnf) : term = let reachable_mcnf _e = let cnd_implied (cnd, _) = is_unsat (check_simple ~solver (mk_not (mk_and (mk_conj assumptions) (mk_conj cnd)))) in List.filter ~f:cnd_implied _e in let e_mcnf' _e = let simpl_branch_cond (cnd, __e) = let cnd' = List.filter ~f:(fun c -> not (is_unsat (check_simple ~solver (mk_and (mk_conj assumptions) (mk_not c))))) cnd in (cnd', simplify_term ~solver ~assume:cnd' __e) in if List.is_empty assumptions then _e else List.map ~f:simpl_branch_cond (reachable_mcnf _e) in match List.find m ~f:(fun (cnd, _) -> List.is_empty cnd) with | Some (_, x) -> x | _ -> expr_of_mcnf solver (e_mcnf' m) and simplify_cond ?(solver = None) ~assume:(assumptions : term list) (t : term) : term = match assumptions with | [] -> t | _ -> let leftorright cond = let conj_assumptions = mk_conj assumptions in if check_implication ~solver conj_assumptions ~implies:cond then (true, false) else if check_implication ~solver conj_assumptions ~implies:(mk_not cond) then (false, true) else (false, false) in Transform.transform (fun f _t -> match _t.texpr with | EIte (c, t1, t2) -> ( let c' = f c in match leftorright c' with | true, false -> Some (f t1) | false, true -> Some (f t2) | _ -> Some (mk_ite c' (f t1) (f t2)) ) | _ -> None) t let compress_mcnf ~(solver : online_solver) (t : mcnf) : mcnf = let elim_if_unsat terms (condl, term) = match condl with | _ :: _ -> ( let condl = simplify_conjunction solver condl in match check_simple ~solver:(Some solver) (mk_conj condl) with | Sat | Unknown | SExps _ -> let s_term = simplify_term ~solver:(Some solver) ~assume:condl ~strategy:"blast_max" term in terms @ [ (condl, s_term) ] | Error s -> failwith ("Solver error: " ^ s) | Unsat -> terms ) | [] -> [ ([], term) ] in let elim_duplicates t_mcnf ( condl , term ) = let has_equiv ( elt , _ ) = match check_simple ~solver:(Some solver ) ( mk_not ( mk_bin ( mk_conj elt ) Eq ( mk_conj condl ) ) ) with./te | Unsat - > true | _ - > false in if List.exists ~f : has_equiv t_mcnf then t_mcnf else t_mcnf @ [ ( condl , term ) ] in let has_equiv (elt, _) = match check_simple ~solver:(Some solver) (mk_not (mk_bin (mk_conj elt) Eq (mk_conj condl))) with./te | Unsat -> true | _ -> false in if List.exists ~f:has_equiv t_mcnf then t_mcnf else t_mcnf @ [(condl, term)] in *) let no_unsat_branches = List.fold_left ~f:elim_if_unsat ~init:[] t in no_unsat_branches let normalize_unfoldings ~solver ~(costly : resource list) unfoldings : normalized_unfolding list = let f s_i = compress_mcnf ~solver (to_mcnf (normalize s_i)) in let couple_branches all_c_mcnfs e_mcnf = let f (c, e) = let conc_state = Map.map ~f:(fun cm -> simplify_mcnf ~solver:(Some solver) ~assume:c ~mcnf:cm) all_c_mcnfs in let computed = Array.of_list (List.map ~f:snd (Map.to_alist conc_state)) in let e' = add_computed_attributes e ~prev:None ~cur:computed in (c, e', computed) in List.map ~f e_mcnf in let per_unfolding u = let from_symb_mcnf, from_init_mcnf, u = let fi i = let s_i = if i > -1 then reduce_exn (mk_mem u.from_symb i) else u.from_symb in normalize_branches_mcnf ~costly (f s_i) in match (u.from_symb.texpr, u.from_init.texpr) with | ETuple els, ETuple elc -> if List.length els = List.length elc then ( Map.of_alist_exn (module Int) (List.mapi ~f:(fun i _ -> (i, fi i)) els), Map.of_alist_exn (module Int) (List.mapi ~f:(fun j e -> (j, f e)) elc), Map.of_alist_exn (module Int) (List.map2_exn ~f:(fun (j, from_symb) (_, from_init) -> (j, { input = u.input; from_init; from_symb })) (List.mapi ~f:(fun j e -> (j, e)) els) (List.mapi ~f:(fun j e -> (j, e)) elc)) ) else failhere Caml.__FILE__ "normalize_unfoldings" "Type mismatch between concrete and symbolic." | _ -> ( Map.of_alist_exn (module Int) [ (0, fi (-1)) ], Map.of_alist_exn (module Int) [ (0, f u.from_init) ], Map.of_alist_exn (module Int) [ (0, u) ] ) in let compress_components = Map.map ~f:(fun m -> compress_mcnf ~solver m) in let from_symb_mcnf = compress_components from_symb_mcnf in let from_init_mcnf = compress_components from_init_mcnf in let from_symb_mcnf = Map.map ~f:(couple_branches from_init_mcnf) from_symb_mcnf in { u; from_symb_mcnf; from_init_mcnf } in List.map ~f:per_unfolding unfoldings let normalize_eqns_unfoldings ~solver ~cinit ~(costly : resource list) (eqns_unfoldings : unfolding IM.t list) : normalized_unfolding list = let term_to_mcnf x = compress_mcnf ~solver (to_mcnf (normalize x)) in let couple_branches all_c_mcnfs e_mcnf = let f (prev, l) (c, e) = let conc_state = Map.map ~f:(fun cm -> simplify_mcnf ~solver:(Some solver) ~assume:c ~mcnf:cm) all_c_mcnfs in let computed = Array.of_list (List.map ~f:snd (Map.to_alist conc_state)) in let e' = add_computed_attributes e ~prev:(Some prev) ~cur:computed in (computed, l @ [ (c, e', prev) ]) in List.fold ~init:(cinit, []) ~f e_mcnf in let per_eqns_unfolding eqnu = let per_unfolding sel ~key:_ ~data:u = let mcnf = normalize_branches_mcnf ~costly (term_to_mcnf (sel u)) in let mcnf = compress_mcnf ~solver mcnf in mcnf in let from_symbs = Map.mapi ~f:(per_unfolding (fun u -> u.from_symb)) eqnu in let from_init_mcnf = Map.mapi ~f:(per_unfolding (fun u -> u.from_init)) eqnu in let from_symb_mcnf = Map.map ~f:(couple_branches from_init_mcnf --> snd) from_symbs in { u = eqnu; from_symb_mcnf; from_init_mcnf } in List.map ~f:per_eqns_unfolding eqns_unfoldings let normalize_soln_unfoldings ~solver ~cinit:_ ~(costly : resource list) (_unfoldings : unfolding list) = let term_to_mcnf x = let n_x, elapsed = timed normalize x in Log.debug ~level:3 (printer_msg "Normalize in %a s." Fmt.float elapsed); let m_x, elapsed = timed to_mcnf n_x in Log.debug ~level:3 (printer_msg "To mcnf in %a s." Fmt.float elapsed); let m_f, elapsed = timed (compress_mcnf ~solver) m_x in Log.debug ~level:3 (printer_msg "Compress in %a s." Fmt.float elapsed); m_f in let to_mcnf t = let m0 = term_to_mcnf t in normalize_branches_mcnf ~costly (compress_mcnf ~solver m0) in let per_unfolding unf = let this_unfolding sel = match (sel unf).texpr with | EStruct fields -> Map.of_alist_exn (module String) (List.map ~f:(fun (a, b) -> (a, to_mcnf b)) fields) | _ -> Map.empty (module String) in let from_symbs = this_unfolding (fun u -> u.from_symb) in let from_init = this_unfolding (fun u -> u.from_init) in Map.iter ~f:(fun mcnf -> Log.debug ~level:3 (printer_msg "@[Mcnf of unfolding:@;@[%a@]@]" pp_mcnf mcnf)) from_symbs; (from_init, from_symbs) in List.map ~f:per_unfolding _unfoldings let norm_cond_unfoldings (t : term) = Log.debug ~level:3 (wrap "Apply norm cond@."); let t = simplify_easy (Transform.apply_top_down_rule not_rule t) in rebuild_tree_AC ACES.compare (to_ac t) * Find a condition such that forall cond in cpos , cond = > c. If possible , this condition should be minimal . If possible, this condition should be minimal. *) let splitting_condition ~(solver : online_solver) (e : mcnf) (sube : int list) : term = let epos = List.(filteri ~f:(fun i _ -> mem sube i ~equal:( = ))) e in let eneg = List.(filteri ~f:(fun i _ -> not (mem sube i ~equal:( = )))) e in let check_valid_split s = List.for_all epos ~f:(fun (cnd, _) -> is_unsat (check_simple ~solver:(Some solver) (mk_and (mk_not s) (mk_conj cnd)))) && List.for_all eneg ~f:(fun (cnd, _) -> is_unsat (check_simple ~solver:(Some solver) (mk_and s (mk_conj cnd)))) in let conjs = unique_conjuncts e in let num_conjs = List.length conjs in let split_level i = let allk = List.(concat (map ~f:cond_possibilities (ListTools.k_combinations i conjs))) in let allsplits = List.(map ~f:mk_conj allk @ map ~f:mk_disj allk) in List.find ~f:check_valid_split allsplits in let rec find_split k = if k > num_conjs then mk_false else match split_level k with Some split -> split | None -> find_split (k + 1) in find_split 1
aff02a625f126afc59385a4a2f5a6a0a8cb02582cce0ec4141e3746a30dcf732
nasa/Common-Metadata-Repository
json_schema.clj
(ns cmr.schema-validation.test.json-schema "Tests to verify JSON schema validation." (:require [cheshire.core :as json] [clojure.string :as string] [clojure.test :refer :all] [cmr.schema-validation.json-schema :as json-schema]) (:import (org.everit.json.schema SchemaException))) (def sample-json-schema "Schema to test validation against" (json-schema/parse-json-schema {:type :object :additionalProperties false :properties {:foo {:oneOf [{:type :string} {:type :integer}]} :bar {:type :boolean} :alpha {:type :string} :subfield {:$ref "#/definitions/omega"}} :required [:bar] :definitions {:omega {:type :object :properties {:zeta {:type :integer}} :required [:zeta]}}})) (comment ;; This is handy for trying out different capabilities of JSON schema. (json-schema/validate-json (json-schema/parse-json-schema {:definitions {:omega {:type "object" :properties {:a {:type :integer} :b {:type :integer} :c {:type :integer}} :oneOf [{:required [:a]} {:required [:b]} {:required [:c]}]}} :type "object" :additionalProperties false :properties {:omega {"$ref" "#/definitions/omega"}} :required ["omega"]}) (json/generate-string {:omega {:b 2}}))) (deftest validate-json-test (testing "Valid json" (are [json] (nil? (seq (json-schema/validate-json sample-json-schema (json/generate-string json)))) {"bar" true} {"bar" true :subfield {"zeta" 123 "gamma" "ray"}})) (testing "Validation failures" (are [invalid-json errors] (= errors (json-schema/validate-json sample-json-schema (json/generate-string invalid-json))) {"alpha" "omega"} ["#: required key [bar] not found"] {"bar" true :subfield {"gamma" "ray"}} ["#/subfield: required key [zeta] not found"] {"alpha" 17 "bar" true} ["#/alpha: expected type: String, found: Integer"] {"foo" true "bar" true} ["#/foo: expected type: String, found: Boolean" "#/foo: expected type: Integer, found: Boolean"] {"bad-property" "bad-value" "bar" true} ["#: extraneous key [bad-property] is not permitted"])) (testing "Invalid JSON structure" (is (= ["Missing value at 7 [character 8 line 1]"] (json-schema/validate-json sample-json-schema "{\"bar\":}"))) (are [invalid-json] (string/includes? (json-schema/validate-json sample-json-schema invalid-json) "Trailing characters are not permitted.") "{}random garbage." "{} random garbage." "{}\n\n{}{}[][]random garbage." "{}\n\r random garbage[][][][]")) (testing "Valid JSON Structure" (are [valid-json] (nil? (json-schema/validate-json sample-json-schema valid-json)) "{\"bar\": false} " "{\"bar\": false}\n\n\n\n\n\n\n\n\n" "{\"bar\": true}\t\n\t\t\n\r\r \r\n\t\t\n\n\t\n")) (testing "Invalid schema - description cannot be an array" (is (thrown-with-msg? SchemaException #"#/description: expected type: String, found: JsonArray" (json-schema/validate-json (json-schema/parse-json-schema {"title" "The title" "description" ["A description" "B description"]}) "{}")))))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/78e9ab2403d35fc1b8480c00463695b79f0ff7e0/schema-validation-lib/test/cmr/schema_validation/test/json_schema.clj
clojure
This is handy for trying out different capabilities of JSON schema.
(ns cmr.schema-validation.test.json-schema "Tests to verify JSON schema validation." (:require [cheshire.core :as json] [clojure.string :as string] [clojure.test :refer :all] [cmr.schema-validation.json-schema :as json-schema]) (:import (org.everit.json.schema SchemaException))) (def sample-json-schema "Schema to test validation against" (json-schema/parse-json-schema {:type :object :additionalProperties false :properties {:foo {:oneOf [{:type :string} {:type :integer}]} :bar {:type :boolean} :alpha {:type :string} :subfield {:$ref "#/definitions/omega"}} :required [:bar] :definitions {:omega {:type :object :properties {:zeta {:type :integer}} :required [:zeta]}}})) (comment (json-schema/validate-json (json-schema/parse-json-schema {:definitions {:omega {:type "object" :properties {:a {:type :integer} :b {:type :integer} :c {:type :integer}} :oneOf [{:required [:a]} {:required [:b]} {:required [:c]}]}} :type "object" :additionalProperties false :properties {:omega {"$ref" "#/definitions/omega"}} :required ["omega"]}) (json/generate-string {:omega {:b 2}}))) (deftest validate-json-test (testing "Valid json" (are [json] (nil? (seq (json-schema/validate-json sample-json-schema (json/generate-string json)))) {"bar" true} {"bar" true :subfield {"zeta" 123 "gamma" "ray"}})) (testing "Validation failures" (are [invalid-json errors] (= errors (json-schema/validate-json sample-json-schema (json/generate-string invalid-json))) {"alpha" "omega"} ["#: required key [bar] not found"] {"bar" true :subfield {"gamma" "ray"}} ["#/subfield: required key [zeta] not found"] {"alpha" 17 "bar" true} ["#/alpha: expected type: String, found: Integer"] {"foo" true "bar" true} ["#/foo: expected type: String, found: Boolean" "#/foo: expected type: Integer, found: Boolean"] {"bad-property" "bad-value" "bar" true} ["#: extraneous key [bad-property] is not permitted"])) (testing "Invalid JSON structure" (is (= ["Missing value at 7 [character 8 line 1]"] (json-schema/validate-json sample-json-schema "{\"bar\":}"))) (are [invalid-json] (string/includes? (json-schema/validate-json sample-json-schema invalid-json) "Trailing characters are not permitted.") "{}random garbage." "{} random garbage." "{}\n\n{}{}[][]random garbage." "{}\n\r random garbage[][][][]")) (testing "Valid JSON Structure" (are [valid-json] (nil? (json-schema/validate-json sample-json-schema valid-json)) "{\"bar\": false} " "{\"bar\": false}\n\n\n\n\n\n\n\n\n" "{\"bar\": true}\t\n\t\t\n\r\r \r\n\t\t\n\n\t\n")) (testing "Invalid schema - description cannot be an array" (is (thrown-with-msg? SchemaException #"#/description: expected type: String, found: JsonArray" (json-schema/validate-json (json-schema/parse-json-schema {"title" "The title" "description" ["A description" "B description"]}) "{}")))))
e9aa6a5b4dbd3e478268f85f7017473b74d55dfa46e27d913eb8e3ba635500c7
kadena-io/chainweaver
SigBuilder.hs
# LANGUAGE RecursiveDo # # LANGUAGE TupleSections # {-# LANGUAGE ConstraintKinds #-} # LANGUAGE CPP # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE DataKinds # # LANGUAGE TypeApplications # module Frontend.UI.Dialogs.SigBuilder where #if !defined(ghcjs_HOST_OS) import qualified Codec.QRCode as QR import qualified Codec.QRCode.JuicyPixels as QR #endif import Control.Error hiding (bool, mapMaybe) import Control.Lens import Control.Monad (forM) import qualified Data.Aeson as A import qualified Data.Aeson.Types as A import Data.Decimal (Decimal) import Data.Aeson.Parser.Internal (jsonEOF') import Data.Attoparsec.ByteString import Data.Bifunctor (first) import qualified Data.ByteString.Lazy as LB import Data.Either (fromRight) import Data.Functor (void) import Data.List (partition) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import Data.Map (Map) import qualified Data.Map as Map import qualified Data.IntMap as IMap import Data.YAML import qualified Data.YAML.Aeson as Y import Pact.Types.ChainMeta import Pact.Types.ChainId (networkId, NetworkId) import Pact.Types.Gas import Pact.Types.RPC import Pact.Types.Command import Pact.Types.Hash (Hash, hash, toUntypedHash, unHash, hashToText) import Pact.Types.SigData import Pact.Types.PactValue (PactValue(..)) import Pact.Types.Capability import Pact.Types.Names (QualifiedName(..)) import Pact.Types.Exp (Literal(..)) import Pact.Types.Util (asString) import Pact.Types.Pretty import Pact.Parse (ParsedInteger(..)) import Kadena.SigningTypes ------------------------------------------------------------------------------ import Reflex import Reflex.Dom hiding (Key, Command) ------------------------------------------------------------------------------ import Common.Wallet import Frontend.Crypto.Class import Frontend.Foundation import Frontend.Log import Frontend.Network import Frontend.UI.Dialogs.DeployConfirmation import Frontend.UI.Modal import Frontend.UI.TabBar import Frontend.UI.Transfer import Frontend.UI.Widgets import Frontend.UI.Widgets.Helpers (dialogSectionHeading) import Frontend.Wallet ------------------------------------------------------------------------------ import Frontend.UI.Modal.Impl ------------------------------------------------------------------------------ type SigBuilderWorkflow t m model key = ( MonadWidget t m , HasNetwork model t , HasWallet model key t , HasCrypto key m , HasTransactionLogger m , HasLogger model t , HasCrypto key (Performable m) ) sigBuilderCfg :: SigBuilderWorkflow t m model key => model -> Event t () -> m (ModalIdeCfg m key t) sigBuilderCfg m evt = do pure $ mempty & modalCfg_setModal .~ (Just (uiSigBuilderDialog m) <$ evt) uiSigBuilderDialog :: ( Monoid mConf , SigBuilderWorkflow t m model key ) => model -> Event t () -> m (mConf, Event t ()) uiSigBuilderDialog model _onCloseExternal = do dCloses <- workflow $ txnInputDialog model Nothing pure (mempty, switch $ current dCloses) -------------------------------------------------------------------------------- -- Input Flow -------------------------------------------------------------------------------- data PayloadSigningRequest = PayloadSigningRequest { _psr_sigData :: SigData Text , _psr_payload :: Payload PublicMeta Text } deriving (Show, Eq) data SigningRequestWalletState key = SigningRequestWalletState { _srws_currentNetwork :: Maybe NetworkName , _srws_cwKeys :: [ KeyPair key ] } deriving (Show, Eq) fetchKeysAndNetwork :: (Reflex t, HasNetwork model t, HasWallet model key t) => model -> Behavior t (SigningRequestWalletState key) fetchKeysAndNetwork model = let cwKeys = fmap _key_pair . IMap.elems <$> (model^.wallet_keys) selNodes = model ^. network_selectedNodes nid = (fmap (mkNetworkName . nodeVersion) . headMay . rights) <$> selNodes in current $ SigningRequestWalletState <$> nid <*> cwKeys txnInputDialog :: SigBuilderWorkflow t m model key => model -> Maybe (SigData Text) -> Workflow t m (Event t ()) txnInputDialog model mInitVal = Workflow $ mdo onClose <- modalHeader $ text "Signature Builder" let keysAndNet = fetchKeysAndNetwork model dmSigData <- modalMain $ divClass "group" $ parseInputToSigDataWidget mInitVal (onCancel, approve) <- modalFooter $ (,) <$> cancelButton def "Cancel" <*> confirmButton (def & uiButtonCfg_disabled .~ ( isNothing <$> dmSigData )) "Review" let approveE = fmap (\(a, b) -> [PayloadSigningRequest a b]) $ fmapMaybe id $ tag (current dmSigData) approve sbr = attach keysAndNet approveE return (onCancel <> onClose, uncurry (checkAndSummarize model) <$> sbr) data DataToBeSigned = DTB_SigData (SigData T.Text, Payload PublicMeta Text) | DTB_ErrorString String | DTB_EmptyString deriving (Show, Eq) payloadToSigData :: Payload PublicMeta Text -> Text -> SigData Text payloadToSigData parsedPayload payloadTxt = SigData cmdHash sigs $ Just payloadTxt where cmdHash = hash $ T.encodeUtf8 payloadTxt sigs = map (\s -> (PublicKeyHex $ _siPubKey s, Nothing)) $ _pSigners parsedPayload parseInputToSigDataWidget :: MonadWidget t m => Maybe (SigData Text) -> m (Dynamic t (Maybe (SigData Text, Payload PublicMeta Text))) parseInputToSigDataWidget mInit = divClass "group" $ do txt <- fmap value $ mkLabeledClsInput False "Paste SigData, CommandSigData, or Payload" $ \cls -> uiTxSigner mInit cls def let parsedBytes = parseBytes . T.encodeUtf8 <$> txt dyn_ $ ffor parsedBytes $ \case DTB_ErrorString e -> elClass "p" "error_inline" $ text $ T.pack e _ -> blank return $ validInput <$> parsedBytes where parsePayload :: Text -> Either String (Payload PublicMeta Text) parsePayload cmdText = first (const "Invalid cmd field inside SigData.") $ A.eitherDecodeStrict (T.encodeUtf8 cmdText) csdToSd :: CommandSigData -> SigData Text csdToSd (CommandSigData (SignatureList sl) payload) = let cmdHash = hash $ T.encodeUtf8 payload sdSigList = ffor sl $ \(CSDSigner k mSig) -> (k, mSig) in SigData cmdHash sdSigList $ Just payload parseAndAttachPayload sd = case parsePayload =<< (justErr "Payload missing" $ _sigDataCmd sd) of Left e -> DTB_ErrorString e Right p -> DTB_SigData (sd, p) parseSigDataJson = fmap parseAndAttachPayload . A.parseJSON parseCommandSigDataJson = fmap (parseAndAttachPayload . csdToSd) . A.parseJSON parsePayloadJson bytes val = let payload = parseAndAttachPayload . flip payloadToSigData (encodeAsText $ LB.fromStrict bytes) in fmap payload $ A.parseJSON @(Payload PublicMeta Text) val parseEmbeddedPayloadJson val = do t <- A.parseJSON @Text val let f = fmap (parseAndAttachPayload . flip payloadToSigData t) . A.parseJSON A.withEmbeddedJSON "Nested JSON Payload" f val sigBuilderJsonInputParsers rawBytes = mconcat [ parseSigDataJson , parsePayloadJson rawBytes , parseEmbeddedPayloadJson , parseCommandSigDataJson ] parseYaml b = case Y.decode1Strict b of Right sigData -> Just sigData Left _ -> case Y.decode1Strict b of Right csd -> Just $ csdToSd csd Left _ -> Nothing parseBytes "" = DTB_EmptyString parseBytes bytes = case parseYaml bytes of Just sd -> parseAndAttachPayload sd -- Didn't receive yaml, try json -- Parse the JSON, and consume all the input Nothing -> case parseOnly jsonEOF' bytes of Right val -> let errStr = DTB_ErrorString "Failed to detect SigData, CommandSigData, Payload, or Embedded Payload" in fromRight errStr $ A.parseEither (sigBuilderJsonInputParsers bytes) val Left _ -> DTB_ErrorString "Failed to detect SigData, CommandSigData, Payload, or Embedded Payload" validInput DTB_EmptyString = Nothing validInput (DTB_ErrorString _) = Nothing validInput (DTB_SigData info) = Just info -------------------------------------------------------------------------------- -- Preprocessing and Handling -------------------------------------------------------------------------------- warningDialog :: (MonadWidget t m) => Text -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) warningDialog warningMsg backW nextW = Workflow $ do onClose <- modalHeader $ text "Warning" void $ modalMain $ do el "h3" $ text "Warning" el "p" $ text warningMsg (back, next) <- modalFooter $ (,) <$> cancelButton def "Back" <*> confirmButton def "Continue" pure $ (onClose, leftmost [ backW <$ back , nextW <$ next ]) errorDialog :: (MonadWidget t m) => m () -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) errorDialog errorMsg backW = Workflow $ do onClose <- modalHeader $ text "Error" void $ modalMain $ do el "h3" $ text "Error" errorMsg back <- modalFooter $ cancelButton def "Back" pure $ (onClose, backW <$ back) -- Checks a list of workflow-based functions that take a next param which allows us to chain through -- all errors and warnings. The difference between a "Warning" and an "Error" workflow is that the -- warning allows the user to select to continue even if the predicate it checks against is true, -- whereas an error will only continue if the predicate it checks for is false checkAll :: a -> [(a -> a)] -> a checkAll nextW [] = nextW checkAll nextW [singleW] = singleW nextW checkAll nextW (x:xs) = x $ checkAll nextW xs checkAndSummarize :: SigBuilderWorkflow t m model key => model -> SigningRequestWalletState key -> [PayloadSigningRequest] -> Workflow t m (Event t ()) checkAndSummarize model srws (psr:rest) = let errorWorkflows = [checkForHashMismatch, checkMissingSigs] warningWorkflows = [checkNetwork] in flip checkAll errorWorkflows $ checkAll nextW warningWorkflows where sigData = _psr_sigData psr backW = txnInputDialog model (Just sigData) nextW = approveSigDialog model srws psr cwNetwork = _srws_currentNetwork srws payloadNetwork = mkNetworkName . view networkId <$> (_pNetworkId $ _psr_payload psr) checkForHashMismatch next = do let sbrHash = _sigDataHash sigData payloadTxt = _sigDataCmd sigData case fmap (hash . T.encodeUtf8) payloadTxt of Just payloadHash -> if sbrHash == payloadHash then next else flip errorDialog backW $ do el "p" $ text "Danger! The actual hash of the payload does not match the supplied hash" el "p" $ text $ "Supplied hash: " <> tshow sbrHash el "p" $ text $ "Actual hash: " <> tshow payloadHash -- This case shouldn't happen but we will fail anyways Nothing -> flip errorDialog backW $ text "Internal error -- Your supplied sig data does not contain a payload" networkWarning currentKnown mPayNet = case mPayNet of Nothing -> "The payload you are signing does not have an associated network" Just p -> "The payload you are signing has network id: \"" <> textNetworkName p <> "\" but your active chainweaver node is on: \"" <> textNetworkName currentKnown <> "\"" checkNetwork next = case (cwNetwork, payloadNetwork) of (Nothing, _) -> next (Just x, Just y) | x == y -> next (Just x, pNet) -> warningDialog (networkWarning x pNet) backW next checkMissingSigs next = let sigs = fmap snd $ _sigDataSigs sigData in case (length $ catMaybes sigs) == length sigs of False -> next True -> let warnMsg = "Everything has been signed. There is nothing to add" in warningDialog warnMsg backW next -------------------------------------------------------------------------------- -- Approval -------------------------------------------------------------------------------- approveSigDialog :: SigBuilderWorkflow t m model key => model -> SigningRequestWalletState key -> PayloadSigningRequest -> Workflow t m (Event t ()) approveSigDialog model srws psr = Workflow $ do let sigData = _psr_sigData psr [ ( PublicKeyHex , Maybe ) ] p = _psr_payload psr onClose <- modalHeader $ text "Review Transaction" sbTabDyn <- fst <$> sigBuilderTabs never sigsOrKeysE <- modalMain $ do -- TODO: Do this in a way that isnt completely stupid -- The Summary tab produces a list of all external sigs -- when we switch tabs, we clear this -- list instead of accumulating eeSigList <- dyn $ ffor sbTabDyn $ \case SigBuilderTab_Summary -> updated . sequence <$> showSigsWidget p (_keyPair_publicKey <$> _srws_cwKeys srws) sigs sigData SigBuilderTab_Details -> sigBuilderDetailsUI p sigs "" Nothing >> ([] <$) <$> getPostBuild switchHoldPromptly never eeSigList sigsOrKeys <- holdDyn [] sigsOrKeysE (back, sign) <- modalFooter $ (,) <$> cancelButton def "Back" <*> confirmButton def "Sign" let sigsOnSubmit = mapMaybe (\(a, mb) -> fmap (a,) mb) <$> current sigsOrKeys <@ sign let workflowEvent = leftmost [ txnInputDialog model (Just sigData) <$ back , signAndShowSigDialog model srws psr (approveSigDialog model srws psr) <$> sigsOnSubmit ] return (onClose, workflowEvent) data SigBuilderTab = SigBuilderTab_Summary | SigBuilderTab_Details deriving (Show, Eq) sigBuilderTabs :: (DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => Event t SigBuilderTab -> m (Dynamic t SigBuilderTab, Event t ()) sigBuilderTabs tabEv = do let f t0 g = case g t0 of Nothing -> (Just t0, Just ()) Just t -> (Just t, Nothing) rec (curSelection, done) <- mapAccumMaybeDyn f SigBuilderTab_Summary $ leftmost [ const . Just <$> onTabClick , const . Just <$> tabEv ] (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = [SigBuilderTab_Summary, SigBuilderTab_Details] , _tabBarCfg_mkLabel = \_ -> displaySigBuilderTab , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Secondary } pure (curSelection, done) where displaySigBuilderTab SigBuilderTab_Details = text "Details" displaySigBuilderTab SigBuilderTab_Summary = text "Summary" signersPartitonDisplay :: MonadWidget t m => Text -> ([Signer] -> m [Maybe (Dynamic t (PublicKeyHex, Maybe UserSig))]) -> [Signer] -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] signersPartitonDisplay label widget signers = divClass "signer__group" $ ifEmptyBlankSigner signers $ do dialogSectionHeading mempty label fmap catMaybes $ widget signers where ifEmptyBlankSigner l w = if l == [] then blank >> pure [] else w showSigsWidget :: (MonadWidget t m, HasCrypto key m) => Payload PublicMeta Text -> [PublicKey] -> [(PublicKeyHex, Maybe UserSig)] -> SigData Text -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] showSigsWidget p cwKeys sigs sd = do let orderedSigs = catMaybes $ ffor (p^.pSigners) $ \s -> ffor (lookup (PublicKeyHex $ _siPubKey s) sigs) $ \a-> (PublicKeyHex $ _siPubKey s, s, a) missingSigs = filter (\(_, _, sig) -> isNothing sig) orderedSigs -- CwSigners we only need the signer structure; ExternalSigners we need a ( pkh , Signer ) tuple to make lookup more efficient -- when a new signature is added (cwSigs, externalSigs) = partition isCWSigner missingSigs (cwUnscoped, cwScoped) = partition isUnscoped $ view _2 <$> cwSigs cwSigners = cwScoped <> cwUnscoped externalLookup = fmap (\(a, b, _) -> (a, b)) externalSigs hashWidget sdHash rec showTransactionSummary (signersToSummary <$> dSigners) p --TODO: Specialize the function for ones with no opitinal sig void $ signersPartitonDisplay "My Unscoped Signers" unscopedSignerGroup cwUnscoped void $ signersPartitonDisplay "My Scoped Signers" (mapM scopedSignerRow) cwScoped keysetOpen <- toggle False clk (clk,(_,dExternal)) <- controlledAccordionItem keysetOpen mempty (accordionHeaderBtn "External Signatures and QR Codes") $ do sigBuilderAdvancedTab sd externalSigs scopedSignerRow signersPartitonDisplay " External Signatures " ( ) $ view _ 2 < $ > externalSigs dExternal < - signersPartitonDisplay " External Signatures " ( ) $ view _ 2 < $ > externalSigs -- This constructs the entire list of all signers going to be signed each time a new signer is -- added. dSigners <- foldDyn ($) cwSigners $ leftmost [ ffor (updated $ sequence dExternal) $ \new _ -> let newSigners = catMaybes -- lookups shouldn't fail but we use this to get rid of the maybes use the pkh to get the official Signer structure $ fmap fst -- we only care about the pubkey, not the sig get rid of unsigned elems in cwSigners <> newSigners ] pure dExternal where sdHash = toUntypedHash $ _sigDataHash sd signersToSummary signers = let (trans, paysGas, unscoped) = foldr go (mempty, False, 0) signers pm = p ^. pMeta totalGas = fromIntegral (_pmGasLimit pm) * _pmGasPrice pm gas = if paysGas then Just totalGas else Nothing in TransactionSummary trans gas unscoped $ length signers go signer (tokenMap, doesPayGas, unscopedCounter) = let capList = signer^.siCapList tokenTransfers = mapMaybe parseFungibleTransferCap capList <> mapMaybe parseFungibleXChainTransferCap capList tokenMap' = foldr (\(k, v) m -> Map.insertWith (+) k v m) tokenMap tokenTransfers signerHasGas = isJust $ find (\cap -> asString (_scName cap) == "coin.GAS") capList in if capList == [] then (tokenMap, doesPayGas, unscopedCounter + 1) else (tokenMap', doesPayGas || signerHasGas, unscopedCounter) cwKeysPKH = PublicKeyHex . keyToText <$> cwKeys isCWSigner (pkh, _, _) = pkh `elem` cwKeysPKH isUnscoped (Signer _ _ _ capList) = capList == [] unOwnedSigningInput s = let mPub = hush $ parsePublicKey $ _siPubKey s in case mPub of Nothing -> text "^ ERROR parsing public key -- Cannot collect external signature" >> pure Nothing Just pub -> if pub `elem` cwKeys then blank >> pure Nothing else fmap Just $ uiSigningInput sdHash pub unscopedSignerGroup signers = divClass "group" $ forM signers $ \s -> do divClass "signer__pubkey" $ text $ _siPubKey s pure Nothing scopedSignerRow signer = do signerSection True (PublicKeyHex $ _siPubKey signer) $ do capListWidget $ _siCapList signer unOwnedSigningInput signer signerSection :: MonadWidget t m => Bool -> PublicKeyHex -> m a -> m a signerSection initToggleState pkh capListWidget =do visible <- divClass "group signer__header" $ do let accordionCell o = (if o then "" else "accordion-collapsed ") <> "payload__accordion " rec clk <- elDynClass "div" (accordionCell <$> visible') $ accordionButton def visible' <- toggle initToggleState clk divClass "signer__pubkey" $ text $ unPublicKeyHex pkh pure visible' elDynAttr "div" (ffor visible $ bool ("hidden"=:mempty) ("class" =: "group signer__capList") )$ capListWidget data SigBuilderAdvancedTab = SigBuilderAdvancedTab_ExternalSigs | SigBuilderAdvancedTab_HashQR | SigBuilderAdvancedTab_FullQR deriving (Eq,Ord,Show,Read,Enum,Bounded) showSBTabName :: SigBuilderAdvancedTab -> Text showSBTabName = \case SigBuilderAdvancedTab_HashQR -> "Hash QR Code" SigBuilderAdvancedTab_FullQR -> "Full Tx QR Code" SigBuilderAdvancedTab_ExternalSigs -> "External Signatures" sigBuilderAdvancedTab :: MonadWidget t m => SigData Text -> [(PublicKeyHex, Signer, Maybe UserSig)] -> (Signer -> m (Maybe (Dynamic t (PublicKeyHex, Maybe UserSig)))) -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] sigBuilderAdvancedTab sd externalSigs signerRow = do divClass "tabset" $ mdo curSelection <- holdDyn SigBuilderAdvancedTab_ExternalSigs onTabClick (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = [minBound .. maxBound] , _tabBarCfg_mkLabel = const $ text . showSBTabName , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Primary } externalSigs' <- tabPane mempty curSelection SigBuilderAdvancedTab_ExternalSigs $ case externalSigs of [] -> text "No External Signatures required" >> pure [] _ -> signersPartitonDisplay "External Signatures" (mapM signerRow) $ view _2 <$> externalSigs #if !defined(ghcjs_HOST_OS) tabPane mempty curSelection SigBuilderAdvancedTab_HashQR $ do let hashText = hashToText $ toUntypedHash $ _sigDataHash sd qrImage = QR.encodeText (QR.defaultQRCodeOptions QR.L) QR.Iso8859_1OrUtf8WithECI hashText img = maybe "Error creating QR code" (QR.toPngDataUrlT 4 6) qrImage el "div" $ text $ T.unwords [ "This QR code contains only the hash." , "It doesn't give any transaction information, so some wallets may not accept it." , "This is useful when you are signing your own transactions and don't want to transmit as much data." ] el "br" blank elAttr "img" ("src" =: LT.toStrict img) blank tabPane mempty curSelection SigBuilderAdvancedTab_FullQR $ do let yamlText = T.decodeUtf8 $ Y.encode1Strict sd qrImage = QR.encodeText (QR.defaultQRCodeOptions QR.L) QR.Iso8859_1OrUtf8WithECI yamlText img = maybe "Error creating QR code" (QR.toPngDataUrlT 4 4) qrImage elAttr "img" ("src" =: LT.toStrict img) blank #endif pure externalSigs' parseFungibleXChainTransferCap :: SigCapability -> Maybe (Text, Decimal) parseFungibleXChainTransferCap cap = xChainTransferCap cap where isFungible (QualifiedName _capModName capName _) = capName == "TRANSFER_XCHAIN" xChainTransferCap (SigCapability modName [PLiteral (LString _sender) ,PLiteral (LString _receiver) ,PLiteral (LDecimal amount) , PLiteral (LString _chain)]) | isFungible modName = Just (renderCompactText $ _qnQual modName, amount) | otherwise = Nothing xChainTransferCap _ = Nothing parseFungibleTransferCap :: SigCapability -> Maybe (Text, Decimal) parseFungibleTransferCap cap = transferCap cap where isFungible (QualifiedName _capModName capName _) = capName == "TRANSFER" transferCap (SigCapability modName [(PLiteral (LString _sender)) ,(PLiteral (LString _receiver)) ,(PLiteral (LDecimal amount))]) | isFungible modName = Just (renderCompactText $ _qnQual modName, amount) | otherwise = Nothing transferCap _ = Nothing data TransactionSummary = TransactionSummary { _ts_tokenTransfers :: Map Text Decimal , _ts_maxGas :: Maybe GasPrice -- Checks for GAS cap -- and then uses meta to calc , _ts_numUnscoped :: Int -- Unscoped that are BEING SIGNED FOR , _ts_sigsAdded :: Int } deriving (Show, Eq) showTransactionSummary :: MonadWidget t m => Dynamic t (TransactionSummary) -> Payload PublicMeta Text -> m () showTransactionSummary dSummary p = do dialogSectionHeading mempty "Impact Summary" divClass "group" $ dyn_ $ ffor dSummary $ \summary -> do let tokens = _ts_tokenTransfers summary kda = Map.lookup "coin" tokens tokens' = Map.delete "coin" tokens mkLabeledClsInput True "On Chain" $ const $ text $ renderCompactText $ p^.pMeta.pmChainId mkLabeledClsInput True "Tx Type" $ const $ text $ prpc $ p^.pPayload case _ts_maxGas summary of Nothing -> blank Just price -> void $ mkLabeledClsInput True "Max Gas Cost" $ const $ text $ renderCompactText price <> " KDA" flip (maybe blank) kda $ \kdaAmount -> void $ mkLabeledClsInput True "Amount KDA" $ const $ text $ showWithDecimal kdaAmount <> " KDA" if tokens' == mempty then blank else void $ mkLabeledClsInput True "Amount (Tokens)" $ const $ el "div" $ forM_ (Map.toList tokens') $ \(name, amount) -> el "p" $ text $ showWithDecimal amount <> " " <> name void $ mkLabeledClsInput True "Supplied Signatures" $ const $ text $ tshow $ _ts_sigsAdded summary if _ts_numUnscoped summary == 0 then blank else void $ mkLabeledClsInput True "Unscoped Sigs Added" $ const $ text $ tshow $ _ts_numUnscoped summary where prpc (Exec _) = "Exec" prpc (Continuation _) = "Continuation" -------------------------------------------------------------------------------- Signature and Submission -------------------------------------------------------------------------------- data SigDetails = SD_SigData_Yaml | SD_SigData_Json | SD_CommandSigData_Json | SD_CommandSigData_Yaml | SD_Command deriving (Eq,Ord,Show,Read,Enum,Bounded) showSigDetailsTabName :: SigDetails -> Text showSigDetailsTabName SD_SigData_Json = "SigData JSON" showSigDetailsTabName SD_SigData_Yaml = "SigData YAML" showSigDetailsTabName SD_CommandSigData_Json = "CommandSigData JSON" showSigDetailsTabName SD_CommandSigData_Yaml = "CommandSigData YAML" showSigDetailsTabName SD_Command = "Command JSON" sdToCsd :: SigData Text-> Maybe CommandSigData sdToCsd (SigData _ sigs Nothing) = Nothing sdToCsd (SigData _ sigs (Just cmdTxt) ) = let csdSigs = ffor sigs $ \(pkh, mSig) -> CSDSigner pkh mSig in Just $ CommandSigData (SignatureList csdSigs) cmdTxt signatureDetails :: (MonadWidget t m) => SigData Text -> m () signatureDetails sd = do hashWidget $ toUntypedHash $ _sigDataHash sd let canMakeCmd = (length $ _sigDataSigs sd) == (length $ catMaybes $ snd <$> _sigDataSigs sd) divClass "tabset" $ mdo curSelection <- holdDyn (if canMakeCmd then SD_Command else SD_SigData_Yaml) onTabClick (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = if canMakeCmd then [minBound .. maxBound] else init [minBound .. maxBound] , _tabBarCfg_mkLabel = const $ text . showSigDetailsTabName , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Primary } tabPane mempty curSelection SD_SigData_Yaml $ do let sigDataText = T.decodeUtf8 $ Y.encode1Strict sd void $ uiSignatureResult sigDataText tabPane mempty curSelection SD_SigData_Json $ do let sigDataText = T.decodeUtf8 $ LB.toStrict $ A.encode $ A.toJSON sd void $ uiSignatureResult sigDataText tabPane mempty curSelection SD_CommandSigData_Yaml $ do let csdText = maybe "" (T.decodeUtf8 . Y.encode1Strict) $ sdToCsd sd void $ uiSignatureResult csdText tabPane mempty curSelection SD_CommandSigData_Json $ do let csdText = maybe "" (T.decodeUtf8 . LB.toStrict . A.encode . A.toJSON) $ sdToCsd sd void $ uiSignatureResult csdText if canMakeCmd then tabPane mempty curSelection SD_Command $ do let cmdText = either (const "Command not available") (T.decodeUtf8 . LB.toStrict . A.encode . A.toJSON) $ sigDataToCommand sd void $ uiSignatureResult cmdText else blank pure () where uiSignatureResult txt = do void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ txt & initialAttributes <>~ fold [ "disabled" =: "true" , "class" =: " labeled-input__input labeled-input__sig-builder" ] uiDetailsCopyButton $ constant txt signAndShowSigDialog :: (SigBuilderWorkflow t m model key) => model -> SigningRequestWalletState key -> PayloadSigningRequest -> Workflow t m (Event t ()) -- Workflow for going back User - supplied -> Workflow t m (Event t ()) signAndShowSigDialog model srws psr backW externalKeySigs = Workflow $ mdo onClose <- modalHeader $ text "SigData / CommandSigData" -- This allows a "loading" page to render before we attempt to do the really computationally expensive sigs pb <- delay 0.1 =<< getPostBuild dmCmd <- holdDyn Nothing $ snd <$> eSDmCmdTuple eSDmCmdTuple <- performEvent $ ffor pb $ \_-> do sd <- addSigsToSigData (_psr_sigData psr) keys externalKeySigs if Nothing `elem` (snd <$> _sigDataSigs sd) then pure (sd, Nothing) else pure (sd, hush $ sigDataToCommand sd) -- TODO: Can we forkIO the sig process and display something after they are done? widgetHold_ (modalMain $ text "Loading Signatures ...") $ ffor eSDmCmdTuple $ \(sd, mCmd) -> do modalMain $ do pb' <- getPostBuild case mCmd of Nothing -> blank Just cmd -> previewTransaction model chain (constDyn p) $ cmd <$ pb' signatureDetails sd (back, done, submit) <- modalFooter $ (,,) <$> cancelButton def "Back" <*> confirmButton def "Done" <*> submitButton dmCmd let cmdAndNet = (,) <$> dmCmd <*> model ^. network_selectedNodes -- Gets rid of Maybe over Command by filtering eCmdAndNet = fmapMaybe (\(mCmd, ni) -> fmap (,ni) mCmd) $ current cmdAndNet <@ submit -- Given M (a, b) and f :: a -> b -> c , give us M c uncurryM f functor = fmap (\tpl -> uncurry f tpl) functor sender = p^.pMeta.pmSender submitToNetworkE = transferAndStatus model (AccountName sender, chain) `uncurryM` eCmdAndNet return (onClose <> done, leftmost [backW <$ back, submitToNetworkE]) where keys = _srws_cwKeys srws p = _psr_payload psr chain = p^.pMeta.pmChainId submitButton dmCmd = do let baseCfg = "class" =: "button button_type_confirm" dynAttr = ffor dmCmd $ \case Nothing -> baseCfg <> ("hidden" =: "true") Just _ -> baseCfg (e, _) <- elDynAttr' "button" dynAttr $ text "Submit to Network" pure $ domEvent Click e addSigsToSigData :: ( MonadJSM m , HasCrypto key m ) => SigData Text -> [KeyPair key] -- ^ Keys which we are signing with -> [(PublicKeyHex, UserSig)] -- External signatures collected -> m (SigData Text) addSigsToSigData sd signingKeys sigList = do let hashToSign = unHash $ toUntypedHash $ _sigDataHash sd someSigs = _sigDataSigs sd pubKeyToTxt = PublicKeyHex . keyToText . _keyPair_publicKey cwSigners = fmap (\x -> (pubKeyToTxt x, _keyPair_privateKey x)) signingKeys toPactSig sig = UserSig $ keyToText sig sigList' <- forM someSigs $ \(pkHex, mSig) -> case mSig of Just sig -> pure (pkHex, Just sig) Nothing -> case pkHex `lookup` cwSigners of Just (Just priv) -> do sig <- cryptoSign hashToSign priv pure (pkHex, Just $ toPactSig sig ) _ -> pure (pkHex, pkHex `lookup` sigList) pure $ sd { _sigDataSigs = sigList' } transferAndStatus :: (MonadWidget t m, HasLogger model t, HasTransactionLogger m) => model -> (AccountName, ChainId) -> Command Text -> [Either Text NodeInfo] -> Workflow t m (Event t ()) transferAndStatus model (sender, cid) cmd nodeInfos = Workflow $ do close <- modalHeader $ text "Transfer Status" _ <- elClass "div" "modal__main transaction_details" $ submitTransactionWithFeedback model cmd sender cid nodeInfos done <- modalFooter $ confirmButton def "Done" pure (close <> done, never) -------------------------------------------------------------------------------- -- Display Widgets -------------------------------------------------------------------------------- sigBuilderDetailsUI :: MonadWidget t m => Payload PublicMeta Text -> [(PublicKeyHex, Maybe UserSig)] -> Text -> Maybe Text -> m () sigBuilderDetailsUI p sigList wrapperCls mCls = divClass wrapperCls $ do txMetaWidget (p^.pMeta) (p^.pNetworkId) (p^.pNonce) mCls pactRpcWidget (_pPayload p) mCls signerWidget sigList (p^.pSigners) mCls pure () txMetaWidget :: MonadWidget t m => PublicMeta -> Maybe NetworkId -> Text -> Maybe Text -> m () txMetaWidget pm mNet nonce mCls = do dialogSectionHeading mempty "Transaction Metadata & Information" _ <- divClass (maybe "group segment" ("group segment " <>) mCls) $ do case mNet of Nothing -> blank Just n -> mkLabeledClsInput True "Network" $ \_ -> text $ renderCompactText n mkLabeledClsInput True "Chain" $ const $ text $ renderCompactText $ pm^.pmChainId mkLabeledClsInput True "Gas Payer" $ \_ -> text $ pm^.pmSender mkLabeledClsInput True "Gas Price" $ \_ -> text $ renderCompactText $ pm^.pmGasPrice mkLabeledClsInput True "Gas Limit" $ \_ -> text $ renderCompactText $ pm^.pmGasLimit let totalGas = fromIntegral (_pmGasLimit pm) * _pmGasPrice pm mkLabeledClsInput True "Max Gas Cost" $ \_ -> text $ renderCompactText totalGas <> " KDA" let (TxCreationTime ct) = pm^.pmCreationTime mkLabeledClsInput True "Creation Time" $ \_ -> text $ renderCompactText ct let prettyTTL (TTLSeconds (ParsedInteger s)) = tshow s <> case s of 1 -> " second" _ -> " seconds" mkLabeledClsInput True "TTL" $ \_ -> text $ prettyTTL $ pm^.pmTTL mkLabeledClsInput True "Nonce" $ \_ -> text nonce pure () pactRpcWidget :: MonadWidget t m => PactRPC Text -> Maybe Text -> m () pactRpcWidget (Exec e) mCls = do dialogSectionHeading mempty "Code" divClass (maybe "group" ("group " <>) mCls) $ do el "code" $ text $ tshow $ pretty $ _pmCode e case _pmData e of A.Null -> blank jsonVal -> do dialogSectionHeading mempty "Data" divClass (maybe "group" ("group " <>) mCls) $ void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ (T.decodeUtf8 $ LB.toStrict $ A.encode jsonVal) & initialAttributes .~ "disabled" =: "" <> "style" =: "width: 100%" pactRpcWidget (Continuation c) mCls = do dialogSectionHeading mempty "Continuation Data" divClass (maybe "group" ("group " <>) mCls) $ do mkLabeledClsInput True "Pact ID" $ \_ -> text $ renderCompactText $ _cmPactId c mkLabeledClsInput True "Step" $ \_ -> text $ tshow $ _cmStep c mkLabeledClsInput True "Rollback" $ \_ -> text $ tshow $ _cmRollback c mkLabeledClsInput True "Data" $ \_ -> do let contData = renderCompactText $ _cmData c void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ contData & initialAttributes .~ fold [ "disabled" =: "true" , "rows" =: "2" , "style" =: "color: black; width: 100%; height: auto;" ] mkLabeledClsInput True "Proof" $ \_ -> do let mProof = _cmProof c case mProof of Nothing -> blank Just p -> void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ (renderCompactText p) & initialAttributes .~ fold [ "disabled" =: "true" , "rows" =: "20" , "style" =: "color: black; width: 100%; height: auto;" ] signerWidget :: (MonadWidget t m) => [(PublicKeyHex, Maybe UserSig)] -> [Signer] -> Maybe Text -> m () signerWidget sigList signers mCls= do dialogSectionHeading mempty "Signers" forM_ signers $ \s -> divClass (maybe "group segment" ("group segment " <>) mCls) $ do mkLabeledClsInput True "Key:" $ \_ -> text (renderCompactText $ s ^.siPubKey) mkLabeledClsInput True "Caps:" $ \_ -> capListWidget $ s^.siCapList case lookup (PublicKeyHex $ s^.siPubKey) sigList of Nothing -> blank Just (Nothing) -> blank Just (Just (UserSig sig)) -> mkLabeledClsInput True "Signature:" $ \_ -> void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ sig & initialAttributes .~ fold [ "disabled" =: "" , "style" =: "color: black; width: 100%; height: auto;" ] capListWidget :: MonadWidget t m => [SigCapability] -> m () capListWidget [] = text "Unscoped Signer" capListWidget cl = do let capLines = foldl (\acc cap -> (renderCompactText cap):"":acc) [] cl txt = T.init $ T.init $ T.unlines capLines rows = tshow $ 2 * length capLines void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ txt & initialAttributes .~ fold [ "disabled" =: "" , "rows" =: rows , "style" =: "color: black; width: 100%; height: auto;" ] networkWidget :: MonadWidget t m => Payload PublicMeta a -> m () networkWidget p = case p^.pNetworkId of Nothing -> blank Just n -> do dialogSectionHeading mempty "Network" divClass "group" $ text $ n ^. networkId hashWidget :: MonadWidget t m => Hash -> m () hashWidget hash = void $ mkLabeledInput False "Hash" (\c -> uiInputElement $ c & initialAttributes %~ Map.insert "disabled" "") $ def & inputElementConfig_initialValue .~ hashToText hash
null
https://raw.githubusercontent.com/kadena-io/chainweaver/def9a10a97f51e8a8e749d0026b6c5f8bac2a0cd/frontend/src/Frontend/UI/Dialogs/SigBuilder.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE OverloadedStrings # ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- ------------------------------------------------------------------------------ Input Flow ------------------------------------------------------------------------------ Didn't receive yaml, try json Parse the JSON, and consume all the input ------------------------------------------------------------------------------ Preprocessing and Handling ------------------------------------------------------------------------------ Checks a list of workflow-based functions that take a next param which allows us to chain through all errors and warnings. The difference between a "Warning" and an "Error" workflow is that the warning allows the user to select to continue even if the predicate it checks against is true, whereas an error will only continue if the predicate it checks for is false This case shouldn't happen but we will fail anyways ------------------------------------------------------------------------------ Approval ------------------------------------------------------------------------------ TODO: Do this in a way that isnt completely stupid The Summary tab produces a list of all external sigs -- when we switch tabs, we clear this list instead of accumulating CwSigners we only need the signer structure; when a new signature is added TODO: Specialize the function for ones with no opitinal sig This constructs the entire list of all signers going to be signed each time a new signer is added. lookups shouldn't fail but we use this to get rid of the maybes we only care about the pubkey, not the sig Checks for GAS cap -- and then uses meta to calc Unscoped that are BEING SIGNED FOR ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Workflow for going back This allows a "loading" page to render before we attempt to do the really computationally TODO: Can we forkIO the sig process and display something after they are done? Gets rid of Maybe over Command by filtering Given M (a, b) and f :: a -> b -> c , give us M c ^ Keys which we are signing with External signatures collected ------------------------------------------------------------------------------ Display Widgets ------------------------------------------------------------------------------
# LANGUAGE RecursiveDo # # LANGUAGE TupleSections # # LANGUAGE CPP # # LANGUAGE DataKinds # # LANGUAGE TypeApplications # module Frontend.UI.Dialogs.SigBuilder where #if !defined(ghcjs_HOST_OS) import qualified Codec.QRCode as QR import qualified Codec.QRCode.JuicyPixels as QR #endif import Control.Error hiding (bool, mapMaybe) import Control.Lens import Control.Monad (forM) import qualified Data.Aeson as A import qualified Data.Aeson.Types as A import Data.Decimal (Decimal) import Data.Aeson.Parser.Internal (jsonEOF') import Data.Attoparsec.ByteString import Data.Bifunctor (first) import qualified Data.ByteString.Lazy as LB import Data.Either (fromRight) import Data.Functor (void) import Data.List (partition) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as LT import Data.Map (Map) import qualified Data.Map as Map import qualified Data.IntMap as IMap import Data.YAML import qualified Data.YAML.Aeson as Y import Pact.Types.ChainMeta import Pact.Types.ChainId (networkId, NetworkId) import Pact.Types.Gas import Pact.Types.RPC import Pact.Types.Command import Pact.Types.Hash (Hash, hash, toUntypedHash, unHash, hashToText) import Pact.Types.SigData import Pact.Types.PactValue (PactValue(..)) import Pact.Types.Capability import Pact.Types.Names (QualifiedName(..)) import Pact.Types.Exp (Literal(..)) import Pact.Types.Util (asString) import Pact.Types.Pretty import Pact.Parse (ParsedInteger(..)) import Kadena.SigningTypes import Reflex import Reflex.Dom hiding (Key, Command) import Common.Wallet import Frontend.Crypto.Class import Frontend.Foundation import Frontend.Log import Frontend.Network import Frontend.UI.Dialogs.DeployConfirmation import Frontend.UI.Modal import Frontend.UI.TabBar import Frontend.UI.Transfer import Frontend.UI.Widgets import Frontend.UI.Widgets.Helpers (dialogSectionHeading) import Frontend.Wallet import Frontend.UI.Modal.Impl type SigBuilderWorkflow t m model key = ( MonadWidget t m , HasNetwork model t , HasWallet model key t , HasCrypto key m , HasTransactionLogger m , HasLogger model t , HasCrypto key (Performable m) ) sigBuilderCfg :: SigBuilderWorkflow t m model key => model -> Event t () -> m (ModalIdeCfg m key t) sigBuilderCfg m evt = do pure $ mempty & modalCfg_setModal .~ (Just (uiSigBuilderDialog m) <$ evt) uiSigBuilderDialog :: ( Monoid mConf , SigBuilderWorkflow t m model key ) => model -> Event t () -> m (mConf, Event t ()) uiSigBuilderDialog model _onCloseExternal = do dCloses <- workflow $ txnInputDialog model Nothing pure (mempty, switch $ current dCloses) data PayloadSigningRequest = PayloadSigningRequest { _psr_sigData :: SigData Text , _psr_payload :: Payload PublicMeta Text } deriving (Show, Eq) data SigningRequestWalletState key = SigningRequestWalletState { _srws_currentNetwork :: Maybe NetworkName , _srws_cwKeys :: [ KeyPair key ] } deriving (Show, Eq) fetchKeysAndNetwork :: (Reflex t, HasNetwork model t, HasWallet model key t) => model -> Behavior t (SigningRequestWalletState key) fetchKeysAndNetwork model = let cwKeys = fmap _key_pair . IMap.elems <$> (model^.wallet_keys) selNodes = model ^. network_selectedNodes nid = (fmap (mkNetworkName . nodeVersion) . headMay . rights) <$> selNodes in current $ SigningRequestWalletState <$> nid <*> cwKeys txnInputDialog :: SigBuilderWorkflow t m model key => model -> Maybe (SigData Text) -> Workflow t m (Event t ()) txnInputDialog model mInitVal = Workflow $ mdo onClose <- modalHeader $ text "Signature Builder" let keysAndNet = fetchKeysAndNetwork model dmSigData <- modalMain $ divClass "group" $ parseInputToSigDataWidget mInitVal (onCancel, approve) <- modalFooter $ (,) <$> cancelButton def "Cancel" <*> confirmButton (def & uiButtonCfg_disabled .~ ( isNothing <$> dmSigData )) "Review" let approveE = fmap (\(a, b) -> [PayloadSigningRequest a b]) $ fmapMaybe id $ tag (current dmSigData) approve sbr = attach keysAndNet approveE return (onCancel <> onClose, uncurry (checkAndSummarize model) <$> sbr) data DataToBeSigned = DTB_SigData (SigData T.Text, Payload PublicMeta Text) | DTB_ErrorString String | DTB_EmptyString deriving (Show, Eq) payloadToSigData :: Payload PublicMeta Text -> Text -> SigData Text payloadToSigData parsedPayload payloadTxt = SigData cmdHash sigs $ Just payloadTxt where cmdHash = hash $ T.encodeUtf8 payloadTxt sigs = map (\s -> (PublicKeyHex $ _siPubKey s, Nothing)) $ _pSigners parsedPayload parseInputToSigDataWidget :: MonadWidget t m => Maybe (SigData Text) -> m (Dynamic t (Maybe (SigData Text, Payload PublicMeta Text))) parseInputToSigDataWidget mInit = divClass "group" $ do txt <- fmap value $ mkLabeledClsInput False "Paste SigData, CommandSigData, or Payload" $ \cls -> uiTxSigner mInit cls def let parsedBytes = parseBytes . T.encodeUtf8 <$> txt dyn_ $ ffor parsedBytes $ \case DTB_ErrorString e -> elClass "p" "error_inline" $ text $ T.pack e _ -> blank return $ validInput <$> parsedBytes where parsePayload :: Text -> Either String (Payload PublicMeta Text) parsePayload cmdText = first (const "Invalid cmd field inside SigData.") $ A.eitherDecodeStrict (T.encodeUtf8 cmdText) csdToSd :: CommandSigData -> SigData Text csdToSd (CommandSigData (SignatureList sl) payload) = let cmdHash = hash $ T.encodeUtf8 payload sdSigList = ffor sl $ \(CSDSigner k mSig) -> (k, mSig) in SigData cmdHash sdSigList $ Just payload parseAndAttachPayload sd = case parsePayload =<< (justErr "Payload missing" $ _sigDataCmd sd) of Left e -> DTB_ErrorString e Right p -> DTB_SigData (sd, p) parseSigDataJson = fmap parseAndAttachPayload . A.parseJSON parseCommandSigDataJson = fmap (parseAndAttachPayload . csdToSd) . A.parseJSON parsePayloadJson bytes val = let payload = parseAndAttachPayload . flip payloadToSigData (encodeAsText $ LB.fromStrict bytes) in fmap payload $ A.parseJSON @(Payload PublicMeta Text) val parseEmbeddedPayloadJson val = do t <- A.parseJSON @Text val let f = fmap (parseAndAttachPayload . flip payloadToSigData t) . A.parseJSON A.withEmbeddedJSON "Nested JSON Payload" f val sigBuilderJsonInputParsers rawBytes = mconcat [ parseSigDataJson , parsePayloadJson rawBytes , parseEmbeddedPayloadJson , parseCommandSigDataJson ] parseYaml b = case Y.decode1Strict b of Right sigData -> Just sigData Left _ -> case Y.decode1Strict b of Right csd -> Just $ csdToSd csd Left _ -> Nothing parseBytes "" = DTB_EmptyString parseBytes bytes = case parseYaml bytes of Just sd -> parseAndAttachPayload sd Nothing -> case parseOnly jsonEOF' bytes of Right val -> let errStr = DTB_ErrorString "Failed to detect SigData, CommandSigData, Payload, or Embedded Payload" in fromRight errStr $ A.parseEither (sigBuilderJsonInputParsers bytes) val Left _ -> DTB_ErrorString "Failed to detect SigData, CommandSigData, Payload, or Embedded Payload" validInput DTB_EmptyString = Nothing validInput (DTB_ErrorString _) = Nothing validInput (DTB_SigData info) = Just info warningDialog :: (MonadWidget t m) => Text -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) warningDialog warningMsg backW nextW = Workflow $ do onClose <- modalHeader $ text "Warning" void $ modalMain $ do el "h3" $ text "Warning" el "p" $ text warningMsg (back, next) <- modalFooter $ (,) <$> cancelButton def "Back" <*> confirmButton def "Continue" pure $ (onClose, leftmost [ backW <$ back , nextW <$ next ]) errorDialog :: (MonadWidget t m) => m () -> Workflow t m (Event t ()) -> Workflow t m (Event t ()) errorDialog errorMsg backW = Workflow $ do onClose <- modalHeader $ text "Error" void $ modalMain $ do el "h3" $ text "Error" errorMsg back <- modalFooter $ cancelButton def "Back" pure $ (onClose, backW <$ back) checkAll :: a -> [(a -> a)] -> a checkAll nextW [] = nextW checkAll nextW [singleW] = singleW nextW checkAll nextW (x:xs) = x $ checkAll nextW xs checkAndSummarize :: SigBuilderWorkflow t m model key => model -> SigningRequestWalletState key -> [PayloadSigningRequest] -> Workflow t m (Event t ()) checkAndSummarize model srws (psr:rest) = let errorWorkflows = [checkForHashMismatch, checkMissingSigs] warningWorkflows = [checkNetwork] in flip checkAll errorWorkflows $ checkAll nextW warningWorkflows where sigData = _psr_sigData psr backW = txnInputDialog model (Just sigData) nextW = approveSigDialog model srws psr cwNetwork = _srws_currentNetwork srws payloadNetwork = mkNetworkName . view networkId <$> (_pNetworkId $ _psr_payload psr) checkForHashMismatch next = do let sbrHash = _sigDataHash sigData payloadTxt = _sigDataCmd sigData case fmap (hash . T.encodeUtf8) payloadTxt of Just payloadHash -> if sbrHash == payloadHash then next else flip errorDialog backW $ do el "p" $ text "Danger! The actual hash of the payload does not match the supplied hash" el "p" $ text $ "Supplied hash: " <> tshow sbrHash el "p" $ text $ "Actual hash: " <> tshow payloadHash Nothing -> flip errorDialog backW $ text "Internal error -- Your supplied sig data does not contain a payload" networkWarning currentKnown mPayNet = case mPayNet of Nothing -> "The payload you are signing does not have an associated network" Just p -> "The payload you are signing has network id: \"" <> textNetworkName p <> "\" but your active chainweaver node is on: \"" <> textNetworkName currentKnown <> "\"" checkNetwork next = case (cwNetwork, payloadNetwork) of (Nothing, _) -> next (Just x, Just y) | x == y -> next (Just x, pNet) -> warningDialog (networkWarning x pNet) backW next checkMissingSigs next = let sigs = fmap snd $ _sigDataSigs sigData in case (length $ catMaybes sigs) == length sigs of False -> next True -> let warnMsg = "Everything has been signed. There is nothing to add" in warningDialog warnMsg backW next approveSigDialog :: SigBuilderWorkflow t m model key => model -> SigningRequestWalletState key -> PayloadSigningRequest -> Workflow t m (Event t ()) approveSigDialog model srws psr = Workflow $ do let sigData = _psr_sigData psr [ ( PublicKeyHex , Maybe ) ] p = _psr_payload psr onClose <- modalHeader $ text "Review Transaction" sbTabDyn <- fst <$> sigBuilderTabs never sigsOrKeysE <- modalMain $ do eeSigList <- dyn $ ffor sbTabDyn $ \case SigBuilderTab_Summary -> updated . sequence <$> showSigsWidget p (_keyPair_publicKey <$> _srws_cwKeys srws) sigs sigData SigBuilderTab_Details -> sigBuilderDetailsUI p sigs "" Nothing >> ([] <$) <$> getPostBuild switchHoldPromptly never eeSigList sigsOrKeys <- holdDyn [] sigsOrKeysE (back, sign) <- modalFooter $ (,) <$> cancelButton def "Back" <*> confirmButton def "Sign" let sigsOnSubmit = mapMaybe (\(a, mb) -> fmap (a,) mb) <$> current sigsOrKeys <@ sign let workflowEvent = leftmost [ txnInputDialog model (Just sigData) <$ back , signAndShowSigDialog model srws psr (approveSigDialog model srws psr) <$> sigsOnSubmit ] return (onClose, workflowEvent) data SigBuilderTab = SigBuilderTab_Summary | SigBuilderTab_Details deriving (Show, Eq) sigBuilderTabs :: (DomBuilder t m, PostBuild t m, MonadHold t m, MonadFix m) => Event t SigBuilderTab -> m (Dynamic t SigBuilderTab, Event t ()) sigBuilderTabs tabEv = do let f t0 g = case g t0 of Nothing -> (Just t0, Just ()) Just t -> (Just t, Nothing) rec (curSelection, done) <- mapAccumMaybeDyn f SigBuilderTab_Summary $ leftmost [ const . Just <$> onTabClick , const . Just <$> tabEv ] (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = [SigBuilderTab_Summary, SigBuilderTab_Details] , _tabBarCfg_mkLabel = \_ -> displaySigBuilderTab , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Secondary } pure (curSelection, done) where displaySigBuilderTab SigBuilderTab_Details = text "Details" displaySigBuilderTab SigBuilderTab_Summary = text "Summary" signersPartitonDisplay :: MonadWidget t m => Text -> ([Signer] -> m [Maybe (Dynamic t (PublicKeyHex, Maybe UserSig))]) -> [Signer] -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] signersPartitonDisplay label widget signers = divClass "signer__group" $ ifEmptyBlankSigner signers $ do dialogSectionHeading mempty label fmap catMaybes $ widget signers where ifEmptyBlankSigner l w = if l == [] then blank >> pure [] else w showSigsWidget :: (MonadWidget t m, HasCrypto key m) => Payload PublicMeta Text -> [PublicKey] -> [(PublicKeyHex, Maybe UserSig)] -> SigData Text -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] showSigsWidget p cwKeys sigs sd = do let orderedSigs = catMaybes $ ffor (p^.pSigners) $ \s -> ffor (lookup (PublicKeyHex $ _siPubKey s) sigs) $ \a-> (PublicKeyHex $ _siPubKey s, s, a) missingSigs = filter (\(_, _, sig) -> isNothing sig) orderedSigs ExternalSigners we need a ( pkh , Signer ) tuple to make lookup more efficient (cwSigs, externalSigs) = partition isCWSigner missingSigs (cwUnscoped, cwScoped) = partition isUnscoped $ view _2 <$> cwSigs cwSigners = cwScoped <> cwUnscoped externalLookup = fmap (\(a, b, _) -> (a, b)) externalSigs hashWidget sdHash rec showTransactionSummary (signersToSummary <$> dSigners) p void $ signersPartitonDisplay "My Unscoped Signers" unscopedSignerGroup cwUnscoped void $ signersPartitonDisplay "My Scoped Signers" (mapM scopedSignerRow) cwScoped keysetOpen <- toggle False clk (clk,(_,dExternal)) <- controlledAccordionItem keysetOpen mempty (accordionHeaderBtn "External Signatures and QR Codes") $ do sigBuilderAdvancedTab sd externalSigs scopedSignerRow signersPartitonDisplay " External Signatures " ( ) $ view _ 2 < $ > externalSigs dExternal < - signersPartitonDisplay " External Signatures " ( ) $ view _ 2 < $ > externalSigs dSigners <- foldDyn ($) cwSigners $ leftmost [ ffor (updated $ sequence dExternal) $ \new _ -> use the pkh to get the official Signer structure get rid of unsigned elems in cwSigners <> newSigners ] pure dExternal where sdHash = toUntypedHash $ _sigDataHash sd signersToSummary signers = let (trans, paysGas, unscoped) = foldr go (mempty, False, 0) signers pm = p ^. pMeta totalGas = fromIntegral (_pmGasLimit pm) * _pmGasPrice pm gas = if paysGas then Just totalGas else Nothing in TransactionSummary trans gas unscoped $ length signers go signer (tokenMap, doesPayGas, unscopedCounter) = let capList = signer^.siCapList tokenTransfers = mapMaybe parseFungibleTransferCap capList <> mapMaybe parseFungibleXChainTransferCap capList tokenMap' = foldr (\(k, v) m -> Map.insertWith (+) k v m) tokenMap tokenTransfers signerHasGas = isJust $ find (\cap -> asString (_scName cap) == "coin.GAS") capList in if capList == [] then (tokenMap, doesPayGas, unscopedCounter + 1) else (tokenMap', doesPayGas || signerHasGas, unscopedCounter) cwKeysPKH = PublicKeyHex . keyToText <$> cwKeys isCWSigner (pkh, _, _) = pkh `elem` cwKeysPKH isUnscoped (Signer _ _ _ capList) = capList == [] unOwnedSigningInput s = let mPub = hush $ parsePublicKey $ _siPubKey s in case mPub of Nothing -> text "^ ERROR parsing public key -- Cannot collect external signature" >> pure Nothing Just pub -> if pub `elem` cwKeys then blank >> pure Nothing else fmap Just $ uiSigningInput sdHash pub unscopedSignerGroup signers = divClass "group" $ forM signers $ \s -> do divClass "signer__pubkey" $ text $ _siPubKey s pure Nothing scopedSignerRow signer = do signerSection True (PublicKeyHex $ _siPubKey signer) $ do capListWidget $ _siCapList signer unOwnedSigningInput signer signerSection :: MonadWidget t m => Bool -> PublicKeyHex -> m a -> m a signerSection initToggleState pkh capListWidget =do visible <- divClass "group signer__header" $ do let accordionCell o = (if o then "" else "accordion-collapsed ") <> "payload__accordion " rec clk <- elDynClass "div" (accordionCell <$> visible') $ accordionButton def visible' <- toggle initToggleState clk divClass "signer__pubkey" $ text $ unPublicKeyHex pkh pure visible' elDynAttr "div" (ffor visible $ bool ("hidden"=:mempty) ("class" =: "group signer__capList") )$ capListWidget data SigBuilderAdvancedTab = SigBuilderAdvancedTab_ExternalSigs | SigBuilderAdvancedTab_HashQR | SigBuilderAdvancedTab_FullQR deriving (Eq,Ord,Show,Read,Enum,Bounded) showSBTabName :: SigBuilderAdvancedTab -> Text showSBTabName = \case SigBuilderAdvancedTab_HashQR -> "Hash QR Code" SigBuilderAdvancedTab_FullQR -> "Full Tx QR Code" SigBuilderAdvancedTab_ExternalSigs -> "External Signatures" sigBuilderAdvancedTab :: MonadWidget t m => SigData Text -> [(PublicKeyHex, Signer, Maybe UserSig)] -> (Signer -> m (Maybe (Dynamic t (PublicKeyHex, Maybe UserSig)))) -> m [Dynamic t (PublicKeyHex, Maybe UserSig)] sigBuilderAdvancedTab sd externalSigs signerRow = do divClass "tabset" $ mdo curSelection <- holdDyn SigBuilderAdvancedTab_ExternalSigs onTabClick (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = [minBound .. maxBound] , _tabBarCfg_mkLabel = const $ text . showSBTabName , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Primary } externalSigs' <- tabPane mempty curSelection SigBuilderAdvancedTab_ExternalSigs $ case externalSigs of [] -> text "No External Signatures required" >> pure [] _ -> signersPartitonDisplay "External Signatures" (mapM signerRow) $ view _2 <$> externalSigs #if !defined(ghcjs_HOST_OS) tabPane mempty curSelection SigBuilderAdvancedTab_HashQR $ do let hashText = hashToText $ toUntypedHash $ _sigDataHash sd qrImage = QR.encodeText (QR.defaultQRCodeOptions QR.L) QR.Iso8859_1OrUtf8WithECI hashText img = maybe "Error creating QR code" (QR.toPngDataUrlT 4 6) qrImage el "div" $ text $ T.unwords [ "This QR code contains only the hash." , "It doesn't give any transaction information, so some wallets may not accept it." , "This is useful when you are signing your own transactions and don't want to transmit as much data." ] el "br" blank elAttr "img" ("src" =: LT.toStrict img) blank tabPane mempty curSelection SigBuilderAdvancedTab_FullQR $ do let yamlText = T.decodeUtf8 $ Y.encode1Strict sd qrImage = QR.encodeText (QR.defaultQRCodeOptions QR.L) QR.Iso8859_1OrUtf8WithECI yamlText img = maybe "Error creating QR code" (QR.toPngDataUrlT 4 4) qrImage elAttr "img" ("src" =: LT.toStrict img) blank #endif pure externalSigs' parseFungibleXChainTransferCap :: SigCapability -> Maybe (Text, Decimal) parseFungibleXChainTransferCap cap = xChainTransferCap cap where isFungible (QualifiedName _capModName capName _) = capName == "TRANSFER_XCHAIN" xChainTransferCap (SigCapability modName [PLiteral (LString _sender) ,PLiteral (LString _receiver) ,PLiteral (LDecimal amount) , PLiteral (LString _chain)]) | isFungible modName = Just (renderCompactText $ _qnQual modName, amount) | otherwise = Nothing xChainTransferCap _ = Nothing parseFungibleTransferCap :: SigCapability -> Maybe (Text, Decimal) parseFungibleTransferCap cap = transferCap cap where isFungible (QualifiedName _capModName capName _) = capName == "TRANSFER" transferCap (SigCapability modName [(PLiteral (LString _sender)) ,(PLiteral (LString _receiver)) ,(PLiteral (LDecimal amount))]) | isFungible modName = Just (renderCompactText $ _qnQual modName, amount) | otherwise = Nothing transferCap _ = Nothing data TransactionSummary = TransactionSummary { _ts_tokenTransfers :: Map Text Decimal , _ts_sigsAdded :: Int } deriving (Show, Eq) showTransactionSummary :: MonadWidget t m => Dynamic t (TransactionSummary) -> Payload PublicMeta Text -> m () showTransactionSummary dSummary p = do dialogSectionHeading mempty "Impact Summary" divClass "group" $ dyn_ $ ffor dSummary $ \summary -> do let tokens = _ts_tokenTransfers summary kda = Map.lookup "coin" tokens tokens' = Map.delete "coin" tokens mkLabeledClsInput True "On Chain" $ const $ text $ renderCompactText $ p^.pMeta.pmChainId mkLabeledClsInput True "Tx Type" $ const $ text $ prpc $ p^.pPayload case _ts_maxGas summary of Nothing -> blank Just price -> void $ mkLabeledClsInput True "Max Gas Cost" $ const $ text $ renderCompactText price <> " KDA" flip (maybe blank) kda $ \kdaAmount -> void $ mkLabeledClsInput True "Amount KDA" $ const $ text $ showWithDecimal kdaAmount <> " KDA" if tokens' == mempty then blank else void $ mkLabeledClsInput True "Amount (Tokens)" $ const $ el "div" $ forM_ (Map.toList tokens') $ \(name, amount) -> el "p" $ text $ showWithDecimal amount <> " " <> name void $ mkLabeledClsInput True "Supplied Signatures" $ const $ text $ tshow $ _ts_sigsAdded summary if _ts_numUnscoped summary == 0 then blank else void $ mkLabeledClsInput True "Unscoped Sigs Added" $ const $ text $ tshow $ _ts_numUnscoped summary where prpc (Exec _) = "Exec" prpc (Continuation _) = "Continuation" Signature and Submission data SigDetails = SD_SigData_Yaml | SD_SigData_Json | SD_CommandSigData_Json | SD_CommandSigData_Yaml | SD_Command deriving (Eq,Ord,Show,Read,Enum,Bounded) showSigDetailsTabName :: SigDetails -> Text showSigDetailsTabName SD_SigData_Json = "SigData JSON" showSigDetailsTabName SD_SigData_Yaml = "SigData YAML" showSigDetailsTabName SD_CommandSigData_Json = "CommandSigData JSON" showSigDetailsTabName SD_CommandSigData_Yaml = "CommandSigData YAML" showSigDetailsTabName SD_Command = "Command JSON" sdToCsd :: SigData Text-> Maybe CommandSigData sdToCsd (SigData _ sigs Nothing) = Nothing sdToCsd (SigData _ sigs (Just cmdTxt) ) = let csdSigs = ffor sigs $ \(pkh, mSig) -> CSDSigner pkh mSig in Just $ CommandSigData (SignatureList csdSigs) cmdTxt signatureDetails :: (MonadWidget t m) => SigData Text -> m () signatureDetails sd = do hashWidget $ toUntypedHash $ _sigDataHash sd let canMakeCmd = (length $ _sigDataSigs sd) == (length $ catMaybes $ snd <$> _sigDataSigs sd) divClass "tabset" $ mdo curSelection <- holdDyn (if canMakeCmd then SD_Command else SD_SigData_Yaml) onTabClick (TabBar onTabClick) <- makeTabBar $ TabBarCfg { _tabBarCfg_tabs = if canMakeCmd then [minBound .. maxBound] else init [minBound .. maxBound] , _tabBarCfg_mkLabel = const $ text . showSigDetailsTabName , _tabBarCfg_selectedTab = Just <$> curSelection , _tabBarCfg_classes = mempty , _tabBarCfg_type = TabBarType_Primary } tabPane mempty curSelection SD_SigData_Yaml $ do let sigDataText = T.decodeUtf8 $ Y.encode1Strict sd void $ uiSignatureResult sigDataText tabPane mempty curSelection SD_SigData_Json $ do let sigDataText = T.decodeUtf8 $ LB.toStrict $ A.encode $ A.toJSON sd void $ uiSignatureResult sigDataText tabPane mempty curSelection SD_CommandSigData_Yaml $ do let csdText = maybe "" (T.decodeUtf8 . Y.encode1Strict) $ sdToCsd sd void $ uiSignatureResult csdText tabPane mempty curSelection SD_CommandSigData_Json $ do let csdText = maybe "" (T.decodeUtf8 . LB.toStrict . A.encode . A.toJSON) $ sdToCsd sd void $ uiSignatureResult csdText if canMakeCmd then tabPane mempty curSelection SD_Command $ do let cmdText = either (const "Command not available") (T.decodeUtf8 . LB.toStrict . A.encode . A.toJSON) $ sigDataToCommand sd void $ uiSignatureResult cmdText else blank pure () where uiSignatureResult txt = do void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ txt & initialAttributes <>~ fold [ "disabled" =: "true" , "class" =: " labeled-input__input labeled-input__sig-builder" ] uiDetailsCopyButton $ constant txt signAndShowSigDialog :: (SigBuilderWorkflow t m model key) => model -> SigningRequestWalletState key -> PayloadSigningRequest User - supplied -> Workflow t m (Event t ()) signAndShowSigDialog model srws psr backW externalKeySigs = Workflow $ mdo onClose <- modalHeader $ text "SigData / CommandSigData" expensive sigs pb <- delay 0.1 =<< getPostBuild dmCmd <- holdDyn Nothing $ snd <$> eSDmCmdTuple eSDmCmdTuple <- performEvent $ ffor pb $ \_-> do sd <- addSigsToSigData (_psr_sigData psr) keys externalKeySigs if Nothing `elem` (snd <$> _sigDataSigs sd) then pure (sd, Nothing) else pure (sd, hush $ sigDataToCommand sd) widgetHold_ (modalMain $ text "Loading Signatures ...") $ ffor eSDmCmdTuple $ \(sd, mCmd) -> do modalMain $ do pb' <- getPostBuild case mCmd of Nothing -> blank Just cmd -> previewTransaction model chain (constDyn p) $ cmd <$ pb' signatureDetails sd (back, done, submit) <- modalFooter $ (,,) <$> cancelButton def "Back" <*> confirmButton def "Done" <*> submitButton dmCmd let cmdAndNet = (,) <$> dmCmd <*> model ^. network_selectedNodes eCmdAndNet = fmapMaybe (\(mCmd, ni) -> fmap (,ni) mCmd) $ current cmdAndNet <@ submit uncurryM f functor = fmap (\tpl -> uncurry f tpl) functor sender = p^.pMeta.pmSender submitToNetworkE = transferAndStatus model (AccountName sender, chain) `uncurryM` eCmdAndNet return (onClose <> done, leftmost [backW <$ back, submitToNetworkE]) where keys = _srws_cwKeys srws p = _psr_payload psr chain = p^.pMeta.pmChainId submitButton dmCmd = do let baseCfg = "class" =: "button button_type_confirm" dynAttr = ffor dmCmd $ \case Nothing -> baseCfg <> ("hidden" =: "true") Just _ -> baseCfg (e, _) <- elDynAttr' "button" dynAttr $ text "Submit to Network" pure $ domEvent Click e addSigsToSigData :: ( MonadJSM m , HasCrypto key m ) => SigData Text -> [KeyPair key] -> m (SigData Text) addSigsToSigData sd signingKeys sigList = do let hashToSign = unHash $ toUntypedHash $ _sigDataHash sd someSigs = _sigDataSigs sd pubKeyToTxt = PublicKeyHex . keyToText . _keyPair_publicKey cwSigners = fmap (\x -> (pubKeyToTxt x, _keyPair_privateKey x)) signingKeys toPactSig sig = UserSig $ keyToText sig sigList' <- forM someSigs $ \(pkHex, mSig) -> case mSig of Just sig -> pure (pkHex, Just sig) Nothing -> case pkHex `lookup` cwSigners of Just (Just priv) -> do sig <- cryptoSign hashToSign priv pure (pkHex, Just $ toPactSig sig ) _ -> pure (pkHex, pkHex `lookup` sigList) pure $ sd { _sigDataSigs = sigList' } transferAndStatus :: (MonadWidget t m, HasLogger model t, HasTransactionLogger m) => model -> (AccountName, ChainId) -> Command Text -> [Either Text NodeInfo] -> Workflow t m (Event t ()) transferAndStatus model (sender, cid) cmd nodeInfos = Workflow $ do close <- modalHeader $ text "Transfer Status" _ <- elClass "div" "modal__main transaction_details" $ submitTransactionWithFeedback model cmd sender cid nodeInfos done <- modalFooter $ confirmButton def "Done" pure (close <> done, never) sigBuilderDetailsUI :: MonadWidget t m => Payload PublicMeta Text -> [(PublicKeyHex, Maybe UserSig)] -> Text -> Maybe Text -> m () sigBuilderDetailsUI p sigList wrapperCls mCls = divClass wrapperCls $ do txMetaWidget (p^.pMeta) (p^.pNetworkId) (p^.pNonce) mCls pactRpcWidget (_pPayload p) mCls signerWidget sigList (p^.pSigners) mCls pure () txMetaWidget :: MonadWidget t m => PublicMeta -> Maybe NetworkId -> Text -> Maybe Text -> m () txMetaWidget pm mNet nonce mCls = do dialogSectionHeading mempty "Transaction Metadata & Information" _ <- divClass (maybe "group segment" ("group segment " <>) mCls) $ do case mNet of Nothing -> blank Just n -> mkLabeledClsInput True "Network" $ \_ -> text $ renderCompactText n mkLabeledClsInput True "Chain" $ const $ text $ renderCompactText $ pm^.pmChainId mkLabeledClsInput True "Gas Payer" $ \_ -> text $ pm^.pmSender mkLabeledClsInput True "Gas Price" $ \_ -> text $ renderCompactText $ pm^.pmGasPrice mkLabeledClsInput True "Gas Limit" $ \_ -> text $ renderCompactText $ pm^.pmGasLimit let totalGas = fromIntegral (_pmGasLimit pm) * _pmGasPrice pm mkLabeledClsInput True "Max Gas Cost" $ \_ -> text $ renderCompactText totalGas <> " KDA" let (TxCreationTime ct) = pm^.pmCreationTime mkLabeledClsInput True "Creation Time" $ \_ -> text $ renderCompactText ct let prettyTTL (TTLSeconds (ParsedInteger s)) = tshow s <> case s of 1 -> " second" _ -> " seconds" mkLabeledClsInput True "TTL" $ \_ -> text $ prettyTTL $ pm^.pmTTL mkLabeledClsInput True "Nonce" $ \_ -> text nonce pure () pactRpcWidget :: MonadWidget t m => PactRPC Text -> Maybe Text -> m () pactRpcWidget (Exec e) mCls = do dialogSectionHeading mempty "Code" divClass (maybe "group" ("group " <>) mCls) $ do el "code" $ text $ tshow $ pretty $ _pmCode e case _pmData e of A.Null -> blank jsonVal -> do dialogSectionHeading mempty "Data" divClass (maybe "group" ("group " <>) mCls) $ void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ (T.decodeUtf8 $ LB.toStrict $ A.encode jsonVal) & initialAttributes .~ "disabled" =: "" <> "style" =: "width: 100%" pactRpcWidget (Continuation c) mCls = do dialogSectionHeading mempty "Continuation Data" divClass (maybe "group" ("group " <>) mCls) $ do mkLabeledClsInput True "Pact ID" $ \_ -> text $ renderCompactText $ _cmPactId c mkLabeledClsInput True "Step" $ \_ -> text $ tshow $ _cmStep c mkLabeledClsInput True "Rollback" $ \_ -> text $ tshow $ _cmRollback c mkLabeledClsInput True "Data" $ \_ -> do let contData = renderCompactText $ _cmData c void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ contData & initialAttributes .~ fold [ "disabled" =: "true" , "rows" =: "2" , "style" =: "color: black; width: 100%; height: auto;" ] mkLabeledClsInput True "Proof" $ \_ -> do let mProof = _cmProof c case mProof of Nothing -> blank Just p -> void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ (renderCompactText p) & initialAttributes .~ fold [ "disabled" =: "true" , "rows" =: "20" , "style" =: "color: black; width: 100%; height: auto;" ] signerWidget :: (MonadWidget t m) => [(PublicKeyHex, Maybe UserSig)] -> [Signer] -> Maybe Text -> m () signerWidget sigList signers mCls= do dialogSectionHeading mempty "Signers" forM_ signers $ \s -> divClass (maybe "group segment" ("group segment " <>) mCls) $ do mkLabeledClsInput True "Key:" $ \_ -> text (renderCompactText $ s ^.siPubKey) mkLabeledClsInput True "Caps:" $ \_ -> capListWidget $ s^.siCapList case lookup (PublicKeyHex $ s^.siPubKey) sigList of Nothing -> blank Just (Nothing) -> blank Just (Just (UserSig sig)) -> mkLabeledClsInput True "Signature:" $ \_ -> void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ sig & initialAttributes .~ fold [ "disabled" =: "" , "style" =: "color: black; width: 100%; height: auto;" ] capListWidget :: MonadWidget t m => [SigCapability] -> m () capListWidget [] = text "Unscoped Signer" capListWidget cl = do let capLines = foldl (\acc cap -> (renderCompactText cap):"":acc) [] cl txt = T.init $ T.init $ T.unlines capLines rows = tshow $ 2 * length capLines void $ uiTextAreaElement $ def & textAreaElementConfig_initialValue .~ txt & initialAttributes .~ fold [ "disabled" =: "" , "rows" =: rows , "style" =: "color: black; width: 100%; height: auto;" ] networkWidget :: MonadWidget t m => Payload PublicMeta a -> m () networkWidget p = case p^.pNetworkId of Nothing -> blank Just n -> do dialogSectionHeading mempty "Network" divClass "group" $ text $ n ^. networkId hashWidget :: MonadWidget t m => Hash -> m () hashWidget hash = void $ mkLabeledInput False "Hash" (\c -> uiInputElement $ c & initialAttributes %~ Map.insert "disabled" "") $ def & inputElementConfig_initialValue .~ hashToText hash
4c688fdfa7ef6d18f5c973aed8f6a2b9da3e7353ba98c6ff2601ccb1af692517
OCamlPro/opam-manager
managerWrapper.mli
(**************************************************************************) (* *) Copyright 2014 - 2015 , (* *) (* All rights reserved.This file is distributed under the terms of the *) GNU Lesser General Public License version 3.0 with linking (* exception. *) (* *) OPAM 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. *) (* *) (**************************************************************************) open ManagerTypes val create: OpamFilename.Base.t -> unit (** Create wrappers for all the binaries found in 'switch'. *) val update_switch: opam_switch -> unit (** Create or remove wrappers to match the binaries found in all known switches. *) val update: ?check_symlink:bool -> ?verbose:bool -> unit -> unit
null
https://raw.githubusercontent.com/OCamlPro/opam-manager/2b5b9cc834c0595c6bf00b07f47f25ab71f21acc/src/core/managerWrapper.mli
ocaml
************************************************************************ All rights reserved.This file is distributed under the terms of the exception. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY License for more details. ************************************************************************ * Create wrappers for all the binaries found in 'switch'. * Create or remove wrappers to match the binaries found in all known switches.
Copyright 2014 - 2015 , GNU Lesser General Public License version 3.0 with linking OPAM is distributed in the hope that it will be useful , but WITHOUT or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public open ManagerTypes val create: OpamFilename.Base.t -> unit val update_switch: opam_switch -> unit val update: ?check_symlink:bool -> ?verbose:bool -> unit -> unit
e40108d4c32355164b9484b73345c83b11097920a3f01e3ec8d337927fe2f6d4
avsm/platform
opam_admin_top.ml
(**************************************************************************) (* *) Copyright 2014 OCamlPro (* *) (* 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. *) (* *) (**************************************************************************) (* To be used for quick repo scripts using the toplevel *) open OpamFilename.Op open OpamStd.Op open OpamTypes let identity _ x = x let true_ _ = true let repo = OpamRepositoryBackend.local (OpamFilename.cwd ()) let packages = OpamRepository.packages repo let wopt w f = function | None -> OpamFilename.remove (OpamFile.filename f) | Some contents -> w f contents let apply f x prefix y = match f with | None -> () | Some f -> f x prefix y type 'a action = [`Update of 'a | `Remove | `Keep] let to_action f x y = match f with | None -> `Keep | Some f -> match y with | None -> `Keep | Some y -> `Update (f x y) let of_action o = function | `Keep -> o | `Update x -> Some x | `Remove -> None let iter_packages_gen ?(quiet=false) f = let packages = OpamRepository.packages_with_prefixes repo in let changed_pkgs = ref 0 in let changed_files = ref 0 in (* packages *) OpamPackage.Map.iter (fun package prefix -> if not quiet then OpamConsole.msg "Processing package %s... " (OpamPackage.to_string package); let opam_file = OpamRepositoryPath.opam repo.repo_root prefix package in let opam = OpamFile.OPAM.read opam_file in let descr_file = OpamRepositoryPath.descr repo.repo_root prefix package in let descr = OpamFile.Descr.read_opt descr_file in let url_file = OpamRepositoryPath.url repo.repo_root prefix package in let url = OpamFile.URL.read_opt url_file in let dot_install_file : OpamFile.Dot_install.t OpamFile.t = OpamFile.make (OpamRepositoryPath.files repo.repo_root prefix package // (OpamPackage.Name.to_string (OpamPackage.name package) ^ ".install")) in let dot_install = OpamFile.Dot_install.read_opt dot_install_file in let opam2, descr2, url2, dot_install2 = f package ~prefix ~opam ~descr ~url ~dot_install in let descr2 = of_action descr descr2 in let url2 = of_action url url2 in let dot_install2 = of_action dot_install dot_install2 in let changed = ref false in let upd () = changed := true; incr changed_files in if opam <> opam2 then (upd (); OpamFile.OPAM.write_with_preserved_format opam_file opam2); if descr <> descr2 then (upd (); wopt OpamFile.Descr.write descr_file descr2); if url <> url2 then (upd (); wopt OpamFile.URL.write url_file url2); if dot_install <> dot_install2 then (upd (); wopt OpamFile.Dot_install.write dot_install_file dot_install2); if !changed then (incr changed_pkgs; if not quiet then begin OpamConsole.carriage_delete (); OpamConsole.msg "Updated %s\n" (OpamPackage.to_string package) end) else if not quiet then OpamConsole.carriage_delete (); ) packages; if not quiet then OpamConsole.msg "Done. Updated %d files in %d packages.\n" !changed_files !changed_pkgs let iter_packages ?quiet ?(filter=true_) ?f ?(opam=identity) ?descr ?url ?dot_install () = iter_packages_gen ?quiet (fun p ~prefix ~opam:o ~descr:d ~url:u ~dot_install:i -> if filter p then ( apply f p prefix o; opam p o, to_action descr p d , to_action url p u, to_action dot_install p i ) else o, `Keep, `Keep, `Keep) let regexps_of_patterns patterns = let contains_dot str = let len = String.length str in let rec aux = function | -1 -> false | i -> str.[i] = '.' || aux (i-1) in aux (len-1) in List.map (fun pattern -> if contains_dot pattern then pattern else pattern ^ ".*" ) patterns |> List.map (fun pattern -> Re.compile (Re.Glob.globx pattern)) let filter fn patterns = let regexps = regexps_of_patterns patterns in fun t -> match regexps with | [] -> true | _ -> let str = fn t in List.exists (fun re -> OpamStd.String.exact_match re str) regexps let filter_packages = filter OpamPackage.to_string let _ = Topmain.main ()
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/tools/opam_admin_top.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ To be used for quick repo scripts using the toplevel packages
Copyright 2014 OCamlPro GNU Lesser General Public License version 2.1 , with the special open OpamFilename.Op open OpamStd.Op open OpamTypes let identity _ x = x let true_ _ = true let repo = OpamRepositoryBackend.local (OpamFilename.cwd ()) let packages = OpamRepository.packages repo let wopt w f = function | None -> OpamFilename.remove (OpamFile.filename f) | Some contents -> w f contents let apply f x prefix y = match f with | None -> () | Some f -> f x prefix y type 'a action = [`Update of 'a | `Remove | `Keep] let to_action f x y = match f with | None -> `Keep | Some f -> match y with | None -> `Keep | Some y -> `Update (f x y) let of_action o = function | `Keep -> o | `Update x -> Some x | `Remove -> None let iter_packages_gen ?(quiet=false) f = let packages = OpamRepository.packages_with_prefixes repo in let changed_pkgs = ref 0 in let changed_files = ref 0 in OpamPackage.Map.iter (fun package prefix -> if not quiet then OpamConsole.msg "Processing package %s... " (OpamPackage.to_string package); let opam_file = OpamRepositoryPath.opam repo.repo_root prefix package in let opam = OpamFile.OPAM.read opam_file in let descr_file = OpamRepositoryPath.descr repo.repo_root prefix package in let descr = OpamFile.Descr.read_opt descr_file in let url_file = OpamRepositoryPath.url repo.repo_root prefix package in let url = OpamFile.URL.read_opt url_file in let dot_install_file : OpamFile.Dot_install.t OpamFile.t = OpamFile.make (OpamRepositoryPath.files repo.repo_root prefix package // (OpamPackage.Name.to_string (OpamPackage.name package) ^ ".install")) in let dot_install = OpamFile.Dot_install.read_opt dot_install_file in let opam2, descr2, url2, dot_install2 = f package ~prefix ~opam ~descr ~url ~dot_install in let descr2 = of_action descr descr2 in let url2 = of_action url url2 in let dot_install2 = of_action dot_install dot_install2 in let changed = ref false in let upd () = changed := true; incr changed_files in if opam <> opam2 then (upd (); OpamFile.OPAM.write_with_preserved_format opam_file opam2); if descr <> descr2 then (upd (); wopt OpamFile.Descr.write descr_file descr2); if url <> url2 then (upd (); wopt OpamFile.URL.write url_file url2); if dot_install <> dot_install2 then (upd (); wopt OpamFile.Dot_install.write dot_install_file dot_install2); if !changed then (incr changed_pkgs; if not quiet then begin OpamConsole.carriage_delete (); OpamConsole.msg "Updated %s\n" (OpamPackage.to_string package) end) else if not quiet then OpamConsole.carriage_delete (); ) packages; if not quiet then OpamConsole.msg "Done. Updated %d files in %d packages.\n" !changed_files !changed_pkgs let iter_packages ?quiet ?(filter=true_) ?f ?(opam=identity) ?descr ?url ?dot_install () = iter_packages_gen ?quiet (fun p ~prefix ~opam:o ~descr:d ~url:u ~dot_install:i -> if filter p then ( apply f p prefix o; opam p o, to_action descr p d , to_action url p u, to_action dot_install p i ) else o, `Keep, `Keep, `Keep) let regexps_of_patterns patterns = let contains_dot str = let len = String.length str in let rec aux = function | -1 -> false | i -> str.[i] = '.' || aux (i-1) in aux (len-1) in List.map (fun pattern -> if contains_dot pattern then pattern else pattern ^ ".*" ) patterns |> List.map (fun pattern -> Re.compile (Re.Glob.globx pattern)) let filter fn patterns = let regexps = regexps_of_patterns patterns in fun t -> match regexps with | [] -> true | _ -> let str = fn t in List.exists (fun re -> OpamStd.String.exact_match re str) regexps let filter_packages = filter OpamPackage.to_string let _ = Topmain.main ()
887ed405461f39fa77b4bba2bd29d74fe37fe9b2ed5d73453aef3305abd63690
alexandergunnarson/quantum
primitive.cljc
(ns quantum.core.data.primitive (:require [quantum.core.macros :refer [defnt]])) (defnt ->min-magnitude #?(:clj ([^byte x] (byte 0))) #?(:clj ([^char x] (char 0))) #?(:clj ([^short x] (short 0))) #?(:clj ([^int x] (int 0))) #?(:clj ([^long x] (long 0))) #?(:clj ([^float x] Float/MIN_VALUE )) ([^double x] #?(:clj Double/MIN_VALUE :cljs js/Number.MIN_VALUE))) #?(:clj (def ^:const min-float (- Float/MAX_VALUE))) (def ^:const min-double (- #?(:clj Double/MAX_VALUE :cljs js/Number.MAX_VALUE))) (defnt ->min-value #?(:clj ([^byte x] Byte/MIN_VALUE )) #?(:clj ([^char x] Character/MIN_VALUE)) #?(:clj ([^short x] Short/MIN_VALUE )) #?(:clj ([^int x] Integer/MIN_VALUE )) #?(:clj ([^long x] Long/MIN_VALUE )) #?(:clj ([^float x] min-float )) ([^double x] min-double )) (defnt ->max-value #?(:clj ([^byte x] Byte/MAX_VALUE )) #?(:clj ([^char x] Character/MAX_VALUE)) #?(:clj ([^short x] Short/MAX_VALUE )) #?(:clj ([^int x] Integer/MAX_VALUE )) #?(:clj ([^long x] Long/MAX_VALUE )) #?(:clj ([^float x] Float/MAX_VALUE )) ([^double x] #?(:clj Double/MAX_VALUE :cljs js/Number.MAX_VALUE)))
null
https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/src/quantum/core/data/primitive.cljc
clojure
(ns quantum.core.data.primitive (:require [quantum.core.macros :refer [defnt]])) (defnt ->min-magnitude #?(:clj ([^byte x] (byte 0))) #?(:clj ([^char x] (char 0))) #?(:clj ([^short x] (short 0))) #?(:clj ([^int x] (int 0))) #?(:clj ([^long x] (long 0))) #?(:clj ([^float x] Float/MIN_VALUE )) ([^double x] #?(:clj Double/MIN_VALUE :cljs js/Number.MIN_VALUE))) #?(:clj (def ^:const min-float (- Float/MAX_VALUE))) (def ^:const min-double (- #?(:clj Double/MAX_VALUE :cljs js/Number.MAX_VALUE))) (defnt ->min-value #?(:clj ([^byte x] Byte/MIN_VALUE )) #?(:clj ([^char x] Character/MIN_VALUE)) #?(:clj ([^short x] Short/MIN_VALUE )) #?(:clj ([^int x] Integer/MIN_VALUE )) #?(:clj ([^long x] Long/MIN_VALUE )) #?(:clj ([^float x] min-float )) ([^double x] min-double )) (defnt ->max-value #?(:clj ([^byte x] Byte/MAX_VALUE )) #?(:clj ([^char x] Character/MAX_VALUE)) #?(:clj ([^short x] Short/MAX_VALUE )) #?(:clj ([^int x] Integer/MAX_VALUE )) #?(:clj ([^long x] Long/MAX_VALUE )) #?(:clj ([^float x] Float/MAX_VALUE )) ([^double x] #?(:clj Double/MAX_VALUE :cljs js/Number.MAX_VALUE)))
70bcb5503ca8e5e0a7841f46d690b722f79840d69d5b659cd33269abb7fcbfee
dtgoitia/civil-autolisp
SortAlphanumeric.lsp
(defun DT:SortAlphanumeric ( l / onlyStrings chunkedList ) ; Sort considering numbers and letters (if (DT:Arg 'DT:SortAlphanumeric '((l 'list))) (progn (setq onlyStrings T) (foreach element l (if (/= 'str (type element)) (setq onlyStrings nil))) (if onlyStrings (progn ALPHANUMERIC SORT ALGORITHM : ; Split strings in only number and only letter chunks (setq chunkedList (DT:SplitAlphanumericList l)) ; Sort split strings (setq sortedchunkedList (DT:ShortChunkedLists chunkedList)) ; Join chunks in sortedchunkedList (setq sortedList (DT:ConcatenateChunkedList sortedchunkedList)) );END progn (DT:Error 'DT:SortAlphanumeric "one or more elements in l are not strings") );END if );END progn );END if sortedList ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericList ( l / return ) ; Split passed list of strings in chunks of only letters and only numbers, and return it (if (DT:Arg 'DT:SplitAlphanumericList '((l 'list))) (progn (foreach element l (setq return (append return (list (DT:SplitAlphanumeric element)))) );END foreach return );END progn );END if ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumeric ( string / stringLength charPosition char asciiChar charType lastCharType return ) ; Split string in chunks of only letters and only numbers, and return them in a list (if (DT:Arg 'DT:SplitAlphanumeric '((string 'str))) (progn (setq stringLength (strlen string)) (setq charPosition 0) (repeat stringLength (setq charPosition (+ charPosition 1)) (setq char (substr string charPosition 1)) (setq asciiChar (ascii char)) if same type , concatenate at the end of last element of the list if different type , add new element to list ( add new chunck ) (if (and (<= 48 asciiChar) (<= asciiChar 57)) (progn ; char is a number (if lastCharType ; Later rounds (if (= 1 lastCharType) ; previous char was same type, concatenate (setq return (DT:SplitAlphanumericConcatenate return char)) ; previous char was different type, add new chunk (setq return (append return (list char))) );END if First round (setq return (list char) ) );END if (setq charType 1) );END progn (progn ; char is not a number (if lastCharType ; Later rounds (if (= 0 lastCharType) ; previous char was same type, concatenate (setq return (DT:SplitAlphanumericConcatenate return char)) ; previous char was different type, add new chunk (setq return (append return (list char))) );END if First round (setq return (list char) ) );END if (setq charType 0) );END progn );END if (setq lastCharType charType) );END repeat return );END progn );END if ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericConcatenate ( l char / nChunks i return ) at the end (setq nChunks (length l)) (setq i 0) (foreach chunk l (setq i (+ i 1)) (if (= i nChunks) (setq return (append return (list (strcat chunk char)))) (setq return (append return (list chunk))) );END if );END foreach return ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericAddChunk ( l char ) ; Add a new chunk (append l (list char)) ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:ConcatenateChunkedList ( chunkedList / return ) Concatenate chunked list (if (DT:Arg 'DT:ConcatenateChunkedList '((chunkedList 'list))) (mapcar '(lambda (chunk) (apply 'strcat chunk) );END lambda chunkedList );END mapcar );END if ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun DT:CompareChunks ( a b ) ; Compare chunks and return: ; 0 : if a = b 1 : if a < b 2 : if a > b (if (and a b) (progn (if (and (>= (ascii a) 48) (<= (ascii a) 57) ) (setq a (atoi a)) nil ) (if (and (>= (ascii b) 48) (<= (ascii b) 57) ) (setq b (atoi b)) nil ) (cond ; Both are strings ((and (= 'str (type a)) (= 'str (type b))) (if (< a b) 1 (if (> a b) 2 0) ) );END subcond ; Both are numbers ((and (numberp a) (numberp b)) (if (< a b) 1 (if (> a b) 2 0) ) );END subcond One number and one letter ((or (and (= 'str (type a)) (numberp b) ) (and (numberp a) (= 'str (type b)) ) ) (if (numberp a) 1 2 ) );END subcond ; Return nil if a or b was not a string or a number (t nil) );END cond );END progn nil );END if ; v0.0 - 2017.07.11 - First issue Author : Last revision : 2017.07.11 ) (defun DT:CompareChunksByIndex ( a b n ) ; Compare a and b chunks' n-th elements: (if (and a b n) ; Ensure all a b and n are passed (if (and (<= n (length a)) (<= n (length b)) );END and (DT:CompareChunks (nth n a) (nth n b)) nil );END if nil );END if ; v0.0 - 2017.07.11 - First issue Author : Last revision : 2017.07.11 ) (defun DT:ShortChunkedLists ( chunkedLists / i ii chunkA chunkB n comparisonResult return ) ; Sort chunked lists according to ASCII (if (DT:Arg 'DT:ShortChunkedLists '((chunkedList 'list))) (progn (setq i (- (length chunkedList) 1)) (setq return chunkedList) some of the iteration indexes are wrong , is a failure for 1 loop in " while " or in " repeat " (while (> i 0) (setq ii 0) (repeat i (setq chunkA (nth ii return)) (setq chunkB (nth (+ ii 1) return)) (setq n 0) (setq comparisonResult (tempDTCompare chunkA chunkB n)) (cond ((not comparisonResult) ; A = B leave them as they are nil );END subcond ((= 1 comparisonResult) ; A < B leave them as they are nil );END subcond ((= 2 comparisonResult) ; A > B swap them (setq return (LM:SubstNth chunkA (+ ii 1) return)) (setq return (LM:SubstNth chunkB ii return)) );END subcond (t (DT:Error 'DT:ShortChunkedLists "comparisonResult has an unexpected value.") (exit) );END subcond );END cond (setq ii (+ ii 1)) );END repeat (setq i (- i 1)) );END while );END progn );END if return ; v0.0 - 2017.06.02 - First issue Author : Last revision : 2017.06.02 ) (defun tempDTCompare (a b n / result) (if (= 0 (setq result (DT:CompareChunksByIndex a b n))) (tempDTCompare a b (+ n 1)) result );END if )
null
https://raw.githubusercontent.com/dtgoitia/civil-autolisp/72d68139d372c84014d160f8e4918f062356349f/Dump%20folder/SortAlphanumeric.lsp
lisp
Sort considering numbers and letters Split strings in only number and only letter chunks Sort split strings Join chunks in sortedchunkedList END progn END if END progn END if v0.0 - 2017.06.02 - First issue Split passed list of strings in chunks of only letters and only numbers, and return it END foreach END progn END if v0.0 - 2017.06.02 - First issue Split string in chunks of only letters and only numbers, and return them in a list char is a number Later rounds previous char was same type, concatenate previous char was different type, add new chunk END if END if END progn char is not a number Later rounds previous char was same type, concatenate previous char was different type, add new chunk END if END if END progn END if END repeat END progn END if v0.0 - 2017.06.02 - First issue END if END foreach v0.0 - 2017.06.02 - First issue Add a new chunk v0.0 - 2017.06.02 - First issue END lambda END mapcar END if v0.0 - 2017.06.02 - First issue Compare chunks and return: 0 : if a = b Both are strings END subcond Both are numbers END subcond END subcond Return nil if a or b was not a string or a number END cond END progn END if v0.0 - 2017.07.11 - First issue Compare a and b chunks' n-th elements: Ensure all a b and n are passed END and END if END if v0.0 - 2017.07.11 - First issue Sort chunked lists according to ASCII A = B leave them as they are END subcond A < B leave them as they are END subcond A > B swap them END subcond END subcond END cond END repeat END while END progn END if v0.0 - 2017.06.02 - First issue END if
(defun DT:SortAlphanumeric ( l / onlyStrings chunkedList ) (if (DT:Arg 'DT:SortAlphanumeric '((l 'list))) (progn (setq onlyStrings T) (foreach element l (if (/= 'str (type element)) (setq onlyStrings nil))) (if onlyStrings (progn ALPHANUMERIC SORT ALGORITHM : (setq chunkedList (DT:SplitAlphanumericList l)) (setq sortedchunkedList (DT:ShortChunkedLists chunkedList)) (setq sortedList (DT:ConcatenateChunkedList sortedchunkedList)) (DT:Error 'DT:SortAlphanumeric "one or more elements in l are not strings") sortedList Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericList ( l / return ) (if (DT:Arg 'DT:SplitAlphanumericList '((l 'list))) (progn (foreach element l (setq return (append return (list (DT:SplitAlphanumeric element)))) return Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumeric ( string / stringLength charPosition char asciiChar charType lastCharType return ) (if (DT:Arg 'DT:SplitAlphanumeric '((string 'str))) (progn (setq stringLength (strlen string)) (setq charPosition 0) (repeat stringLength (setq charPosition (+ charPosition 1)) (setq char (substr string charPosition 1)) (setq asciiChar (ascii char)) if same type , concatenate at the end of last element of the list if different type , add new element to list ( add new chunck ) (if (and (<= 48 asciiChar) (<= asciiChar 57)) (progn (if lastCharType (if (= 1 lastCharType) (setq return (DT:SplitAlphanumericConcatenate return char)) (setq return (append return (list char))) First round (setq return (list char) ) (setq charType 1) (progn (if lastCharType (if (= 0 lastCharType) (setq return (DT:SplitAlphanumericConcatenate return char)) (setq return (append return (list char))) First round (setq return (list char) ) (setq charType 0) (setq lastCharType charType) return Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericConcatenate ( l char / nChunks i return ) at the end (setq nChunks (length l)) (setq i 0) (foreach chunk l (setq i (+ i 1)) (if (= i nChunks) (setq return (append return (list (strcat chunk char)))) (setq return (append return (list chunk))) return Author : Last revision : 2017.06.02 ) (defun DT:SplitAlphanumericAddChunk ( l char ) (append l (list char)) Author : Last revision : 2017.06.02 ) (defun DT:ConcatenateChunkedList ( chunkedList / return ) Concatenate chunked list (if (DT:Arg 'DT:ConcatenateChunkedList '((chunkedList 'list))) (mapcar '(lambda (chunk) (apply 'strcat chunk) chunkedList Author : Last revision : 2017.06.02 ) (defun DT:CompareChunks ( a b ) 1 : if a < b 2 : if a > b (if (and a b) (progn (if (and (>= (ascii a) 48) (<= (ascii a) 57) ) (setq a (atoi a)) nil ) (if (and (>= (ascii b) 48) (<= (ascii b) 57) ) (setq b (atoi b)) nil ) (cond ((and (= 'str (type a)) (= 'str (type b))) (if (< a b) 1 (if (> a b) 2 0) ) ((and (numberp a) (numberp b)) (if (< a b) 1 (if (> a b) 2 0) ) One number and one letter ((or (and (= 'str (type a)) (numberp b) ) (and (numberp a) (= 'str (type b)) ) ) (if (numberp a) 1 2 ) (t nil) nil Author : Last revision : 2017.07.11 ) (defun DT:CompareChunksByIndex ( a b n ) (if (and (<= n (length a)) (<= n (length b)) (DT:CompareChunks (nth n a) (nth n b)) nil nil Author : Last revision : 2017.07.11 ) (defun DT:ShortChunkedLists ( chunkedLists / i ii chunkA chunkB n comparisonResult return ) (if (DT:Arg 'DT:ShortChunkedLists '((chunkedList 'list))) (progn (setq i (- (length chunkedList) 1)) (setq return chunkedList) some of the iteration indexes are wrong , is a failure for 1 loop in " while " or in " repeat " (while (> i 0) (setq ii 0) (repeat i (setq chunkA (nth ii return)) (setq chunkB (nth (+ ii 1) return)) (setq n 0) (setq comparisonResult (tempDTCompare chunkA chunkB n)) (cond nil nil (setq return (LM:SubstNth chunkA (+ ii 1) return)) (setq return (LM:SubstNth chunkB ii return)) (t (DT:Error 'DT:ShortChunkedLists "comparisonResult has an unexpected value.") (exit) (setq ii (+ ii 1)) (setq i (- i 1)) return Author : Last revision : 2017.06.02 ) (defun tempDTCompare (a b n / result) (if (= 0 (setq result (DT:CompareChunksByIndex a b n))) (tempDTCompare a b (+ n 1)) result )
4b292d455bfe271799f6b5564dc40dfc89b772b14b3c7e8cf2299e96cc6d4ca1
ceramic/ceramic
integration.lisp
(in-package :cl-user) (defpackage ceramic-test.integration (:use :cl :fiveam) (:export :integration)) (in-package :ceramic-test.integration) (def-suite integration :description "Integration tests.") (in-suite integration) (defvar *extraction-directory* (asdf:system-relative-pathname :ceramic-test-app #p"extract/")) (test lifecycle (finishes (ceramic:start)) (finishes (ceramic:stop))) (test compiled (finishes (asdf:load-system :ceramic-test-app :force t)) (let* ((app-file (merge-pathnames #p"ceramic-test-app.tar" *extraction-directory*)) (binary (merge-pathnames #p"ceramic-test-app" *extraction-directory*))) (ensure-directories-exist *extraction-directory*) (finishes (ceramic.bundler:bundle :ceramic-test-app :bundle-pathname app-file)) (is-true (probe-file app-file)) (finishes (trivial-extract:extract-tar app-file)) (is-true (probe-file binary)) (is-true (probe-file (merge-pathnames #p"resources/files/file.txt" *extraction-directory*))) (finishes (trivial-exe:ensure-executable (merge-pathnames #p"electron/electron" *extraction-directory*)) (trivial-exe:ensure-executable binary)) (is (equal (ceramic.resource:resource-directory 'ceramic-test-app::files) (asdf:system-relative-pathname :ceramic-test-app #p"files/"))) (is (equal (ceramic.resource:resource 'ceramic-test-app::files #p"file.txt") (asdf:system-relative-pathname :ceramic-test-app #p"files/file.txt"))))) (test cleanup (uiop:delete-directory-tree *extraction-directory* :validate t))
null
https://raw.githubusercontent.com/ceramic/ceramic/5d81e2bd954440a6adebde31fac9c730a698c74b/t/integration.lisp
lisp
(in-package :cl-user) (defpackage ceramic-test.integration (:use :cl :fiveam) (:export :integration)) (in-package :ceramic-test.integration) (def-suite integration :description "Integration tests.") (in-suite integration) (defvar *extraction-directory* (asdf:system-relative-pathname :ceramic-test-app #p"extract/")) (test lifecycle (finishes (ceramic:start)) (finishes (ceramic:stop))) (test compiled (finishes (asdf:load-system :ceramic-test-app :force t)) (let* ((app-file (merge-pathnames #p"ceramic-test-app.tar" *extraction-directory*)) (binary (merge-pathnames #p"ceramic-test-app" *extraction-directory*))) (ensure-directories-exist *extraction-directory*) (finishes (ceramic.bundler:bundle :ceramic-test-app :bundle-pathname app-file)) (is-true (probe-file app-file)) (finishes (trivial-extract:extract-tar app-file)) (is-true (probe-file binary)) (is-true (probe-file (merge-pathnames #p"resources/files/file.txt" *extraction-directory*))) (finishes (trivial-exe:ensure-executable (merge-pathnames #p"electron/electron" *extraction-directory*)) (trivial-exe:ensure-executable binary)) (is (equal (ceramic.resource:resource-directory 'ceramic-test-app::files) (asdf:system-relative-pathname :ceramic-test-app #p"files/"))) (is (equal (ceramic.resource:resource 'ceramic-test-app::files #p"file.txt") (asdf:system-relative-pathname :ceramic-test-app #p"files/file.txt"))))) (test cleanup (uiop:delete-directory-tree *extraction-directory* :validate t))
b4718839d1a7beea107eb3594bb2271c48038bb18ab3c0255fe0656d06ebc4dc
scrive/hpqtypes
Compat.hs
# LANGUAGE CPP # # LANGUAGE DerivingStrategies # module Test.Aeson.Compat ( fromList , Value0 , mkValue0 ) where import Data.Aeson import Data.Text (Text) #if MIN_VERSION_aeson(2,0,0) import Data.Bifunctor (first) import qualified Data.Aeson.Key as K import qualified Data.Aeson.KeyMap as KM import Database.PostgreSQL.PQTypes.Internal.C.Types import Database.PostgreSQL.PQTypes fromList :: [(Text, v)] -> KM.KeyMap v fromList = KM.fromList . map (first K.fromText) newtype Value0 = Value0 { unValue0 :: Value } deriving newtype (Eq, Show) instance ToSQL (JSON Value0) where type PQDest (JSON Value0) = PGbytea toSQL = aesonToSQL . unValue0 . unJSON instance FromSQL (JSON Value0) where type PQBase (JSON Value0) = PGbytea fromSQL = fmap (JSON . Value0) . aesonFromSQL instance ToSQL (JSONB Value0) where type PQDest (JSONB Value0) = PGbytea toSQL = aesonToSQL . unValue0 . unJSONB instance FromSQL (JSONB Value0) where type PQBase (JSONB Value0) = PGbytea fromSQL = fmap (JSONB . Value0) . aesonFromSQL mkValue0 :: Value -> Value0 mkValue0 = Value0 #else import qualified Data.HashMap.Strict as HM fromList :: [(Text, v)] -> HM.HashMap Text v fromList = HM.fromList type Value0 = Value mkValue0 :: Value0 -> Value0 mkValue0 = id #endif
null
https://raw.githubusercontent.com/scrive/hpqtypes/69d87f0dd86cc168a1c927b6769f4d9b3fe3707d/test/Test/Aeson/Compat.hs
haskell
# LANGUAGE CPP # # LANGUAGE DerivingStrategies # module Test.Aeson.Compat ( fromList , Value0 , mkValue0 ) where import Data.Aeson import Data.Text (Text) #if MIN_VERSION_aeson(2,0,0) import Data.Bifunctor (first) import qualified Data.Aeson.Key as K import qualified Data.Aeson.KeyMap as KM import Database.PostgreSQL.PQTypes.Internal.C.Types import Database.PostgreSQL.PQTypes fromList :: [(Text, v)] -> KM.KeyMap v fromList = KM.fromList . map (first K.fromText) newtype Value0 = Value0 { unValue0 :: Value } deriving newtype (Eq, Show) instance ToSQL (JSON Value0) where type PQDest (JSON Value0) = PGbytea toSQL = aesonToSQL . unValue0 . unJSON instance FromSQL (JSON Value0) where type PQBase (JSON Value0) = PGbytea fromSQL = fmap (JSON . Value0) . aesonFromSQL instance ToSQL (JSONB Value0) where type PQDest (JSONB Value0) = PGbytea toSQL = aesonToSQL . unValue0 . unJSONB instance FromSQL (JSONB Value0) where type PQBase (JSONB Value0) = PGbytea fromSQL = fmap (JSONB . Value0) . aesonFromSQL mkValue0 :: Value -> Value0 mkValue0 = Value0 #else import qualified Data.HashMap.Strict as HM fromList :: [(Text, v)] -> HM.HashMap Text v fromList = HM.fromList type Value0 = Value mkValue0 :: Value0 -> Value0 mkValue0 = id #endif
128d7433e0eb82995172a2c824bfefed95acecde955d9a98cf0b5b3828712f0d
siclait/6.824-cljlabs-2020
worker.clj
(ns map-reduce.impl.worker "Write your code here." (:require [go.fnv :as fnv] [go.rpc :as rpc])) (def output-directory "mr-tmp") (def port 3000) (defn ihash "Use ihash(key) % `n-reduce` to choose the reduce task number for each key/value pair emitted by map." [s] (bit-and (fnv/fnv1a32 s) 0x7fffffff)) (defn call! [rpc-name args] (let [client (rpc/dial port) response (rpc/call! client rpc-name args)] (rpc/close! client) response)) (defrecord Worker [mapf reducef]) (defn new-worker [mapf reducef] (map->Worker {:mapf mapf :reducef reducef})) (defn call-example! "Example function to show how to make an RPC call to the master." [] Send the RPC request , wait for the reply . (let [reply (call! :Master/Example {:x 99})] reply.y should be 100 . (println "reply.y:" (:y reply)))) (defn worker "map-reduce.worker calls this function." [mapf reducef] ;; Your worker implementation here. Uncomment to send the Example RPC to the master . #_(call-example!))
null
https://raw.githubusercontent.com/siclait/6.824-cljlabs-2020/0c7ad7ae07d7617b1eb7240080c65f1937ca8a2d/map-reduce/src/map_reduce/impl/worker.clj
clojure
Your worker implementation here.
(ns map-reduce.impl.worker "Write your code here." (:require [go.fnv :as fnv] [go.rpc :as rpc])) (def output-directory "mr-tmp") (def port 3000) (defn ihash "Use ihash(key) % `n-reduce` to choose the reduce task number for each key/value pair emitted by map." [s] (bit-and (fnv/fnv1a32 s) 0x7fffffff)) (defn call! [rpc-name args] (let [client (rpc/dial port) response (rpc/call! client rpc-name args)] (rpc/close! client) response)) (defrecord Worker [mapf reducef]) (defn new-worker [mapf reducef] (map->Worker {:mapf mapf :reducef reducef})) (defn call-example! "Example function to show how to make an RPC call to the master." [] Send the RPC request , wait for the reply . (let [reply (call! :Master/Example {:x 99})] reply.y should be 100 . (println "reply.y:" (:y reply)))) (defn worker "map-reduce.worker calls this function." [mapf reducef] Uncomment to send the Example RPC to the master . #_(call-example!))
ce11184a1b0bac465e6641728d074129d3d519c0ef37e77e903f62f51489e5ca
nasa/Common-Metadata-Repository
granule.clj
(ns ^:system cmr.metadata.proxy.tests.system.concepts.granule "Note: this namespace is exclusively for system tests." (:require [clojure.test :refer :all] [cmr.metadata.proxy.concepts.granule :as granule] [cmr.metadata.proxy.testing.config :as test-system] [ring.util.codec :as codec])) (use-fixtures :once test-system/with-system) (deftest build-query (testing "No granules ..." (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123"}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules []}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [nil]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [nil nil]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [""]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules ["" ""]})))) (testing "With granule ids ..." (is (= "collection_concept_id=C123&page_size=1&concept_id%5B%5D=G234" (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234"]}))) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"]})))) (testing "With granule ids and exclude ..." (is (= (str "collection_concept_id=C123&page_size=2000&" "exclude%5Becho_granule_id%5D%5B%5D=G234") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234"] :exclude-granules true}))) (is (= (str "collection_concept_id=C123&page_size=2000&" "exclude%5Becho_granule_id%5D%5B%5D=G234&" "exclude%5Becho_granule_id%5D%5B%5D=G345") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :exclude-granules true})))) (testing "With exclude but no granule ids..." (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :exclude-granules true}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :exclude-granules false})))) (testing "With temporal ...." (let [result (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :temporal ["2002-09-01T00:00:00Z,2016-07-03T00:00:00Z"]})] (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345&" "temporal%5B%5D=2002-09-01T00%3A00%3A00Z%2C2016-07-03T00%3A00%3A00Z") result)) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id[]=G234&concept_id[]=G345&" "temporal[]=2002-09-01T00:00:00Z,2016-07-03T00:00:00Z") (codec/url-decode result))))) (testing "With multiple temporals ...." (let [result (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :temporal ["2000-09-01T00:00:00Z,2003-07-03T00:00:00Z" "2010-09-01T00:00:00Z,2016-07-03T00:00:00Z"]})] (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345&" "temporal%5B%5D=2000-09-01T00%3A00%3A00Z%2C2003-07-03T00%3A00%3A00Z&" "temporal%5B%5D=2010-09-01T00%3A00%3A00Z%2C2016-07-03T00%3A00%3A00Z") result)) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id[]=G234&concept_id[]=G345&" "temporal[]=2000-09-01T00:00:00Z,2003-07-03T00:00:00Z&" "temporal[]=2010-09-01T00:00:00Z,2016-07-03T00:00:00Z") (codec/url-decode result))))))
null
https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/63001cf021d32d61030b1dcadd8b253e4a221662/other/cmr-exchange/metadata-proxy/test/cmr/metadata/proxy/tests/system/concepts/granule.clj
clojure
(ns ^:system cmr.metadata.proxy.tests.system.concepts.granule "Note: this namespace is exclusively for system tests." (:require [clojure.test :refer :all] [cmr.metadata.proxy.concepts.granule :as granule] [cmr.metadata.proxy.testing.config :as test-system] [ring.util.codec :as codec])) (use-fixtures :once test-system/with-system) (deftest build-query (testing "No granules ..." (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123"}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules []}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [nil]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [nil nil]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules [""]}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :granules ["" ""]})))) (testing "With granule ids ..." (is (= "collection_concept_id=C123&page_size=1&concept_id%5B%5D=G234" (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234"]}))) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"]})))) (testing "With granule ids and exclude ..." (is (= (str "collection_concept_id=C123&page_size=2000&" "exclude%5Becho_granule_id%5D%5B%5D=G234") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234"] :exclude-granules true}))) (is (= (str "collection_concept_id=C123&page_size=2000&" "exclude%5Becho_granule_id%5D%5B%5D=G234&" "exclude%5Becho_granule_id%5D%5B%5D=G345") (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :exclude-granules true})))) (testing "With exclude but no granule ids..." (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :exclude-granules true}))) (is (= "collection_concept_id=C123" (granule/build-query (test-system/system) {:collection-id "C123" :exclude-granules false})))) (testing "With temporal ...." (let [result (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :temporal ["2002-09-01T00:00:00Z,2016-07-03T00:00:00Z"]})] (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345&" "temporal%5B%5D=2002-09-01T00%3A00%3A00Z%2C2016-07-03T00%3A00%3A00Z") result)) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id[]=G234&concept_id[]=G345&" "temporal[]=2002-09-01T00:00:00Z,2016-07-03T00:00:00Z") (codec/url-decode result))))) (testing "With multiple temporals ...." (let [result (granule/build-query (test-system/system) {:collection-id "C123" :granules ["G234" "G345"] :temporal ["2000-09-01T00:00:00Z,2003-07-03T00:00:00Z" "2010-09-01T00:00:00Z,2016-07-03T00:00:00Z"]})] (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id%5B%5D=G234&concept_id%5B%5D=G345&" "temporal%5B%5D=2000-09-01T00%3A00%3A00Z%2C2003-07-03T00%3A00%3A00Z&" "temporal%5B%5D=2010-09-01T00%3A00%3A00Z%2C2016-07-03T00%3A00%3A00Z") result)) (is (= (str "collection_concept_id=C123&page_size=2&" "concept_id[]=G234&concept_id[]=G345&" "temporal[]=2000-09-01T00:00:00Z,2003-07-03T00:00:00Z&" "temporal[]=2010-09-01T00:00:00Z,2016-07-03T00:00:00Z") (codec/url-decode result))))))
04be4824e8e5ff5009058d3fc358bc600c64825365b7e7fe46a70bb49e5db0b1
wavewave/hoodle
ForeignJS.hs
# LANGUAGE JavaScriptFFI # module Hoodle.Web.ForeignJS where import qualified Data.JSString as JSS import GHCJS.Foreign.Callback (Callback) import GHCJS.Marshal (FromJSVal (fromJSValUncheckedListOf), ToJSVal (toJSValListOf)) import GHCJS.Types (JSString, JSVal) foreign import javascript unsafe "console.log($1)" js_console_log :: JSVal -> IO () foreign import javascript unsafe "$r = location.hostname" js_hostname :: IO JSString foreign import javascript unsafe "preventDefaultTouchMove()" js_prevent_default_touch_move :: IO () foreign import javascript unsafe "$r = SVG('#box')" js_svg_box :: IO JSVal foreign import javascript unsafe "$1.on($2,$3)" js_on :: JSVal -> JSString -> Callback a -> IO () foreign import javascript unsafe "$r = $1.clientX" js_clientX :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientY" js_clientY :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientX" js_x :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientY" js_y :: JSVal -> IO Double foreign import javascript unsafe "$r = toSVGPoint($1,$2,$3)" js_to_svg_point :: JSVal -> Double -> Double -> IO JSVal foreign import javascript unsafe "$r = toSVGPointArray($1,$2)" js_to_svg_point_array :: JSVal -> JSVal -> IO JSVal foreign import javascript unsafe "drawPath($1,$2,$3)" js_draw_path :: JSVal -> JSString -> JSVal -> IO () foreign import javascript unsafe "window.requestAnimationFrame($1)" js_requestAnimationFrame :: Callback a -> IO () foreign import javascript unsafe "refresh($1,$2)" js_refresh :: JSVal -> JSVal -> IO () foreign import javascript unsafe "$1.addEventListener($2,$3)" js_addEventListener :: JSVal -> JSString -> Callback a -> IO () foreign import javascript unsafe "overlay_point($1,$2,$3,$4,$5,$6)" js_overlay_point :: JSVal -> JSVal -> Double -> Double -> Double -> Double -> IO () foreign import javascript unsafe "clear_overlay($1)" js_clear_overlay :: JSVal -> IO () foreign import javascript unsafe "fix_dpi($1)" js_fix_dpi :: JSVal -> IO () foreign import javascript unsafe "$r = $1.width" js_get_width :: JSVal -> IO Double foreign import javascript unsafe "$1.width = $2" js_set_width :: JSVal -> Double -> IO () foreign import javascript unsafe "$r = $1.height" js_get_height :: JSVal -> IO Double foreign import javascript unsafe "$1.height = $2" js_set_height :: JSVal -> Double -> IO () foreign import javascript unsafe "$r = document.createElement('canvas')" js_create_canvas :: IO JSVal foreign import javascript unsafe "$r = $1.pointerType" js_pointer_type :: JSVal -> IO JSString foreign import javascript unsafe "debug_show($1)" js_debug_show :: JSVal -> IO () foreign import javascript unsafe "document.getElementById($1)" js_document_getElementById :: JSString -> IO JSVal foreign import javascript unsafe "stroke_change_color($1,$2)" js_stroke_change_color :: JSVal -> JSString -> IO () foreign import javascript unsafe "stroke_remove($1,$2)" js_stroke_remove :: JSVal -> JSString -> IO () foreign import javascript unsafe "$1.classList.add($2)" js_add_class :: JSVal -> JSString -> IO () foreign import javascript unsafe "$1.classList.remove($2)" js_remove_class :: JSVal -> JSString -> IO () data PointerType = Mouse | Touch | Pen deriving (Show, Eq) getXY :: JSVal -> IO (Double, Double) getXY ev = (,) <$> js_clientX ev <*> js_clientY ev getXYinSVG :: JSVal -> (Double, Double) -> IO (Double, Double) getXYinSVG svg (x0, y0) = do r <- js_to_svg_point svg x0 y0 [x, y] <- fromJSValUncheckedListOf r pure (x, y) getPointerType :: JSVal -> IO PointerType getPointerType ev = js_pointer_type ev >>= \s -> do case JSS.unpack s of "touch" -> pure Touch "pen" -> pure Pen _ -> pure Mouse drawPath :: JSVal -> String -> [(Double, Double)] -> IO () drawPath svg id' xys = do arr <- toJSValListOf xys js_draw_path svg (JSS.pack id') arr strokeChangeColor :: JSVal -> String -> IO () strokeChangeColor svg id' = js_stroke_change_color svg (JSS.pack id') strokeRemove :: JSVal -> String -> IO () strokeRemove svg id' = js_stroke_remove svg (JSS.pack id')
null
https://raw.githubusercontent.com/wavewave/hoodle/1acd7a713697b6146bda13a38591cf868cea6685/web/client/Hoodle/Web/ForeignJS.hs
haskell
# LANGUAGE JavaScriptFFI # module Hoodle.Web.ForeignJS where import qualified Data.JSString as JSS import GHCJS.Foreign.Callback (Callback) import GHCJS.Marshal (FromJSVal (fromJSValUncheckedListOf), ToJSVal (toJSValListOf)) import GHCJS.Types (JSString, JSVal) foreign import javascript unsafe "console.log($1)" js_console_log :: JSVal -> IO () foreign import javascript unsafe "$r = location.hostname" js_hostname :: IO JSString foreign import javascript unsafe "preventDefaultTouchMove()" js_prevent_default_touch_move :: IO () foreign import javascript unsafe "$r = SVG('#box')" js_svg_box :: IO JSVal foreign import javascript unsafe "$1.on($2,$3)" js_on :: JSVal -> JSString -> Callback a -> IO () foreign import javascript unsafe "$r = $1.clientX" js_clientX :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientY" js_clientY :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientX" js_x :: JSVal -> IO Double foreign import javascript unsafe "$r = $1.clientY" js_y :: JSVal -> IO Double foreign import javascript unsafe "$r = toSVGPoint($1,$2,$3)" js_to_svg_point :: JSVal -> Double -> Double -> IO JSVal foreign import javascript unsafe "$r = toSVGPointArray($1,$2)" js_to_svg_point_array :: JSVal -> JSVal -> IO JSVal foreign import javascript unsafe "drawPath($1,$2,$3)" js_draw_path :: JSVal -> JSString -> JSVal -> IO () foreign import javascript unsafe "window.requestAnimationFrame($1)" js_requestAnimationFrame :: Callback a -> IO () foreign import javascript unsafe "refresh($1,$2)" js_refresh :: JSVal -> JSVal -> IO () foreign import javascript unsafe "$1.addEventListener($2,$3)" js_addEventListener :: JSVal -> JSString -> Callback a -> IO () foreign import javascript unsafe "overlay_point($1,$2,$3,$4,$5,$6)" js_overlay_point :: JSVal -> JSVal -> Double -> Double -> Double -> Double -> IO () foreign import javascript unsafe "clear_overlay($1)" js_clear_overlay :: JSVal -> IO () foreign import javascript unsafe "fix_dpi($1)" js_fix_dpi :: JSVal -> IO () foreign import javascript unsafe "$r = $1.width" js_get_width :: JSVal -> IO Double foreign import javascript unsafe "$1.width = $2" js_set_width :: JSVal -> Double -> IO () foreign import javascript unsafe "$r = $1.height" js_get_height :: JSVal -> IO Double foreign import javascript unsafe "$1.height = $2" js_set_height :: JSVal -> Double -> IO () foreign import javascript unsafe "$r = document.createElement('canvas')" js_create_canvas :: IO JSVal foreign import javascript unsafe "$r = $1.pointerType" js_pointer_type :: JSVal -> IO JSString foreign import javascript unsafe "debug_show($1)" js_debug_show :: JSVal -> IO () foreign import javascript unsafe "document.getElementById($1)" js_document_getElementById :: JSString -> IO JSVal foreign import javascript unsafe "stroke_change_color($1,$2)" js_stroke_change_color :: JSVal -> JSString -> IO () foreign import javascript unsafe "stroke_remove($1,$2)" js_stroke_remove :: JSVal -> JSString -> IO () foreign import javascript unsafe "$1.classList.add($2)" js_add_class :: JSVal -> JSString -> IO () foreign import javascript unsafe "$1.classList.remove($2)" js_remove_class :: JSVal -> JSString -> IO () data PointerType = Mouse | Touch | Pen deriving (Show, Eq) getXY :: JSVal -> IO (Double, Double) getXY ev = (,) <$> js_clientX ev <*> js_clientY ev getXYinSVG :: JSVal -> (Double, Double) -> IO (Double, Double) getXYinSVG svg (x0, y0) = do r <- js_to_svg_point svg x0 y0 [x, y] <- fromJSValUncheckedListOf r pure (x, y) getPointerType :: JSVal -> IO PointerType getPointerType ev = js_pointer_type ev >>= \s -> do case JSS.unpack s of "touch" -> pure Touch "pen" -> pure Pen _ -> pure Mouse drawPath :: JSVal -> String -> [(Double, Double)] -> IO () drawPath svg id' xys = do arr <- toJSValListOf xys js_draw_path svg (JSS.pack id') arr strokeChangeColor :: JSVal -> String -> IO () strokeChangeColor svg id' = js_stroke_change_color svg (JSS.pack id') strokeRemove :: JSVal -> String -> IO () strokeRemove svg id' = js_stroke_remove svg (JSS.pack id')
cfbcc7880bb3486b6e73f4cb3d0882c6117add2fc5b4ec38b88e10eebc0fee9c
pfdietz/ansi-test
with-hash-table-iterator.lsp
;-*- Mode: Lisp -*- Author : Created : Fri Nov 28 20:08:43 2003 ;;;; Contains: Tests of WITH-HASH-TABLE-ITERATOR (deftest with-hash-table-iterator.1 (with-hash-table-iterator (x (make-hash-table))) nil) (deftest with-hash-table-iterator.2 (with-hash-table-iterator (x (make-hash-table)) (values))) (deftest with-hash-table-iterator.3 (with-hash-table-iterator (x (make-hash-table)) (values 'a 'b 'c 'd)) a b c d) (deftest with-hash-table-iterator.4 (with-hash-table-iterator (%x (make-hash-table)) (%x)) nil) (deftest with-hash-table-iterator.5 (let ((table (make-hash-table))) (setf (gethash 'a table) 'b) (with-hash-table-iterator (%x table) (multiple-value-bind (success-p key val) (%x) (values (notnot success-p) key val)))) t a b) (deftest with-hash-table-iterator.6 (let ((table (make-hash-table))) (setf (gethash 'a table) 'b) (with-hash-table-iterator (%x table) (length (multiple-value-list (%x))))) 3) (deftest with-hash-table-iterator.7 (let ((keys '("a" "b" "c" "d" "e"))) (loop for test in '(eq eql equal equalp) for test-fn of-type function = (symbol-function test) collect (let ((table (make-hash-table :test test))) (loop for k in keys for i from 0 do (setf (gethash k table) i)) (let ((count 0) (found-keys)) (with-hash-table-iterator (%x table) (block done (loop (multiple-value-bind (success key val) (%x) (unless success (return-from done nil)) (incf count) (push key found-keys) (assert (= val (position key keys :test test-fn)))))) (and (= count (length keys)) (every test-fn (sort (remove-duplicates found-keys :test test) #'string<) keys) t)))))) (t t t t)) (deftest with-hash-table-iterator.8 (with-hash-table-iterator (%x (make-hash-table)) (declare (optimize))) nil) (deftest with-hash-table-iterator.8a (with-hash-table-iterator (%x (make-hash-table)) (declare (optimize)) (declare (optimize))) nil) (deftest with-hash-table-iterator.9 (with-hash-table-iterator (%x (make-hash-table)) (macrolet ((expand-%x (&environment env) (let ((expanded-form (macroexpand '(%x) env))) (if (equal expanded-form '(%x)) nil t)))) (expand-%x))) t) (deftest with-hash-table-iterator.10 (let ((table (make-hash-table))) (loop for key from 1 to 100 for val from 101 to 200 do (setf (gethash key table) val)) (let ((pairs nil)) (with-hash-table-iterator (%x table) (loop (multiple-value-bind (success key val) (%x) (unless success (return nil)) (remhash key table) (push (cons key val) pairs)))) (assert (eql (length pairs) 100)) (setq pairs (sort pairs #'(lambda (p1 p2) (< (car p1) (car p2))))) (values (hash-table-count table) (loop for (key . val) in pairs for expected-key from 1 for expected-val from 101 always (and (eql key expected-key) (eql val expected-val)))))) 0 t) (deftest with-hash-table-iterator.11 (let ((table (make-hash-table))) (loop for key from 1 to 100 for val from 101 to 200 do (setf (gethash key table) val)) (let ((pairs nil)) (with-hash-table-iterator (%x table) (loop (multiple-value-bind (success key val) (%x) (unless success (return nil)) (setf (gethash key table) (+ 1000 val)) (push (cons key val) pairs)))) (assert (eql (length pairs) 100)) (setq pairs (sort pairs #'(lambda (p1 p2) (< (car p1) (car p2))))) (values (hash-table-count table) (loop for (key . val) in pairs for expected-key from 1 for expected-val from 101 always (and (eql key expected-key) (eql val expected-val) (eql (gethash key table) (+ 1000 val)) ))))) 100 t) ;;; Free declaration scope (deftest with-hash-table-iterator.12 (block done (let ((x :bad)) (declare (special x)) (let ((x :good)) (with-hash-table-iterator (m (return-from done x)) (declare (special x)))))) :good)
null
https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/hash-tables/with-hash-table-iterator.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of WITH-HASH-TABLE-ITERATOR Free declaration scope
Author : Created : Fri Nov 28 20:08:43 2003 (deftest with-hash-table-iterator.1 (with-hash-table-iterator (x (make-hash-table))) nil) (deftest with-hash-table-iterator.2 (with-hash-table-iterator (x (make-hash-table)) (values))) (deftest with-hash-table-iterator.3 (with-hash-table-iterator (x (make-hash-table)) (values 'a 'b 'c 'd)) a b c d) (deftest with-hash-table-iterator.4 (with-hash-table-iterator (%x (make-hash-table)) (%x)) nil) (deftest with-hash-table-iterator.5 (let ((table (make-hash-table))) (setf (gethash 'a table) 'b) (with-hash-table-iterator (%x table) (multiple-value-bind (success-p key val) (%x) (values (notnot success-p) key val)))) t a b) (deftest with-hash-table-iterator.6 (let ((table (make-hash-table))) (setf (gethash 'a table) 'b) (with-hash-table-iterator (%x table) (length (multiple-value-list (%x))))) 3) (deftest with-hash-table-iterator.7 (let ((keys '("a" "b" "c" "d" "e"))) (loop for test in '(eq eql equal equalp) for test-fn of-type function = (symbol-function test) collect (let ((table (make-hash-table :test test))) (loop for k in keys for i from 0 do (setf (gethash k table) i)) (let ((count 0) (found-keys)) (with-hash-table-iterator (%x table) (block done (loop (multiple-value-bind (success key val) (%x) (unless success (return-from done nil)) (incf count) (push key found-keys) (assert (= val (position key keys :test test-fn)))))) (and (= count (length keys)) (every test-fn (sort (remove-duplicates found-keys :test test) #'string<) keys) t)))))) (t t t t)) (deftest with-hash-table-iterator.8 (with-hash-table-iterator (%x (make-hash-table)) (declare (optimize))) nil) (deftest with-hash-table-iterator.8a (with-hash-table-iterator (%x (make-hash-table)) (declare (optimize)) (declare (optimize))) nil) (deftest with-hash-table-iterator.9 (with-hash-table-iterator (%x (make-hash-table)) (macrolet ((expand-%x (&environment env) (let ((expanded-form (macroexpand '(%x) env))) (if (equal expanded-form '(%x)) nil t)))) (expand-%x))) t) (deftest with-hash-table-iterator.10 (let ((table (make-hash-table))) (loop for key from 1 to 100 for val from 101 to 200 do (setf (gethash key table) val)) (let ((pairs nil)) (with-hash-table-iterator (%x table) (loop (multiple-value-bind (success key val) (%x) (unless success (return nil)) (remhash key table) (push (cons key val) pairs)))) (assert (eql (length pairs) 100)) (setq pairs (sort pairs #'(lambda (p1 p2) (< (car p1) (car p2))))) (values (hash-table-count table) (loop for (key . val) in pairs for expected-key from 1 for expected-val from 101 always (and (eql key expected-key) (eql val expected-val)))))) 0 t) (deftest with-hash-table-iterator.11 (let ((table (make-hash-table))) (loop for key from 1 to 100 for val from 101 to 200 do (setf (gethash key table) val)) (let ((pairs nil)) (with-hash-table-iterator (%x table) (loop (multiple-value-bind (success key val) (%x) (unless success (return nil)) (setf (gethash key table) (+ 1000 val)) (push (cons key val) pairs)))) (assert (eql (length pairs) 100)) (setq pairs (sort pairs #'(lambda (p1 p2) (< (car p1) (car p2))))) (values (hash-table-count table) (loop for (key . val) in pairs for expected-key from 1 for expected-val from 101 always (and (eql key expected-key) (eql val expected-val) (eql (gethash key table) (+ 1000 val)) ))))) 100 t) (deftest with-hash-table-iterator.12 (block done (let ((x :bad)) (declare (special x)) (let ((x :good)) (with-hash-table-iterator (m (return-from done x)) (declare (special x)))))) :good)
8b11ff3f7fc6bca2fb670b86426873e1ae173e904efce5c30a544e7c78c802a7
mcorbin/tour-of-clojure
atom.clj
;; defines an atom (def my-atom (atom [])) ;; redefs the atom to get its value (println @my-atom "\n") ;; updates the atom value (swap! my-atom conj 10) (println @my-atom "\n") ;; a function can be passed to swap! (swap! my-atom (fn [old-state] (conj old-state 20))) (println @my-atom "\n") ;; swap! returns the new value of the atom (println (swap! my-atom conj 30) "\n") ;; reset! sets the atom value to something (println (reset! my-atom [100]))
null
https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/resources/public/pages/code/atom.clj
clojure
defines an atom redefs the atom to get its value updates the atom value a function can be passed to swap! swap! returns the new value of the atom reset! sets the atom value to something
(def my-atom (atom [])) (println @my-atom "\n") (swap! my-atom conj 10) (println @my-atom "\n") (swap! my-atom (fn [old-state] (conj old-state 20))) (println @my-atom "\n") (println (swap! my-atom conj 30) "\n") (println (reset! my-atom [100]))
9ad14900be65018917abaf84909642799054c3b6e32da7db09aef5a5f89ba3f3
3b/learnopengl
coordinate-systems.lisp
;;;; shader code (defpackage coordinate-systems/shaders (:use #:3bgl-glsl/cl) ;; shadow POSITION so we don't conflict with the default definition of CL : POSITION as ( input position : vec4 : location 0 ) (:shadow position)) (in-package coordinate-systems/shaders) (input position :vec3 :location 0) (input color :vec3 :location 1 :stage :vertex) (input tex-coord :vec2 :location 2) (output our-color :vec3 :stage :vertex) (output -tex-coord :vec2 :stage :vertex) (uniform model :mat4) (uniform view :mat4) (uniform projection :mat4) (input our-color :vec3 :stage :fragment) (input -tex-coord :vec2 :stage :fragment) (output color :vec4 :stage :fragment) (uniform our-texture :sampler-2d) (uniform our-texture2 :sampler-2d) (defun vertex () (declare (stage :vertex)) (setf gl-position (* projection view model (vec4 position 1)) our-color color -tex-coord tex-coord)) (defun fragment () (declare (stage :fragment)) (setf color (mix (texture our-texture -tex-coord) (texture our-texture2 -tex-coord) 0.2))) ;;;; back to normal lisp code (in-package learning-opengl) (defclass coordinate-systems (textures-combined) () (:default-initargs :shader-parts '(:vertex-shader coordinate-systems/shaders::vertex :fragment-shader coordinate-systems/shaders::fragment))) (defmethod draw :before ((w coordinate-systems)) (let (model view projection (time (float (/ (get-internal-real-time) internal-time-units-per-second)))) ;; create the transformation (setf model (sb-cga:rotate-around (sb-cga:vec 1.0 0.0 0.0) (radians -55))) (setf view (sb-cga:translate* 0.0 0.0 -3.0)) ;; sb-cga doesn't include a perspective matrix, so we will get that from mathkit (setf projection (kit.math:perspective-matrix (radians 45) (float (/ (glop:window-width w) (glop:window-height w))) 0.1 100)) ;; get matrix's uniform location and set matrix (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "model") model nil) (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "view") view nil) (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "projection") projection nil)) ) #++ (common 'coordinate-systems)
null
https://raw.githubusercontent.com/3b/learnopengl/30f910895ef336ac5ff0b4cc676af506413bb953/factored/coordinate-systems.lisp
lisp
shader code shadow POSITION so we don't conflict with the default definition back to normal lisp code create the transformation sb-cga doesn't include a perspective matrix, so we will get get matrix's uniform location and set matrix
(defpackage coordinate-systems/shaders (:use #:3bgl-glsl/cl) of CL : POSITION as ( input position : vec4 : location 0 ) (:shadow position)) (in-package coordinate-systems/shaders) (input position :vec3 :location 0) (input color :vec3 :location 1 :stage :vertex) (input tex-coord :vec2 :location 2) (output our-color :vec3 :stage :vertex) (output -tex-coord :vec2 :stage :vertex) (uniform model :mat4) (uniform view :mat4) (uniform projection :mat4) (input our-color :vec3 :stage :fragment) (input -tex-coord :vec2 :stage :fragment) (output color :vec4 :stage :fragment) (uniform our-texture :sampler-2d) (uniform our-texture2 :sampler-2d) (defun vertex () (declare (stage :vertex)) (setf gl-position (* projection view model (vec4 position 1)) our-color color -tex-coord tex-coord)) (defun fragment () (declare (stage :fragment)) (setf color (mix (texture our-texture -tex-coord) (texture our-texture2 -tex-coord) 0.2))) (in-package learning-opengl) (defclass coordinate-systems (textures-combined) () (:default-initargs :shader-parts '(:vertex-shader coordinate-systems/shaders::vertex :fragment-shader coordinate-systems/shaders::fragment))) (defmethod draw :before ((w coordinate-systems)) (let (model view projection (time (float (/ (get-internal-real-time) internal-time-units-per-second)))) (setf model (sb-cga:rotate-around (sb-cga:vec 1.0 0.0 0.0) (radians -55))) (setf view (sb-cga:translate* 0.0 0.0 -3.0)) that from mathkit (setf projection (kit.math:perspective-matrix (radians 45) (float (/ (glop:window-width w) (glop:window-height w))) 0.1 100)) (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "model") model nil) (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "view") view nil) (gl:uniform-matrix-4fv (gl:get-uniform-location (shader-program w) "projection") projection nil)) ) #++ (common 'coordinate-systems)
119b14a682cff3be7ccb0b555e9a5d54de44773cfbb567923c5f65f742467617
lasp-lang/lasp
state_orset_ext.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2016 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(state_orset_ext). -author("Christopher S. Meiklejohn <>"). -export([intersect/2, map/2, union/2, product/2, filter/2]). union(LValue, RValue) -> state_orset:merge(LValue, RValue). product({state_orset, LValue}, {state_orset, RValue}) -> FolderFun = fun({X, XCausality}, {state_orset, Acc}) -> {state_orset, Acc ++ [{{X, Y}, causal_product(XCausality, YCausality)} || {Y, YCausality} <- RValue]} end, lists:foldl(FolderFun, new(), LValue). intersect({state_orset, LValue}, RValue) -> lists:foldl(intersect_folder(RValue), new(), LValue). @private intersect_folder({state_orset, RValue}) -> fun({X, XCausality}, {state_orset, Acc}) -> Values = case lists:keyfind(X, 1, RValue) of {_Y, YCausality} -> [{X, causal_union(XCausality, YCausality)}]; false -> [] end, {state_orset, Acc ++ Values} end. map(Function, {state_orset, V}) -> FolderFun = fun({X, Causality}, {state_orset, Acc}) -> {state_orset, Acc ++ [{Function(X), Causality}]} end, lists:foldl(FolderFun, new(), V). filter(Function, {state_orset, V}) -> FolderFun = fun({X, Causality}, {state_orset, Acc}) -> case Function(X) of true -> {state_orset, Acc ++ [{X, Causality}]}; false -> {state_orset, Acc} end end, lists:foldl(FolderFun, new(), V). @private new() -> state_orset:new(). @private causal_product(Xs, Ys) -> lists:foldl(fun({X, XActive}, XAcc) -> lists:foldl(fun({Y, YActive}, YAcc) -> [{[X, Y], XActive andalso YActive}] ++ YAcc end, [], Ys) ++ XAcc end, [], Xs). @private causal_union(Xs, Ys) -> Xs ++ Ys.
null
https://raw.githubusercontent.com/lasp-lang/lasp/1701c8af77e193738dfc4ef4a5a703d205da41a1/src/state_orset_ext.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------
Copyright ( c ) 2016 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(state_orset_ext). -author("Christopher S. Meiklejohn <>"). -export([intersect/2, map/2, union/2, product/2, filter/2]). union(LValue, RValue) -> state_orset:merge(LValue, RValue). product({state_orset, LValue}, {state_orset, RValue}) -> FolderFun = fun({X, XCausality}, {state_orset, Acc}) -> {state_orset, Acc ++ [{{X, Y}, causal_product(XCausality, YCausality)} || {Y, YCausality} <- RValue]} end, lists:foldl(FolderFun, new(), LValue). intersect({state_orset, LValue}, RValue) -> lists:foldl(intersect_folder(RValue), new(), LValue). @private intersect_folder({state_orset, RValue}) -> fun({X, XCausality}, {state_orset, Acc}) -> Values = case lists:keyfind(X, 1, RValue) of {_Y, YCausality} -> [{X, causal_union(XCausality, YCausality)}]; false -> [] end, {state_orset, Acc ++ Values} end. map(Function, {state_orset, V}) -> FolderFun = fun({X, Causality}, {state_orset, Acc}) -> {state_orset, Acc ++ [{Function(X), Causality}]} end, lists:foldl(FolderFun, new(), V). filter(Function, {state_orset, V}) -> FolderFun = fun({X, Causality}, {state_orset, Acc}) -> case Function(X) of true -> {state_orset, Acc ++ [{X, Causality}]}; false -> {state_orset, Acc} end end, lists:foldl(FolderFun, new(), V). @private new() -> state_orset:new(). @private causal_product(Xs, Ys) -> lists:foldl(fun({X, XActive}, XAcc) -> lists:foldl(fun({Y, YActive}, YAcc) -> [{[X, Y], XActive andalso YActive}] ++ YAcc end, [], Ys) ++ XAcc end, [], Xs). @private causal_union(Xs, Ys) -> Xs ++ Ys.
ab5c50e53b98126b5c9dd164ee462e4b84babbbff37c16d3d8d7ba2b3825b784
seckcoder/course-compiler
s0_20.rkt
(let ([a 42]) (let ([b a]) b))
null
https://raw.githubusercontent.com/seckcoder/course-compiler/4363e5b3e15eaa7553902c3850b6452de80b2ef6/tests/s0_20.rkt
racket
(let ([a 42]) (let ([b a]) b))
456f74cc440357807884c772c82c42bbfa83de2dd47ca03338802c2410259b8c
scicloj/scicloj-data-science-handbook
04_visualization_with_hanami.clj
(ns scicloj.04-visualization-with-hanami (:require [notespace.api :as notespace] [notespace.kinds :as kind])) Notespace ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Listen for changes in the namespace and update notespace automatically ;; Hidden kinds should not show in the notespace page ^kind/hidden (comment ;; Manually start an empty notespace (notespace/init-with-browser) ;; Renders the notes and listens to file changes (notespace/listen) ;; Clear an existing notespace browser (notespace/init) ;; Evaluating a whole notespace (notespace/eval-this-notespace)) Chapter 04 - Visualization with Hanami ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ["# Visualization with Hanami"] ^kind/hidden ["This chapter will dive into practical aspects of visualizing data using the Clojure library Hanami and other tools (TODO)"] ^kind/hidden ["## General Matplotlib Tips" "Before we dive into the details of creating visualizations with Hanami, there are a few useful things you should know about using the package."] ["## Getting Started With Hanami and Vega/Vega-lite" "Vega is a declarative format for creating, saving, and sharing data visualizations. Vega-lite is a high-level visualization grammar. It provides a more concise JSON syntax than Vega for supporting rapid generation of visualizations to support analysis. Vega-Lite support static plot generation but also interactive multi-view graphics. Specifications can be compiled to Vega. Hanami is a library that allows you to create Vega and Vega-lite plot specifications in a more user friendly manner by affording a simple API to express the plots through transformations on the templates and thus creating a powerful and fast way to express data visualisations. Before we dive into the details of creating visualizations with Hanami, here are a few preparations to start with"] ["### Importing Hanami"] (require '[aerial.hanami.common :as hanami-common] '[aerial.hanami.templates :as hanami-templates] '[tech.v3.datatype.functional :as dtype-func] '[fastmath.core :as fastmath] '[tablecloth.api :as tablecloth]) ["### For our convenience" "Lets start by defining a conveniance function that makes plot expression syntax slightly less verbose. The function is built so that it will receive the data we want to visualize as a first argument and thus enabling it to be used as is in a thread first, `->`, macro at the end of our data transformations"] (defn hanami-plot "Syntactic sugar for hanami plots, lets you pipe data directly in a thread first macro" [data template & substitutions] (apply hanami-common/xform template :DATA data substitutions)) ^kind/hidden ["### Setting Styles" "We will use the plt.style directive to choose appropriate aesthetic styles for our figures. Here we will set the classic style, which ensures that the plots we create use the classic Matplotlib style:"] ;;todo ^kind/hidden ["Throughout this section, we will adjust this style as needed. Note that the stylesheets used here are supported as of Matplotlib version 1.5; if you are using an earlier version of Matplotlib, only the default style is available. For more information on stylesheets, see Customizing Matplotlib: Configurations and Style Sheets."] ^kind/hidden ["### `show()` or `No show()`? How to Display Your Plots" "A visualization you can't see won't be of much use, but just how you view your Matplotlib plots depends on the context. The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook."] ^kind/hidden ["#### Plotting from a script" "If you are using Matplotlib from within a script, the function plt.show() is your friend. plt.show() starts an event loop, looks for all currently active figure objects, and opens one or more interactive windows that display your figure or figures. So, for example, you may have a file called myplot.py containing the following:"] ;; todo ^kind/hidden ["You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:"] ;; todo ^kind/hidden ["The plt.show() command does a lot under the hood, as it must interact with your system's interactive graphical backend. The details of this operation can vary greatly from system to system and even installation to installation, but matplotlib does its best to hide all these details from you." "One thing to be aware of: the plt.show() command should be used only once per Python session, and is most often seen at the very end of the script. Multiple show() commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided."] ^kind/hidden ["#### Plotting from an IPython shell" "It can be very convenient to use Matplotlib interactively within an IPython shell (see IPython: Beyond Normal Python). IPython is built to work well with Matplotlib if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:"] ;; todo ^kind/hidden ["At this point, any plt plot command will cause a figure window to open, and further commands can be run to update the plot. Some changes (such as modifying properties of lines that are already drawn) will not draw automatically: to force an update, use plt.draw(). Using plt.show() in Matplotlib mode is not required."] ["#### Plotting from an Notespace notebook" "We are using notespace to do literate programming and to render the plots. All the sections are decorated with Clojure metadata to let the rendering engine know what we want to happen with the section. `^kind/vega` for instance means that the following output should be rendered as a vega/vega-lite plot. Why we like Notespace is that we can continue to work from the editors we love, be it emacs, vi, vscode, IntelliJ, atom or any other that supports developing Clojure. Lets create some data and see how the process can look."] ^kind/hidden ["### Plotting from an Notespace notebook" "The IPython notebook is a browser-based interactive data analysis tool that can combine narrative, code, graphics, HTML elements, and much more into a single executable document (see IPython: Beyond Normal Python). Plotting interactively within an IPython notebook can be done with the %matplotlib command, and works in a similar way to the IPython shell. In the IPython notebook, you also have the option of embedding graphics directly in the notebook, with two possible options: %matplotlib notebook will lead to interactive plots embedded within the notebook %matplotlib inline will lead to static images of your plot embedded in the notebook After running this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic: TO-DO need to clean all this:"] ["First we will create a range with 100 values from 0 to 10"] (def x-range (fastmath/slice-range 0 10 100)) (take 5 x-range) ["Instead priting all 100 values we just looked at the first 5 there." "Next we'll make a helper function that builds a row in the format that hanami/vega likes it"] (defn map-row "a helper to create a row (=map) of data in the form that vega likes" [label x y] {:x x, :y y, :label label}) ["The following helper uses the helper above and but also appends a new series with a label, x and a y. The x values are given as a parameter and the y values are calculated by applying the function, also passed as parameter, to x."] (defn add-series "append new series with transformation to dataset" [coll f label range] (into coll (map #(map-row label % (f %)) range))) ["Here is an example. We create a series with x as defined above and define y by adding a function that just doubles x"] (take 5 (add-series [] #(* % 2) "double-up" x-range)) ["Now, lets define the data we want to visualize using the sin and cos functions"] (def sin-cos-data (-> [] (add-series dtype-func/sin "sin" x-range) (add-series dtype-func/cos "cos" x-range))) ["This is how the data looks like:"] (take 5 sin-cos-data) ["Not lets plot that:"] (def my-figure (-> sin-cos-data (hanami-plot hanami-templates/line-chart) (#(assoc-in % [:encoding :strokeDash] {:field :label, :type "nominal"})))) ^kind/vega my-figure ^kind/hidden ["### Saving Figures to File One nice feature of Matplotlib is the ability to save figures in a wide variety of formats. Saving a figure can be done using the savefig() command. For example, to save the previous figure as a PNG file, you can run this:"] ["### Saving Figures to File Sometimes we want to to save the plots as files on our filesystem for other usages. Next we will look at how to create save the Vega/Vega-lite plots as SVGs on the filesystem or alternatively as PNG or TIFFs."] ["First we will load some libraries to help us."] (require '[applied-science.darkstar :as darkstar] '[clojure.data.json :as json] '[batik.rasterize :as batik] '[clojure.string :as string]) ["Next we will need a simple helper again to do the saving."] (defn save-plot! [m & [filename type]] (let [svg-render (if (= (:MODE m) "vega") darkstar/vega-spec->svg darkstar/vega-lite-spec->svg)] (->> m json/write-str svg-render (#(if (#{:tif :tiff :png} type) (batik/render-svg-string % filename type) (spit (or filename "plot.svg") %)))))) ["This could be made much more robust with more features, but it will suffice for now. Now we can save the plot, by default our helper saves the file as an SVG but a number of formats can be used."] ^kind/void (save-plot! my-figure "my_figure.svg") ^kind/void (save-plot! my-figure "my_figure.png" :png) ^kind/hidden ["We now have a file called my_figure.png in the current working directory:"] ["We have now saved a file called my_figure.png on the filesystem:"] (require '[clojure.java.shell :refer [sh]]) ^kind/hidden ["!ls -lh my_figure.png"] (string/split-lines (:out (sh "ls" "-lh" "my_figure.png" "my_figure.svg"))) ^kind/hidden ["To confirm that it contains what we think it contains, let's use the IPython Image object to display the contents of this file:"] ^kind/hidden ["from IPython.display import Image Image('my_figure.png')"] ^kind/hidden ["In savefig(), the file format is inferred from the extension of the given filename. Depending on what backends you have installed, many different file formats are available. The list of supported file types can be found for your system by using the following method of the figure canvas object:"] ^kind/hidden [:pre "fig.canvas.get_supported_filetypes()"] ^kind/hidden ["{'eps': 'Encapsulated Postscript', 'jpeg': 'Joint Photographic Experts Group', 'jpg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}"] ^kind/hidden ["Note that when saving your figure, it's not necessary to use plt.show() or related commands discussed earlier."] ^kind/hidden ["## Two Interfaces for the Price of One¶ A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface. We'll quickly highlight the differences between the two here. ### MATLAB-style interface Matplotlib was originally written as a Python alternative for MATLAB users, and much of its syntax reflects that fact. The MATLAB-style tools are contained in the pyplot (plt) interface. For example, the following code will probably look quite familiar to MATLAB users:"] ^kind/hidden ["plt.figure() # create a plot figure # create the first of two panels and set current axis plt.subplot(2, 1, 1) # (rows, columns, panel number) plt.plot(x, np.sin(x)) # create the second panel and set current axis plt.subplot(2, 1, 2) plt.plot(x, np.cos(x));"] ["### Another example Now, lets use the previous plot that we still have saved in the my-figure var, and modify it a bit. The definition is just data after all. Lets have a peek. jAgain, not to fill this document with all the data we want to visualize, lets only take the first 5 lines"] (update-in my-figure [:data :values] (partial take 5)) ["What you see there is the vega-lite spec of the plot as a Clojure map but instead of json it is in `edn`, a data format we work with in Clojure and is a bit nicer to read. So what if we want to separate the figures to their own panels that are placed above each other. This can be achieved by adding and transformng these key value pairs in the specification, using the Clojure functions we are used to."] ^kind/vega (-> my-figure (assoc :height 150) (assoc-in [:encoding :row] {:field :label, :type "nominal"})) ^kind/hidden ["### Object-oriented interface The object-oriented interface is available for these more complicated situations, and for when you want more control over your figure. Rather than depending on some notion of an \"active\" figure or axes, in the object-oriented interface the plotting functions are methods of explicit Figure and Axes objects. To re-create the previous plot using this style of plotting, you might do the following:"] ^kind/hidden ["# First create a grid of plots # ax will be an array of two Axes objects fig, ax = plt.subplots(2) # Call plot() method on the appropriate object ax[0].plot(x, np.sin(x)) ax[1].plot(x, np.cos(x));"] ^kind/hidden ["For more simple plots, the choice of which style to use is largely a matter of preference, but the object-oriented approach can become a necessity as plots become more complicated. Throughout this chapter, we will switch between the MATLAB-style and object-oriented interfaces, depending on what is most convenient. In most cases, the difference is as small as switching plt.plot() to ax.plot(), but there are a few gotchas that we will highlight as they come up in the following sections."] ["# Simple Line Plots"] ["We have now seen a couple of simple examples how do work with data and do plotting in Clojure with the help of Hanami and Vega/Vega-lite. In the following section we will go through the steps to make simple line plots in a bit more detail."] ^kind/hidden ["Perhaps the simplest of all plots is the visualization of a single function y=f(x). Here we will take a first look at creating a simple plot of this type. As with all the following sections, we'll start by setting up the notebook for plotting and importing the packages we will use:"] ^kind/hidden ["%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np"] ^kind/hidden ["For all Matplotlib plots, we start by creating a figure and an axes. In their simplest form, a figure and axes can be created as follows:"] ^kind/hidden ["fig = plt.figure() ax = plt.axes()"] ^kind/vega (hanami-plot {} hanami-templates/line-chart :XSCALE {:domain [0 10]} :YSCALE {:domain [-1 1]}) ^kind/hidden ["In Matplotlib, the figure (an instance of the class plt.Figure) can be thought of as a single container that contains all the objects representing axes, graphics, text, and labels. The axes (an instance of the class plt.Axes) is what we see above: a bounding box with ticks and labels, which will eventually contain the plot elements that make up our visualization. Throughout this book, we'll commonly use the variable name fig to refer to a figure instance, and ax to refer to an axes instance or group of axes instances. Once we have created an axes, we can use the ax.plot function to plot some data. Let's start with a simple sinusoid:"] ^kind/hidden ["fig = plt.figure() ax = plt.axes() x = np.linspace(0, 10, 1000) ax.plot(x, np.sin(x));"] ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin (- x 0))}) x-range) (hanami-plot hanami-templates/line-chart)) ^kind/hidden ["Alternatively, we can use the pylab interface and let the figure and axes be created for us in the background (see Two Interfaces for the Price of One for a discussion of these two interfaces):"] ^kind/vega (-> sin-cos-data (hanami-plot hanami-templates/line-chart) (#(assoc-in % [:encoding :strokeDash] {:field :label, :type "nominal"}))) ^kind/hidden ["That's all there is to plotting simple functions in Matplotlib! We'll now dive into some more details about how to control the appearance of the axes and lines."] ^kind/hidden ["Adjusting the Plot: Line Colors and Styles The first adjustment you might wish to make to a plot is to control the line colors and styles. The plt.plot() function takes additional arguments that can be used to specify these. To adjust the color, you can use the color keyword, which accepts a string argument representing virtually any imaginable color. The color can be specified in a variety of ways:"] ^kind/hidden ["plt.plot(x, np.sin(x - 0), color='blue') # specify color by name plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk) plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1 plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF) plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1 plt.plot(x, np.sin(x - 5), color='chartreuse'); # all HTML color names supported"] (def with-manual-colors (-> [] (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 0)), :color "blue"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 1)), :color "green"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 2)), :color "hsl(0, 0%, 75%)"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 3)), :color "#FFDD44"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 4)), :color "rgb(256, 51, 77)"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 5)), :color "chartreus"}) x-range)))) ^kind/vega (-> with-manual-colors (hanami-plot hanami-templates/line-chart :COLOR {:field :color, :type "nominal", :scale nil})) ^kind/hidden ["If no color is specified, Matplotlib will automatically cycle through a set of default colors for multiple lines. Similarly, the line style can be adjusted using the linestyle keyword:"] ^kind/hidden ["plt.plot(x, x + 0, linestyle='solid') plt.plot(x, x + 1, linestyle='dashed') plt.plot(x, x + 2, linestyle='dashdot') plt.plot(x, x + 3, linestyle='dotted'); # For short, you can use the following codes: plt.plot(x, x + 4, linestyle='-') # solid plt.plot(x, x + 5, linestyle='--') # dashed plt.plot(x, x + 6, linestyle='-.') # dashdot plt.plot(x, x + 7, linestyle=':'); # dotted"] (def linestyle {:solid [1 0], "-" [1 0], :dashed [10 10], "--" [10 10], :dashdot [2 5 5 5], "-." [2 5 5 5], :dotted [2 2], ":" [2 2]}) (def stroked-lines (->> [] (into (map (fn [x] {:label 0, :x x, :y (+ x 0), :stroke (:solid linestyle)}) x-range)) (into (map (fn [x] {:label 1, :x x, :y (+ x 1), :stroke (:dashed linestyle)}) x-range)) (into (map (fn [x] {:label 2, :x x, :y (+ x 2), :stroke (:dasheddot linestyle)}) x-range)) (into (map (fn [x] {:label 3, :x x, :y (+ x 3), :stroke (:dotted linestyle)}) x-range)) (into (map (fn [x] {:label 4, :x x, :y (+ x 4), :stroke (get linestyle "-")}) x-range)) (into (map (fn [x] {:label 5, :x x, :y (+ x 5), :stroke (get linestyle "--")}) x-range)) (into (map (fn [x] {:label 6, :x x, :y (+ x 6), :stroke (get linestyle "-.")}) x-range)) (into (map (fn [x] {:label 7, :x x, :y (+ x 7), :stroke (get linestyle ":")}) x-range)))) ^kind/dataset (-> (tablecloth/dataset stroked-lines) (tablecloth/order-by :label)) ^kind/vega (-> stroked-lines (hanami-plot hanami-templates/line-chart :COLOR {:field :label}) (assoc-in [:encoding :strokeDash] {:field :stroke, :scale nil})) ["If you would like to be extremely terse, these linestyle and color codes can be combined into a single non-keyword argument to the plt.plot() function"] ^kind/hidden ["plt.plot(x, x + 0, '-g') # solid green plt.plot(x, x + 1, '--c') # dashed cyan plt.plot(x, x + 2, '-.k') # dashdot black plt.plot(x, x + 3, ':r'); # dotted red"] ^kind/hidden ["These single-character color codes reflect the standard abbreviations in the RGB (Red/Green/Blue) and CMYK (Cyan/Magenta/Yellow/blacK) color systems, commonly used for digital color graphics. There are many other keyword arguments that can be used to fine-tune the appearance of the plot; for more details, I'd suggest viewing the docstring of the plt.plot() function using IPython's help tools (See Help and Documentation in IPython)."] ^kind/hidden ["## Adjusting the Plot: Axes Limits Matplotlib does a decent job of choosing default axes limits for your plot, but sometimes it's nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods:"] ^kind/hidden ["plt.plot(x, np.sin(x)) plt.xlim(-1, 11) plt.ylim(-1.5, 1.5);"] ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [-1.5 1.5]} :XSCALE {:domain [-1 11]} :COLOR {:field :label})) ^kind/hidden ["If for some reason you'd like either axis to be displayed in reverse, you can simply reverse the order of the arguments:"] ^kind/void ["plt.plot(x, np.sin(x)) plt.xlim(10, 0) plt.ylim(1.2, -1.2);"] ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [1.2 -1.2]} :XSCALE {:domain [10 0]} :COLOR {:field :label})) ^kind/hidden ["A useful related method is plt.axis() (note here the potential confusion between axes with an e, and axis with an i). The plt.axis() method allows you to set the x and y limits with a single call, by passing a list which specifies [xmin, xmax, ymin, ymax]:"] ^kind/hidden ["plt.plot(x, np.sin(x)) plt.axis([-1, 11, -1.5, 1.5]);"] ^kind/hidden ["The plt.axis() method goes even beyond this, allowing you to do things like automatically tighten the bounds around the current plot:"] ^kind/hidden ["plt.plot(x, np.sin(x)) plt.axis('tight');"] ["It allows even higher-level specifications, such as ensuring an equal aspect ratio so that on your screen, one unit in x is equal to one unit in y:"] ^kind/hidden ["plt.plot(x, np.sin(x)) plt.axis('equal');"] ^kind/hidden ["For more information on axis limits and the other capabilities of the plt.axis method, refer to the plt.axis docstring."] ^kind/hidden ["## Labeling Plots As the last piece of this section, we'll briefly look at the labeling of plots: titles, axis labels, and simple legends. Titles and axis labels are the simplest such labels—there are methods that can be used to quickly set them:"] ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (#(hanami-common/xform hanami-templates/line-chart :TITLE "A Sine Curve" :YTITLE "sin(x)" :DATA %))) ^kind/hidden ["The position, size, and style of these labels can be adjusted using optional arguments to the function. For more information, see the Matplotlib documentation and the docstrings of each of these functions. When multiple lines are being shown within a single axes, it can be useful to create a plot legend that labels each line type. Again, Matplotlib has a built-in way of quickly creating such a legend. It is done via the (you guessed it) plt.legend() method. Though there are several valid ways of using this, I find it easiest to specify the label of each line using the label keyword of the plot function:"] ^kind/hidden ["plt.plot(x, np.sin(x), '-g', label='sin(x)') plt.plot(x, np.cos(x), ':b', label='cos(x)') plt.axis('equal') plt.legend();"] ^kind/vega (-> [] (into (map (fn [x] {:label "sin(x)", :color "green", :x x, :y (dtype-func/sin x), :stroke (:solid linestyle)}) x-range)) (into (map (fn [x] {:label "cos(x)", :color "blue", :x x, :y (dtype-func/cos x), :stroke (:dotted linestyle)}) x-range)) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [-3 3]} :COLOR {:field :label, :scale {:range {:field :color}}}) (assoc-in [:encoding :strokeDash] {:field :stroke, :scale nil})) ^kind/hidden ["As you can see, the plt.legend() function keeps track of the line style and color, and matches these with the correct label. More information on specifying and formatting plot legends can be found in the plt.legend docstring; additionally, we will cover some more advanced legend options in Customizing Plot Legends."] ^kind/hidden ["## Aside: Matplotlib Gotchas While most plt functions translate directly to ax methods (such as plt.plot() → ax.plot(), plt.legend() → ax.legend(), etc.), this is not the case for all commands. In particular, functions to set limits, labels, and titles are slightly modified. For transitioning between MATLAB-style functions and object-oriented methods, make the following changes: plt.xlabel() → ax.set_xlabel() plt.ylabel() → ax.set_ylabel() plt.xlim() → ax.set_xlim() plt.ylim() → ax.set_ylim() plt.title() → ax.set_title() In the object-oriented interface to plotting, rather than calling these functions individually, it is often more convenient to use the ax.set() method to set all these properties at once:"] ^kind/hidden ["ax = plt.axes() ax.plot(x, np.sin(x)) ax.set(xlim=(0, 10), ylim=(-2, 2), xlabel='x', ylabel='sin(x)', title='A Simple Plot');"]
null
https://raw.githubusercontent.com/scicloj/scicloj-data-science-handbook/7c0488199ec0a63a9d5e785780c2bbfd102c5978/src/scicloj/04_visualization_with_hanami.clj
clojure
Listen for changes in the namespace and update notespace automatically Hidden kinds should not show in the notespace page Manually start an empty notespace Renders the notes and listens to file changes Clear an existing notespace browser Evaluating a whole notespace todo todo todo todo "] "] "] # all HTML color names supported"] # dotted"] # dotted red"] for more details, I'd suggest viewing the docstring of the plt.plot() function using IPython's help tools (See Help and Documentation in IPython)."] "] "] "] "] "] "] "]
(ns scicloj.04-visualization-with-hanami (:require [notespace.api :as notespace] [notespace.kinds :as kind])) Notespace ^kind/hidden (comment (notespace/init-with-browser) (notespace/listen) (notespace/init) (notespace/eval-this-notespace)) Chapter 04 - Visualization with Hanami ["# Visualization with Hanami"] ^kind/hidden ["This chapter will dive into practical aspects of visualizing data using the Clojure library Hanami and other tools (TODO)"] ^kind/hidden ["## General Matplotlib Tips" "Before we dive into the details of creating visualizations with Hanami, there are a few useful things you should know about using the package."] ["## Getting Started With Hanami and Vega/Vega-lite" "Vega is a declarative format for creating, saving, and sharing data visualizations. Vega-lite is a high-level visualization grammar. It provides a more concise JSON syntax than Vega for supporting rapid generation of visualizations to support analysis. Vega-Lite support static plot generation but also interactive multi-view graphics. Specifications can be compiled to Vega. Hanami is a library that allows you to create Vega and Vega-lite plot specifications in a more user friendly manner by affording a simple API to express the plots through transformations on the templates and thus creating a powerful and fast way to express data visualisations. Before we dive into the details of creating visualizations with Hanami, here are a few preparations to start with"] ["### Importing Hanami"] (require '[aerial.hanami.common :as hanami-common] '[aerial.hanami.templates :as hanami-templates] '[tech.v3.datatype.functional :as dtype-func] '[fastmath.core :as fastmath] '[tablecloth.api :as tablecloth]) ["### For our convenience" "Lets start by defining a conveniance function that makes plot expression syntax slightly less verbose. The function is built so that it will receive the data we want to visualize as a first argument and thus enabling it to be used as is in a thread first, `->`, macro at the end of our data transformations"] (defn hanami-plot "Syntactic sugar for hanami plots, lets you pipe data directly in a thread first macro" [data template & substitutions] (apply hanami-common/xform template :DATA data substitutions)) ^kind/hidden ["### Setting Styles" "We will use the plt.style directive to choose appropriate aesthetic styles for our figures. Here we will set the classic style, which ensures that the plots we create use the classic Matplotlib style:"] ^kind/hidden ["Throughout this section, we will adjust this style as needed. Note that the stylesheets used here are supported as of Matplotlib version 1.5; if you are using an earlier version of Matplotlib, only the default style is available. For more information on stylesheets, see Customizing Matplotlib: Configurations and Style Sheets."] ^kind/hidden ["### `show()` or `No show()`? How to Display Your Plots" "A visualization you can't see won't be of much use, but just how you view your Matplotlib plots depends on the context. The best use of Matplotlib differs depending on how you are using it; roughly, the three applicable contexts are using Matplotlib in a script, in an IPython terminal, or in an IPython notebook."] ^kind/hidden ["#### Plotting from a script" "If you are using Matplotlib from within a script, the function plt.show() is your friend. plt.show() starts an event loop, looks for all currently active figure objects, and opens one or more interactive windows that display your figure or figures. So, for example, you may have a file called myplot.py containing the following:"] ^kind/hidden ["You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:"] ^kind/hidden ["The plt.show() command does a lot under the hood, as it must interact with your system's interactive graphical backend. The details of this operation can vary greatly from system to system and even installation to installation, but matplotlib does its best to hide all these details from you." "One thing to be aware of: the plt.show() command should be used only once per Python session, and is most often seen at the very end of the script. Multiple show() commands can lead to unpredictable backend-dependent behavior, and should mostly be avoided."] ^kind/hidden ["#### Plotting from an IPython shell" "It can be very convenient to use Matplotlib interactively within an IPython shell (see IPython: Beyond Normal Python). IPython is built to work well with Matplotlib if you specify Matplotlib mode. To enable this mode, you can use the %matplotlib magic command after starting ipython:"] ^kind/hidden ["At this point, any plt plot command will cause a figure window to open, and further commands can be run to update the plot. Some changes (such as modifying properties of lines that are already drawn) will not draw automatically: to force an update, use plt.draw(). Using plt.show() in Matplotlib mode is not required."] ["#### Plotting from an Notespace notebook" "We are using notespace to do literate programming and to render the plots. All the sections are decorated with Clojure metadata to let the rendering engine know what we want to happen with the section. `^kind/vega` for instance means that the following output should be rendered as a vega/vega-lite plot. Why we like Notespace is that we can continue to work from the editors we love, be it emacs, vi, vscode, IntelliJ, atom or any other that supports developing Clojure. Lets create some data and see how the process can look."] ^kind/hidden ["### Plotting from an Notespace notebook" "The IPython notebook is a browser-based interactive data analysis tool that can combine narrative, code, graphics, HTML elements, and much more into a single executable document (see IPython: Beyond Normal Python). Plotting interactively within an IPython notebook can be done with the %matplotlib command, and works in a similar way to the IPython shell. In the IPython notebook, you also have the option of embedding graphics directly in the notebook, with two possible options: %matplotlib notebook will lead to interactive plots embedded within the notebook %matplotlib inline will lead to static images of your plot embedded in the notebook After running this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic: TO-DO need to clean all this:"] ["First we will create a range with 100 values from 0 to 10"] (def x-range (fastmath/slice-range 0 10 100)) (take 5 x-range) ["Instead priting all 100 values we just looked at the first 5 there." "Next we'll make a helper function that builds a row in the format that hanami/vega likes it"] (defn map-row "a helper to create a row (=map) of data in the form that vega likes" [label x y] {:x x, :y y, :label label}) ["The following helper uses the helper above and but also appends a new series with a label, x and a y. The x values are given as a parameter and the y values are calculated by applying the function, also passed as parameter, to x."] (defn add-series "append new series with transformation to dataset" [coll f label range] (into coll (map #(map-row label % (f %)) range))) ["Here is an example. We create a series with x as defined above and define y by adding a function that just doubles x"] (take 5 (add-series [] #(* % 2) "double-up" x-range)) ["Now, lets define the data we want to visualize using the sin and cos functions"] (def sin-cos-data (-> [] (add-series dtype-func/sin "sin" x-range) (add-series dtype-func/cos "cos" x-range))) ["This is how the data looks like:"] (take 5 sin-cos-data) ["Not lets plot that:"] (def my-figure (-> sin-cos-data (hanami-plot hanami-templates/line-chart) (#(assoc-in % [:encoding :strokeDash] {:field :label, :type "nominal"})))) ^kind/vega my-figure ^kind/hidden ["### Saving Figures to File One nice feature of Matplotlib is the ability to save figures in a wide variety of formats. Saving a figure can be done using the savefig() command. For example, to save the previous figure as a PNG file, you can run this:"] ["### Saving Figures to File Sometimes we want to to save the plots as files on our filesystem for other usages. Next we will look at how to create save the Vega/Vega-lite plots as SVGs on the filesystem or alternatively as PNG or TIFFs."] ["First we will load some libraries to help us."] (require '[applied-science.darkstar :as darkstar] '[clojure.data.json :as json] '[batik.rasterize :as batik] '[clojure.string :as string]) ["Next we will need a simple helper again to do the saving."] (defn save-plot! [m & [filename type]] (let [svg-render (if (= (:MODE m) "vega") darkstar/vega-spec->svg darkstar/vega-lite-spec->svg)] (->> m json/write-str svg-render (#(if (#{:tif :tiff :png} type) (batik/render-svg-string % filename type) (spit (or filename "plot.svg") %)))))) ["This could be made much more robust with more features, but it will suffice for now. Now we can save the plot, by default our helper saves the file as an SVG but a number of formats can be used."] ^kind/void (save-plot! my-figure "my_figure.svg") ^kind/void (save-plot! my-figure "my_figure.png" :png) ^kind/hidden ["We now have a file called my_figure.png in the current working directory:"] ["We have now saved a file called my_figure.png on the filesystem:"] (require '[clojure.java.shell :refer [sh]]) ^kind/hidden ["!ls -lh my_figure.png"] (string/split-lines (:out (sh "ls" "-lh" "my_figure.png" "my_figure.svg"))) ^kind/hidden ["To confirm that it contains what we think it contains, let's use the IPython Image object to display the contents of this file:"] ^kind/hidden ["from IPython.display import Image Image('my_figure.png')"] ^kind/hidden ["In savefig(), the file format is inferred from the extension of the given filename. Depending on what backends you have installed, many different file formats are available. The list of supported file types can be found for your system by using the following method of the figure canvas object:"] ^kind/hidden [:pre "fig.canvas.get_supported_filetypes()"] ^kind/hidden ["{'eps': 'Encapsulated Postscript', 'jpeg': 'Joint Photographic Experts Group', 'jpg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}"] ^kind/hidden ["Note that when saving your figure, it's not necessary to use plt.show() or related commands discussed earlier."] ^kind/hidden ["## Two Interfaces for the Price of One¶ A potentially confusing feature of Matplotlib is its dual interfaces: a convenient MATLAB-style state-based interface, and a more powerful object-oriented interface. We'll quickly highlight the differences between the two here. ### MATLAB-style interface Matplotlib was originally written as a Python alternative for MATLAB users, and much of its syntax reflects that fact. The MATLAB-style tools are contained in the pyplot (plt) interface. For example, the following code will probably look quite familiar to MATLAB users:"] ^kind/hidden ["plt.figure() # create a plot figure # create the first of two panels and set current axis plt.subplot(2, 1, 1) # (rows, columns, panel number) plt.plot(x, np.sin(x)) # create the second panel and set current axis plt.subplot(2, 1, 2) ["### Another example Now, lets use the previous plot that we still have saved in the my-figure var, and modify it a bit. The definition is just data after all. Lets have a peek. jAgain, not to fill this document with all the data we want to visualize, lets only take the first 5 lines"] (update-in my-figure [:data :values] (partial take 5)) ["What you see there is the vega-lite spec of the plot as a Clojure map but instead of json it is in `edn`, a data format we work with in Clojure and is a bit nicer to read. So what if we want to separate the figures to their own panels that are placed above each other. This can be achieved by adding and transformng these key value pairs in the specification, using the Clojure functions we are used to."] ^kind/vega (-> my-figure (assoc :height 150) (assoc-in [:encoding :row] {:field :label, :type "nominal"})) ^kind/hidden ["### Object-oriented interface The object-oriented interface is available for these more complicated situations, and for when you want more control over your figure. Rather than depending on some notion of an \"active\" figure or axes, in the object-oriented interface the plotting functions are methods of explicit Figure and Axes objects. To re-create the previous plot using this style of plotting, you might do the following:"] ^kind/hidden ["# First create a grid of plots # ax will be an array of two Axes objects fig, ax = plt.subplots(2) # Call plot() method on the appropriate object ax[0].plot(x, np.sin(x)) ^kind/hidden ["For more simple plots, the choice of which style to use is largely a matter of preference, but the object-oriented approach can become a necessity as plots become more complicated. Throughout this chapter, we will switch between the MATLAB-style and object-oriented interfaces, depending on what is most convenient. In most cases, the difference is as small as switching plt.plot() to ax.plot(), but there are a few gotchas that we will highlight as they come up in the following sections."] ["# Simple Line Plots"] ["We have now seen a couple of simple examples how do work with data and do plotting in Clojure with the help of Hanami and Vega/Vega-lite. In the following section we will go through the steps to make simple line plots in a bit more detail."] ^kind/hidden ["Perhaps the simplest of all plots is the visualization of a single function y=f(x). Here we will take a first look at creating a simple plot of this type. As with all the following sections, we'll start by setting up the notebook for plotting and importing the packages we will use:"] ^kind/hidden ["%matplotlib inline import matplotlib.pyplot as plt plt.style.use('seaborn-whitegrid') import numpy as np"] ^kind/hidden ["For all Matplotlib plots, we start by creating a figure and an axes. In their simplest form, a figure and axes can be created as follows:"] ^kind/hidden ["fig = plt.figure() ax = plt.axes()"] ^kind/vega (hanami-plot {} hanami-templates/line-chart :XSCALE {:domain [0 10]} :YSCALE {:domain [-1 1]}) ^kind/hidden ["In Matplotlib, the figure (an instance of the class plt.Figure) can be thought of as a single container that contains all the objects representing axes, graphics, text, and labels. The axes (an instance of the class plt.Axes) is what we see above: a bounding box with ticks and labels, which will eventually contain the plot elements that make up our visualization. Throughout this book, we'll commonly use the variable name fig to refer to a figure instance, and ax to refer to an axes instance or group of axes instances. Once we have created an axes, we can use the ax.plot function to plot some data. Let's start with a simple sinusoid:"] ^kind/hidden ["fig = plt.figure() ax = plt.axes() x = np.linspace(0, 10, 1000) ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin (- x 0))}) x-range) (hanami-plot hanami-templates/line-chart)) ^kind/hidden ["Alternatively, we can use the pylab interface and let the figure and axes be created for us in the background (see Two Interfaces for the Price of One for a discussion of these two interfaces):"] ^kind/vega (-> sin-cos-data (hanami-plot hanami-templates/line-chart) (#(assoc-in % [:encoding :strokeDash] {:field :label, :type "nominal"}))) ^kind/hidden ["That's all there is to plotting simple functions in Matplotlib! We'll now dive into some more details about how to control the appearance of the axes and lines."] ^kind/hidden ["Adjusting the Plot: Line Colors and Styles The first adjustment you might wish to make to a plot is to control the line colors and styles. The plt.plot() function takes additional arguments that can be used to specify these. To adjust the color, you can use the color keyword, which accepts a string argument representing virtually any imaginable color. The color can be specified in a variety of ways:"] ^kind/hidden ["plt.plot(x, np.sin(x - 0), color='blue') # specify color by name plt.plot(x, np.sin(x - 1), color='g') # short color code (rgbcmyk) plt.plot(x, np.sin(x - 2), color='0.75') # Grayscale between 0 and 1 plt.plot(x, np.sin(x - 3), color='#FFDD44') # Hex code (RRGGBB from 00 to FF) plt.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB tuple, values 0 to 1 (def with-manual-colors (-> [] (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 0)), :color "blue"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 1)), :color "green"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 2)), :color "hsl(0, 0%, 75%)"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 3)), :color "#FFDD44"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 4)), :color "rgb(256, 51, 77)"}) x-range)) (into (map (fn [x] {:x x, :y (dtype-func/sin (- x 5)), :color "chartreus"}) x-range)))) ^kind/vega (-> with-manual-colors (hanami-plot hanami-templates/line-chart :COLOR {:field :color, :type "nominal", :scale nil})) ^kind/hidden ["If no color is specified, Matplotlib will automatically cycle through a set of default colors for multiple lines. Similarly, the line style can be adjusted using the linestyle keyword:"] ^kind/hidden ["plt.plot(x, x + 0, linestyle='solid') plt.plot(x, x + 1, linestyle='dashed') plt.plot(x, x + 2, linestyle='dashdot') # For short, you can use the following codes: plt.plot(x, x + 4, linestyle='-') # solid plt.plot(x, x + 5, linestyle='--') # dashed plt.plot(x, x + 6, linestyle='-.') # dashdot (def linestyle {:solid [1 0], "-" [1 0], :dashed [10 10], "--" [10 10], :dashdot [2 5 5 5], "-." [2 5 5 5], :dotted [2 2], ":" [2 2]}) (def stroked-lines (->> [] (into (map (fn [x] {:label 0, :x x, :y (+ x 0), :stroke (:solid linestyle)}) x-range)) (into (map (fn [x] {:label 1, :x x, :y (+ x 1), :stroke (:dashed linestyle)}) x-range)) (into (map (fn [x] {:label 2, :x x, :y (+ x 2), :stroke (:dasheddot linestyle)}) x-range)) (into (map (fn [x] {:label 3, :x x, :y (+ x 3), :stroke (:dotted linestyle)}) x-range)) (into (map (fn [x] {:label 4, :x x, :y (+ x 4), :stroke (get linestyle "-")}) x-range)) (into (map (fn [x] {:label 5, :x x, :y (+ x 5), :stroke (get linestyle "--")}) x-range)) (into (map (fn [x] {:label 6, :x x, :y (+ x 6), :stroke (get linestyle "-.")}) x-range)) (into (map (fn [x] {:label 7, :x x, :y (+ x 7), :stroke (get linestyle ":")}) x-range)))) ^kind/dataset (-> (tablecloth/dataset stroked-lines) (tablecloth/order-by :label)) ^kind/vega (-> stroked-lines (hanami-plot hanami-templates/line-chart :COLOR {:field :label}) (assoc-in [:encoding :strokeDash] {:field :stroke, :scale nil})) ["If you would like to be extremely terse, these linestyle and color codes can be combined into a single non-keyword argument to the plt.plot() function"] ^kind/hidden ["plt.plot(x, x + 0, '-g') # solid green plt.plot(x, x + 1, '--c') # dashed cyan plt.plot(x, x + 2, '-.k') # dashdot black ^kind/hidden ["These single-character color codes reflect the standard abbreviations in the RGB (Red/Green/Blue) and CMYK (Cyan/Magenta/Yellow/blacK) color systems, commonly used for digital color graphics. ^kind/hidden ["## Adjusting the Plot: Axes Limits Matplotlib does a decent job of choosing default axes limits for your plot, but sometimes it's nice to have finer control. The most basic way to adjust axis limits is to use the plt.xlim() and plt.ylim() methods:"] ^kind/hidden ["plt.plot(x, np.sin(x)) plt.xlim(-1, 11) ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [-1.5 1.5]} :XSCALE {:domain [-1 11]} :COLOR {:field :label})) ^kind/hidden ["If for some reason you'd like either axis to be displayed in reverse, you can simply reverse the order of the arguments:"] ^kind/void ["plt.plot(x, np.sin(x)) plt.xlim(10, 0) ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [1.2 -1.2]} :XSCALE {:domain [10 0]} :COLOR {:field :label})) ^kind/hidden ["A useful related method is plt.axis() (note here the potential confusion between axes with an e, and axis with an i). The plt.axis() method allows you to set the x and y limits with a single call, by passing a list which specifies [xmin, xmax, ymin, ymax]:"] ^kind/hidden ["plt.plot(x, np.sin(x)) ^kind/hidden ["The plt.axis() method goes even beyond this, allowing you to do things like automatically tighten the bounds around the current plot:"] ^kind/hidden ["plt.plot(x, np.sin(x)) ["It allows even higher-level specifications, such as ensuring an equal aspect ratio so that on your screen, one unit in x is equal to one unit in y:"] ^kind/hidden ["plt.plot(x, np.sin(x)) ^kind/hidden ["For more information on axis limits and the other capabilities of the plt.axis method, refer to the plt.axis docstring."] ^kind/hidden ["## Labeling Plots As the last piece of this section, we'll briefly look at the labeling of plots: titles, axis labels, and simple legends. Titles and axis labels are the simplest such labels—there are methods that can be used to quickly set them:"] ^kind/vega (-> (map (fn [x] {:x x, :y (dtype-func/sin x)}) x-range) (#(hanami-common/xform hanami-templates/line-chart :TITLE "A Sine Curve" :YTITLE "sin(x)" :DATA %))) ^kind/hidden ["The position, size, and style of these labels can be adjusted using optional arguments to the function. For more information, see the Matplotlib documentation and the docstrings of each of these functions. When multiple lines are being shown within a single axes, it can be useful to create a plot legend that labels each line type. Again, Matplotlib has a built-in way of quickly creating such a legend. It is done via the (you guessed it) plt.legend() method. Though there are several valid ways of using this, I find it easiest to specify the label of each line using the label keyword of the plot function:"] ^kind/hidden ["plt.plot(x, np.sin(x), '-g', label='sin(x)') plt.plot(x, np.cos(x), ':b', label='cos(x)') plt.axis('equal') ^kind/vega (-> [] (into (map (fn [x] {:label "sin(x)", :color "green", :x x, :y (dtype-func/sin x), :stroke (:solid linestyle)}) x-range)) (into (map (fn [x] {:label "cos(x)", :color "blue", :x x, :y (dtype-func/cos x), :stroke (:dotted linestyle)}) x-range)) (hanami-plot hanami-templates/line-chart :YSCALE {:domain [-3 3]} :COLOR {:field :label, :scale {:range {:field :color}}}) (assoc-in [:encoding :strokeDash] {:field :stroke, :scale nil})) ^kind/hidden ["As you can see, the plt.legend() function keeps track of the line style and color, and matches these with the correct label. More information on specifying and formatting plot legends can be found in the plt.legend docstring; additionally, we will cover some more advanced legend options in Customizing Plot Legends."] ^kind/hidden ["## Aside: Matplotlib Gotchas While most plt functions translate directly to ax methods (such as plt.plot() → ax.plot(), plt.legend() → ax.legend(), etc.), this is not the case for all commands. In particular, functions to set limits, labels, and titles are slightly modified. For transitioning between MATLAB-style functions and object-oriented methods, make the following changes: plt.xlabel() → ax.set_xlabel() plt.ylabel() → ax.set_ylabel() plt.xlim() → ax.set_xlim() plt.ylim() → ax.set_ylim() plt.title() → ax.set_title() In the object-oriented interface to plotting, rather than calling these functions individually, it is often more convenient to use the ax.set() method to set all these properties at once:"] ^kind/hidden ["ax = plt.axes() ax.plot(x, np.sin(x)) ax.set(xlim=(0, 10), ylim=(-2, 2), xlabel='x', ylabel='sin(x)',
67cce2a6066bbbf922724c6db7e5e53f92c9e97db6559e1631fb0609ca9ceb89
vyorkin/tiger
semant.ml
open Core_kernel open Err module T = Type module L = Location module U = Unique module S = Symbol module ST = Symbol_table type expr_ty = { expr : Translate.t; ty : T.t; } let ret ty = Trace.Semant.ret_ty ty; { expr = (); ty } let ret_int = ret T.Int let ret_string = ret T.String let ret_nil = ret T.Nil let ret_unit = ret T.Unit let type_mismatch_error4 msg l t1 t2 = let msg' = sprintf "type \"%s\" is expected, but found \"%s\"" (T.to_string t1) (T.to_string t2) in type_error l @@ msg ^ msg' let type_mismatch_error3 l t1 t2 = type_mismatch_error4 "" l t1 t2 let missing_field_error t name = id_error name @@ sprintf "record of type \"%s\" doesn't have field \"%s\"" (T.to_string t) (name.L.value.S.name) let rec trans_prog expr = Trace.Semant.trans_prog expr; ignore @@ trans_expr (L.dummy expr) ~env:(Env.mk ()) and trans_expr expr ~env = let open Syntax in let open Env in let rec assert_ty t expr ~env = Trace.Semant.assert_ty t expr; let { ty; _ } = tr_expr expr ~env in if T.(~!ty <> ~!t) then type_mismatch_error3 expr t ty and assert_int expr ~env = assert_ty T.Int expr ~env and assert_unit expr ~env = assert_ty T.Unit expr ~env and tr_expr expr ~env = Trace.Semant.tr_expr expr; (* Push the current [expr] to the [path] stack *) let env = Env.enter_expr env expr in match expr.L.value with | Var var -> tr_var var ~env | Nil _ -> ret_nil | Int _ -> ret_int | String _ -> ret_string | Call (f, args) -> tr_call f args ~env | Op (l, op, r) -> tr_op expr l r op.L.value ~env | Record (name, fields) -> tr_record name fields ~env | Seq [] -> ret_unit (* in our grammar unit is empty seq *) | Seq exprs -> tr_seq exprs ~env | Assign (var, expr) -> tr_assign var expr ~env | If (cond, t, f) -> tr_cond cond t f ~env | While (cond, body) -> tr_while cond body ~env | For (var, lo, hi, body, _) -> tr_for var lo hi body ~env | Break br -> tr_break br ~env | Let (decs, body) -> tr_let decs body ~env | Array (ty, size, init) -> tr_array ty size init ~env and tr_break br ~env = Trace.Semant.tr_break br env.loop; match env.loop with | Some _ -> ret_unit | None -> syntax_error br "unexpected break statement" and tr_call f args ~env = Trace.Semant.tr_call f args; match ST.look_fun env.venv f with | Env.VarEntry t -> type_error f @@ sprintf "expected function, but found variable \"%s\" of type \"%s\"" (f.L.value.S.name) (T.to_string t) | Env.FunEntry (formals, result) -> (* Check if all the arguments are supplied *) if List.length formals <> List.length args then type_error f @@ sprintf "function \"%s\" expects %d formal arguments, but %d was given" (f.L.value.S.name) (List.length formals) (List.length args) ; List.iter2_exn formals args ~f:(assert_ty ~env); T.(ret ~!result) (* In our language binary operators work only with integer operands, except for (=) and (<>) *) and tr_op expr l r op ~env = Trace.Semant.tr_op l r op; match op with | Syntax.Eq | Syntax.Neq -> assert_comparison expr l r ~env | _ -> assert_op l r ~env and assert_comparison expr l r ~env = let { ty = ty_l; _ } = tr_expr l ~env in let { ty = ty_r; _ } = tr_expr r ~env in if T.(~!ty_l <> ~!ty_r) then type_mismatch_error3 expr ty_l ty_r; ret ty_l and assert_op l r ~env = assert_int l ~env; assert_int r ~env; ret_int and tr_assign var expr ~env = Trace.Semant.tr_assign var expr; let { ty = var_ty; _ } = tr_var var ~env in let { ty = expr_ty; _ } = tr_expr expr ~env in if T.(var_ty = expr_ty) then ret var_ty else type_error expr @@ sprintf "invalid assigment of type \"%s\" to a variable of type \"%s\"" (T.to_string expr_ty) (T.to_string var_ty) (* Type of a sequence is a type of its last expression, but we need to check all previous expressions too *) and tr_seq exprs ~env = Trace.Semant.tr_seq exprs; List.fold_left ~f:(fun _ expr -> tr_expr expr ~env) ~init:ret_unit exprs and tr_cond cond t f ~env = Trace.Semant.tr_cond cond t f; assert_int cond ~env; let { ty = t_ty; _ } = tr_expr t ~env in match f with | None -> ret t_ty | Some f -> (* If there is a false-branch then we should check if types of both branches match *) let { ty = f_ty; _ } = tr_expr f ~env in if T.(t_ty = f_ty) then ret t_ty else type_error expr @@ sprintf "different types of branch expressions: \"%s\" and \"%s\"" (T.to_string t_ty) (T.to_string f_ty) and tr_while cond body ~env = Trace.Semant.tr_while cond body; assert_int cond ~env; assert_unit body ~env:(Env.enter_loop env "while"); ret_unit and tr_for var lo hi body ~env = Trace.Semant.tr_for var lo hi body; assert_int lo ~env; assert_int hi ~env; (* Add iterator var to the term-level env *) let entry = Env.VarEntry T.Int in let venv' = ST.bind_var env.venv var entry in let env = Env.enter_loop { env with venv = venv' } "for" in assert_unit body ~env; ret_unit (* In Tiger declarations appear only in a "let" expression, the let expression modifies both: type-level (tenv) and term-level (value-level/venv) environments *) and tr_let decs body ~env = Trace.Semant.tr_let decs body; (* Update env's according to declarations *) let env' = trans_decs decs ~env in (* Then translate the body expression using the new augmented environments *) trans_expr body ~env:env' (* Then the new environments are discarded *) and tr_record_field rec_typ tfields (name, expr) ~env = Trace.Semant.tr_record_field name expr rec_typ; (* Find a type of the field with [name] *) match List.Assoc.find tfields ~equal:S.equal name.L.value with | Some ty_field -> let { ty = ty_expr; _ } = tr_expr expr ~env in if T.(ty_field @<> ty_expr) then type_mismatch_error3 expr ty_field ty_expr | None -> missing_field_error rec_typ name and tr_record ty_name vfields ~env = let open T in Trace.Semant.tr_record ty_name vfields; (* Get the record type definition *) let rec_typ = ST.look_typ env.tenv ty_name in match ~!rec_typ with | T.Record (tfields, _) -> (* We want to check each field of the variable against the corresponding record type definition *) List.iter ~f:(tr_record_field rec_typ tfields ~env) vfields; ret rec_typ | _ -> type_error ty_name @@ sprintf "\"%s\" is not a record" (T.to_string rec_typ) and tr_array typ size init ~env = let open T in Trace.Semant.tr_array typ size init; assert_int size ~env; let { ty = init_tn; _ } = tr_expr init ~env in (* Find the type of this particular array *) let arr_ty = ST.look_typ env.tenv typ in match ~!arr_ty with | T.Array (tn, _) -> let t = ~!tn in let init_t = ~!init_tn in if t = init_t then ret arr_ty else type_mismatch_error4 "invalid type of array initial value, " init t init_t | _ -> type_error typ @@ sprintf "\"%s\" is not array" (T.to_string arr_ty) and tr_var var ~env = Trace.Semant.tr_var var; match var.L.value with | SimpleVar var -> tr_simple_var var ~env | FieldVar (var, field) -> tr_field_var var field ~env | SubscriptVar (var, sub) -> tr_subscript_var var sub ~env and tr_simple_var var ~env = Trace.Semant.tr_simple_var var; match ST.look_var env.venv var with | Env.VarEntry tn -> T.(ret ~!tn) | Env.FunEntry (formals, result) -> let signature = formals |> List.map ~f:T.to_string |> String.concat ~sep:", " in type_error var @@ sprintf "expected variable, but found a function \"(%s) : %s\"" signature (T.to_string result) and tr_field_var var field ~env = Trace.Semant.tr_field_var var field; (* Find a type of the record variable *) let rec_ty = tr_var var ~env in (* Lets see if its actually a record *) match rec_ty.ty with | Record (fields, _) -> (* Record is just a list of pairs [S.t * Type.t], lets try to find a type for the given [field], it is the type of the [FieldVar] expression *) (match List.Assoc.find fields ~equal:S.equal field.L.value with | Some tt -> T.(ret ~!tt) | None -> missing_field_error rec_ty.ty field) | _ -> type_error var @@ sprintf "expected record, but \"%s\" found" (T.to_string rec_ty.ty) and tr_subscript_var var sub ~env = Trace.Semant.tr_subscript_var var sub; let arr_ty = tr_var var ~env in match arr_ty.ty with | Array (tn, _) -> assert_int sub ~env; T.(ret ~!tn) | _ -> type_error var @@ sprintf "\"%s\" is not an array" (T.to_string arr_ty.ty) in tr_expr expr ~env and trans_decs decs ~env = Trace.Semant.trans_decs decs; List.fold_left decs ~f:(fun env dec -> trans_dec dec ~env) ~init:env (* Modifies and returns value/term-level and type-level environments adding the given declaration [Syntax.dec] *) and trans_dec ~env = function | TypeDec tys -> trans_type_decs tys ~env | FunDec fs -> trans_fun_decs fs ~env | VarDec var -> trans_var_dec var ~env and trans_type_decs tys ~env = let open Syntax in let tr_ty_head (tns, tenv) ty_dec = let typ = ty_dec.L.value.type_name in let tn = ref None in (* Add a type-reference, without body *) let tenv' = ST.bind_typ tenv typ (T.Name (typ.L.value, tn)) in tn :: tns, tenv' in First , we add all the type names to the [ tenv ] let (tns, tenv') = List.fold_left tys ~init:([], env.tenv) ~f:tr_ty_head in let resolve_ty tn ty_dec = let { typ; _ } = ty_dec.L.value in (* Resolve the type body *) let t = trans_ty tenv' typ in tn := Some t in Trace.Semant.trans_type_decs tys; (* Resolve the (possibly mutually recursive) types *) List.iter2_exn (List.rev tns) tys ~f:resolve_ty; { env with tenv = tenv' } (* Checks (possibly mutually-recursive) functions *) and trans_fun_decs fs ~env = let open Syntax in let open Env in let tr_fun_head (sigs, venv) fun_dec = Trace.Semant.trans_fun_head fun_dec; let { fun_name; params; result_typ; _ } = fun_dec.L.value in (* Check function arguments *) let tr_arg f = f.name, ST.look_typ env.tenv f.typ in let args = List.map params ~f:tr_arg in let formals = List.map args ~f:snd in (* Check the result type *) let result = match result_typ with | None -> T.Unit | Some t -> ST.look_typ env.tenv t in let entry = FunEntry (formals, result) in let venv' = ST.bind_fun venv fun_name entry in (args, result) :: sigs, venv' in First , we add all the function entries to the [ venv ] let (sigs, venv') = List.fold_left fs ~f:tr_fun_head ~init:([], env.venv) in let assert_fun_body (args, result) fun_dec = Trace.Semant.assert_fun_body fun_dec result; (* Here, we build another [venv''] to be used for body processing it should have all the arguments in it *) let add_var e (name, ty) = ST.bind_var e name (VarEntry ty) in let venv'' = List.fold_left args ~init:venv' ~f:add_var in let env' = { env with venv = venv'' } in let { body; _ } = fun_dec.L.value in let { ty = body_ty; _ } = trans_expr body ~env:env' in if T.(body_ty <> result) then type_mismatch_error4 "type of the body expression doesn't match the declared result type, " body result body_ty; in Trace.Semant.trans_fun_decs fs; (* Now, lets check the bodies *) List.iter2_exn (List.rev sigs) fs ~f:assert_fun_body; { env with venv = venv' } and assert_init var init_ty ~env = let open Syntax in let open Env in let { var_typ; init; _ } = var.L.value in (* Lets see if the variable is annotated *) match var_typ with | None -> () | Some ann_ty -> (* Check if the init expression has the same type as the variable annotation *) let var_ty = ST.look_typ env.tenv ann_ty in if T.(var_ty @<> init_ty) then type_mismatch_error3 init var_ty init_ty and trans_var_dec var ~env = let open Syntax in Trace.Semant.trans_var_dec var; let { var_name; init; _ } = var.L.value in let { ty = init_ty; _ } = trans_expr init ~env in assert_init var init_ty ~env; (* Add a new var to the term-level env *) let entry = Env.VarEntry init_ty in let venv' = ST.bind_var env.venv var_name entry in { env with venv = venv' } (* Translates AST type expression into a digested type description that we keep in the [tenv] *) and trans_ty tenv typ = let open Syntax in Trace.Semant.trans_ty typ; match typ with | NameTy t -> ST.look_typ tenv t | RecordTy dec_fields -> let to_field { name; typ; _ } = name.L.value, ST.look_typ tenv typ in let ty_fields = List.map dec_fields ~f:to_field in T.Record (ty_fields, U.mk ()) | ArrayTy t -> T.Array (ST.look_typ tenv t, U.mk ())
null
https://raw.githubusercontent.com/vyorkin/tiger/54dd179c1cd291df42f7894abce3ee9064e18def/chapter5/lib/semant.ml
ocaml
Push the current [expr] to the [path] stack in our grammar unit is empty seq Check if all the arguments are supplied In our language binary operators work only with integer operands, except for (=) and (<>) Type of a sequence is a type of its last expression, but we need to check all previous expressions too If there is a false-branch then we should check if types of both branches match Add iterator var to the term-level env In Tiger declarations appear only in a "let" expression, the let expression modifies both: type-level (tenv) and term-level (value-level/venv) environments Update env's according to declarations Then translate the body expression using the new augmented environments Then the new environments are discarded Find a type of the field with [name] Get the record type definition We want to check each field of the variable against the corresponding record type definition Find the type of this particular array Find a type of the record variable Lets see if its actually a record Record is just a list of pairs [S.t * Type.t], lets try to find a type for the given [field], it is the type of the [FieldVar] expression Modifies and returns value/term-level and type-level environments adding the given declaration [Syntax.dec] Add a type-reference, without body Resolve the type body Resolve the (possibly mutually recursive) types Checks (possibly mutually-recursive) functions Check function arguments Check the result type Here, we build another [venv''] to be used for body processing it should have all the arguments in it Now, lets check the bodies Lets see if the variable is annotated Check if the init expression has the same type as the variable annotation Add a new var to the term-level env Translates AST type expression into a digested type description that we keep in the [tenv]
open Core_kernel open Err module T = Type module L = Location module U = Unique module S = Symbol module ST = Symbol_table type expr_ty = { expr : Translate.t; ty : T.t; } let ret ty = Trace.Semant.ret_ty ty; { expr = (); ty } let ret_int = ret T.Int let ret_string = ret T.String let ret_nil = ret T.Nil let ret_unit = ret T.Unit let type_mismatch_error4 msg l t1 t2 = let msg' = sprintf "type \"%s\" is expected, but found \"%s\"" (T.to_string t1) (T.to_string t2) in type_error l @@ msg ^ msg' let type_mismatch_error3 l t1 t2 = type_mismatch_error4 "" l t1 t2 let missing_field_error t name = id_error name @@ sprintf "record of type \"%s\" doesn't have field \"%s\"" (T.to_string t) (name.L.value.S.name) let rec trans_prog expr = Trace.Semant.trans_prog expr; ignore @@ trans_expr (L.dummy expr) ~env:(Env.mk ()) and trans_expr expr ~env = let open Syntax in let open Env in let rec assert_ty t expr ~env = Trace.Semant.assert_ty t expr; let { ty; _ } = tr_expr expr ~env in if T.(~!ty <> ~!t) then type_mismatch_error3 expr t ty and assert_int expr ~env = assert_ty T.Int expr ~env and assert_unit expr ~env = assert_ty T.Unit expr ~env and tr_expr expr ~env = Trace.Semant.tr_expr expr; let env = Env.enter_expr env expr in match expr.L.value with | Var var -> tr_var var ~env | Nil _ -> ret_nil | Int _ -> ret_int | String _ -> ret_string | Call (f, args) -> tr_call f args ~env | Op (l, op, r) -> tr_op expr l r op.L.value ~env | Record (name, fields) -> tr_record name fields ~env | Seq exprs -> tr_seq exprs ~env | Assign (var, expr) -> tr_assign var expr ~env | If (cond, t, f) -> tr_cond cond t f ~env | While (cond, body) -> tr_while cond body ~env | For (var, lo, hi, body, _) -> tr_for var lo hi body ~env | Break br -> tr_break br ~env | Let (decs, body) -> tr_let decs body ~env | Array (ty, size, init) -> tr_array ty size init ~env and tr_break br ~env = Trace.Semant.tr_break br env.loop; match env.loop with | Some _ -> ret_unit | None -> syntax_error br "unexpected break statement" and tr_call f args ~env = Trace.Semant.tr_call f args; match ST.look_fun env.venv f with | Env.VarEntry t -> type_error f @@ sprintf "expected function, but found variable \"%s\" of type \"%s\"" (f.L.value.S.name) (T.to_string t) | Env.FunEntry (formals, result) -> if List.length formals <> List.length args then type_error f @@ sprintf "function \"%s\" expects %d formal arguments, but %d was given" (f.L.value.S.name) (List.length formals) (List.length args) ; List.iter2_exn formals args ~f:(assert_ty ~env); T.(ret ~!result) and tr_op expr l r op ~env = Trace.Semant.tr_op l r op; match op with | Syntax.Eq | Syntax.Neq -> assert_comparison expr l r ~env | _ -> assert_op l r ~env and assert_comparison expr l r ~env = let { ty = ty_l; _ } = tr_expr l ~env in let { ty = ty_r; _ } = tr_expr r ~env in if T.(~!ty_l <> ~!ty_r) then type_mismatch_error3 expr ty_l ty_r; ret ty_l and assert_op l r ~env = assert_int l ~env; assert_int r ~env; ret_int and tr_assign var expr ~env = Trace.Semant.tr_assign var expr; let { ty = var_ty; _ } = tr_var var ~env in let { ty = expr_ty; _ } = tr_expr expr ~env in if T.(var_ty = expr_ty) then ret var_ty else type_error expr @@ sprintf "invalid assigment of type \"%s\" to a variable of type \"%s\"" (T.to_string expr_ty) (T.to_string var_ty) and tr_seq exprs ~env = Trace.Semant.tr_seq exprs; List.fold_left ~f:(fun _ expr -> tr_expr expr ~env) ~init:ret_unit exprs and tr_cond cond t f ~env = Trace.Semant.tr_cond cond t f; assert_int cond ~env; let { ty = t_ty; _ } = tr_expr t ~env in match f with | None -> ret t_ty | Some f -> let { ty = f_ty; _ } = tr_expr f ~env in if T.(t_ty = f_ty) then ret t_ty else type_error expr @@ sprintf "different types of branch expressions: \"%s\" and \"%s\"" (T.to_string t_ty) (T.to_string f_ty) and tr_while cond body ~env = Trace.Semant.tr_while cond body; assert_int cond ~env; assert_unit body ~env:(Env.enter_loop env "while"); ret_unit and tr_for var lo hi body ~env = Trace.Semant.tr_for var lo hi body; assert_int lo ~env; assert_int hi ~env; let entry = Env.VarEntry T.Int in let venv' = ST.bind_var env.venv var entry in let env = Env.enter_loop { env with venv = venv' } "for" in assert_unit body ~env; ret_unit and tr_let decs body ~env = Trace.Semant.tr_let decs body; let env' = trans_decs decs ~env in trans_expr body ~env:env' and tr_record_field rec_typ tfields (name, expr) ~env = Trace.Semant.tr_record_field name expr rec_typ; match List.Assoc.find tfields ~equal:S.equal name.L.value with | Some ty_field -> let { ty = ty_expr; _ } = tr_expr expr ~env in if T.(ty_field @<> ty_expr) then type_mismatch_error3 expr ty_field ty_expr | None -> missing_field_error rec_typ name and tr_record ty_name vfields ~env = let open T in Trace.Semant.tr_record ty_name vfields; let rec_typ = ST.look_typ env.tenv ty_name in match ~!rec_typ with | T.Record (tfields, _) -> List.iter ~f:(tr_record_field rec_typ tfields ~env) vfields; ret rec_typ | _ -> type_error ty_name @@ sprintf "\"%s\" is not a record" (T.to_string rec_typ) and tr_array typ size init ~env = let open T in Trace.Semant.tr_array typ size init; assert_int size ~env; let { ty = init_tn; _ } = tr_expr init ~env in let arr_ty = ST.look_typ env.tenv typ in match ~!arr_ty with | T.Array (tn, _) -> let t = ~!tn in let init_t = ~!init_tn in if t = init_t then ret arr_ty else type_mismatch_error4 "invalid type of array initial value, " init t init_t | _ -> type_error typ @@ sprintf "\"%s\" is not array" (T.to_string arr_ty) and tr_var var ~env = Trace.Semant.tr_var var; match var.L.value with | SimpleVar var -> tr_simple_var var ~env | FieldVar (var, field) -> tr_field_var var field ~env | SubscriptVar (var, sub) -> tr_subscript_var var sub ~env and tr_simple_var var ~env = Trace.Semant.tr_simple_var var; match ST.look_var env.venv var with | Env.VarEntry tn -> T.(ret ~!tn) | Env.FunEntry (formals, result) -> let signature = formals |> List.map ~f:T.to_string |> String.concat ~sep:", " in type_error var @@ sprintf "expected variable, but found a function \"(%s) : %s\"" signature (T.to_string result) and tr_field_var var field ~env = Trace.Semant.tr_field_var var field; let rec_ty = tr_var var ~env in match rec_ty.ty with | Record (fields, _) -> (match List.Assoc.find fields ~equal:S.equal field.L.value with | Some tt -> T.(ret ~!tt) | None -> missing_field_error rec_ty.ty field) | _ -> type_error var @@ sprintf "expected record, but \"%s\" found" (T.to_string rec_ty.ty) and tr_subscript_var var sub ~env = Trace.Semant.tr_subscript_var var sub; let arr_ty = tr_var var ~env in match arr_ty.ty with | Array (tn, _) -> assert_int sub ~env; T.(ret ~!tn) | _ -> type_error var @@ sprintf "\"%s\" is not an array" (T.to_string arr_ty.ty) in tr_expr expr ~env and trans_decs decs ~env = Trace.Semant.trans_decs decs; List.fold_left decs ~f:(fun env dec -> trans_dec dec ~env) ~init:env and trans_dec ~env = function | TypeDec tys -> trans_type_decs tys ~env | FunDec fs -> trans_fun_decs fs ~env | VarDec var -> trans_var_dec var ~env and trans_type_decs tys ~env = let open Syntax in let tr_ty_head (tns, tenv) ty_dec = let typ = ty_dec.L.value.type_name in let tn = ref None in let tenv' = ST.bind_typ tenv typ (T.Name (typ.L.value, tn)) in tn :: tns, tenv' in First , we add all the type names to the [ tenv ] let (tns, tenv') = List.fold_left tys ~init:([], env.tenv) ~f:tr_ty_head in let resolve_ty tn ty_dec = let { typ; _ } = ty_dec.L.value in let t = trans_ty tenv' typ in tn := Some t in Trace.Semant.trans_type_decs tys; List.iter2_exn (List.rev tns) tys ~f:resolve_ty; { env with tenv = tenv' } and trans_fun_decs fs ~env = let open Syntax in let open Env in let tr_fun_head (sigs, venv) fun_dec = Trace.Semant.trans_fun_head fun_dec; let { fun_name; params; result_typ; _ } = fun_dec.L.value in let tr_arg f = f.name, ST.look_typ env.tenv f.typ in let args = List.map params ~f:tr_arg in let formals = List.map args ~f:snd in let result = match result_typ with | None -> T.Unit | Some t -> ST.look_typ env.tenv t in let entry = FunEntry (formals, result) in let venv' = ST.bind_fun venv fun_name entry in (args, result) :: sigs, venv' in First , we add all the function entries to the [ venv ] let (sigs, venv') = List.fold_left fs ~f:tr_fun_head ~init:([], env.venv) in let assert_fun_body (args, result) fun_dec = Trace.Semant.assert_fun_body fun_dec result; let add_var e (name, ty) = ST.bind_var e name (VarEntry ty) in let venv'' = List.fold_left args ~init:venv' ~f:add_var in let env' = { env with venv = venv'' } in let { body; _ } = fun_dec.L.value in let { ty = body_ty; _ } = trans_expr body ~env:env' in if T.(body_ty <> result) then type_mismatch_error4 "type of the body expression doesn't match the declared result type, " body result body_ty; in Trace.Semant.trans_fun_decs fs; List.iter2_exn (List.rev sigs) fs ~f:assert_fun_body; { env with venv = venv' } and assert_init var init_ty ~env = let open Syntax in let open Env in let { var_typ; init; _ } = var.L.value in match var_typ with | None -> () | Some ann_ty -> let var_ty = ST.look_typ env.tenv ann_ty in if T.(var_ty @<> init_ty) then type_mismatch_error3 init var_ty init_ty and trans_var_dec var ~env = let open Syntax in Trace.Semant.trans_var_dec var; let { var_name; init; _ } = var.L.value in let { ty = init_ty; _ } = trans_expr init ~env in assert_init var init_ty ~env; let entry = Env.VarEntry init_ty in let venv' = ST.bind_var env.venv var_name entry in { env with venv = venv' } and trans_ty tenv typ = let open Syntax in Trace.Semant.trans_ty typ; match typ with | NameTy t -> ST.look_typ tenv t | RecordTy dec_fields -> let to_field { name; typ; _ } = name.L.value, ST.look_typ tenv typ in let ty_fields = List.map dec_fields ~f:to_field in T.Record (ty_fields, U.mk ()) | ArrayTy t -> T.Array (ST.look_typ tenv t, U.mk ())
1322d63556f4dc6f31e6bb4da10044e63a1176b184b88f083926c0ca32fa232b
tlringer/plugin-tutorial
termutils.ml
* Utilities for dealing with Coq terms , to abstract away some pain for students * Utilities for dealing with Coq terms, to abstract away some pain for students *) open Evd (* --- State monad --- *) * All terms in Coq have to carry around evar_maps ( found in the Evd module ) , * which store a bunch of constraints about terms that help with things like * unification , type inference , and equality checking . This is annoying to * deal with , so I usually define some helper functions to make it easier . * * These come from -plugin-lib in stateutils.ml , * and the idea to use this design pattern comes from my grad school advisor * . * * For any type ' a , a ' a state is a tuple of an evar_map and a ' a. * So basically , a ' a that carries around an evar_map . * All terms in Coq have to carry around evar_maps (found in the Evd module), * which store a bunch of constraints about terms that help with things like * unification, type inference, and equality checking. This is annoying to * deal with, so I usually define some helper functions to make it easier. * * These come from -plugin-lib in stateutils.ml, * and the idea to use this design pattern comes from my grad school advisor * Dan Grossman. * * For any type 'a, a 'a state is a tuple of an evar_map and a 'a. * So basically, a 'a that carries around an evar_map. *) type 'a state = evar_map * 'a * These are monadic return and bind . Basically , they let you kind of pretend * you 're not in the state monad ( that is , pretend you 're not carrying around * an evar_map with you everywhere ) . If you 've ever used , it 's common * to have syntax that makes this kind of thing look even nicer . * These are monadic return and bind. Basically, they let you kind of pretend * you're not in the state monad (that is, pretend you're not carrying around * an evar_map with you everywhere). If you've ever used Haskell, it's common * to have syntax that makes this kind of thing look even nicer. *) let ret a = fun sigma -> sigma, a let bind f1 f2 = (fun sigma -> let sigma, a = f1 sigma in f2 a sigma) Like List.fold_left , but threading state let fold_left_state f b l sigma = List.fold_left (fun (sigma, b) a -> f b a sigma) (sigma, b) l List List.map , but threading state let map_state f args = bind (fold_left_state (fun bs a sigma -> let sigma, b = f a sigma in sigma, b :: bs) [] args) (fun fargs -> ret (List.rev fargs)) Like , but over arrays let fold_left_state_array f b args = fold_left_state f b (Array.to_list args) (* Like map_state, but over arrays *) let map_state_array f args = bind (map_state f (Array.to_list args)) (fun fargs -> ret (Array.of_list fargs)) (* --- Environments and definitions --- *) * Environments in the Coq kernel map names ( local and global variables ) to definitions and types . Here are a few * utility functions for environments . * Environments in the Coq kernel map names (local and global variables) to definitions and types. Here are a few * utility functions for environments. *) (* * This gets the global environment and the corresponding state: *) let global_env () = let env = Global.env () in Evd.from_env env, env (* Push a local binding to an environment *) let push_local (n, t) env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum (n, t)) env * One of the coolest things about plugins is that you can use them * to define new terms . Here 's a simplified ( yes it looks terrifying , * but it really is simplified ) function for defining new terms and storing them * in the global environment . * * This will only work if the term you produce * type checks in the end , so do n't worry about accidentally proving False . * If you want to use the defined function later in your plugin , you * have to refresh the global environment by calling global_env ( ) again , * but we do n't need that in this plugin . * One of the coolest things about plugins is that you can use them * to define new terms. Here's a simplified (yes it looks terrifying, * but it really is simplified) function for defining new terms and storing them * in the global environment. * * This will only work if the term you produce * type checks in the end, so don't worry about accidentally proving False. * If you want to use the defined function later in your plugin, you * have to refresh the global environment by calling global_env () again, * but we don't need that in this plugin. *) let define name body sigma = let udecl = UState.default_univ_decl in let scope = Locality.Global Locality.ImportDefaultBehavior in let kind = Decls.(IsDefinition Definition) in let cinfo = Declare.CInfo.make ~name ~typ:None () in let info = Declare.Info.make ~scope ~kind ~udecl ~poly:false () in ignore (Declare.declare_definition ~info ~cinfo ~opaque:false ~body sigma) * When you first start using a plugin , if you want to manipulate terms * in an interesting way , you need to move from the external representation * of terms to the internal representation of terms . This does that for you . * When you first start using a plugin, if you want to manipulate terms * in an interesting way, you need to move from the external representation * of terms to the internal representation of terms. This does that for you. *) let internalize env trm sigma = Constrintern.interp_constr_evars env sigma trm (* --- Equality --- *) (* * This checks if there is any set of internal constraints in the state * such that trm1 and trm2 are definitionally equal in the current environment. *) let equal env trm1 trm2 sigma = let opt = Reductionops.infer_conv env sigma trm1 trm2 in match opt with | Some sigma -> sigma, true | None -> sigma, false
null
https://raw.githubusercontent.com/tlringer/plugin-tutorial/e17b9e495782903b3f056e1816e305fdc8283665/src/termutils.ml
ocaml
--- State monad --- Like map_state, but over arrays --- Environments and definitions --- * This gets the global environment and the corresponding state: Push a local binding to an environment --- Equality --- * This checks if there is any set of internal constraints in the state * such that trm1 and trm2 are definitionally equal in the current environment.
* Utilities for dealing with Coq terms , to abstract away some pain for students * Utilities for dealing with Coq terms, to abstract away some pain for students *) open Evd * All terms in Coq have to carry around evar_maps ( found in the Evd module ) , * which store a bunch of constraints about terms that help with things like * unification , type inference , and equality checking . This is annoying to * deal with , so I usually define some helper functions to make it easier . * * These come from -plugin-lib in stateutils.ml , * and the idea to use this design pattern comes from my grad school advisor * . * * For any type ' a , a ' a state is a tuple of an evar_map and a ' a. * So basically , a ' a that carries around an evar_map . * All terms in Coq have to carry around evar_maps (found in the Evd module), * which store a bunch of constraints about terms that help with things like * unification, type inference, and equality checking. This is annoying to * deal with, so I usually define some helper functions to make it easier. * * These come from -plugin-lib in stateutils.ml, * and the idea to use this design pattern comes from my grad school advisor * Dan Grossman. * * For any type 'a, a 'a state is a tuple of an evar_map and a 'a. * So basically, a 'a that carries around an evar_map. *) type 'a state = evar_map * 'a * These are monadic return and bind . Basically , they let you kind of pretend * you 're not in the state monad ( that is , pretend you 're not carrying around * an evar_map with you everywhere ) . If you 've ever used , it 's common * to have syntax that makes this kind of thing look even nicer . * These are monadic return and bind. Basically, they let you kind of pretend * you're not in the state monad (that is, pretend you're not carrying around * an evar_map with you everywhere). If you've ever used Haskell, it's common * to have syntax that makes this kind of thing look even nicer. *) let ret a = fun sigma -> sigma, a let bind f1 f2 = (fun sigma -> let sigma, a = f1 sigma in f2 a sigma) Like List.fold_left , but threading state let fold_left_state f b l sigma = List.fold_left (fun (sigma, b) a -> f b a sigma) (sigma, b) l List List.map , but threading state let map_state f args = bind (fold_left_state (fun bs a sigma -> let sigma, b = f a sigma in sigma, b :: bs) [] args) (fun fargs -> ret (List.rev fargs)) Like , but over arrays let fold_left_state_array f b args = fold_left_state f b (Array.to_list args) let map_state_array f args = bind (map_state f (Array.to_list args)) (fun fargs -> ret (Array.of_list fargs)) * Environments in the Coq kernel map names ( local and global variables ) to definitions and types . Here are a few * utility functions for environments . * Environments in the Coq kernel map names (local and global variables) to definitions and types. Here are a few * utility functions for environments. *) let global_env () = let env = Global.env () in Evd.from_env env, env let push_local (n, t) env = EConstr.push_rel Context.Rel.Declaration.(LocalAssum (n, t)) env * One of the coolest things about plugins is that you can use them * to define new terms . Here 's a simplified ( yes it looks terrifying , * but it really is simplified ) function for defining new terms and storing them * in the global environment . * * This will only work if the term you produce * type checks in the end , so do n't worry about accidentally proving False . * If you want to use the defined function later in your plugin , you * have to refresh the global environment by calling global_env ( ) again , * but we do n't need that in this plugin . * One of the coolest things about plugins is that you can use them * to define new terms. Here's a simplified (yes it looks terrifying, * but it really is simplified) function for defining new terms and storing them * in the global environment. * * This will only work if the term you produce * type checks in the end, so don't worry about accidentally proving False. * If you want to use the defined function later in your plugin, you * have to refresh the global environment by calling global_env () again, * but we don't need that in this plugin. *) let define name body sigma = let udecl = UState.default_univ_decl in let scope = Locality.Global Locality.ImportDefaultBehavior in let kind = Decls.(IsDefinition Definition) in let cinfo = Declare.CInfo.make ~name ~typ:None () in let info = Declare.Info.make ~scope ~kind ~udecl ~poly:false () in ignore (Declare.declare_definition ~info ~cinfo ~opaque:false ~body sigma) * When you first start using a plugin , if you want to manipulate terms * in an interesting way , you need to move from the external representation * of terms to the internal representation of terms . This does that for you . * When you first start using a plugin, if you want to manipulate terms * in an interesting way, you need to move from the external representation * of terms to the internal representation of terms. This does that for you. *) let internalize env trm sigma = Constrintern.interp_constr_evars env sigma trm let equal env trm1 trm2 sigma = let opt = Reductionops.infer_conv env sigma trm1 trm2 in match opt with | Some sigma -> sigma, true | None -> sigma, false
90e9203acc902c742ae618b9c5a7b41e4f83aaa20a516f2b5c3f42e957289cef
sudo-rushil/lambda
Combinator.hs
module Combinator ( module Combinator.Convert , module Combinator.Reduce , module Combinator.Syntax , module Combinator.Transform ) where import Combinator.Convert import Combinator.Reduce import Combinator.Syntax import Combinator.Transform
null
https://raw.githubusercontent.com/sudo-rushil/lambda/70474f5053540a693be2f317062074417a687ff7/src/Combinator.hs
haskell
module Combinator ( module Combinator.Convert , module Combinator.Reduce , module Combinator.Syntax , module Combinator.Transform ) where import Combinator.Convert import Combinator.Reduce import Combinator.Syntax import Combinator.Transform
e8139e2ab1927dcc382dc07bf338f60f43a0d273f360f27ef53ff709ad248602
SumitPadhiyar/confuzz
lwt_unix_jobs.ml
This file is part of Lwt , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) module type Job = sig type 'a t end module Make(Job : Job) = struct external access_job : string -> Unix.access_permission list -> unit Job.t = "lwt_unix_access_job" external chdir_job : string -> unit Job.t = "lwt_unix_chdir_job" external chmod_job : string -> int -> unit Job.t = "lwt_unix_chmod_job" external chown_job : string -> int -> int -> unit Job.t = "lwt_unix_chown_job" external chroot_job : string -> unit Job.t = "lwt_unix_chroot_job" external close_job : Unix.file_descr -> unit Job.t = "lwt_unix_close_job" external fchmod_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_fchmod_job" external fchown_job : Unix.file_descr -> int -> int -> unit Job.t = "lwt_unix_fchown_job" external fdatasync_job : Unix.file_descr -> unit Job.t = "lwt_unix_fdatasync_job" external fsync_job : Unix.file_descr -> unit Job.t = "lwt_unix_fsync_job" external ftruncate_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_ftruncate_job" external ftruncate_64_job : Unix.file_descr -> int64 -> unit Job.t = "lwt_unix_ftruncate_64_job" external link_job : string -> string -> unit Job.t = "lwt_unix_link_job" external lseek_job : Unix.file_descr -> int -> Unix.seek_command -> int Job.t = "lwt_unix_lseek_job" external lseek_64_job : Unix.file_descr -> int64 -> Unix.seek_command -> int64 Job.t = "lwt_unix_lseek_64_job" external mkdir_job : string -> int -> unit Job.t = "lwt_unix_mkdir_job" external mkfifo_job : string -> int -> unit Job.t = "lwt_unix_mkfifo_job" external rename_job : string -> string -> unit Job.t = "lwt_unix_rename_job" external rmdir_job : string -> unit Job.t = "lwt_unix_rmdir_job" external symlink_job : string -> string -> unit Job.t = "lwt_unix_symlink_job" external tcdrain_job : Unix.file_descr -> unit Job.t = "lwt_unix_tcdrain_job" external tcflow_job : Unix.file_descr -> Unix.flow_action -> unit Job.t = "lwt_unix_tcflow_job" external tcflush_job : Unix.file_descr -> Unix.flush_queue -> unit Job.t = "lwt_unix_tcflush_job" external tcsendbreak_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_tcsendbreak_job" external truncate_job : string -> int -> unit Job.t = "lwt_unix_truncate_job" external truncate_64_job : string -> int64 -> unit Job.t = "lwt_unix_truncate_64_job" external unlink_job : string -> unit Job.t = "lwt_unix_unlink_job" end
null
https://raw.githubusercontent.com/SumitPadhiyar/confuzz/7d6b2af51d7135025f9ed1e013a9ae0940f3663e/src/unix/unix_c/lwt_unix_jobs.ml
ocaml
This file is part of Lwt , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) module type Job = sig type 'a t end module Make(Job : Job) = struct external access_job : string -> Unix.access_permission list -> unit Job.t = "lwt_unix_access_job" external chdir_job : string -> unit Job.t = "lwt_unix_chdir_job" external chmod_job : string -> int -> unit Job.t = "lwt_unix_chmod_job" external chown_job : string -> int -> int -> unit Job.t = "lwt_unix_chown_job" external chroot_job : string -> unit Job.t = "lwt_unix_chroot_job" external close_job : Unix.file_descr -> unit Job.t = "lwt_unix_close_job" external fchmod_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_fchmod_job" external fchown_job : Unix.file_descr -> int -> int -> unit Job.t = "lwt_unix_fchown_job" external fdatasync_job : Unix.file_descr -> unit Job.t = "lwt_unix_fdatasync_job" external fsync_job : Unix.file_descr -> unit Job.t = "lwt_unix_fsync_job" external ftruncate_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_ftruncate_job" external ftruncate_64_job : Unix.file_descr -> int64 -> unit Job.t = "lwt_unix_ftruncate_64_job" external link_job : string -> string -> unit Job.t = "lwt_unix_link_job" external lseek_job : Unix.file_descr -> int -> Unix.seek_command -> int Job.t = "lwt_unix_lseek_job" external lseek_64_job : Unix.file_descr -> int64 -> Unix.seek_command -> int64 Job.t = "lwt_unix_lseek_64_job" external mkdir_job : string -> int -> unit Job.t = "lwt_unix_mkdir_job" external mkfifo_job : string -> int -> unit Job.t = "lwt_unix_mkfifo_job" external rename_job : string -> string -> unit Job.t = "lwt_unix_rename_job" external rmdir_job : string -> unit Job.t = "lwt_unix_rmdir_job" external symlink_job : string -> string -> unit Job.t = "lwt_unix_symlink_job" external tcdrain_job : Unix.file_descr -> unit Job.t = "lwt_unix_tcdrain_job" external tcflow_job : Unix.file_descr -> Unix.flow_action -> unit Job.t = "lwt_unix_tcflow_job" external tcflush_job : Unix.file_descr -> Unix.flush_queue -> unit Job.t = "lwt_unix_tcflush_job" external tcsendbreak_job : Unix.file_descr -> int -> unit Job.t = "lwt_unix_tcsendbreak_job" external truncate_job : string -> int -> unit Job.t = "lwt_unix_truncate_job" external truncate_64_job : string -> int64 -> unit Job.t = "lwt_unix_truncate_64_job" external unlink_job : string -> unit Job.t = "lwt_unix_unlink_job" end
1cff722e22f55c2738bf2f5521bca81d0b9c6dc52f6dcde4bd248cd41b8c306d
ghollisjr/cl-ana
logres-test.lisp
cl - ana is a Common Lisp data analysis library . Copyright 2013 - 2015 ;;;; This file is part of cl - ana . ;;;; ;;;; cl-ana 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. ;;;; ;;;; cl-ana 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 cl-ana. If not, see </>. ;;;; You may contact ( me ! ) via email at ;;;; (require 'cl-ana.makeres) (in-package :cl-ana.makeres) (in-project logres-test) (set-project-path "~/logres-test/") (defres source (list (list :x 1) (list :x 2) (list :x 3))) (defres vector (vector 1 2 3 4 5)) (defres (mean x) (/ (sum (mapcar (lambda (x) (getf x :x)) (res source))) (length (res source)))) (defres hash-table (let ((hash-table (make-hash-table :test 'equal))) (setf (gethash 'x hash-table) 'x) hash-table)) (defres nested (let ((ht (make-hash-table :test 'equal))) (setf (gethash 'hash-table ht) (res hash-table)) ht))
null
https://raw.githubusercontent.com/ghollisjr/cl-ana/5cb4c0b0c9c4957452ad2a769d6ff9e8d5df0b10/makeres/logres-test.lisp
lisp
cl-ana is free software: you can redistribute it and/or modify it (at your option) any later version. cl-ana is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with cl-ana. If not, see </>.
cl - ana is a Common Lisp data analysis library . Copyright 2013 - 2015 This file is part of cl - ana . under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License You may contact ( me ! ) via email at (require 'cl-ana.makeres) (in-package :cl-ana.makeres) (in-project logres-test) (set-project-path "~/logres-test/") (defres source (list (list :x 1) (list :x 2) (list :x 3))) (defres vector (vector 1 2 3 4 5)) (defres (mean x) (/ (sum (mapcar (lambda (x) (getf x :x)) (res source))) (length (res source)))) (defres hash-table (let ((hash-table (make-hash-table :test 'equal))) (setf (gethash 'x hash-table) 'x) hash-table)) (defres nested (let ((ht (make-hash-table :test 'equal))) (setf (gethash 'hash-table ht) (res hash-table)) ht))
dd415a2a25ec710cbb1a50db4a754251c2250fcef626678c817edfade9c49240
graninas/The-Amoeba-World
TypeFamilyTest3.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE TypeFamilies # # LANGUAGE ExistentialQuantification # {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} module Main where type Caption = String type Name = String type PlayerName = String data PropertyToken a where IntProperty :: Name -> Int -> PropertyToken Int IntResource :: Name -> (Int, Int) -> PropertyToken (Int, Int) instance Show (PropertyToken Int) where show (IntProperty _ i) = show i instance Show (PropertyToken (Int, Int)) where show (IntResource _ i) = show i class (Show a) => Prop a where type Out a b :: * getProperty :: (a ~ Out b ()) => a -> Out a () printProperty :: a -> String instance Prop (PropertyToken a) where type Out (PropertyToken a) a = a getProperty (IntProperty _ k) = k getProperty (IntResource _ k) = k printProperty (IntProperty _ k) = show k printProperty (IntResource _ k) = show k instance Show (PropertyToken a) where show (IntProperty _ k) = show k show (IntResource _ k) = show k data Wrap = forall p. Prop p => MkWrap p instance Show Wrap where show (MkWrap p) = show p instance Prop Wrap where type Out Wrap a = PropertyToken a getProperty (MkWrap p) = undefined printProperty = undefined type PropList = [Wrap] token1 = MkWrap $ IntProperty "int" 10 token2 = MkWrap $ IntResource "intResource" (10, 1000) tokens = [token1, token2] :: PropList main = do print $ getProperty (IntProperty "a" 10) print $ getProperty (IntResource "b" (20, 20)) print $ map show tokens print tokens let res1 = getProperty $ head tokens -- putStrLn $ printProperty res1 putStrLn "Ok."
null
https://raw.githubusercontent.com/graninas/The-Amoeba-World/a147cd4dabf860bec8a6ae1c45c02b030916ddf4/src/Amoeba/Test/Experiments/TypeFamilies/TypeFamilyTest3.hs
haskell
# LANGUAGE TypeSynonymInstances # # LANGUAGE GADTs # # LANGUAGE RankNTypes # putStrLn $ printProperty res1
# LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # # LANGUAGE ExistentialQuantification # module Main where type Caption = String type Name = String type PlayerName = String data PropertyToken a where IntProperty :: Name -> Int -> PropertyToken Int IntResource :: Name -> (Int, Int) -> PropertyToken (Int, Int) instance Show (PropertyToken Int) where show (IntProperty _ i) = show i instance Show (PropertyToken (Int, Int)) where show (IntResource _ i) = show i class (Show a) => Prop a where type Out a b :: * getProperty :: (a ~ Out b ()) => a -> Out a () printProperty :: a -> String instance Prop (PropertyToken a) where type Out (PropertyToken a) a = a getProperty (IntProperty _ k) = k getProperty (IntResource _ k) = k printProperty (IntProperty _ k) = show k printProperty (IntResource _ k) = show k instance Show (PropertyToken a) where show (IntProperty _ k) = show k show (IntResource _ k) = show k data Wrap = forall p. Prop p => MkWrap p instance Show Wrap where show (MkWrap p) = show p instance Prop Wrap where type Out Wrap a = PropertyToken a getProperty (MkWrap p) = undefined printProperty = undefined type PropList = [Wrap] token1 = MkWrap $ IntProperty "int" 10 token2 = MkWrap $ IntResource "intResource" (10, 1000) tokens = [token1, token2] :: PropList main = do print $ getProperty (IntProperty "a" 10) print $ getProperty (IntResource "b" (20, 20)) print $ map show tokens print tokens let res1 = getProperty $ head tokens putStrLn "Ok."
611373bd02930b31dfff810f3df5b8d7070a004244402a483ea9c16dc29d099d
duncanatt/detecter
cowboy_router.erl
Copyright ( c ) 2011 - 2017 , < > %% %% 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. %% Routing middleware. %% %% Resolve the handler to be used for the request based on the %% routing information found in the <em>dispatch</em> environment value. %% When found, the handler module and associated data are added to %% the environment as the <em>handler</em> and <em>handler_opts</em> values %% respectively. %% %% If the route cannot be found, processing stops with either a 400 or a 404 reply . -module(cowboy_router). -behaviour(cowboy_middleware). -export([compile/1]). -export([execute/2]). -include("log.hrl"). -type bindings() :: #{atom() => any()}. -type tokens() :: [binary()]. -export_type([bindings/0]). -export_type([tokens/0]). -type route_match() :: '_' | iodata(). -type route_path() :: {Path::route_match(), Handler::module(), Opts::any()} | {Path::route_match(), cowboy:fields(), Handler::module(), Opts::any()}. -type route_rule() :: {Host::route_match(), Paths::[route_path()]} | {Host::route_match(), cowboy:fields(), Paths::[route_path()]}. -type routes() :: [route_rule()]. -export_type([routes/0]). -type dispatch_match() :: '_' | <<_:8>> | [binary() | '_' | '...' | atom()]. -type dispatch_path() :: {dispatch_match(), cowboy:fields(), module(), any()}. -type dispatch_rule() :: {Host::dispatch_match(), cowboy:fields(), Paths::[dispatch_path()]}. -opaque dispatch_rules() :: [dispatch_rule()]. -export_type([dispatch_rules/0]). -spec compile(routes()) -> dispatch_rules(). compile(Routes) -> compile(Routes, []). compile([], Acc) -> lists:reverse(Acc); compile([{Host, Paths}|Tail], Acc) -> compile([{Host, [], Paths}|Tail], Acc); compile([{HostMatch, Fields, Paths}|Tail], Acc) -> HostRules = case HostMatch of '_' -> '_'; _ -> compile_host(HostMatch) end, PathRules = compile_paths(Paths, []), Hosts = case HostRules of '_' -> [{'_', Fields, PathRules}]; _ -> [{R, Fields, PathRules} || R <- HostRules] end, compile(Tail, Hosts ++ Acc). compile_host(HostMatch) when is_list(HostMatch) -> compile_host(list_to_binary(HostMatch)); compile_host(HostMatch) when is_binary(HostMatch) -> compile_rules(HostMatch, $., [], [], <<>>). compile_paths([], Acc) -> lists:reverse(Acc); compile_paths([{PathMatch, Handler, Opts}|Tail], Acc) -> compile_paths([{PathMatch, [], Handler, Opts}|Tail], Acc); compile_paths([{PathMatch, Fields, Handler, Opts}|Tail], Acc) when is_list(PathMatch) -> compile_paths([{iolist_to_binary(PathMatch), Fields, Handler, Opts}|Tail], Acc); compile_paths([{'_', Fields, Handler, Opts}|Tail], Acc) -> compile_paths(Tail, [{'_', Fields, Handler, Opts}] ++ Acc); compile_paths([{<<"*">>, Fields, Handler, Opts}|Tail], Acc) -> compile_paths(Tail, [{<<"*">>, Fields, Handler, Opts}|Acc]); compile_paths([{<< $/, PathMatch/bits >>, Fields, Handler, Opts}|Tail], Acc) -> PathRules = compile_rules(PathMatch, $/, [], [], <<>>), Paths = [{lists:reverse(R), Fields, Handler, Opts} || R <- PathRules], compile_paths(Tail, Paths ++ Acc); compile_paths([{PathMatch, _, _, _}|_], _) -> error({badarg, "The following route MUST begin with a slash: " ++ binary_to_list(PathMatch)}). compile_rules(<<>>, _, Segments, Rules, <<>>) -> [Segments|Rules]; compile_rules(<<>>, _, Segments, Rules, Acc) -> [[Acc|Segments]|Rules]; compile_rules(<< S, Rest/bits >>, S, Segments, Rules, <<>>) -> compile_rules(Rest, S, Segments, Rules, <<>>); compile_rules(<< S, Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, [Acc|Segments], Rules, <<>>); %% Colon on path segment start is special, otherwise allow. compile_rules(<< $:, Rest/bits >>, S, Segments, Rules, <<>>) -> {NameBin, Rest2} = compile_binding(Rest, S, <<>>), Name = binary_to_atom(NameBin, utf8), compile_rules(Rest2, S, Segments, Rules, Name); compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) when Acc =:= <<>> -> compile_rules(Rest, S, ['...'|Segments], Rules, Acc); compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc); compile_rules(<< $[, S, Rest/bits >>, S, Segments, Rules, Acc) -> compile_brackets(Rest, S, [Acc|Segments], Rules); compile_rules(<< $[, Rest/bits >>, S, Segments, Rules, <<>>) -> compile_brackets(Rest, S, Segments, Rules); %% Open bracket in the middle of a segment. compile_rules(<< $[, _/bits >>, _, _, _, _) -> error(badarg); %% Missing an open bracket. compile_rules(<< $], _/bits >>, _, _, _, _) -> error(badarg); compile_rules(<< C, Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>). %% Everything past $: until the segment separator ($. for hosts, %% $/ for paths) or $[ or $] or end of binary is the binding name. compile_binding(<<>>, _, <<>>) -> error(badarg); compile_binding(Rest = <<>>, _, Acc) -> {Acc, Rest}; compile_binding(Rest = << C, _/bits >>, S, Acc) when C =:= S; C =:= $[; C =:= $] -> {Acc, Rest}; compile_binding(<< C, Rest/bits >>, S, Acc) -> compile_binding(Rest, S, << Acc/binary, C >>). compile_brackets(Rest, S, Segments, Rules) -> {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0), Rules1 = compile_rules(Rest2, S, Segments, [], <<>>), Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>, S, Segments, [], <<>>), Rules ++ Rules2 ++ Rules1. %% Missing a close bracket. compile_brackets_split(<<>>, _, _) -> error(badarg); %% Make sure we don't confuse the closing bracket we're looking for. compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $[ -> compile_brackets_split(Rest, << Acc/binary, C >>, N + 1); compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $], N > 0 -> compile_brackets_split(Rest, << Acc/binary, C >>, N - 1); %% That's the right one. compile_brackets_split(<< $], Rest/bits >>, Acc, 0) -> {Acc, Rest}; compile_brackets_split(<< C, Rest/bits >>, Acc, N) -> compile_brackets_split(Rest, << Acc/binary, C >>, N). -spec execute(Req, Env) -> {ok, Req, Env} | {stop, Req} when Req:: cowboy_req:req(), Env:: cowboy_middleware:env(). execute(Req=#{host := Host, path := Path}, Env=#{dispatch := Dispatch0}) -> ?TRACE("Attempting to route request from host ~s to path '~s'.", [Host, Path]), Dispatch = case Dispatch0 of {persistent_term, Key} -> persistent_term:get(Key); _ -> Dispatch0 end, case match(Dispatch, Host, Path) of {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} -> ?TRACE("Found ~w handler for request from host ~s to path '~s'.", [Handler, Host, Path]), {ok, Req#{ host_info => HostInfo, path_info => PathInfo, bindings => Bindings }, Env#{ handler => Handler, handler_opts => HandlerOpts }}; {error, notfound, host} -> ?TRACE("Unable to find request handler for host ~s.", [Host]), {stop, cowboy_req:reply(400, Req)}; {error, badrequest, path} -> ?TRACE("Bad request for path '~s'.", [Path]), {stop, cowboy_req:reply(400, Req)}; {error, notfound, path} -> ?TRACE("Unable to find request handler for path '~s'.", [Path]), {stop, cowboy_req:reply(404, Req)} end. Internal . %% Match hostname tokens and path tokens against dispatch rules. %% %% It is typically used for matching tokens for the hostname and path of %% the request against a global dispatch rule for your listener. %% Dispatch rules are a list of < em>{Hostname , > tuples , with < em > PathRules</em > being a list of < em>{Path , HandlerMod , HandlerOpts}</em > . %% %% <em>Hostname</em> and <em>Path</em> are match rules and can be either the %% atom <em>'_'</em>, which matches everything, `<<"*">>', which match the %% wildcard path, or a list of tokens. %% %% Each token can be either a binary, the atom <em>'_'</em>, %% the atom '...' or a named atom. A binary token must match exactly, < em>'_'</em > matches everything for a single token , < em>' ... > matches %% everything for the rest of the tokens and a named atom will bind the %% corresponding token value and return it. %% %% The list of hostname tokens is reversed before matching. For example, if we were to match " www.ninenines.eu " , we would first match " eu " , then %% "ninenines", then "www". This means that in the context of hostnames, %% the <em>'...'</em> atom matches properly the lower levels of the domain %% as would be expected. %% %% When a result is found, this function will return the handler module and %% options found in the dispatch list, a key-value list of bindings and %% the tokens that were matched by the <em>'...'</em> atom for both the %% hostname and path. -spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, host} | {error, notfound, path} | {error, badrequest, path}. match([], _, _) -> {error, notfound, host}; %% If the host is '_' then there can be no constraints. match([{'_', [], PathMatchs}|_Tail], _, Path) -> match_path(PathMatchs, undefined, Path, #{}); match([{HostMatch, Fields, PathMatchs}|Tail], Tokens, Path) when is_list(Tokens) -> case list_match(Tokens, HostMatch, #{}) of false -> match(Tail, Tokens, Path); {true, Bindings, HostInfo} -> HostInfo2 = case HostInfo of undefined -> undefined; _ -> lists:reverse(HostInfo) end, case check_constraints(Fields, Bindings) of {ok, Bindings2} -> match_path(PathMatchs, HostInfo2, Path, Bindings2); nomatch -> match(Tail, Tokens, Path) end end; match(Dispatch, Host, Path) -> match(Dispatch, split_host(Host), Path). -spec match_path([dispatch_path()], HostInfo::undefined | tokens(), binary() | tokens(), bindings()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, path} | {error, badrequest, path}. match_path([], _, _, _) -> {error, notfound, path}; %% If the path is '_' then there can be no constraints. match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; match_path([{<<"*">>, _, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; match_path([_|Tail], HostInfo, <<"*">>, Bindings) -> match_path(Tail, HostInfo, <<"*">>, Bindings); match_path([{PathMatch, Fields, Handler, Opts}|Tail], HostInfo, Tokens, Bindings) when is_list(Tokens) -> case list_match(Tokens, PathMatch, Bindings) of false -> match_path(Tail, HostInfo, Tokens, Bindings); {true, PathBinds, PathInfo} -> case check_constraints(Fields, PathBinds) of {ok, PathBinds2} -> {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo}; nomatch -> match_path(Tail, HostInfo, Tokens, Bindings) end end; match_path(_Dispatch, _HostInfo, badrequest, _Bindings) -> {error, badrequest, path}; match_path(Dispatch, HostInfo, Path, Bindings) -> match_path(Dispatch, HostInfo, split_path(Path), Bindings). check_constraints([], Bindings) -> {ok, Bindings}; check_constraints([Field|Tail], Bindings) when is_atom(Field) -> check_constraints(Tail, Bindings); check_constraints([Field|Tail], Bindings) -> Name = element(1, Field), case Bindings of #{Name := Value0} -> Constraints = element(2, Field), case cowboy_constraints:validate(Value0, Constraints) of {ok, Value} -> check_constraints(Tail, Bindings#{Name => Value}); {error, _} -> nomatch end; _ -> check_constraints(Tail, Bindings) end. -spec split_host(binary()) -> tokens(). split_host(Host) -> split_host(Host, []). split_host(Host, Acc) -> case binary:match(Host, <<".">>) of nomatch when Host =:= <<>> -> Acc; nomatch -> [Host|Acc]; {Pos, _} -> << Segment:Pos/binary, _:8, Rest/bits >> = Host, false = byte_size(Segment) == 0, split_host(Rest, [Segment|Acc]) end. Following RFC2396 , this function may return path segments containing any %% character, including <em>/</em> if, and only if, a <em>/</em> was escaped %% and part of a path segment. -spec split_path(binary()) -> tokens() | badrequest. split_path(<< $/, Path/bits >>) -> split_path(Path, []); split_path(_) -> badrequest. split_path(Path, Acc) -> try case binary:match(Path, <<"/">>) of nomatch when Path =:= <<>> -> remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- Acc]), []); nomatch -> remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- [Path|Acc]]), []); {Pos, _} -> << Segment:Pos/binary, _:8, Rest/bits >> = Path, split_path(Rest, [Segment|Acc]) end catch error:_ -> badrequest end. remove_dot_segments([], Acc) -> lists:reverse(Acc); remove_dot_segments([<<".">>|Segments], Acc) -> remove_dot_segments(Segments, Acc); remove_dot_segments([<<"..">>|Segments], Acc=[]) -> remove_dot_segments(Segments, Acc); remove_dot_segments([<<"..">>|Segments], [_|Acc]) -> remove_dot_segments(Segments, Acc); remove_dot_segments([S|Segments], Acc) -> remove_dot_segments(Segments, [S|Acc]). -ifdef(TEST). remove_dot_segments_test_() -> Tests = [ {[<<"a">>, <<"b">>, <<"c">>, <<".">>, <<"..">>, <<"..">>, <<"g">>], [<<"a">>, <<"g">>]}, {[<<"mid">>, <<"content=5">>, <<"..">>, <<"6">>], [<<"mid">>, <<"6">>]}, {[<<"..">>, <<"a">>], [<<"a">>]} ], [fun() -> R = remove_dot_segments(S, []) end || {S, R} <- Tests]. -endif. -spec list_match(tokens(), dispatch_match(), bindings()) -> {true, bindings(), undefined | tokens()} | false. %% Atom '...' matches any trailing path, stop right now. list_match(List, ['...'], Binds) -> {true, Binds, List}; %% Atom '_' matches anything, continue. list_match([_E|Tail], ['_'|TailMatch], Binds) -> list_match(Tail, TailMatch, Binds); %% Both values match, continue. list_match([E|Tail], [E|TailMatch], Binds) -> list_match(Tail, TailMatch, Binds); %% Bind E to the variable name V and continue, %% unless V was already defined and E isn't identical to the previous value. list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) -> case Binds of @todo This is n't right , the constraint must be applied FIRST %% otherwise we can't check for example ints in both host/path. #{V := E} -> list_match(Tail, TailMatch, Binds); #{V := _} -> false; _ -> list_match(Tail, TailMatch, Binds#{V => E}) end; %% Match complete. list_match([], [], Binds) -> {true, Binds, undefined}; %% Values don't match, stop. list_match(_List, _Match, _Binds) -> false. %% Tests. -ifdef(TEST). compile_test_() -> Tests = [ %% Match any host and path. {[{'_', [{'_', h, o}]}], [{'_', [], [{'_', [], h, o}]}]}, {[{"cowboy.example.org", [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [ {[], [], ha, oa}, {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]}, {[{'_', [{"/path/to/resource/", h, o}]}], [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]}, Cyrillic from a latin1 encoded file . {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128, 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}], [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>, <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>], [], h, o}]}]}, {[{"cowboy.example.org.", [{'_', h, o}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, {[{".cowboy.example.org", [{'_', h, o}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, Cyrillic from a latin1 encoded file . {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176, 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}], [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>, <<208,189,208,181,208,186,208,184,208,185>>], [], [{'_', [], h, o}]}]}, {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}], [{[<<"org">>, <<"example">>, subdomain], [], [ {[<<"hats">>, name, <<"prices">>], [], h, o}]}]}, {[{"ninenines.:_", [{"/hats/:_", h, o}]}], [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]}, {[{"[www.]ninenines.eu", [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [ {[<<"eu">>, <<"ninenines">>], [], [ {[<<"horses">>], [], h, o}, {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}, {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ {[<<"horses">>], [], h, o}, {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, {[{'_', [{"/hats/:page/:number", h, o}]}], [{'_', [], [ {[<<"hats">>, page, number], [], h, o}]}]}, {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [ {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}], [{[<<"eu">>, <<"ninenines">>, '...'], [], [ {[<<"hats">>, '...'], [], h, o}]}]}, %% Path segment containing a colon. {[{'_', [{"/foo/bar:blah", h, o}]}], [{'_', [], [ {[<<"foo">>, <<"bar:blah">>], [], h, o}]}]} ], [{lists:flatten(io_lib:format("~p", [Rt])), fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests]. split_host_test_() -> Tests = [ {<<"">>, []}, {<<"*">>, [<<"*">>]}, {<<"cowboy.ninenines.eu">>, [<<"eu">>, <<"ninenines">>, <<"cowboy">>]}, {<<"ninenines.eu">>, [<<"eu">>, <<"ninenines">>]}, {<<"ninenines.eu.">>, [<<"eu">>, <<"ninenines">>]}, {<<"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">>, [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>, <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>, <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>, <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]} ], [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests]. split_path_test_() -> Tests = [ {<<"/">>, []}, {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]}, {<<"/users">>, [<<"users">>]}, {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]}, {<<"/users/a%20b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]} ], [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests]. match_test_() -> Dispatch = [ {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [ {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []} ]}, {[<<"eu">>, <<"ninenines">>], [], [ {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []}, {'_', [], match_extend, []} ]}, {[var, <<"ninenines">>], [], [ {[<<"threads">>, var], [], match_duplicate_vars, [we, {expect, two}, var, here]} ]}, {[ext, <<"erlang">>], [], [ {'_', [], match_erlang_ext, []} ]}, {'_', [], [ {[<<"users">>, id, <<"friends">>], [], match_users_friends, []}, {'_', [], match_any, []} ]} ], Tests = [ {<<"any">>, <<"/">>, {ok, match_any, [], #{}}}, {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>, {ok, match_any_subdomain_users, [], #{}}}, {<<"www.ninenines.eu">>, <<"/users/42/mails">>, {ok, match_any, [], #{}}}, {<<"www.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}}}, {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>, {error, notfound, path}}, {<<"ninenines.eu">>, <<"/">>, {ok, match_extend, [], #{}}}, {<<"ninenines.eu">>, <<"/users/42/friends">>, {ok, match_extend_users_friends, [], #{id => <<"42">>}}}, {<<"erlang.fr">>, '_', {ok, match_erlang_ext, [], #{ext => <<"fr">>}}}, {<<"any">>, <<"/users/444/friends">>, {ok, match_users_friends, [], #{id => <<"444">>}}}, {<<"any">>, <<"/users//friends">>, {ok, match_users_friends, [], #{id => <<>>}}} ], [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> {ok, Handler, Opts, Binds, undefined, undefined} = match(Dispatch, H, P) end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests]. match_info_test_() -> Dispatch = [ {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []} ]}, {[<<"eu">>, <<"ninenines">>, '...'], [], [ {'_', [], match_any, []} ]} ], Tests = [ {<<"ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [], undefined}}, {<<"bugs.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [<<"bugs">>], undefined}}, {<<"cowboy.bugs.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [<<"cowboy">>, <<"bugs">>], undefined}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>, {ok, match_path, [], #{}, undefined, []}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>, {ok, match_path, [], #{}, undefined, [<<"path_info">>]}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>, {ok, match_path, [], #{}, undefined, [<<"foo">>, <<"bar">>]}} ], [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> R = match(Dispatch, H, P) end} || {H, P, R} <- Tests]. match_constraints_test() -> Dispatch0 = [{'_', [], [{[<<"path">>, value], [{value, int}], match, []}]}], {ok, _, [], #{value := 123}, _, _} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/123">>), {ok, _, [], #{value := 123}, _, _} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/123/">>), {error, notfound, path} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/NaN/">>), Dispatch1 = [{'_', [], [{[<<"path">>, value, <<"more">>], [{value, nonempty}], match, []}]}], {ok, _, [], #{value := <<"something">>}, _, _} = match(Dispatch1, <<"ninenines.eu">>, <<"/path/something/more">>), {error, notfound, path} = match(Dispatch1, <<"ninenines.eu">>, <<"/path//more">>), Dispatch2 = [{'_', [], [{[<<"path">>, username], [{username, fun(_, Value) -> case cowboy_bstr:to_lower(Value) of Value -> {ok, Value}; _ -> {error, not_lowercase} end end}], match, []}]}], {ok, _, [], #{username := <<"essen">>}, _, _} = match(Dispatch2, <<"ninenines.eu">>, <<"/path/essen">>), {error, notfound, path} = match(Dispatch2, <<"ninenines.eu">>, <<"/path/ESSEN">>), ok. match_same_bindings_test() -> Dispatch = [{[same, same], [], [{'_', [], match, []}]}], {ok, _, [], #{same := <<"eu">>}, _, _} = match(Dispatch, <<"eu.eu">>, <<"/">>), {error, notfound, host} = match(Dispatch, <<"ninenines.eu">>, <<"/">>), Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [], [{[<<"path">>, user], [], match, []}]}], {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/essen">>), {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/essen/">>), {error, notfound, path} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/notessen">>), Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}], {ok, _, [], #{same := <<"path">>}, _, _} = match(Dispatch3, <<"ninenines.eu">>, <<"/path/path">>), {error, notfound, path} = match(Dispatch3, <<"ninenines.eu">>, <<"/path/to">>), ok. -endif.
null
https://raw.githubusercontent.com/duncanatt/detecter/95b6a758ce6c60f3b7377c07607f24d126cbdacf/experiments/coordination_2022/src/cowboy/cowboy_router.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. Routing middleware. Resolve the handler to be used for the request based on the routing information found in the <em>dispatch</em> environment value. When found, the handler module and associated data are added to the environment as the <em>handler</em> and <em>handler_opts</em> values respectively. If the route cannot be found, processing stops with either Colon on path segment start is special, otherwise allow. Open bracket in the middle of a segment. Missing an open bracket. Everything past $: until the segment separator ($. for hosts, $/ for paths) or $[ or $] or end of binary is the binding name. Missing a close bracket. Make sure we don't confuse the closing bracket we're looking for. That's the right one. Match hostname tokens and path tokens against dispatch rules. It is typically used for matching tokens for the hostname and path of the request against a global dispatch rule for your listener. <em>Hostname</em> and <em>Path</em> are match rules and can be either the atom <em>'_'</em>, which matches everything, `<<"*">>', which match the wildcard path, or a list of tokens. Each token can be either a binary, the atom <em>'_'</em>, the atom '...' or a named atom. A binary token must match exactly, everything for the rest of the tokens and a named atom will bind the corresponding token value and return it. The list of hostname tokens is reversed before matching. For example, if "ninenines", then "www". This means that in the context of hostnames, the <em>'...'</em> atom matches properly the lower levels of the domain as would be expected. When a result is found, this function will return the handler module and options found in the dispatch list, a key-value list of bindings and the tokens that were matched by the <em>'...'</em> atom for both the hostname and path. If the host is '_' then there can be no constraints. If the path is '_' then there can be no constraints. character, including <em>/</em> if, and only if, a <em>/</em> was escaped and part of a path segment. Atom '...' matches any trailing path, stop right now. Atom '_' matches anything, continue. Both values match, continue. Bind E to the variable name V and continue, unless V was already defined and E isn't identical to the previous value. otherwise we can't check for example ints in both host/path. Match complete. Values don't match, stop. Tests. Match any host and path. Path segment containing a colon.
Copyright ( c ) 2011 - 2017 , < > 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 a 400 or a 404 reply . -module(cowboy_router). -behaviour(cowboy_middleware). -export([compile/1]). -export([execute/2]). -include("log.hrl"). -type bindings() :: #{atom() => any()}. -type tokens() :: [binary()]. -export_type([bindings/0]). -export_type([tokens/0]). -type route_match() :: '_' | iodata(). -type route_path() :: {Path::route_match(), Handler::module(), Opts::any()} | {Path::route_match(), cowboy:fields(), Handler::module(), Opts::any()}. -type route_rule() :: {Host::route_match(), Paths::[route_path()]} | {Host::route_match(), cowboy:fields(), Paths::[route_path()]}. -type routes() :: [route_rule()]. -export_type([routes/0]). -type dispatch_match() :: '_' | <<_:8>> | [binary() | '_' | '...' | atom()]. -type dispatch_path() :: {dispatch_match(), cowboy:fields(), module(), any()}. -type dispatch_rule() :: {Host::dispatch_match(), cowboy:fields(), Paths::[dispatch_path()]}. -opaque dispatch_rules() :: [dispatch_rule()]. -export_type([dispatch_rules/0]). -spec compile(routes()) -> dispatch_rules(). compile(Routes) -> compile(Routes, []). compile([], Acc) -> lists:reverse(Acc); compile([{Host, Paths}|Tail], Acc) -> compile([{Host, [], Paths}|Tail], Acc); compile([{HostMatch, Fields, Paths}|Tail], Acc) -> HostRules = case HostMatch of '_' -> '_'; _ -> compile_host(HostMatch) end, PathRules = compile_paths(Paths, []), Hosts = case HostRules of '_' -> [{'_', Fields, PathRules}]; _ -> [{R, Fields, PathRules} || R <- HostRules] end, compile(Tail, Hosts ++ Acc). compile_host(HostMatch) when is_list(HostMatch) -> compile_host(list_to_binary(HostMatch)); compile_host(HostMatch) when is_binary(HostMatch) -> compile_rules(HostMatch, $., [], [], <<>>). compile_paths([], Acc) -> lists:reverse(Acc); compile_paths([{PathMatch, Handler, Opts}|Tail], Acc) -> compile_paths([{PathMatch, [], Handler, Opts}|Tail], Acc); compile_paths([{PathMatch, Fields, Handler, Opts}|Tail], Acc) when is_list(PathMatch) -> compile_paths([{iolist_to_binary(PathMatch), Fields, Handler, Opts}|Tail], Acc); compile_paths([{'_', Fields, Handler, Opts}|Tail], Acc) -> compile_paths(Tail, [{'_', Fields, Handler, Opts}] ++ Acc); compile_paths([{<<"*">>, Fields, Handler, Opts}|Tail], Acc) -> compile_paths(Tail, [{<<"*">>, Fields, Handler, Opts}|Acc]); compile_paths([{<< $/, PathMatch/bits >>, Fields, Handler, Opts}|Tail], Acc) -> PathRules = compile_rules(PathMatch, $/, [], [], <<>>), Paths = [{lists:reverse(R), Fields, Handler, Opts} || R <- PathRules], compile_paths(Tail, Paths ++ Acc); compile_paths([{PathMatch, _, _, _}|_], _) -> error({badarg, "The following route MUST begin with a slash: " ++ binary_to_list(PathMatch)}). compile_rules(<<>>, _, Segments, Rules, <<>>) -> [Segments|Rules]; compile_rules(<<>>, _, Segments, Rules, Acc) -> [[Acc|Segments]|Rules]; compile_rules(<< S, Rest/bits >>, S, Segments, Rules, <<>>) -> compile_rules(Rest, S, Segments, Rules, <<>>); compile_rules(<< S, Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, [Acc|Segments], Rules, <<>>); compile_rules(<< $:, Rest/bits >>, S, Segments, Rules, <<>>) -> {NameBin, Rest2} = compile_binding(Rest, S, <<>>), Name = binary_to_atom(NameBin, utf8), compile_rules(Rest2, S, Segments, Rules, Name); compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) when Acc =:= <<>> -> compile_rules(Rest, S, ['...'|Segments], Rules, Acc); compile_rules(<< $[, $., $., $., $], Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, ['...', Acc|Segments], Rules, Acc); compile_rules(<< $[, S, Rest/bits >>, S, Segments, Rules, Acc) -> compile_brackets(Rest, S, [Acc|Segments], Rules); compile_rules(<< $[, Rest/bits >>, S, Segments, Rules, <<>>) -> compile_brackets(Rest, S, Segments, Rules); compile_rules(<< $[, _/bits >>, _, _, _, _) -> error(badarg); compile_rules(<< $], _/bits >>, _, _, _, _) -> error(badarg); compile_rules(<< C, Rest/bits >>, S, Segments, Rules, Acc) -> compile_rules(Rest, S, Segments, Rules, << Acc/binary, C >>). compile_binding(<<>>, _, <<>>) -> error(badarg); compile_binding(Rest = <<>>, _, Acc) -> {Acc, Rest}; compile_binding(Rest = << C, _/bits >>, S, Acc) when C =:= S; C =:= $[; C =:= $] -> {Acc, Rest}; compile_binding(<< C, Rest/bits >>, S, Acc) -> compile_binding(Rest, S, << Acc/binary, C >>). compile_brackets(Rest, S, Segments, Rules) -> {Bracket, Rest2} = compile_brackets_split(Rest, <<>>, 0), Rules1 = compile_rules(Rest2, S, Segments, [], <<>>), Rules2 = compile_rules(<< Bracket/binary, Rest2/binary >>, S, Segments, [], <<>>), Rules ++ Rules2 ++ Rules1. compile_brackets_split(<<>>, _, _) -> error(badarg); compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $[ -> compile_brackets_split(Rest, << Acc/binary, C >>, N + 1); compile_brackets_split(<< C, Rest/bits >>, Acc, N) when C =:= $], N > 0 -> compile_brackets_split(Rest, << Acc/binary, C >>, N - 1); compile_brackets_split(<< $], Rest/bits >>, Acc, 0) -> {Acc, Rest}; compile_brackets_split(<< C, Rest/bits >>, Acc, N) -> compile_brackets_split(Rest, << Acc/binary, C >>, N). -spec execute(Req, Env) -> {ok, Req, Env} | {stop, Req} when Req:: cowboy_req:req(), Env:: cowboy_middleware:env(). execute(Req=#{host := Host, path := Path}, Env=#{dispatch := Dispatch0}) -> ?TRACE("Attempting to route request from host ~s to path '~s'.", [Host, Path]), Dispatch = case Dispatch0 of {persistent_term, Key} -> persistent_term:get(Key); _ -> Dispatch0 end, case match(Dispatch, Host, Path) of {ok, Handler, HandlerOpts, Bindings, HostInfo, PathInfo} -> ?TRACE("Found ~w handler for request from host ~s to path '~s'.", [Handler, Host, Path]), {ok, Req#{ host_info => HostInfo, path_info => PathInfo, bindings => Bindings }, Env#{ handler => Handler, handler_opts => HandlerOpts }}; {error, notfound, host} -> ?TRACE("Unable to find request handler for host ~s.", [Host]), {stop, cowboy_req:reply(400, Req)}; {error, badrequest, path} -> ?TRACE("Bad request for path '~s'.", [Path]), {stop, cowboy_req:reply(400, Req)}; {error, notfound, path} -> ?TRACE("Unable to find request handler for path '~s'.", [Path]), {stop, cowboy_req:reply(404, Req)} end. Internal . Dispatch rules are a list of < em>{Hostname , > tuples , with < em > PathRules</em > being a list of < em>{Path , HandlerMod , HandlerOpts}</em > . < em>'_'</em > matches everything for a single token , < em>' ... > matches we were to match " www.ninenines.eu " , we would first match " eu " , then -spec match(dispatch_rules(), Host::binary() | tokens(), Path::binary()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, host} | {error, notfound, path} | {error, badrequest, path}. match([], _, _) -> {error, notfound, host}; match([{'_', [], PathMatchs}|_Tail], _, Path) -> match_path(PathMatchs, undefined, Path, #{}); match([{HostMatch, Fields, PathMatchs}|Tail], Tokens, Path) when is_list(Tokens) -> case list_match(Tokens, HostMatch, #{}) of false -> match(Tail, Tokens, Path); {true, Bindings, HostInfo} -> HostInfo2 = case HostInfo of undefined -> undefined; _ -> lists:reverse(HostInfo) end, case check_constraints(Fields, Bindings) of {ok, Bindings2} -> match_path(PathMatchs, HostInfo2, Path, Bindings2); nomatch -> match(Tail, Tokens, Path) end end; match(Dispatch, Host, Path) -> match(Dispatch, split_host(Host), Path). -spec match_path([dispatch_path()], HostInfo::undefined | tokens(), binary() | tokens(), bindings()) -> {ok, module(), any(), bindings(), HostInfo::undefined | tokens(), PathInfo::undefined | tokens()} | {error, notfound, path} | {error, badrequest, path}. match_path([], _, _, _) -> {error, notfound, path}; match_path([{'_', [], Handler, Opts}|_Tail], HostInfo, _, Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; match_path([{<<"*">>, _, Handler, Opts}|_Tail], HostInfo, <<"*">>, Bindings) -> {ok, Handler, Opts, Bindings, HostInfo, undefined}; match_path([_|Tail], HostInfo, <<"*">>, Bindings) -> match_path(Tail, HostInfo, <<"*">>, Bindings); match_path([{PathMatch, Fields, Handler, Opts}|Tail], HostInfo, Tokens, Bindings) when is_list(Tokens) -> case list_match(Tokens, PathMatch, Bindings) of false -> match_path(Tail, HostInfo, Tokens, Bindings); {true, PathBinds, PathInfo} -> case check_constraints(Fields, PathBinds) of {ok, PathBinds2} -> {ok, Handler, Opts, PathBinds2, HostInfo, PathInfo}; nomatch -> match_path(Tail, HostInfo, Tokens, Bindings) end end; match_path(_Dispatch, _HostInfo, badrequest, _Bindings) -> {error, badrequest, path}; match_path(Dispatch, HostInfo, Path, Bindings) -> match_path(Dispatch, HostInfo, split_path(Path), Bindings). check_constraints([], Bindings) -> {ok, Bindings}; check_constraints([Field|Tail], Bindings) when is_atom(Field) -> check_constraints(Tail, Bindings); check_constraints([Field|Tail], Bindings) -> Name = element(1, Field), case Bindings of #{Name := Value0} -> Constraints = element(2, Field), case cowboy_constraints:validate(Value0, Constraints) of {ok, Value} -> check_constraints(Tail, Bindings#{Name => Value}); {error, _} -> nomatch end; _ -> check_constraints(Tail, Bindings) end. -spec split_host(binary()) -> tokens(). split_host(Host) -> split_host(Host, []). split_host(Host, Acc) -> case binary:match(Host, <<".">>) of nomatch when Host =:= <<>> -> Acc; nomatch -> [Host|Acc]; {Pos, _} -> << Segment:Pos/binary, _:8, Rest/bits >> = Host, false = byte_size(Segment) == 0, split_host(Rest, [Segment|Acc]) end. Following RFC2396 , this function may return path segments containing any -spec split_path(binary()) -> tokens() | badrequest. split_path(<< $/, Path/bits >>) -> split_path(Path, []); split_path(_) -> badrequest. split_path(Path, Acc) -> try case binary:match(Path, <<"/">>) of nomatch when Path =:= <<>> -> remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- Acc]), []); nomatch -> remove_dot_segments(lists:reverse([cow_uri:urldecode(S) || S <- [Path|Acc]]), []); {Pos, _} -> << Segment:Pos/binary, _:8, Rest/bits >> = Path, split_path(Rest, [Segment|Acc]) end catch error:_ -> badrequest end. remove_dot_segments([], Acc) -> lists:reverse(Acc); remove_dot_segments([<<".">>|Segments], Acc) -> remove_dot_segments(Segments, Acc); remove_dot_segments([<<"..">>|Segments], Acc=[]) -> remove_dot_segments(Segments, Acc); remove_dot_segments([<<"..">>|Segments], [_|Acc]) -> remove_dot_segments(Segments, Acc); remove_dot_segments([S|Segments], Acc) -> remove_dot_segments(Segments, [S|Acc]). -ifdef(TEST). remove_dot_segments_test_() -> Tests = [ {[<<"a">>, <<"b">>, <<"c">>, <<".">>, <<"..">>, <<"..">>, <<"g">>], [<<"a">>, <<"g">>]}, {[<<"mid">>, <<"content=5">>, <<"..">>, <<"6">>], [<<"mid">>, <<"6">>]}, {[<<"..">>, <<"a">>], [<<"a">>]} ], [fun() -> R = remove_dot_segments(S, []) end || {S, R} <- Tests]. -endif. -spec list_match(tokens(), dispatch_match(), bindings()) -> {true, bindings(), undefined | tokens()} | false. list_match(List, ['...'], Binds) -> {true, Binds, List}; list_match([_E|Tail], ['_'|TailMatch], Binds) -> list_match(Tail, TailMatch, Binds); list_match([E|Tail], [E|TailMatch], Binds) -> list_match(Tail, TailMatch, Binds); list_match([E|Tail], [V|TailMatch], Binds) when is_atom(V) -> case Binds of @todo This is n't right , the constraint must be applied FIRST #{V := E} -> list_match(Tail, TailMatch, Binds); #{V := _} -> false; _ -> list_match(Tail, TailMatch, Binds#{V => E}) end; list_match([], [], Binds) -> {true, Binds, undefined}; list_match(_List, _Match, _Binds) -> false. -ifdef(TEST). compile_test_() -> Tests = [ {[{'_', [{'_', h, o}]}], [{'_', [], [{'_', [], h, o}]}]}, {[{"cowboy.example.org", [{"/", ha, oa}, {"/path/to/resource", hb, ob}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [ {[], [], ha, oa}, {[<<"path">>, <<"to">>, <<"resource">>], [], hb, ob}]}]}, {[{'_', [{"/path/to/resource/", h, o}]}], [{'_', [], [{[<<"path">>, <<"to">>, <<"resource">>], [], h, o}]}]}, Cyrillic from a latin1 encoded file . {[{'_', [{[47,208,191,209,131,209,130,209,140,47,208,186,47,209,128, 208,181,209,129,209,131,209,128,209,129,209,131,47], h, o}]}], [{'_', [], [{[<<208,191,209,131,209,130,209,140>>, <<208,186>>, <<209,128,208,181,209,129,209,131,209,128,209,129,209,131>>], [], h, o}]}]}, {[{"cowboy.example.org.", [{'_', h, o}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, {[{".cowboy.example.org", [{'_', h, o}]}], [{[<<"org">>, <<"example">>, <<"cowboy">>], [], [{'_', [], h, o}]}]}, Cyrillic from a latin1 encoded file . {[{[208,189,208,181,208,186,208,184,208,185,46,209,129,208,176, 208,185,209,130,46,209,128,209,132,46], [{'_', h, o}]}], [{[<<209,128,209,132>>, <<209,129,208,176,208,185,209,130>>, <<208,189,208,181,208,186,208,184,208,185>>], [], [{'_', [], h, o}]}]}, {[{":subdomain.example.org", [{"/hats/:name/prices", h, o}]}], [{[<<"org">>, <<"example">>, subdomain], [], [ {[<<"hats">>, name, <<"prices">>], [], h, o}]}]}, {[{"ninenines.:_", [{"/hats/:_", h, o}]}], [{['_', <<"ninenines">>], [], [{[<<"hats">>, '_'], [], h, o}]}]}, {[{"[www.]ninenines.eu", [{"/horses", h, o}, {"/hats/[page/:number]", h, o}]}], [ {[<<"eu">>, <<"ninenines">>], [], [ {[<<"horses">>], [], h, o}, {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}, {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ {[<<"horses">>], [], h, o}, {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, {[{'_', [{"/hats/:page/:number", h, o}]}], [{'_', [], [ {[<<"hats">>, page, number], [], h, o}]}]}, {[{'_', [{"/hats/[page/[:number]]", h, o}]}], [{'_', [], [ {[<<"hats">>], [], h, o}, {[<<"hats">>, <<"page">>], [], h, o}, {[<<"hats">>, <<"page">>, number], [], h, o}]}]}, {[{"[...]ninenines.eu", [{"/hats/[...]", h, o}]}], [{[<<"eu">>, <<"ninenines">>, '...'], [], [ {[<<"hats">>, '...'], [], h, o}]}]}, {[{'_', [{"/foo/bar:blah", h, o}]}], [{'_', [], [ {[<<"foo">>, <<"bar:blah">>], [], h, o}]}]} ], [{lists:flatten(io_lib:format("~p", [Rt])), fun() -> Rs = compile(Rt) end} || {Rt, Rs} <- Tests]. split_host_test_() -> Tests = [ {<<"">>, []}, {<<"*">>, [<<"*">>]}, {<<"cowboy.ninenines.eu">>, [<<"eu">>, <<"ninenines">>, <<"cowboy">>]}, {<<"ninenines.eu">>, [<<"eu">>, <<"ninenines">>]}, {<<"ninenines.eu.">>, [<<"eu">>, <<"ninenines">>]}, {<<"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">>, [<<"z">>, <<"y">>, <<"x">>, <<"w">>, <<"v">>, <<"u">>, <<"t">>, <<"s">>, <<"r">>, <<"q">>, <<"p">>, <<"o">>, <<"n">>, <<"m">>, <<"l">>, <<"k">>, <<"j">>, <<"i">>, <<"h">>, <<"g">>, <<"f">>, <<"e">>, <<"d">>, <<"c">>, <<"b">>, <<"a">>]} ], [{H, fun() -> R = split_host(H) end} || {H, R} <- Tests]. split_path_test_() -> Tests = [ {<<"/">>, []}, {<<"/extend//cowboy">>, [<<"extend">>, <<>>, <<"cowboy">>]}, {<<"/users">>, [<<"users">>]}, {<<"/users/42/friends">>, [<<"users">>, <<"42">>, <<"friends">>]}, {<<"/users/a%20b/c%21d">>, [<<"users">>, <<"a b">>, <<"c!d">>]} ], [{P, fun() -> R = split_path(P) end} || {P, R} <- Tests]. match_test_() -> Dispatch = [ {[<<"eu">>, <<"ninenines">>, '_', <<"www">>], [], [ {[<<"users">>, '_', <<"mails">>], [], match_any_subdomain_users, []} ]}, {[<<"eu">>, <<"ninenines">>], [], [ {[<<"users">>, id, <<"friends">>], [], match_extend_users_friends, []}, {'_', [], match_extend, []} ]}, {[var, <<"ninenines">>], [], [ {[<<"threads">>, var], [], match_duplicate_vars, [we, {expect, two}, var, here]} ]}, {[ext, <<"erlang">>], [], [ {'_', [], match_erlang_ext, []} ]}, {'_', [], [ {[<<"users">>, id, <<"friends">>], [], match_users_friends, []}, {'_', [], match_any, []} ]} ], Tests = [ {<<"any">>, <<"/">>, {ok, match_any, [], #{}}}, {<<"www.any.ninenines.eu">>, <<"/users/42/mails">>, {ok, match_any_subdomain_users, [], #{}}}, {<<"www.ninenines.eu">>, <<"/users/42/mails">>, {ok, match_any, [], #{}}}, {<<"www.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}}}, {<<"www.any.ninenines.eu">>, <<"/not_users/42/mails">>, {error, notfound, path}}, {<<"ninenines.eu">>, <<"/">>, {ok, match_extend, [], #{}}}, {<<"ninenines.eu">>, <<"/users/42/friends">>, {ok, match_extend_users_friends, [], #{id => <<"42">>}}}, {<<"erlang.fr">>, '_', {ok, match_erlang_ext, [], #{ext => <<"fr">>}}}, {<<"any">>, <<"/users/444/friends">>, {ok, match_users_friends, [], #{id => <<"444">>}}}, {<<"any">>, <<"/users//friends">>, {ok, match_users_friends, [], #{id => <<>>}}} ], [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> {ok, Handler, Opts, Binds, undefined, undefined} = match(Dispatch, H, P) end} || {H, P, {ok, Handler, Opts, Binds}} <- Tests]. match_info_test_() -> Dispatch = [ {[<<"eu">>, <<"ninenines">>, <<"www">>], [], [ {[<<"pathinfo">>, <<"is">>, <<"next">>, '...'], [], match_path, []} ]}, {[<<"eu">>, <<"ninenines">>, '...'], [], [ {'_', [], match_any, []} ]} ], Tests = [ {<<"ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [], undefined}}, {<<"bugs.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [<<"bugs">>], undefined}}, {<<"cowboy.bugs.ninenines.eu">>, <<"/">>, {ok, match_any, [], #{}, [<<"cowboy">>, <<"bugs">>], undefined}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next">>, {ok, match_path, [], #{}, undefined, []}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/path_info">>, {ok, match_path, [], #{}, undefined, [<<"path_info">>]}}, {<<"www.ninenines.eu">>, <<"/pathinfo/is/next/foo/bar">>, {ok, match_path, [], #{}, undefined, [<<"foo">>, <<"bar">>]}} ], [{lists:flatten(io_lib:format("~p, ~p", [H, P])), fun() -> R = match(Dispatch, H, P) end} || {H, P, R} <- Tests]. match_constraints_test() -> Dispatch0 = [{'_', [], [{[<<"path">>, value], [{value, int}], match, []}]}], {ok, _, [], #{value := 123}, _, _} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/123">>), {ok, _, [], #{value := 123}, _, _} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/123/">>), {error, notfound, path} = match(Dispatch0, <<"ninenines.eu">>, <<"/path/NaN/">>), Dispatch1 = [{'_', [], [{[<<"path">>, value, <<"more">>], [{value, nonempty}], match, []}]}], {ok, _, [], #{value := <<"something">>}, _, _} = match(Dispatch1, <<"ninenines.eu">>, <<"/path/something/more">>), {error, notfound, path} = match(Dispatch1, <<"ninenines.eu">>, <<"/path//more">>), Dispatch2 = [{'_', [], [{[<<"path">>, username], [{username, fun(_, Value) -> case cowboy_bstr:to_lower(Value) of Value -> {ok, Value}; _ -> {error, not_lowercase} end end}], match, []}]}], {ok, _, [], #{username := <<"essen">>}, _, _} = match(Dispatch2, <<"ninenines.eu">>, <<"/path/essen">>), {error, notfound, path} = match(Dispatch2, <<"ninenines.eu">>, <<"/path/ESSEN">>), ok. match_same_bindings_test() -> Dispatch = [{[same, same], [], [{'_', [], match, []}]}], {ok, _, [], #{same := <<"eu">>}, _, _} = match(Dispatch, <<"eu.eu">>, <<"/">>), {error, notfound, host} = match(Dispatch, <<"ninenines.eu">>, <<"/">>), Dispatch2 = [{[<<"eu">>, <<"ninenines">>, user], [], [{[<<"path">>, user], [], match, []}]}], {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/essen">>), {ok, _, [], #{user := <<"essen">>}, _, _} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/essen/">>), {error, notfound, path} = match(Dispatch2, <<"essen.ninenines.eu">>, <<"/path/notessen">>), Dispatch3 = [{'_', [], [{[same, same], [], match, []}]}], {ok, _, [], #{same := <<"path">>}, _, _} = match(Dispatch3, <<"ninenines.eu">>, <<"/path/path">>), {error, notfound, path} = match(Dispatch3, <<"ninenines.eu">>, <<"/path/to">>), ok. -endif.
5f2f2703f5700eabae88c31d2797dcb716d1c946d1e4d46a0c52e757cec40ab4
thattommyhall/offline-4clojure
p58.clj
;; Function Composition - Medium ;; Write a function which allows you to create function compositions. The parameter list should take a variable number of functions, and create a function applies them from right-to-left. ;; tags - higher-order-functions:core-functions ;; restricted - comp (ns offline-4clojure.p58 (:use clojure.test)) (def __ ;; your solution here ) (defn -main [] (are [soln] soln (= [3 2 1] ((__ rest reverse) [1 2 3 4])) (= 5 ((__ (partial + 3) second) [1 2 3 4])) (= true ((__ zero? #(mod % 8) +) 3 5 7 9)) (= "HELLO" ((__ #(.toUpperCase %) #(apply str %) take) 5 "hello world")) ))
null
https://raw.githubusercontent.com/thattommyhall/offline-4clojure/73e32fc6687816aea3c514767cef3916176589ab/src/offline_4clojure/p58.clj
clojure
Function Composition - Medium Write a function which allows you to create function compositions. The parameter list should take a variable number of functions, and create a function applies them from right-to-left. tags - higher-order-functions:core-functions restricted - comp your solution here
(ns offline-4clojure.p58 (:use clojure.test)) (def __ ) (defn -main [] (are [soln] soln (= [3 2 1] ((__ rest reverse) [1 2 3 4])) (= 5 ((__ (partial + 3) second) [1 2 3 4])) (= true ((__ zero? #(mod % 8) +) 3 5 7 9)) (= "HELLO" ((__ #(.toUpperCase %) #(apply str %) take) 5 "hello world")) ))
43d8e5d61dd475d238592ca0dcd3578ebc39f7c8841e8b1589042ba7dc53fd3d
input-output-hk/ouroboros-network
Server.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} # LANGUAGE UndecidableInstances # module Ouroboros.Consensus.MiniProtocol.LocalTxSubmission.Server ( localTxSubmissionServer -- * Trace events , TraceLocalTxSubmissionServerEvent (..) ) where import Control.Tracer import Ouroboros.Network.Protocol.LocalTxSubmission.Server import Ouroboros.Network.Protocol.LocalTxSubmission.Type import Ouroboros.Consensus.Ledger.SupportsMempool import Ouroboros.Consensus.Mempool.API import Ouroboros.Consensus.Util.IOLike | Local transaction submission server , for adding to the ' ' -- localTxSubmissionServer :: MonadSTM m => Tracer m (TraceLocalTxSubmissionServerEvent blk) -> Mempool m blk -> LocalTxSubmissionServer (GenTx blk) (ApplyTxErr blk) m () localTxSubmissionServer tracer mempool = server where server = LocalTxSubmissionServer { recvMsgSubmitTx = \tx -> do traceWith tracer $ TraceReceivedTx tx res <- addLocalTxs mempool [tx] case res of [addTxRes] -> case addTxRes of MempoolTxAdded _tx -> return (SubmitSuccess, server) MempoolTxRejected _tx addTxErr -> return (SubmitFail addTxErr, server) -- The output list of addTxs has the same length as the input list. _ -> error "addTxs: unexpected result" , recvMsgDone = () } ------------------------------------------------------------------------------ Trace events ------------------------------------------------------------------------------ Trace events -------------------------------------------------------------------------------} data TraceLocalTxSubmissionServerEvent blk = TraceReceivedTx (GenTx blk) -- ^ A transaction was received. deriving instance Eq (GenTx blk) => Eq (TraceLocalTxSubmissionServerEvent blk) deriving instance Show (GenTx blk) => Show (TraceLocalTxSubmissionServerEvent blk)
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/ebb34fa4d1ba1357e3b803a49f750d2ae3df19e5/ouroboros-consensus/src/Ouroboros/Consensus/MiniProtocol/LocalTxSubmission/Server.hs
haskell
# LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # * Trace events The output list of addTxs has the same length as the input list. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -----------------------------------------------------------------------------} ^ A transaction was received.
# LANGUAGE FlexibleContexts # # LANGUAGE UndecidableInstances # module Ouroboros.Consensus.MiniProtocol.LocalTxSubmission.Server ( localTxSubmissionServer , TraceLocalTxSubmissionServerEvent (..) ) where import Control.Tracer import Ouroboros.Network.Protocol.LocalTxSubmission.Server import Ouroboros.Network.Protocol.LocalTxSubmission.Type import Ouroboros.Consensus.Ledger.SupportsMempool import Ouroboros.Consensus.Mempool.API import Ouroboros.Consensus.Util.IOLike | Local transaction submission server , for adding to the ' ' localTxSubmissionServer :: MonadSTM m => Tracer m (TraceLocalTxSubmissionServerEvent blk) -> Mempool m blk -> LocalTxSubmissionServer (GenTx blk) (ApplyTxErr blk) m () localTxSubmissionServer tracer mempool = server where server = LocalTxSubmissionServer { recvMsgSubmitTx = \tx -> do traceWith tracer $ TraceReceivedTx tx res <- addLocalTxs mempool [tx] case res of [addTxRes] -> case addTxRes of MempoolTxAdded _tx -> return (SubmitSuccess, server) MempoolTxRejected _tx addTxErr -> return (SubmitFail addTxErr, server) _ -> error "addTxs: unexpected result" , recvMsgDone = () } Trace events Trace events data TraceLocalTxSubmissionServerEvent blk = TraceReceivedTx (GenTx blk) deriving instance Eq (GenTx blk) => Eq (TraceLocalTxSubmissionServerEvent blk) deriving instance Show (GenTx blk) => Show (TraceLocalTxSubmissionServerEvent blk)
9574f732e1a9d254534a1a8efa45fc6eac3b9e2c6cbd1380a4a2e3885c7cf638
ghuysmans/ocaml-fet
teachers.ml
type t = Teacher.t let header = ["Teacher"] let of_list = function | [t] -> Teacher.of_string t | _ -> failwith "Teachers.of_list" let to_list t = [No_plus.to_string t]
null
https://raw.githubusercontent.com/ghuysmans/ocaml-fet/e1f2ce9e500e16e6d181baf9e440ede21d740ef7/lib/teachers.ml
ocaml
type t = Teacher.t let header = ["Teacher"] let of_list = function | [t] -> Teacher.of_string t | _ -> failwith "Teachers.of_list" let to_list t = [No_plus.to_string t]
0c72830ba32ed5f942a9d9d9aabe5a660a8c0baf8c93de6170b859aa77fe047d
YoshikuniJujo/test_haskell
Middle.hs
# OPTIONS_GHC -Wall -fno - warn - tabs # module Gpu.Vulkan.CommandPool.Middle ( -- * Type C, -- * Create and Destroy create, destroy, CreateInfo(..) ) where import Gpu.Vulkan.CommandPool.Middle.Internal
null
https://raw.githubusercontent.com/YoshikuniJujo/test_haskell/6ea44c1048805a62979669c185ab32ba9f4d2e02/themes/gui/vulkan/try-vulkan-middle/src/Gpu/Vulkan/CommandPool/Middle.hs
haskell
* Type * Create and Destroy
# OPTIONS_GHC -Wall -fno - warn - tabs # module Gpu.Vulkan.CommandPool.Middle ( C, create, destroy, CreateInfo(..) ) where import Gpu.Vulkan.CommandPool.Middle.Internal
b532c9f34301358e714553cefe1ae4e9a03c5c8b9608337e0de61a3b96c15e00
andrewthad/packed
Set.hs
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # {-# OPTIONS_GHC -Weverything -fno-warn-unsafe -fno-warn-implicit-prelude -fno-warn-missing-import-lists #-} module Packed.Bytes.Set ( ByteSet(..) , member , fromList , invert ) where import Data.Primitive (ByteArray) import Data.Semigroup (Semigroup) import Control.Monad.ST (ST,runST) import Data.Word (Word8) import Data.Bits ((.|.),complement) import Control.Monad (forM_) import qualified Data.Primitive as PM import qualified Data.Semigroup as SG data ByteSet = ByteSet {-# UNPACK #-} !ByteArray instance Semigroup ByteSet where (<>) = append instance Monoid ByteSet where mappend = (SG.<>) mempty = empty append :: ByteSet -> ByteSet -> ByteSet append (ByteSet a) (ByteSet b) = ByteSet (zipOrMach 256 a b) empty :: ByteSet empty = ByteSet $ runST $ do marr <- PM.newByteArray 256 PM.fillByteArray marr 0 256 0 PM.unsafeFreezeByteArray marr fromList :: [Word8] -> ByteSet fromList ws = runST $ do marr <- PM.newByteArray 256 PM.fillByteArray marr 0 256 0 forM_ ws $ \w -> do PM.writeByteArray marr (word8ToInt w) (0xFF :: Word8) arr <- PM.unsafeFreezeByteArray marr return (ByteSet arr) invert :: ByteSet -> ByteSet invert (ByteSet arr) = runST $ do marr <- PM.newByteArray 256 let go !ix = if ix < quot 256 (PM.sizeOf (undefined :: Word)) then do PM.writeByteArray marr ix (complement (PM.indexByteArray arr ix :: Word)) go (ix + 1) else return () go 0 newArr <- PM.unsafeFreezeByteArray marr return (ByteSet newArr) word8ToInt :: Word8 -> Int word8ToInt = fromIntegral member :: Word8 -> ByteSet -> Bool member !w (ByteSet arr) = PM.indexByteArray arr (word8ToInt w) == (0xFF :: Word8) -- The machine word size must divide into the length evenly, but this is -- unchecked. zipOrMach :: Int -- len -> ByteArray -- x -> ByteArray -- y -> ByteArray -- z zipOrMach !len !x !y = runST action where action :: forall s. ST s ByteArray action = do let !lenMach = quot len (PM.sizeOf (undefined :: Word)) !marr <- PM.newByteArray len let goMach :: Int -> ST s () goMach !ix = if ix < lenMach then do PM.writeByteArray marr ix (unsafeIndexWord x ix .|. unsafeIndexWord y ix) goMach (ix + 1) else return () goMach 0 PM.unsafeFreezeByteArray marr -- this is only used internally unsafeIndexWord :: ByteArray -> Int -> Word unsafeIndexWord = PM.indexByteArray
null
https://raw.githubusercontent.com/andrewthad/packed/72437b5f99fbe745897a0a27cae72565c9727781/src/Packed/Bytes/Set.hs
haskell
# LANGUAGE BangPatterns # # LANGUAGE RankNTypes # # OPTIONS_GHC -Weverything -fno-warn-unsafe -fno-warn-implicit-prelude -fno-warn-missing-import-lists # # UNPACK # The machine word size must divide into the length evenly, but this is unchecked. len x y z this is only used internally
# LANGUAGE ScopedTypeVariables # module Packed.Bytes.Set ( ByteSet(..) , member , fromList , invert ) where import Data.Primitive (ByteArray) import Data.Semigroup (Semigroup) import Control.Monad.ST (ST,runST) import Data.Word (Word8) import Data.Bits ((.|.),complement) import Control.Monad (forM_) import qualified Data.Primitive as PM import qualified Data.Semigroup as SG instance Semigroup ByteSet where (<>) = append instance Monoid ByteSet where mappend = (SG.<>) mempty = empty append :: ByteSet -> ByteSet -> ByteSet append (ByteSet a) (ByteSet b) = ByteSet (zipOrMach 256 a b) empty :: ByteSet empty = ByteSet $ runST $ do marr <- PM.newByteArray 256 PM.fillByteArray marr 0 256 0 PM.unsafeFreezeByteArray marr fromList :: [Word8] -> ByteSet fromList ws = runST $ do marr <- PM.newByteArray 256 PM.fillByteArray marr 0 256 0 forM_ ws $ \w -> do PM.writeByteArray marr (word8ToInt w) (0xFF :: Word8) arr <- PM.unsafeFreezeByteArray marr return (ByteSet arr) invert :: ByteSet -> ByteSet invert (ByteSet arr) = runST $ do marr <- PM.newByteArray 256 let go !ix = if ix < quot 256 (PM.sizeOf (undefined :: Word)) then do PM.writeByteArray marr ix (complement (PM.indexByteArray arr ix :: Word)) go (ix + 1) else return () go 0 newArr <- PM.unsafeFreezeByteArray marr return (ByteSet newArr) word8ToInt :: Word8 -> Int word8ToInt = fromIntegral member :: Word8 -> ByteSet -> Bool member !w (ByteSet arr) = PM.indexByteArray arr (word8ToInt w) == (0xFF :: Word8) zipOrMach :: zipOrMach !len !x !y = runST action where action :: forall s. ST s ByteArray action = do let !lenMach = quot len (PM.sizeOf (undefined :: Word)) !marr <- PM.newByteArray len let goMach :: Int -> ST s () goMach !ix = if ix < lenMach then do PM.writeByteArray marr ix (unsafeIndexWord x ix .|. unsafeIndexWord y ix) goMach (ix + 1) else return () goMach 0 PM.unsafeFreezeByteArray marr unsafeIndexWord :: ByteArray -> Int -> Word unsafeIndexWord = PM.indexByteArray
a2fc7e36f0e781fee78e8b01cf33d6e456f620d9cbd73a582a9bf91134e449a2
stanfordhaskell/cs43
Main.hs
module Main where import Control.DeepSeq import Control.Parallel.Strategies hiding (parPair, evalList, rdeepseq) main :: IO () main = do putStrLn "hello world" fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) ------------------------------------------- -- Lazy Evaluation ------------------------------------------- -- Non-strict vs Lazy evaluation ghci > let x = 3 : : Int ghci > let x = 1 + 2 : : Int -- ghci> let z = (x, x) -- ghci> let z = (x, x + 1) ghci > let xs = map ( + 1 ) [ 1 .. 10 ] : : [ Int ] ------------------------------------------- ------------------------------------------- data Eval a instance runEval : : Eval a - > a rpar : : a - > Eval a rseq : : a - > Eval a data Eval a instance Monad Eval runEval :: Eval a -> a rpar :: a -> Eval a rseq :: a -> Eval a -} TODO rpar TODO sudoku ------------------------------------------- -- NFData ------------------------------------------- class NFData a where rnf : : a - > ( ) rnf a = a ` seq ` ( ) instance NFData Bool class NFData a where rnf :: a -> () rnf a = a `seq` () instance NFData Bool -} data Tree a = Empty | Branch (Tree a) a (Tree a) instance NFData a => NFData (Tree a) where rnf Empty = () rnf (Branch l a r) = rnf l `seq` rnf a `seq` rnf r deepseq : : NFData a = > a - > b - > b deepseq a b = rnf a ` seq ` b force : : NFData a = > a - > a force x = x ` deepseq ` x deepseq :: NFData a => a -> b -> b deepseq a b = rnf a `seq` b force :: NFData a => a -> a force x = x `deepseq` x -} ------------------------------------------- -- Evaluation Strategies ------------------------------------------- -- type Strategy a = a -> Eval a parPair :: Strategy (a,b) parPair (a,b) = do a' <- rpar a b' <- rpar b return (a',b') -- ghci> (fib 17, fib 18) -- ghci> runEval (parPair (fib 17, fib 18)) {- using :: a -> Strategy a -> a x `using` s = runEval (s x) -} -- ghci> (fib 17, fib 18) `using` parPair evalPair :: Strategy a -> Strategy b -> Strategy (a,b) evalPair sa sb (a,b) = do a' <- sa a b' <- sb b return (a',b') parPair' :: Strategy (a,b) parPair' = evalPair rpar rpar -- fully evaluates arguments rdeepseq :: NFData a => Strategy a rdeepseq x = rseq (force x) -- wrap strategy in rpar -- rparWith :: Strategy a -> Strategy a parPair'' :: Strategy a -> Strategy b -> Strategy (a,b) parPair'' sa sb = evalPair (rparWith sa) (rparWith sb) deepParPair :: (NFData a, NFData b) => Strategy (a,b) deepParPair = parPair'' rdeepseq rdeepseq evalList :: Strategy a -> Strategy [a] evalList strat [] = return [] evalList strat (x:xs) = do x' <- strat x xs' <- evalList strat xs return (x':xs') parList :: Strategy a -> Strategy [a] parList strat = evalList (rparWith strat)
null
https://raw.githubusercontent.com/stanfordhaskell/cs43/8353da9e27336a7fe23488c3536e0dab4aaabfff/lecture-code/week9/src/Main.hs
haskell
----------------------------------------- Lazy Evaluation ----------------------------------------- Non-strict vs Lazy evaluation ghci> let z = (x, x) ghci> let z = (x, x + 1) ----------------------------------------- ----------------------------------------- ----------------------------------------- NFData ----------------------------------------- ----------------------------------------- Evaluation Strategies ----------------------------------------- type Strategy a = a -> Eval a ghci> (fib 17, fib 18) ghci> runEval (parPair (fib 17, fib 18)) using :: a -> Strategy a -> a x `using` s = runEval (s x) ghci> (fib 17, fib 18) `using` parPair fully evaluates arguments wrap strategy in rpar rparWith :: Strategy a -> Strategy a
module Main where import Control.DeepSeq import Control.Parallel.Strategies hiding (parPair, evalList, rdeepseq) main :: IO () main = do putStrLn "hello world" fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) ghci > let x = 3 : : Int ghci > let x = 1 + 2 : : Int ghci > let xs = map ( + 1 ) [ 1 .. 10 ] : : [ Int ] data Eval a instance runEval : : Eval a - > a rpar : : a - > Eval a rseq : : a - > Eval a data Eval a instance Monad Eval runEval :: Eval a -> a rpar :: a -> Eval a rseq :: a -> Eval a -} TODO rpar TODO sudoku class NFData a where rnf : : a - > ( ) rnf a = a ` seq ` ( ) instance NFData Bool class NFData a where rnf :: a -> () rnf a = a `seq` () instance NFData Bool -} data Tree a = Empty | Branch (Tree a) a (Tree a) instance NFData a => NFData (Tree a) where rnf Empty = () rnf (Branch l a r) = rnf l `seq` rnf a `seq` rnf r deepseq : : NFData a = > a - > b - > b deepseq a b = rnf a ` seq ` b force : : NFData a = > a - > a force x = x ` deepseq ` x deepseq :: NFData a => a -> b -> b deepseq a b = rnf a `seq` b force :: NFData a => a -> a force x = x `deepseq` x -} parPair :: Strategy (a,b) parPair (a,b) = do a' <- rpar a b' <- rpar b return (a',b') evalPair :: Strategy a -> Strategy b -> Strategy (a,b) evalPair sa sb (a,b) = do a' <- sa a b' <- sb b return (a',b') parPair' :: Strategy (a,b) parPair' = evalPair rpar rpar rdeepseq :: NFData a => Strategy a rdeepseq x = rseq (force x) parPair'' :: Strategy a -> Strategy b -> Strategy (a,b) parPair'' sa sb = evalPair (rparWith sa) (rparWith sb) deepParPair :: (NFData a, NFData b) => Strategy (a,b) deepParPair = parPair'' rdeepseq rdeepseq evalList :: Strategy a -> Strategy [a] evalList strat [] = return [] evalList strat (x:xs) = do x' <- strat x xs' <- evalList strat xs return (x':xs') parList :: Strategy a -> Strategy [a] parList strat = evalList (rparWith strat)
39dfd5184b2e1a37a5ba427df568c77129b8331d88b46b93dd2c819ff717c54e
nikodemus/SBCL
macros.lisp
lots of basic macros for the target SBCL This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB!IMPL") ASSERT and CHECK - TYPE ASSERT is written this way , to call - ERROR , because of how ;;; closures are compiled. RESTART-CASE has forms with closures that ;;; the compiler causes to be generated at the top of any function using RESTART - CASE , regardless of whether they are needed . Thus if we just wrapped a RESTART - CASE around the call to ERROR , we 'd have ;;; to do a significant amount of work at runtime allocating and ;;; deallocating the closures regardless of whether they were ever ;;; needed. ;;; ASSERT - ERROR is n't defined until a later file because it uses the ;;; macro RESTART-CASE, which isn't defined until a later file. (defmacro-mundanely assert (test-form &optional places datum &rest arguments) #!+sb-doc "Signals an error if the value of test-form is nil. Continuing from this error using the CONTINUE restart will allow the user to alter the value of some locations known to SETF, starting over with test-form. Returns NIL." `(do () (,test-form) (assert-error ',test-form ',places ,datum ,@arguments) ,@(mapcar (lambda (place) `(setf ,place (assert-prompt ',place ,place))) places))) (defun assert-prompt (name value) (cond ((y-or-n-p "The old value of ~S is ~S.~ ~%Do you want to supply a new value? " name value) (format *query-io* "~&Type a form to be evaluated:~%") (flet ((read-it () (eval (read *query-io*)))) (if (symbolp name) ;help user debug lexical variables (progv (list name) (list value) (read-it)) (read-it)))) (t value))) ;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because ;;; of how closures are compiled. RESTART-CASE has forms with closures ;;; that the compiler causes to be generated at the top of any ;;; function using RESTART-CASE, regardless of whether they are ;;; needed. Because it would be nice if CHECK-TYPE were cheap to use, ;;; and some things (e.g., READ-CHAR) can't afford this excessive ;;; consing, we bend backwards a little. ;;; ;;; CHECK-TYPE-ERROR isn't defined until a later file because it uses ;;; the macro RESTART-CASE, which isn't defined until a later file. (defmacro-mundanely check-type (place type &optional type-string &environment env) #!+sb-doc "Signal a restartable error of type TYPE-ERROR if the value of PLACE is not of the specified type. If an error is signalled and the restart is used to return, this can only return if the STORE-VALUE restart is invoked. In that case it will store into PLACE and start over." ;; Detect a common user-error. (when (and (consp type) (eq 'quote (car type))) (error 'simple-reference-error :format-control "Quoted type specifier in ~S: ~S" :format-arguments (list 'check-type type) :references (list '(:ansi-cl :macro check-type)))) : We use a simpler form of expansion if PLACE is just a variable to work around Python 's blind spot in type derivation . ;; For more complex places getting the type derived should not ;; matter so much anyhow. (let ((expanded (%macroexpand place env))) (if (symbolp expanded) `(do () ((typep ,place ',type)) (setf ,place (check-type-error ',place ,place ',type ,type-string))) (let ((value (gensym))) `(do ((,value ,place ,place)) ((typep ,value ',type)) (setf ,place (check-type-error ',place ,value ',type ,type-string))))))) ;;;; DEFINE-SYMBOL-MACRO (defmacro-mundanely define-symbol-macro (name expansion) `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%define-symbol-macro ',name ',expansion (sb!c:source-location)))) (defun sb!c::%define-symbol-macro (name expansion source-location) (unless (symbolp name) (error 'simple-type-error :datum name :expected-type 'symbol :format-control "Symbol macro name is not a symbol: ~S." :format-arguments (list name))) (with-single-package-locked-error (:symbol name "defining ~A as a symbol-macro")) (sb!c:with-source-location (source-location) (setf (info :source-location :symbol-macro name) source-location)) (let ((kind (info :variable :kind name))) (ecase kind ((:macro :unknown) (setf (info :variable :kind name) :macro) (setf (info :variable :macro-expansion name) expansion)) ((:special :global) (error 'simple-program-error :format-control "Symbol macro name already declared ~A: ~S." :format-arguments (list kind name))) (:constant (error 'simple-program-error :format-control "Symbol macro name already defined as a constant: ~S." :format-arguments (list name))))) name) ;;;; DEFINE-COMPILER-MACRO (defmacro-mundanely define-compiler-macro (name lambda-list &body body) #!+sb-doc "Define a compiler-macro for NAME." (legal-fun-name-or-type-error name) (when (and (symbolp name) (special-operator-p name)) (error 'simple-program-error :format-control "cannot define a compiler-macro for a special operator: ~S" :format-arguments (list name))) (with-unique-names (whole environment) (multiple-value-bind (body local-decs doc) (parse-defmacro lambda-list whole body name 'define-compiler-macro :environment environment) (let ((def `(lambda (,whole ,environment) ,@local-decs ,body)) (debug-name (sb!c::debug-name 'compiler-macro-function name))) `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc ',debug-name)))))) ;;; FIXME: This will look remarkably similar to those who have already ;;; seen the code for %DEFMACRO in src/code/defmacro.lisp. Various bits of logic should be shared ( notably arglist setting ) . (macrolet ((def (times set-p) `(eval-when (,@times) (defun sb!c::%define-compiler-macro (name definition lambda-list doc debug-name) ,@(unless set-p '((declare (ignore lambda-list debug-name)))) ;; FIXME: warn about incompatible lambda list with ;; respect to parent function? (setf (sb!xc:compiler-macro-function name) definition) ,(when set-p `(setf (%fun-doc definition) doc (%fun-lambda-list definition) lambda-list (%fun-name definition) debug-name)) name)))) (progn (def (:load-toplevel :execute) #-sb-xc-host t #+sb-xc-host nil) #-sb-xc (def (:compile-toplevel) nil))) CASE , TYPECASE , and friends (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute) Make this a full warning during SBCL build . (define-condition duplicate-case-key-warning (#-sb-xc-host style-warning #+sb-xc-host warning) ((key :initarg :key :reader case-warning-key) (case-kind :initarg :case-kind :reader case-warning-case-kind) (occurrences :initarg :occurrences :type list :reader duplicate-case-key-warning-occurrences)) (:report (lambda (condition stream) (format stream "Duplicate key ~S in ~S form, ~ occurring in~{~#[~; and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}." (case-warning-key condition) (case-warning-case-kind condition) (duplicate-case-key-warning-occurrences condition))))) ;;; CASE-BODY returns code for all the standard "case" macros. NAME is the macro name , and KEYFORM is the thing to case on . MULTI - P ;;; indicates whether a branch may fire off a list of keys; otherwise, ;;; a key that is a list is interpreted in some way as a single key. When MULTI - P , TEST is applied to the value of KEYFORM and each key ;;; for a given branch; otherwise, TEST is applied to the value of KEYFORM and the entire first element , instead of each part , of the case branch . When ERRORP , no OTHERWISE - CLAUSEs are recognized , ;;; and an ERROR form is generated where control falls off the end ;;; of the ordinary clauses. When PROCEEDP, it is an error to omit ERRORP , and the ERROR form generated is executed within a RESTART - CASE allowing KEYFORM to be set and retested . (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp) (unless (or cases (not needcasesp)) (warn "no clauses in ~S" name)) (let ((keyform-value (gensym)) (clauses ()) (keys ()) (keys-seen (make-hash-table :test #'eql))) (do* ((cases cases (cdr cases)) (case (car cases) (car cases)) (case-position 1 (1+ case-position))) ((null cases) nil) (flet ((check-clause (case-keys) (loop for k in case-keys for existing = (gethash k keys-seen) do (when existing (let ((sb!c::*current-path* (when (boundp 'sb!c::*source-paths*) (or (sb!c::get-source-path case) sb!c::*current-path*)))) (warn 'duplicate-case-key-warning :key k :case-kind name :occurrences `(,existing (,case-position (,case))))))) (let ((record (list case-position (list case)))) (dolist (k case-keys) (setf (gethash k keys-seen) record))))) (unless (list-of-length-at-least-p case 1) (error "~S -- bad clause in ~S" case name)) (destructuring-bind (keyoid &rest forms) case (cond (;; an OTHERWISE-CLAUSE ;; ;; By the way... The old code here tried gave ;; STYLE-WARNINGs for normal-clauses which looked as ;; though they might've been intended to be otherwise - clauses . As reported on sbcl - devel 2004 - 11 - 09 there are sometimes good ;; reasons to write clauses like that; and as I noticed ;; when trying to understand the old code so I could ;; understand his patch, trying to guess which clauses ;; don't have good reasons is fundamentally kind of a mess . SBCL does issue style warnings rather ;; enthusiastically, and I have often justified that by ;; arguing that we're doing that to detect issues which ;; are tedious for programmers to detect for by ;; proofreading (like small typoes in long symbol ;; names, or duplicate function definitions in large ;; files). This doesn't seem to be an issue like that, ;; and I can't think of a comparably good justification ;; for giving STYLE-WARNINGs for legal code here, so ;; now we just hope the programmer knows what he's doing . -- WHN 2004 - 11 - 20 possible only in CASE or TYPECASE , ; not in [EC]CASE or [EC]TYPECASE (memq keyoid '(t otherwise)) (null (cdr cases))) (push `(t nil ,@forms) clauses)) ((and multi-p (listp keyoid)) (setf keys (append keyoid keys)) (check-clause keyoid) (push `((or ,@(mapcar (lambda (key) `(,test ,keyform-value ',key)) keyoid)) nil ,@forms) clauses)) (t (when (and (eq name 'case) (cdr cases) (memq keyoid '(t otherwise))) (error 'simple-reference-error :format-control "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~ designator only in the final otherwise-clause, not in a ~ normal-clause. Use (~S) instead, or move the clause the ~ correct position.~:@>" :format-arguments (list 'case case keyoid keyoid) :references `((:ansi-cl :macro case)))) (push keyoid keys) (check-clause (list keyoid)) (push `((,test ,keyform-value ',keyoid) nil ,@forms) clauses)))))) (case-body-aux name keyform keyform-value clauses keys errorp proceedp `(,(if multi-p 'member 'or) ,@keys)))) ;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled ;;; all the cases. Note: it is not necessary that the resulting code signal case - failure conditions , but that 's what KMP 's prototype ;;; code did. We call CASE-BODY-ERROR, because of how closures are ;;; compiled. RESTART-CASE has forms with closures that the compiler ;;; causes to be generated at the top of any function using the case ;;; macros, regardless of whether they are needed. ;;; ;;; The CASE-BODY-ERROR function is defined later, when the ;;; RESTART-CASE macro has been defined. (defun case-body-aux (name keyform keyform-value clauses keys errorp proceedp expected-type) (if proceedp (let ((block (gensym)) (again (gensym))) `(let ((,keyform-value ,keyform)) (block ,block (tagbody ,again (return-from ,block (cond ,@(nreverse clauses) (t (setf ,keyform-value (setf ,keyform (case-body-error ',name ',keyform ,keyform-value ',expected-type ',keys))) (go ,again)))))))) `(let ((,keyform-value ,keyform)) (declare (ignorable ,keyform-value)) ; e.g. (CASE KEY (T)) (cond ,@(nreverse clauses) ,@(if errorp `((t (case-failure ',name ,keyform-value ',keys)))))))) EVAL - WHEN (defmacro-mundanely case (keyform &body cases) #!+sb-doc "CASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If a singleton key is T then the clause is a default clause." (case-body 'case keyform cases t 'eql nil nil nil)) (defmacro-mundanely ccase (keyform &body cases) #!+sb-doc "CCASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If none of the keys matches then a correctable error is signalled." (case-body 'ccase keyform cases t 'eql t t t)) (defmacro-mundanely ecase (keyform &body cases) #!+sb-doc "ECASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If none of the keys matches then an error is signalled." (case-body 'ecase keyform cases t 'eql t nil t)) (defmacro-mundanely typecase (keyform &body cases) #!+sb-doc "TYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true." (case-body 'typecase keyform cases nil 'typep nil nil nil)) (defmacro-mundanely ctypecase (keyform &body cases) #!+sb-doc "CTYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true. If no form is satisfied then a correctable error is signalled." (case-body 'ctypecase keyform cases nil 'typep t t t)) (defmacro-mundanely etypecase (keyform &body cases) #!+sb-doc "ETYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true. If no form is satisfied then an error is signalled." (case-body 'etypecase keyform cases nil 'typep t nil t)) ;;;; WITH-FOO i/o-related macros (defmacro-mundanely with-open-stream ((var stream) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) (let ((abortp (gensym))) `(let ((,var ,stream) (,abortp t)) ,@decls (unwind-protect (multiple-value-prog1 (progn ,@forms) (setq ,abortp nil)) (when ,var (close ,var :abort ,abortp))))))) (defmacro-mundanely with-open-file ((stream filespec &rest options) &body body) `(with-open-stream (,stream (open ,filespec ,@options)) ,@body)) (defmacro-mundanely with-input-from-string ((var string &key index start end) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) ;; The ONCE-ONLY inhibits compiler note for unreachable code when ;; END is true. (once-only ((string string)) `(let ((,var ,(cond ((null end) `(make-string-input-stream ,string ,(or start 0))) ((symbolp end) `(if ,end (make-string-input-stream ,string ,(or start 0) ,end) (make-string-input-stream ,string ,(or start 0)))) (t `(make-string-input-stream ,string ,(or start 0) ,end))))) ,@decls (multiple-value-prog1 (unwind-protect (progn ,@forms) (close ,var)) ,@(when index `((setf ,index (string-input-stream-current ,var))))))))) (defmacro-mundanely with-output-to-string ((var &optional string &key (element-type ''character)) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) (if string (let ((element-type-var (gensym))) `(let ((,var (make-fill-pointer-output-stream ,string)) ;; ELEMENT-TYPE isn't currently used for anything ( see FILL - POINTER - OUTPUT - STREAM FIXME in ) , ;; but it still has to be evaluated for side-effects. (,element-type-var ,element-type)) (declare (ignore ,element-type-var)) ,@decls (unwind-protect (progn ,@forms) (close ,var)))) `(let ((,var (make-string-output-stream :element-type ,element-type))) ,@decls (unwind-protect (progn ,@forms) (close ,var)) (get-output-stream-string ,var))))) ;;;; miscellaneous macros (defmacro-mundanely nth-value (n form) #!+sb-doc "Evaluate FORM and return the Nth value (zero based). This involves no consing when N is a trivial constant integer." ;; FIXME: The above is true, if slightly misleading. The MULTIPLE - VALUE - BIND idiom [ as opposed to MULTIPLE - VALUE - CALL ( LAMBDA ( & REST VALUES ) ( NTH N VALUES ) ) ] does indeed not cons at runtime . However , for large N ( say N = 200 ) , COMPILE on such a ;; form will take longer than can be described as adequate, as the optional dispatch mechanism for the M - V - B gets increasingly ;; hairy. (if (integerp n) (let ((dummy-list (make-gensym-list n)) (keeper (sb!xc:gensym "KEEPER"))) `(multiple-value-bind (,@dummy-list ,keeper) ,form (declare (ignore ,@dummy-list)) ,keeper)) (once-only ((n n)) `(case (the fixnum ,n) (0 (nth-value 0 ,form)) (1 (nth-value 1 ,form)) (2 (nth-value 2 ,form)) (t (nth (the fixnum ,n) (multiple-value-list ,form))))))) (defmacro-mundanely declaim (&rest specs) #!+sb-doc "DECLAIM Declaration* Do a declaration or declarations for the global environment." `(eval-when (:compile-toplevel :load-toplevel :execute) ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec)) specs))) (defmacro-mundanely print-unreadable-object ((object stream &key type identity) &body body) "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally with object-type prefix and object-identity suffix, and executing the code in BODY to provide possible further output." `(%print-unreadable-object ,object ,stream ,type ,identity ,(if body `(lambda () ,@body) nil))) (defmacro-mundanely ignore-errors (&rest forms) #!+sb-doc "Execute FORMS handling ERROR conditions, returning the result of the last form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled." `(handler-case (progn ,@forms) (error (condition) (values nil condition))))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/code/macros.lisp
lisp
more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. closures are compiled. RESTART-CASE has forms with closures that the compiler causes to be generated at the top of any function to do a significant amount of work at runtime allocating and deallocating the closures regardless of whether they were ever needed. macro RESTART-CASE, which isn't defined until a later file. help user debug lexical variables CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how closures are compiled. RESTART-CASE has forms with closures that the compiler causes to be generated at the top of any function using RESTART-CASE, regardless of whether they are needed. Because it would be nice if CHECK-TYPE were cheap to use, and some things (e.g., READ-CHAR) can't afford this excessive consing, we bend backwards a little. CHECK-TYPE-ERROR isn't defined until a later file because it uses the macro RESTART-CASE, which isn't defined until a later file. Detect a common user-error. For more complex places getting the type derived should not matter so much anyhow. DEFINE-SYMBOL-MACRO DEFINE-COMPILER-MACRO FIXME: This will look remarkably similar to those who have already seen the code for %DEFMACRO in src/code/defmacro.lisp. Various FIXME: warn about incompatible lambda list with respect to parent function? and~]~{ the ~:R clause:~%~< ~S~:>~}~^,~}." CASE-BODY returns code for all the standard "case" macros. NAME is indicates whether a branch may fire off a list of keys; otherwise, a key that is a list is interpreted in some way as a single key. for a given branch; otherwise, TEST is applied to the value of and an ERROR form is generated where control falls off the end of the ordinary clauses. When PROCEEDP, it is an error to an OTHERWISE-CLAUSE By the way... The old code here tried gave STYLE-WARNINGs for normal-clauses which looked as though they might've been intended to be reasons to write clauses like that; and as I noticed when trying to understand the old code so I could understand his patch, trying to guess which clauses don't have good reasons is fundamentally kind of a enthusiastically, and I have often justified that by arguing that we're doing that to detect issues which are tedious for programmers to detect for by proofreading (like small typoes in long symbol names, or duplicate function definitions in large files). This doesn't seem to be an issue like that, and I can't think of a comparably good justification for giving STYLE-WARNINGs for legal code here, so now we just hope the programmer knows what he's not in [EC]CASE or [EC]TYPECASE CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the cases. Note: it is not necessary that the resulting code code did. We call CASE-BODY-ERROR, because of how closures are compiled. RESTART-CASE has forms with closures that the compiler causes to be generated at the top of any function using the case macros, regardless of whether they are needed. The CASE-BODY-ERROR function is defined later, when the RESTART-CASE macro has been defined. e.g. (CASE KEY (T)) WITH-FOO i/o-related macros The ONCE-ONLY inhibits compiler note for unreachable code when END is true. ELEMENT-TYPE isn't currently used for anything but it still has to be evaluated for side-effects. miscellaneous macros FIXME: The above is true, if slightly misleading. The form will take longer than can be described as adequate, as the hairy.
lots of basic macros for the target SBCL This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB!IMPL") ASSERT and CHECK - TYPE ASSERT is written this way , to call - ERROR , because of how using RESTART - CASE , regardless of whether they are needed . Thus if we just wrapped a RESTART - CASE around the call to ERROR , we 'd have ASSERT - ERROR is n't defined until a later file because it uses the (defmacro-mundanely assert (test-form &optional places datum &rest arguments) #!+sb-doc "Signals an error if the value of test-form is nil. Continuing from this error using the CONTINUE restart will allow the user to alter the value of some locations known to SETF, starting over with test-form. Returns NIL." `(do () (,test-form) (assert-error ',test-form ',places ,datum ,@arguments) ,@(mapcar (lambda (place) `(setf ,place (assert-prompt ',place ,place))) places))) (defun assert-prompt (name value) (cond ((y-or-n-p "The old value of ~S is ~S.~ ~%Do you want to supply a new value? " name value) (format *query-io* "~&Type a form to be evaluated:~%") (flet ((read-it () (eval (read *query-io*)))) (progv (list name) (list value) (read-it)) (read-it)))) (t value))) (defmacro-mundanely check-type (place type &optional type-string &environment env) #!+sb-doc "Signal a restartable error of type TYPE-ERROR if the value of PLACE is not of the specified type. If an error is signalled and the restart is used to return, this can only return if the STORE-VALUE restart is invoked. In that case it will store into PLACE and start over." (when (and (consp type) (eq 'quote (car type))) (error 'simple-reference-error :format-control "Quoted type specifier in ~S: ~S" :format-arguments (list 'check-type type) :references (list '(:ansi-cl :macro check-type)))) : We use a simpler form of expansion if PLACE is just a variable to work around Python 's blind spot in type derivation . (let ((expanded (%macroexpand place env))) (if (symbolp expanded) `(do () ((typep ,place ',type)) (setf ,place (check-type-error ',place ,place ',type ,type-string))) (let ((value (gensym))) `(do ((,value ,place ,place)) ((typep ,value ',type)) (setf ,place (check-type-error ',place ,value ',type ,type-string))))))) (defmacro-mundanely define-symbol-macro (name expansion) `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%define-symbol-macro ',name ',expansion (sb!c:source-location)))) (defun sb!c::%define-symbol-macro (name expansion source-location) (unless (symbolp name) (error 'simple-type-error :datum name :expected-type 'symbol :format-control "Symbol macro name is not a symbol: ~S." :format-arguments (list name))) (with-single-package-locked-error (:symbol name "defining ~A as a symbol-macro")) (sb!c:with-source-location (source-location) (setf (info :source-location :symbol-macro name) source-location)) (let ((kind (info :variable :kind name))) (ecase kind ((:macro :unknown) (setf (info :variable :kind name) :macro) (setf (info :variable :macro-expansion name) expansion)) ((:special :global) (error 'simple-program-error :format-control "Symbol macro name already declared ~A: ~S." :format-arguments (list kind name))) (:constant (error 'simple-program-error :format-control "Symbol macro name already defined as a constant: ~S." :format-arguments (list name))))) name) (defmacro-mundanely define-compiler-macro (name lambda-list &body body) #!+sb-doc "Define a compiler-macro for NAME." (legal-fun-name-or-type-error name) (when (and (symbolp name) (special-operator-p name)) (error 'simple-program-error :format-control "cannot define a compiler-macro for a special operator: ~S" :format-arguments (list name))) (with-unique-names (whole environment) (multiple-value-bind (body local-decs doc) (parse-defmacro lambda-list whole body name 'define-compiler-macro :environment environment) (let ((def `(lambda (,whole ,environment) ,@local-decs ,body)) (debug-name (sb!c::debug-name 'compiler-macro-function name))) `(eval-when (:compile-toplevel :load-toplevel :execute) (sb!c::%define-compiler-macro ',name #',def ',lambda-list ,doc ',debug-name)))))) bits of logic should be shared ( notably arglist setting ) . (macrolet ((def (times set-p) `(eval-when (,@times) (defun sb!c::%define-compiler-macro (name definition lambda-list doc debug-name) ,@(unless set-p '((declare (ignore lambda-list debug-name)))) (setf (sb!xc:compiler-macro-function name) definition) ,(when set-p `(setf (%fun-doc definition) doc (%fun-lambda-list definition) lambda-list (%fun-name definition) debug-name)) name)))) (progn (def (:load-toplevel :execute) #-sb-xc-host t #+sb-xc-host nil) #-sb-xc (def (:compile-toplevel) nil))) CASE , TYPECASE , and friends (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute) Make this a full warning during SBCL build . (define-condition duplicate-case-key-warning (#-sb-xc-host style-warning #+sb-xc-host warning) ((key :initarg :key :reader case-warning-key) (case-kind :initarg :case-kind :reader case-warning-case-kind) (occurrences :initarg :occurrences :type list :reader duplicate-case-key-warning-occurrences)) (:report (lambda (condition stream) (format stream "Duplicate key ~S in ~S form, ~ (case-warning-key condition) (case-warning-case-kind condition) (duplicate-case-key-warning-occurrences condition))))) the macro name , and KEYFORM is the thing to case on . MULTI - P When MULTI - P , TEST is applied to the value of KEYFORM and each key KEYFORM and the entire first element , instead of each part , of the case branch . When ERRORP , no OTHERWISE - CLAUSEs are recognized , omit ERRORP , and the ERROR form generated is executed within a RESTART - CASE allowing KEYFORM to be set and retested . (defun case-body (name keyform cases multi-p test errorp proceedp needcasesp) (unless (or cases (not needcasesp)) (warn "no clauses in ~S" name)) (let ((keyform-value (gensym)) (clauses ()) (keys ()) (keys-seen (make-hash-table :test #'eql))) (do* ((cases cases (cdr cases)) (case (car cases) (car cases)) (case-position 1 (1+ case-position))) ((null cases) nil) (flet ((check-clause (case-keys) (loop for k in case-keys for existing = (gethash k keys-seen) do (when existing (let ((sb!c::*current-path* (when (boundp 'sb!c::*source-paths*) (or (sb!c::get-source-path case) sb!c::*current-path*)))) (warn 'duplicate-case-key-warning :key k :case-kind name :occurrences `(,existing (,case-position (,case))))))) (let ((record (list case-position (list case)))) (dolist (k case-keys) (setf (gethash k keys-seen) record))))) (unless (list-of-length-at-least-p case 1) (error "~S -- bad clause in ~S" case name)) (destructuring-bind (keyoid &rest forms) case otherwise - clauses . As reported on sbcl - devel 2004 - 11 - 09 there are sometimes good mess . SBCL does issue style warnings rather doing . -- WHN 2004 - 11 - 20 possible only in CASE or TYPECASE , (memq keyoid '(t otherwise)) (null (cdr cases))) (push `(t nil ,@forms) clauses)) ((and multi-p (listp keyoid)) (setf keys (append keyoid keys)) (check-clause keyoid) (push `((or ,@(mapcar (lambda (key) `(,test ,keyform-value ',key)) keyoid)) nil ,@forms) clauses)) (t (when (and (eq name 'case) (cdr cases) (memq keyoid '(t otherwise))) (error 'simple-reference-error :format-control "~@<~IBad ~S clause:~:@_ ~S~:@_~S allowed as the key ~ designator only in the final otherwise-clause, not in a ~ normal-clause. Use (~S) instead, or move the clause the ~ correct position.~:@>" :format-arguments (list 'case case keyoid keyoid) :references `((:ansi-cl :macro case)))) (push keyoid keys) (check-clause (list keyoid)) (push `((,test ,keyform-value ',keyoid) nil ,@forms) clauses)))))) (case-body-aux name keyform keyform-value clauses keys errorp proceedp `(,(if multi-p 'member 'or) ,@keys)))) signal case - failure conditions , but that 's what KMP 's prototype (defun case-body-aux (name keyform keyform-value clauses keys errorp proceedp expected-type) (if proceedp (let ((block (gensym)) (again (gensym))) `(let ((,keyform-value ,keyform)) (block ,block (tagbody ,again (return-from ,block (cond ,@(nreverse clauses) (t (setf ,keyform-value (setf ,keyform (case-body-error ',name ',keyform ,keyform-value ',expected-type ',keys))) (go ,again)))))))) `(let ((,keyform-value ,keyform)) (cond ,@(nreverse clauses) ,@(if errorp `((t (case-failure ',name ,keyform-value ',keys)))))))) EVAL - WHEN (defmacro-mundanely case (keyform &body cases) #!+sb-doc "CASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If a singleton key is T then the clause is a default clause." (case-body 'case keyform cases t 'eql nil nil nil)) (defmacro-mundanely ccase (keyform &body cases) #!+sb-doc "CCASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If none of the keys matches then a correctable error is signalled." (case-body 'ccase keyform cases t 'eql t t t)) (defmacro-mundanely ecase (keyform &body cases) #!+sb-doc "ECASE Keyform {({(Key*) | Key} Form*)}* Evaluates the Forms in the first clause with a Key EQL to the value of Keyform. If none of the keys matches then an error is signalled." (case-body 'ecase keyform cases t 'eql t nil t)) (defmacro-mundanely typecase (keyform &body cases) #!+sb-doc "TYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true." (case-body 'typecase keyform cases nil 'typep nil nil nil)) (defmacro-mundanely ctypecase (keyform &body cases) #!+sb-doc "CTYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true. If no form is satisfied then a correctable error is signalled." (case-body 'ctypecase keyform cases nil 'typep t t t)) (defmacro-mundanely etypecase (keyform &body cases) #!+sb-doc "ETYPECASE Keyform {(Type Form*)}* Evaluates the Forms in the first clause for which TYPEP of Keyform and Type is true. If no form is satisfied then an error is signalled." (case-body 'etypecase keyform cases nil 'typep t nil t)) (defmacro-mundanely with-open-stream ((var stream) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) (let ((abortp (gensym))) `(let ((,var ,stream) (,abortp t)) ,@decls (unwind-protect (multiple-value-prog1 (progn ,@forms) (setq ,abortp nil)) (when ,var (close ,var :abort ,abortp))))))) (defmacro-mundanely with-open-file ((stream filespec &rest options) &body body) `(with-open-stream (,stream (open ,filespec ,@options)) ,@body)) (defmacro-mundanely with-input-from-string ((var string &key index start end) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) (once-only ((string string)) `(let ((,var ,(cond ((null end) `(make-string-input-stream ,string ,(or start 0))) ((symbolp end) `(if ,end (make-string-input-stream ,string ,(or start 0) ,end) (make-string-input-stream ,string ,(or start 0)))) (t `(make-string-input-stream ,string ,(or start 0) ,end))))) ,@decls (multiple-value-prog1 (unwind-protect (progn ,@forms) (close ,var)) ,@(when index `((setf ,index (string-input-stream-current ,var))))))))) (defmacro-mundanely with-output-to-string ((var &optional string &key (element-type ''character)) &body forms-decls) (multiple-value-bind (forms decls) (parse-body forms-decls :doc-string-allowed nil) (if string (let ((element-type-var (gensym))) `(let ((,var (make-fill-pointer-output-stream ,string)) ( see FILL - POINTER - OUTPUT - STREAM FIXME in ) , (,element-type-var ,element-type)) (declare (ignore ,element-type-var)) ,@decls (unwind-protect (progn ,@forms) (close ,var)))) `(let ((,var (make-string-output-stream :element-type ,element-type))) ,@decls (unwind-protect (progn ,@forms) (close ,var)) (get-output-stream-string ,var))))) (defmacro-mundanely nth-value (n form) #!+sb-doc "Evaluate FORM and return the Nth value (zero based). This involves no consing when N is a trivial constant integer." MULTIPLE - VALUE - BIND idiom [ as opposed to MULTIPLE - VALUE - CALL ( LAMBDA ( & REST VALUES ) ( NTH N VALUES ) ) ] does indeed not cons at runtime . However , for large N ( say N = 200 ) , COMPILE on such a optional dispatch mechanism for the M - V - B gets increasingly (if (integerp n) (let ((dummy-list (make-gensym-list n)) (keeper (sb!xc:gensym "KEEPER"))) `(multiple-value-bind (,@dummy-list ,keeper) ,form (declare (ignore ,@dummy-list)) ,keeper)) (once-only ((n n)) `(case (the fixnum ,n) (0 (nth-value 0 ,form)) (1 (nth-value 1 ,form)) (2 (nth-value 2 ,form)) (t (nth (the fixnum ,n) (multiple-value-list ,form))))))) (defmacro-mundanely declaim (&rest specs) #!+sb-doc "DECLAIM Declaration* Do a declaration or declarations for the global environment." `(eval-when (:compile-toplevel :load-toplevel :execute) ,@(mapcar (lambda (spec) `(sb!xc:proclaim ',spec)) specs))) (defmacro-mundanely print-unreadable-object ((object stream &key type identity) &body body) "Output OBJECT to STREAM with \"#<\" prefix, \">\" suffix, optionally with object-type prefix and object-identity suffix, and executing the code in BODY to provide possible further output." `(%print-unreadable-object ,object ,stream ,type ,identity ,(if body `(lambda () ,@body) nil))) (defmacro-mundanely ignore-errors (&rest forms) #!+sb-doc "Execute FORMS handling ERROR conditions, returning the result of the last form, or (VALUES NIL the-ERROR-that-was-caught) if an ERROR was handled." `(handler-case (progn ,@forms) (error (condition) (values nil condition))))
535348cb92620bcddcaee17ca5a8010bb72b36bb0f37b869988676a7bae4faea
hexlet-basics/exercises-clojure
index.clj
(ns index) ;BEGIN (defn sum [v] (reduce + v)) ;END
null
https://raw.githubusercontent.com/hexlet-basics/exercises-clojure/ede14102d01f9ef736e0af811cd92f5b22a83bc2/modules/35-vectors/20-vectors-choose/index.clj
clojure
BEGIN END
(ns index) (defn sum [v] (reduce + v))
ac3a79ff0e4cd054a9f771234ae972aa28e54d55a1fb25efd0175f298b84af24
charlesetc/Orb
utop.ml
open Orb;;
null
https://raw.githubusercontent.com/charlesetc/Orb/d59a6b0513a629146a45d09a9a0c4be5d3615651/ppx/classic/utop.ml
ocaml
open Orb;;
b155edeb73afcb07109b282a30ee80894c32fbb167e1bf98e3cbbf08289b2d81
wardle/hermes
verhoeff_test.clj
(ns com.eldrix.hermes.verhoeff-test (:require [clojure.test :refer [deftest is run-tests]] [com.eldrix.hermes.verhoeff :refer [append calculate valid?]])) (deftest valid-verhoeffs (is (= 3 (calculate 236))) (is (valid? 2363)) (is (= 3 (calculate "236"))) (is (valid? "2363")) (is (= 6 (calculate 31122019000))) (is (= "311220190006" (append "31122019000"))) (is (= "311220190006" (append 31122019000))) (is (valid? "311220190006")) (is (valid? "1234567890")) (is (valid? "14567894"))) (deftest invalid-verhoeffs (is (not (valid? "311220190007"))) (is (not (valid? "1234567891"))) (is (not (valid? "14567895")))) (comment (run-tests))
null
https://raw.githubusercontent.com/wardle/hermes/948a116613b2fa2eb8b628c49e47479f216beac6/test/com/eldrix/hermes/verhoeff_test.clj
clojure
(ns com.eldrix.hermes.verhoeff-test (:require [clojure.test :refer [deftest is run-tests]] [com.eldrix.hermes.verhoeff :refer [append calculate valid?]])) (deftest valid-verhoeffs (is (= 3 (calculate 236))) (is (valid? 2363)) (is (= 3 (calculate "236"))) (is (valid? "2363")) (is (= 6 (calculate 31122019000))) (is (= "311220190006" (append "31122019000"))) (is (= "311220190006" (append 31122019000))) (is (valid? "311220190006")) (is (valid? "1234567890")) (is (valid? "14567894"))) (deftest invalid-verhoeffs (is (not (valid? "311220190007"))) (is (not (valid? "1234567891"))) (is (not (valid? "14567895")))) (comment (run-tests))
2c58f3511a44de63cd9e791984ebfcfa1db87507b8838266e92eabe5effd8cdf
lemmaandrew/CodingBatHaskell
sum2.hs
From Given an array of ints , return the sum of the first 2 elements in the array . If the array length is less than 2 , just sum up the elements that exist , returning 0 if the array is length 0 . Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. -} import Test.Hspec ( hspec, describe, it, shouldBe ) sum2 :: [Int] -> Int sum2 nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "3" $ sum2 [1,2,3] `shouldBe` 3 it "2" $ sum2 [1,1] `shouldBe` 2 it "2" $ sum2 [1,1,1,1] `shouldBe` 2 it "3" $ sum2 [1,2] `shouldBe` 3 it "1" $ sum2 [1] `shouldBe` 1 it "0" $ sum2 [] `shouldBe` 0 it "9" $ sum2 [4,5,6] `shouldBe` 9 it "4" $ sum2 [4] `shouldBe` 4
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Array-1/sum2.hs
haskell
From Given an array of ints , return the sum of the first 2 elements in the array . If the array length is less than 2 , just sum up the elements that exist , returning 0 if the array is length 0 . Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0. -} import Test.Hspec ( hspec, describe, it, shouldBe ) sum2 :: [Int] -> Int sum2 nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "3" $ sum2 [1,2,3] `shouldBe` 3 it "2" $ sum2 [1,1] `shouldBe` 2 it "2" $ sum2 [1,1,1,1] `shouldBe` 2 it "3" $ sum2 [1,2] `shouldBe` 3 it "1" $ sum2 [1] `shouldBe` 1 it "0" $ sum2 [] `shouldBe` 0 it "9" $ sum2 [4,5,6] `shouldBe` 9 it "4" $ sum2 [4] `shouldBe` 4
ed9e70c761a31759935dd5e95376e104003e2f06bcf9b11d3694b5ea07e706d0
alekras/erl.mqtt.server
mqtt_rest_utils.erl
%% Copyright ( C ) 2015 - 2022 by ( ) %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% -module(mqtt_rest_utils). -export([to_binary/1]). -export([to_list/1]). -export([to_float/1]). -export([to_int/1]). -export([to_lower/1]). -export([to_upper/1]). -export([set_resp_headers/2]). -export([to_header/1]). -export([to_qs/1]). -export([to_binding/1]). -export([get_opt/2]). -export([get_opt/3]). -export([priv_dir/0]). -export([priv_dir/1]). -export([priv_path/1]). -spec to_binary(iodata() | atom() | number()) -> binary(). to_binary(V) when is_binary(V) -> V; to_binary(V) when is_list(V) -> iolist_to_binary(V); to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); to_binary(V) when is_integer(V) -> integer_to_binary(V); to_binary(V) when is_float(V) -> float_to_binary(V). -spec to_list(iodata() | atom() | number()) -> string(). to_list(V) when is_list(V) -> V; to_list(V) -> binary_to_list(to_binary(V)). -spec to_float(iodata()) -> number(). to_float(V) -> Data = iolist_to_binary([V]), case binary:split(Data, <<$.>>) of [Data] -> binary_to_integer(Data); [<<>>, _] -> binary_to_float(<<$0, Data/binary>>); _ -> binary_to_float(Data) end. %% -spec to_int(integer() | binary() | list()) -> integer(). to_int(Data) when is_integer(Data) -> Data; to_int(Data) when is_binary(Data) -> binary_to_integer(Data); to_int(Data) when is_list(Data) -> list_to_integer(Data). -spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). set_resp_headers([], Req) -> Req; set_resp_headers([{K, V} | T], Req0) -> Req = cowboy_req:set_resp_header(K, V, Req0), set_resp_headers(T, Req). -spec to_header(iodata() | atom() | number()) -> binary(). to_header(Name) -> Prepared = to_binary(Name), to_lower(Prepared). -spec to_qs(iodata() | atom() | number()) -> binary(). to_qs(Name) -> to_binary(Name). -spec to_binding(iodata() | atom() | number()) -> atom(). to_binding(Name) -> Prepared = to_binary(Name), binary_to_atom(Prepared, utf8). -spec get_opt(any(), []) -> any(). get_opt(Key, Opts) -> get_opt(Key, Opts, undefined). -spec get_opt(any(), [], any()) -> any(). get_opt(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; false -> Default end. -spec priv_dir() -> file:filename(). priv_dir() -> {ok, AppName} = application:get_application(), priv_dir(AppName). -spec priv_dir(Application :: atom()) -> file:filename(). priv_dir(AppName) -> case code:priv_dir(AppName) of Value when is_list(Value) -> Value ++ "/"; _Error -> select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) end. -spec priv_path(Relative :: file:filename()) -> file:filename(). priv_path(Relative) -> filename:join(priv_dir(), Relative). -include_lib("kernel/include/file.hrl"). select_priv_dir(Paths) -> case lists:dropwhile(fun test_priv_dir/1, Paths) of [Path | _] -> Path; _ -> exit(no_priv_dir) end. test_priv_dir(Path) -> case file:read_file_info(Path) of {ok, #file_info{type = directory}} -> false; _ -> true end. %% -spec to_lower(binary()) -> binary(). to_lower(S) -> to_case(lower, S, <<>>). -spec to_upper(binary()) -> binary(). to_upper(S) -> to_case(upper, S, <<>>). to_case(_Case, <<>>, Acc) -> Acc; to_case(_Case, <<C, _/binary>>, _Acc) when C > 127 -> error(badarg); to_case(Case = lower, <<C, Rest/binary>>, Acc) -> to_case(Case, Rest, <<Acc/binary, (to_lower_char(C))>>); to_case(Case = upper, <<C, Rest/binary>>, Acc) -> to_case(Case, Rest, <<Acc/binary, (to_upper_char(C))>>). to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> C + 32; to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> C + 32; to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> C + 32; to_lower_char(C) -> C. to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> C - 32; to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> C - 32; to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> C - 32; to_upper_char(C) -> C.
null
https://raw.githubusercontent.com/alekras/erl.mqtt.server/d05919cfc7bfdb7a252eb97a58da67f6a3c48138/apps/mqtt_rest/src/mqtt_rest_utils.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( C ) 2015 - 2022 by ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(mqtt_rest_utils). -export([to_binary/1]). -export([to_list/1]). -export([to_float/1]). -export([to_int/1]). -export([to_lower/1]). -export([to_upper/1]). -export([set_resp_headers/2]). -export([to_header/1]). -export([to_qs/1]). -export([to_binding/1]). -export([get_opt/2]). -export([get_opt/3]). -export([priv_dir/0]). -export([priv_dir/1]). -export([priv_path/1]). -spec to_binary(iodata() | atom() | number()) -> binary(). to_binary(V) when is_binary(V) -> V; to_binary(V) when is_list(V) -> iolist_to_binary(V); to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); to_binary(V) when is_integer(V) -> integer_to_binary(V); to_binary(V) when is_float(V) -> float_to_binary(V). -spec to_list(iodata() | atom() | number()) -> string(). to_list(V) when is_list(V) -> V; to_list(V) -> binary_to_list(to_binary(V)). -spec to_float(iodata()) -> number(). to_float(V) -> Data = iolist_to_binary([V]), case binary:split(Data, <<$.>>) of [Data] -> binary_to_integer(Data); [<<>>, _] -> binary_to_float(<<$0, Data/binary>>); _ -> binary_to_float(Data) end. -spec to_int(integer() | binary() | list()) -> integer(). to_int(Data) when is_integer(Data) -> Data; to_int(Data) when is_binary(Data) -> binary_to_integer(Data); to_int(Data) when is_list(Data) -> list_to_integer(Data). -spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). set_resp_headers([], Req) -> Req; set_resp_headers([{K, V} | T], Req0) -> Req = cowboy_req:set_resp_header(K, V, Req0), set_resp_headers(T, Req). -spec to_header(iodata() | atom() | number()) -> binary(). to_header(Name) -> Prepared = to_binary(Name), to_lower(Prepared). -spec to_qs(iodata() | atom() | number()) -> binary(). to_qs(Name) -> to_binary(Name). -spec to_binding(iodata() | atom() | number()) -> atom(). to_binding(Name) -> Prepared = to_binary(Name), binary_to_atom(Prepared, utf8). -spec get_opt(any(), []) -> any(). get_opt(Key, Opts) -> get_opt(Key, Opts, undefined). -spec get_opt(any(), [], any()) -> any(). get_opt(Key, Opts, Default) -> case lists:keyfind(Key, 1, Opts) of {_, Value} -> Value; false -> Default end. -spec priv_dir() -> file:filename(). priv_dir() -> {ok, AppName} = application:get_application(), priv_dir(AppName). -spec priv_dir(Application :: atom()) -> file:filename(). priv_dir(AppName) -> case code:priv_dir(AppName) of Value when is_list(Value) -> Value ++ "/"; _Error -> select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) end. -spec priv_path(Relative :: file:filename()) -> file:filename(). priv_path(Relative) -> filename:join(priv_dir(), Relative). -include_lib("kernel/include/file.hrl"). select_priv_dir(Paths) -> case lists:dropwhile(fun test_priv_dir/1, Paths) of [Path | _] -> Path; _ -> exit(no_priv_dir) end. test_priv_dir(Path) -> case file:read_file_info(Path) of {ok, #file_info{type = directory}} -> false; _ -> true end. -spec to_lower(binary()) -> binary(). to_lower(S) -> to_case(lower, S, <<>>). -spec to_upper(binary()) -> binary(). to_upper(S) -> to_case(upper, S, <<>>). to_case(_Case, <<>>, Acc) -> Acc; to_case(_Case, <<C, _/binary>>, _Acc) when C > 127 -> error(badarg); to_case(Case = lower, <<C, Rest/binary>>, Acc) -> to_case(Case, Rest, <<Acc/binary, (to_lower_char(C))>>); to_case(Case = upper, <<C, Rest/binary>>, Acc) -> to_case(Case, Rest, <<Acc/binary, (to_upper_char(C))>>). to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> C + 32; to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> C + 32; to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> C + 32; to_lower_char(C) -> C. to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> C - 32; to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> C - 32; to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> C - 32; to_upper_char(C) -> C.
58a22ca3066b6e3f0035000a9aa19986ecac8ce4e247f096c9ca80309db8a342
alex-gutev/generic-cl
package.lisp
package.lisp ;;;; Copyright 2018 ;;;; ;;;; Permission is hereby granted, free of charge, to any person ;;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;;; restriction, including without limitation the rights to use, ;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the ;;;; Software is furnished to do so, subject to the following ;;;; conditions: ;;;; ;;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;;;; OTHER DEALINGS IN THE SOFTWARE. (uiop:define-package :generic-cl.set (:mix :generic-cl.comparison :generic-cl.arithmetic :generic-cl.object :generic-cl.container :generic-cl.iterator :generic-cl.collector :generic-cl.sequence :generic-cl.map :static-dispatch-cl) (:use :anaphora :cl-custom-hash-table) (:import-from :generic-cl.iterator :list-iterator :make-list-iterator) (:import-from :generic-cl.map :make-hash-map-table :make-generic-hash-table :copy-generic-hash-table :do-generic-map :hash-map-test-p :make-empty-hash-table) (:shadow :subsetp :intersection :nintersection :adjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :union :nunion) (:export :memberp :subsetp :intersection :nintersection :adjoin :nadjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :union :nunion :hash-set :make-hash-set :hash-table-set :hash-set-table :hash-set-p) (:documentation "Generic set interface"))
null
https://raw.githubusercontent.com/alex-gutev/generic-cl/e337b8d2198791994f4377a522bf0200d2285548/src/set/package.lisp
lisp
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package.lisp Copyright 2018 files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , (uiop:define-package :generic-cl.set (:mix :generic-cl.comparison :generic-cl.arithmetic :generic-cl.object :generic-cl.container :generic-cl.iterator :generic-cl.collector :generic-cl.sequence :generic-cl.map :static-dispatch-cl) (:use :anaphora :cl-custom-hash-table) (:import-from :generic-cl.iterator :list-iterator :make-list-iterator) (:import-from :generic-cl.map :make-hash-map-table :make-generic-hash-table :copy-generic-hash-table :do-generic-map :hash-map-test-p :make-empty-hash-table) (:shadow :subsetp :intersection :nintersection :adjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :union :nunion) (:export :memberp :subsetp :intersection :nintersection :adjoin :nadjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :union :nunion :hash-set :make-hash-set :hash-table-set :hash-set-table :hash-set-p) (:documentation "Generic set interface"))
c3d4de22b1bd8b48d7116bbe6bfddcbee9c052e6f1a1220678445454358b6435
ocaml-flambda/ocaml-jst
coloring.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) Register allocation by coloring of the interference graph module Int = Misc.Stdlib.Int module OrderedRegSet = Set.Make(struct type t = Reg.t let compare r1 r2 = let open Reg in let c1 = r1.spill_cost and d1 = r1.degree in let c2 = r2.spill_cost and d2 = r2.degree in let n = c2 * d1 - c1 * d2 in if n <> 0 then n else let n = c2 - c1 in if n <> 0 then n else let n = d1 - d2 in if n <> 0 then n else r1.stamp - r2.stamp end) open Reg let allocate_registers() = Constrained regs with degree > = number of available registers , sorted by spill cost ( highest first ) . The spill cost measure is [ r.spill_cost / r.degree ] . [ r.spill_cost ] estimates the number of accesses to [ r ] . sorted by spill cost (highest first). The spill cost measure is [r.spill_cost / r.degree]. [r.spill_cost] estimates the number of accesses to [r]. *) let constrained = ref OrderedRegSet.empty in (* Unconstrained regs with degree < number of available registers *) let unconstrained = ref [] in (* Reset the stack slot counts *) let num_stack_slots = Array.make Proc.num_register_classes 0 in the spilled registers in the stack . Split the remaining registers into constrained and unconstrained . Split the remaining registers into constrained and unconstrained. *) let remove_reg reg = let cl = Proc.register_class reg in if reg.spill then begin (* Preallocate the registers in the stack *) let nslots = num_stack_slots.(cl) in let conflict = Array.make nslots false in List.iter (fun r -> match r.loc with Stack(Local n) -> if Proc.register_class r = cl then conflict.(n) <- true | _ -> ()) reg.interf; let slot = ref 0 in while !slot < nslots && conflict.(!slot) do incr slot done; reg.loc <- Stack(Local !slot); if !slot >= nslots then num_stack_slots.(cl) <- !slot + 1 end else if reg.degree < Proc.num_available_registers.(cl) then unconstrained := reg :: !unconstrained else begin constrained := OrderedRegSet.add reg !constrained end in (* Iterate over all registers preferred by the given register (transitive) *) let iter_preferred f reg = let rec walk r w = if not (Reg.is_visited r) then begin Reg.mark_visited r; f r w; List.iter (fun (r1, w1) -> walk r1 (Int.min w w1)) r.prefer end in List.iter (fun (r, w) -> walk r w) reg.prefer; Reg.clear_visited_marks () in (* Where to start the search for a suitable register. Used to introduce some "randomness" in the choice between registers with equal scores. This offers more opportunities for scheduling. *) let start_register = Array.make Proc.num_register_classes 0 in (* Assign a location to a register, the best we can. *) let assign_location reg = let cl = Proc.register_class reg in let first_reg = Proc.first_available_register.(cl) in let num_regs = Proc.num_available_registers.(cl) in let score = Array.make num_regs 0 in let best_score = ref (-1000000) and best_reg = ref (-1) in let start = start_register.(cl) in if num_regs <> 0 then begin (* Favor the registers that have been assigned to pseudoregs for which we have a preference. If these pseudoregs have not been assigned already, avoid the registers with which they conflict. *) iter_preferred (fun r w -> match r.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) + w | Unknown -> List.iter (fun neighbour -> match neighbour.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) - w | _ -> ()) r.interf | _ -> ()) reg; List.iter (fun neighbour -> (* Prohibit the registers that have been assigned to our neighbours *) begin match neighbour.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- (-1000000) | _ -> () end; (* Avoid the registers that have been assigned to pseudoregs for which our neighbours have a preference *) iter_preferred (fun r w -> match r.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) - (w-1) w-1 to break the symmetry when two conflicting regs have the same preference for a third reg . have the same preference for a third reg. *) | _ -> ()) neighbour) reg.interf; (* Pick the register with the best score *) for n = start to num_regs - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_reg := n end done; for n = 0 to start - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_reg := n end done end; (* Found a register? *) if !best_reg >= 0 then begin reg.loc <- Reg(first_reg + !best_reg); if Proc.rotate_registers then start_register.(cl) <- (let start = start + 1 in if start >= num_regs then 0 else start) end else begin (* Sorry, we must put the pseudoreg in a stack location *) let nslots = num_stack_slots.(cl) in let score = Array.make nslots 0 in (* Compute the scores as for registers *) List.iter (fun (r, w) -> match r.loc with Stack(Local n) -> score.(n) <- score.(n) + w | Unknown -> List.iter (fun neighbour -> match neighbour.loc with Stack(Local n) -> score.(n) <- score.(n) - w | _ -> ()) r.interf | _ -> ()) reg.prefer; List.iter (fun neighbour -> begin match neighbour.loc with Stack(Local n) -> score.(n) <- (-1000000) | _ -> () end; List.iter (fun (r, w) -> match r.loc with Stack(Local n) -> score.(n) <- score.(n) - w | _ -> ()) neighbour.prefer) reg.interf; (* Pick the location with the best score *) let best_score = ref (-1000000) and best_slot = ref (-1) in for n = 0 to nslots - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_slot := n end done; (* Found one? *) if !best_slot >= 0 then reg.loc <- Stack(Local !best_slot) else begin (* Allocate a new stack slot *) reg.loc <- Stack(Local nslots); num_stack_slots.(cl) <- nslots + 1 end end; (* Cancel the preferences of this register so that they don't influence transitively the allocation of registers that prefer this reg. *) reg.prefer <- [] in First pass : preallocate spill registers and split remaining regs Second pass : assign locations to constrained regs Third pass : assign locations to unconstrained regs Second pass: assign locations to constrained regs Third pass: assign locations to unconstrained regs *) List.iter remove_reg (Reg.all_registers()); OrderedRegSet.iter assign_location !constrained; List.iter assign_location !unconstrained; num_stack_slots
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/5bf2820278c58f6715dcfaf6fa61e09a9b0d8db3/asmcomp/coloring.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Unconstrained regs with degree < number of available registers Reset the stack slot counts Preallocate the registers in the stack Iterate over all registers preferred by the given register (transitive) Where to start the search for a suitable register. Used to introduce some "randomness" in the choice between registers with equal scores. This offers more opportunities for scheduling. Assign a location to a register, the best we can. Favor the registers that have been assigned to pseudoregs for which we have a preference. If these pseudoregs have not been assigned already, avoid the registers with which they conflict. Prohibit the registers that have been assigned to our neighbours Avoid the registers that have been assigned to pseudoregs for which our neighbours have a preference Pick the register with the best score Found a register? Sorry, we must put the pseudoreg in a stack location Compute the scores as for registers Pick the location with the best score Found one? Allocate a new stack slot Cancel the preferences of this register so that they don't influence transitively the allocation of registers that prefer this reg.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the Register allocation by coloring of the interference graph module Int = Misc.Stdlib.Int module OrderedRegSet = Set.Make(struct type t = Reg.t let compare r1 r2 = let open Reg in let c1 = r1.spill_cost and d1 = r1.degree in let c2 = r2.spill_cost and d2 = r2.degree in let n = c2 * d1 - c1 * d2 in if n <> 0 then n else let n = c2 - c1 in if n <> 0 then n else let n = d1 - d2 in if n <> 0 then n else r1.stamp - r2.stamp end) open Reg let allocate_registers() = Constrained regs with degree > = number of available registers , sorted by spill cost ( highest first ) . The spill cost measure is [ r.spill_cost / r.degree ] . [ r.spill_cost ] estimates the number of accesses to [ r ] . sorted by spill cost (highest first). The spill cost measure is [r.spill_cost / r.degree]. [r.spill_cost] estimates the number of accesses to [r]. *) let constrained = ref OrderedRegSet.empty in let unconstrained = ref [] in let num_stack_slots = Array.make Proc.num_register_classes 0 in the spilled registers in the stack . Split the remaining registers into constrained and unconstrained . Split the remaining registers into constrained and unconstrained. *) let remove_reg reg = let cl = Proc.register_class reg in if reg.spill then begin let nslots = num_stack_slots.(cl) in let conflict = Array.make nslots false in List.iter (fun r -> match r.loc with Stack(Local n) -> if Proc.register_class r = cl then conflict.(n) <- true | _ -> ()) reg.interf; let slot = ref 0 in while !slot < nslots && conflict.(!slot) do incr slot done; reg.loc <- Stack(Local !slot); if !slot >= nslots then num_stack_slots.(cl) <- !slot + 1 end else if reg.degree < Proc.num_available_registers.(cl) then unconstrained := reg :: !unconstrained else begin constrained := OrderedRegSet.add reg !constrained end in let iter_preferred f reg = let rec walk r w = if not (Reg.is_visited r) then begin Reg.mark_visited r; f r w; List.iter (fun (r1, w1) -> walk r1 (Int.min w w1)) r.prefer end in List.iter (fun (r, w) -> walk r w) reg.prefer; Reg.clear_visited_marks () in let start_register = Array.make Proc.num_register_classes 0 in let assign_location reg = let cl = Proc.register_class reg in let first_reg = Proc.first_available_register.(cl) in let num_regs = Proc.num_available_registers.(cl) in let score = Array.make num_regs 0 in let best_score = ref (-1000000) and best_reg = ref (-1) in let start = start_register.(cl) in if num_regs <> 0 then begin iter_preferred (fun r w -> match r.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) + w | Unknown -> List.iter (fun neighbour -> match neighbour.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) - w | _ -> ()) r.interf | _ -> ()) reg; List.iter (fun neighbour -> begin match neighbour.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- (-1000000) | _ -> () end; iter_preferred (fun r w -> match r.loc with Reg n -> let n = n - first_reg in if n < num_regs then score.(n) <- score.(n) - (w-1) w-1 to break the symmetry when two conflicting regs have the same preference for a third reg . have the same preference for a third reg. *) | _ -> ()) neighbour) reg.interf; for n = start to num_regs - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_reg := n end done; for n = 0 to start - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_reg := n end done end; if !best_reg >= 0 then begin reg.loc <- Reg(first_reg + !best_reg); if Proc.rotate_registers then start_register.(cl) <- (let start = start + 1 in if start >= num_regs then 0 else start) end else begin let nslots = num_stack_slots.(cl) in let score = Array.make nslots 0 in List.iter (fun (r, w) -> match r.loc with Stack(Local n) -> score.(n) <- score.(n) + w | Unknown -> List.iter (fun neighbour -> match neighbour.loc with Stack(Local n) -> score.(n) <- score.(n) - w | _ -> ()) r.interf | _ -> ()) reg.prefer; List.iter (fun neighbour -> begin match neighbour.loc with Stack(Local n) -> score.(n) <- (-1000000) | _ -> () end; List.iter (fun (r, w) -> match r.loc with Stack(Local n) -> score.(n) <- score.(n) - w | _ -> ()) neighbour.prefer) reg.interf; let best_score = ref (-1000000) and best_slot = ref (-1) in for n = 0 to nslots - 1 do if score.(n) > !best_score then begin best_score := score.(n); best_slot := n end done; if !best_slot >= 0 then reg.loc <- Stack(Local !best_slot) else begin reg.loc <- Stack(Local nslots); num_stack_slots.(cl) <- nslots + 1 end end; reg.prefer <- [] in First pass : preallocate spill registers and split remaining regs Second pass : assign locations to constrained regs Third pass : assign locations to unconstrained regs Second pass: assign locations to constrained regs Third pass: assign locations to unconstrained regs *) List.iter remove_reg (Reg.all_registers()); OrderedRegSet.iter assign_location !constrained; List.iter assign_location !unconstrained; num_stack_slots
a72cfc36a48c7765b0c7101701d4ebbaa5172a1687767f71a828b40c5128d7c9
lambdaclass/holiday_pinger
channel_test_SUITE.erl
-module(channel_test_SUITE). -include_lib("common_test/include/ct.hrl"). -compile(export_all). all() -> [test_channel]. init_per_suite(Config) -> {ok, _Apps} = application:ensure_all_started(holiday_ping), #{email := Email, token := Token} = test_utils:create_user_with_token(), [{user, Email}, {token, Token} | Config]. end_per_suite(Config) -> ok = test_utils:delete_user(?config(user, Config)), ok = application:stop(holiday_ping), ok = application:unload(holiday_ping). test_channel(Config) -> Token = ?config(token, Config), Email = ?config(user, Config), TableId = ets_channel_test_table, ets_channel:init_table(TableId), Body = #{ type => ets, configuration => #{ email => Email, table_id => TableId }, reminder_days_before => [3], reminder_time => <<"9:00">>, reminder_timezone => <<"+02">> }, {ok, 201, _, _} = test_utils:api_request(put, Token, "/api/channels/my_channel", Body), {ok, 204, _, _} = test_utils:api_request(post, Token, "/api/channels/my_channel/test", #{}), timer:sleep(1000), [{Email, Message}] = ets_channel:get_reminders(TableId, Email), <<"This is a Holiday Ping test: John Doe will be out on holidays.">> = Message, ok = test_utils:delete_user(Email).
null
https://raw.githubusercontent.com/lambdaclass/holiday_pinger/a8a6d1e28de57cf24d6205d275981a718305b351/test/channel_test_SUITE.erl
erlang
-module(channel_test_SUITE). -include_lib("common_test/include/ct.hrl"). -compile(export_all). all() -> [test_channel]. init_per_suite(Config) -> {ok, _Apps} = application:ensure_all_started(holiday_ping), #{email := Email, token := Token} = test_utils:create_user_with_token(), [{user, Email}, {token, Token} | Config]. end_per_suite(Config) -> ok = test_utils:delete_user(?config(user, Config)), ok = application:stop(holiday_ping), ok = application:unload(holiday_ping). test_channel(Config) -> Token = ?config(token, Config), Email = ?config(user, Config), TableId = ets_channel_test_table, ets_channel:init_table(TableId), Body = #{ type => ets, configuration => #{ email => Email, table_id => TableId }, reminder_days_before => [3], reminder_time => <<"9:00">>, reminder_timezone => <<"+02">> }, {ok, 201, _, _} = test_utils:api_request(put, Token, "/api/channels/my_channel", Body), {ok, 204, _, _} = test_utils:api_request(post, Token, "/api/channels/my_channel/test", #{}), timer:sleep(1000), [{Email, Message}] = ets_channel:get_reminders(TableId, Email), <<"This is a Holiday Ping test: John Doe will be out on holidays.">> = Message, ok = test_utils:delete_user(Email).
8a594c283b9a4d5e9d5e4dfba6da785a611115b5a889f2d644768fd6934778d5
jfacorro/clojure-lab
trie.clj
(ns lab.core.trie (:refer-clojure :exclude [contains?])) (defn contains? "Returns true if the value x exists in the specified trie." [trie x] (:terminal (get-in trie x) false)) (defn prefix-matches "Returns a list of matches with the prefix specified in the trie specified." [trie prefix] (map :val (filter :val (tree-seq map? vals (get-in trie prefix))))) (defn add "Add a new terminal value." [trie x] (assoc-in trie x (merge (get-in trie x) {:val x :terminal true}))) (defn trie "Builds a trie over the values in the specified seq coll." [coll] (reduce add {} coll))
null
https://raw.githubusercontent.com/jfacorro/clojure-lab/f0b5a4b78172984fc876f063f66e5e1592178da9/src/clj/lab/core/trie.clj
clojure
(ns lab.core.trie (:refer-clojure :exclude [contains?])) (defn contains? "Returns true if the value x exists in the specified trie." [trie x] (:terminal (get-in trie x) false)) (defn prefix-matches "Returns a list of matches with the prefix specified in the trie specified." [trie prefix] (map :val (filter :val (tree-seq map? vals (get-in trie prefix))))) (defn add "Add a new terminal value." [trie x] (assoc-in trie x (merge (get-in trie x) {:val x :terminal true}))) (defn trie "Builds a trie over the values in the specified seq coll." [coll] (reduce add {} coll))
575d08c659416133ea1f84436e36af91c86d289ab281df18f73f275523630c15
mattjbray/ocaml-decoders
decode.mli
include Decoders.Decode.S with type value = Bencode.t val int64 : int64 decoder
null
https://raw.githubusercontent.com/mattjbray/ocaml-decoders/da05e541c1c587151ee3ccadf929e86b287215bb/src-bencode/decode.mli
ocaml
include Decoders.Decode.S with type value = Bencode.t val int64 : int64 decoder
5c9b93f48dddf546fd256183237bdd3fb6d16cc352f086707eb8a9b09e29b57c
thi-ng/demos
texture.cljs
(ns ex04.texture (:require [thi.ng.geom.gl.buffers :as buf] [thi.ng.color.core :as col] [thi.ng.color.gradients :as grad])) (defn gradient-texture [gl w h opts] (let [canv (.createElement js/document "canvas") ctx (.getContext canv "2d") cols (reverse (grad/cosine-gradient h (:rainbow1 grad/cosine-schemes)))] (set! (.-width canv) w) (set! (.-height canv) h) (set! (.-strokeStyle ctx) "none") (loop [y 0, cols cols] (if cols (do (set! (.-fillStyle ctx) @(col/as-css (first cols))) (.fillRect ctx 0 y w 1) (recur (inc y) (next cols))) (buf/make-canvas-texture gl canv opts)))))
null
https://raw.githubusercontent.com/thi-ng/demos/048cd131099a7db29be56b965c053908acad4166/ws-ldn-8/day2/ex04/src/ex04/texture.cljs
clojure
(ns ex04.texture (:require [thi.ng.geom.gl.buffers :as buf] [thi.ng.color.core :as col] [thi.ng.color.gradients :as grad])) (defn gradient-texture [gl w h opts] (let [canv (.createElement js/document "canvas") ctx (.getContext canv "2d") cols (reverse (grad/cosine-gradient h (:rainbow1 grad/cosine-schemes)))] (set! (.-width canv) w) (set! (.-height canv) h) (set! (.-strokeStyle ctx) "none") (loop [y 0, cols cols] (if cols (do (set! (.-fillStyle ctx) @(col/as-css (first cols))) (.fillRect ctx 0 y w 1) (recur (inc y) (next cols))) (buf/make-canvas-texture gl canv opts)))))
0acc2bea5a205849dc4f55738132f69de831ca15555d0ccaf6dc3f6dea545355
pirapira/bamboo
wrapCryptokit.ml
module Hash = Cryptokit.Hash let string_keccak str : string = let sha3_256 = Hash.keccak 256 in let () = sha3_256#add_string str in let ret = sha3_256#result in let tr = Cryptokit.Hexa.encode () in let () = tr#put_string ret in let () = tr#finish in let ret = tr#get_string in need to convert ret into hex ret let strip_0x h = if BatString.starts_with h "0x" then BatString.tail h 2 else h let add_hex sha3_256 h = let h = strip_0x h in let add_byte c = sha3_256#add_char c in let chars = BatString.explode h in let rec work chars = match chars with | [] -> () | [x] -> failwith "odd-length hex" | a :: b :: rest -> let () = add_byte (Hex.to_char a b) in work rest in work chars let hex_keccak h : string = let sha3_256 = Hash.keccak 256 in let () = add_hex sha3_256 h in let ret = sha3_256#result in let tr = Cryptokit.Hexa.encode () in let () = tr#put_string ret in let () = tr#finish in let ret = tr#get_string in need to convert ret into hex ret
null
https://raw.githubusercontent.com/pirapira/bamboo/1cca98e0b6d2579fe32885e66aafd0f5e25d9eb5/src/cross-platform-for-ocamlbuild/wrapCryptokit.ml
ocaml
module Hash = Cryptokit.Hash let string_keccak str : string = let sha3_256 = Hash.keccak 256 in let () = sha3_256#add_string str in let ret = sha3_256#result in let tr = Cryptokit.Hexa.encode () in let () = tr#put_string ret in let () = tr#finish in let ret = tr#get_string in need to convert ret into hex ret let strip_0x h = if BatString.starts_with h "0x" then BatString.tail h 2 else h let add_hex sha3_256 h = let h = strip_0x h in let add_byte c = sha3_256#add_char c in let chars = BatString.explode h in let rec work chars = match chars with | [] -> () | [x] -> failwith "odd-length hex" | a :: b :: rest -> let () = add_byte (Hex.to_char a b) in work rest in work chars let hex_keccak h : string = let sha3_256 = Hash.keccak 256 in let () = add_hex sha3_256 h in let ret = sha3_256#result in let tr = Cryptokit.Hexa.encode () in let () = tr#put_string ret in let () = tr#finish in let ret = tr#get_string in need to convert ret into hex ret
67c7c7590bc636c4e2823418c468bd11d8313d6a41e5b26e1b34087d8d6268cf
binghe/closette
utils.lisp
;;; Utilities ;;; (in-package #:closette) ;;; push-on-end is like push except it uses the other end: (defmacro push-on-end (value location) `(setf ,location (nconc ,location (list ,value)))) ( setf getf * ) is like ( setf getf ) except that it always changes the list , ;;; which must be non-nil. (defun (setf getf*) (new-value plist key) (block body (do ((x plist (cddr x))) ((null x)) (when (eq (car x) key) (setf (car (cdr x)) new-value) (return-from body new-value))) (push-on-end key plist) (push-on-end new-value plist) new-value)) ;;; mapappend is like mapcar except that the results are appended together: (defun mapappend (fun &rest args) (if (some #'null args) () (append (apply fun (mapcar #'car args)) (apply #'mapappend fun (mapcar #'cdr args))))) ;;; mapplist is mapcar for property lists: (defun mapplist (fun x) (if (null x) () (cons (funcall fun (car x) (cadr x)) (mapplist fun (cddr x)))))
null
https://raw.githubusercontent.com/binghe/closette/20ed5c8b0ef459394198e25081f39321e9df643b/utils.lisp
lisp
push-on-end is like push except it uses the other end: which must be non-nil. mapappend is like mapcar except that the results are appended together: mapplist is mapcar for property lists:
Utilities (in-package #:closette) (defmacro push-on-end (value location) `(setf ,location (nconc ,location (list ,value)))) ( setf getf * ) is like ( setf getf ) except that it always changes the list , (defun (setf getf*) (new-value plist key) (block body (do ((x plist (cddr x))) ((null x)) (when (eq (car x) key) (setf (car (cdr x)) new-value) (return-from body new-value))) (push-on-end key plist) (push-on-end new-value plist) new-value)) (defun mapappend (fun &rest args) (if (some #'null args) () (append (apply fun (mapcar #'car args)) (apply #'mapappend fun (mapcar #'cdr args))))) (defun mapplist (fun x) (if (null x) () (cons (funcall fun (car x) (cadr x)) (mapplist fun (cddr x)))))
ec7e907ba04d0faab1331915364bdcfdccdc2e2ad4cd92c964d8ca0bffb146a6
janestreet/incr_dom
entry_id.mli
open! Core open! Import type t val create : int -> t include Identifiable with type t := t val id_string : t -> string
null
https://raw.githubusercontent.com/janestreet/incr_dom/56c04e44d6a8f1cc9b2b841495ec448de4bf61a1/example/entry_table/entry_id.mli
ocaml
open! Core open! Import type t val create : int -> t include Identifiable with type t := t val id_string : t -> string
07a7a72f14e60beeb4d4930319a038456b66933515f28213938088bdcea67f85
ruhler/smten
Yices2.hs
# LANGUAGE DataKinds # # LANGUAGE NoImplicitPrelude # module Smten.Tests.Yices2 (main) where import Smten.Prelude import qualified Smten.Tests.SMT.Core as Core import qualified Smten.Tests.SMT.Datatype as Datatype import qualified Smten.Tests.SMT.Error as Error import qualified Smten.Tests.SMT.Integer as Integer import qualified Smten.Tests.SMT.Bit as Bit import Smten.Tests.SMT.Test import Smten.Search.Solver.Yices2 main :: IO () main = do runtest (SMTTestCfg yices2 [] ["SMT.Core.IteSym"]) Core.smttests putStrLn "Yices2.SMT.Core PASSED" runtest (SMTTestCfg yices2 [] []) Datatype.smttests putStrLn "Yices2.SMT.Datatype PASSED" runtest (SMTTestCfg yices2 [] []) Integer.smttests putStrLn "Yices2.SMT.Integer PASSED" runtest (SMTTestCfg yices2 [] []) Bit.smttests putStrLn "Yices2.SMT.Bit PASSED" runtest (SMTTestCfg yices2 [] []) Error.smttests putStrLn "Yices2.SMT.Error PASSED"
null
https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-lib/Smten/Tests/Yices2.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE NoImplicitPrelude # module Smten.Tests.Yices2 (main) where import Smten.Prelude import qualified Smten.Tests.SMT.Core as Core import qualified Smten.Tests.SMT.Datatype as Datatype import qualified Smten.Tests.SMT.Error as Error import qualified Smten.Tests.SMT.Integer as Integer import qualified Smten.Tests.SMT.Bit as Bit import Smten.Tests.SMT.Test import Smten.Search.Solver.Yices2 main :: IO () main = do runtest (SMTTestCfg yices2 [] ["SMT.Core.IteSym"]) Core.smttests putStrLn "Yices2.SMT.Core PASSED" runtest (SMTTestCfg yices2 [] []) Datatype.smttests putStrLn "Yices2.SMT.Datatype PASSED" runtest (SMTTestCfg yices2 [] []) Integer.smttests putStrLn "Yices2.SMT.Integer PASSED" runtest (SMTTestCfg yices2 [] []) Bit.smttests putStrLn "Yices2.SMT.Bit PASSED" runtest (SMTTestCfg yices2 [] []) Error.smttests putStrLn "Yices2.SMT.Error PASSED"
af43636cb55aeeadc0672551d9dd8e418287d9283b345b750611e32dc1e1be5d
tommaisey/aeon
ring4.help.scm
;; (ring4 a b) ;; Ring modulation variant. Return the value of ((a*a *b) - ;; (a*b*b)). This is more efficient than using separate unit ;; generators for the multiplies. See also , ring1 , , . (audition (out 0 (mul (ring4 (f-sin-osc ar 800 0) (f-sin-osc ar (x-line kr 200 500 5 do-nothing) 0)) 0.125))) (let ((a (f-sin-osc ar 800 0)) (b (f-sin-osc ar (x-line kr 200 500 5 do-nothing) 0))) (audition (out 0 (mul (sub (mul3 a a b) (mul3 a b b)) 0.125))))
null
https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/binary-ops/ring4.help.scm
scheme
(ring4 a b) Ring modulation variant. Return the value of ((a*a *b) - (a*b*b)). This is more efficient than using separate unit generators for the multiplies.
See also , ring1 , , . (audition (out 0 (mul (ring4 (f-sin-osc ar 800 0) (f-sin-osc ar (x-line kr 200 500 5 do-nothing) 0)) 0.125))) (let ((a (f-sin-osc ar 800 0)) (b (f-sin-osc ar (x-line kr 200 500 5 do-nothing) 0))) (audition (out 0 (mul (sub (mul3 a a b) (mul3 a b b)) 0.125))))
516c7f49ecf53423c59886fa9dc72cf993b21bb4cd08cb1135b163f534f16be7
seanomlor/programming-in-haskell
zip.hs
zip' :: [a] -> [b] -> [(a, b)] zip' [] _ = [] zip' _ [] = [] zip' (x:xs) (y:ys) = (x, y) : zip' xs ys
null
https://raw.githubusercontent.com/seanomlor/programming-in-haskell/e05142e6709eeba2e95cf86f376a32c9e629df88/06-recursive-functions/zip.hs
haskell
zip' :: [a] -> [b] -> [(a, b)] zip' [] _ = [] zip' _ [] = [] zip' (x:xs) (y:ys) = (x, y) : zip' xs ys
692aab1aef3f0ba089df6ff6be048fa6e44392c6423f54b7c38b1a7804b98d6c
Simre1/haskell-game
Manual.hs
import Graphics.GPipe import qualified Graphics.GPipe.Context.GLFW as GLFW import qualified Test.Common as C import qualified Test.Control as A main :: IO () main = do putStrLn "== Manual event processing" putStrLn $ "\tRender a scene to a window without automatic event processing." runContextT handleConfig $ do win <- newWindow (WindowFormatColorDepth RGB8 Depth16) (GLFW.defaultWindowConfig "Manual") resources <- C.initRenderContext win [C.xAxis, C.yAxis, C.zAxis] C.mainloop win (A.frames 60) resources (const $ GLFW.mainstep win GLFW.Poll >> C.continue undefined) where -- Config which disables automatic event processing handleConfig = GLFW.defaultHandleConfig {GLFW.configEventPolicy=Nothing}
null
https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/GPipe-GLFW/Smoketests/src/Manual.hs
haskell
Config which disables automatic event processing
import Graphics.GPipe import qualified Graphics.GPipe.Context.GLFW as GLFW import qualified Test.Common as C import qualified Test.Control as A main :: IO () main = do putStrLn "== Manual event processing" putStrLn $ "\tRender a scene to a window without automatic event processing." runContextT handleConfig $ do win <- newWindow (WindowFormatColorDepth RGB8 Depth16) (GLFW.defaultWindowConfig "Manual") resources <- C.initRenderContext win [C.xAxis, C.yAxis, C.zAxis] C.mainloop win (A.frames 60) resources (const $ GLFW.mainstep win GLFW.Poll >> C.continue undefined) where handleConfig = GLFW.defaultHandleConfig {GLFW.configEventPolicy=Nothing}
d3236f01bfcadff745c72cc03d1d2136522fc5721d91fcb32e563996f2fca3a5
jaredly/reason-language-server
btype.ml
(**************************************************************************) (* *) (* OCaml *) (* *) and , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Basic operations on core types *) open Misc open Asttypes open Types (**** Sets, maps and hashtables of types ****) module TypeSet = Set.Make(TypeOps) module TypeMap = Map.Make (TypeOps) module TypeHash = Hashtbl.Make(TypeOps) (**** Forward declarations ****) let print_raw = ref (fun _ -> assert false : Format.formatter -> type_expr -> unit) (**** Type level management ****) let generic_level = 100000000 (* Used to mark a type during a traversal. *) let lowest_level = 0 let pivot_level = 2 * lowest_level - 1 (* pivot_level - lowest_level < lowest_level *) (**** Some type creators ****) let new_id = ref (-1) let newty2 level desc = incr new_id; { desc; level; scope = None; id = !new_id } let newgenty desc = newty2 generic_level desc let newgenvar ?name () = newgenty (Tvar name) let newmarkedvar level = incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id } let ( ) = incr new_id ; { desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id } let newmarkedvar level = incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id } let newmarkedgenvar () = incr new_id; { desc = Tvar; level = pivot_level - generic_level; id = !new_id } *) (**** Check some types ****) let is_Tvar = function {desc=Tvar _} -> true | _ -> false let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false let is_Tconstr = function {desc=Tconstr _} -> true | _ -> false let dummy_method = "*dummy method*" let default_mty = function Some mty -> mty | None -> Mty_signature [] (**** Definitions for backtracking ****) type change = Ctype of type_expr * type_desc | Ccompress of type_expr * type_desc * type_desc | Clevel of type_expr * int | Cscope of type_expr * int option | Cname of (Path.t * type_expr list) option ref * (Path.t * type_expr list) option | Crow of row_field option ref * row_field option | Ckind of field_kind option ref * field_kind option | Ccommu of commutable ref * commutable | Cuniv of type_expr option ref * type_expr option | Ctypeset of TypeSet.t ref * TypeSet.t type changes = Change of change * changes ref | Unchanged | Invalid let trail = Weak.create 1 let log_change ch = match Weak.get trail 0 with None -> () | Some r -> let r' = ref Unchanged in r := Change (ch, r'); Weak.set trail 0 (Some r') (**** Representative of a type ****) let rec field_kind_repr = function Fvar {contents = Some kind} -> field_kind_repr kind | kind -> kind let rec repr_link compress t d = function {desc = Tlink t' as d'} -> repr_link true t d' t' | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent -> repr_link true t d' t' | t' -> if compress then begin log_change (Ccompress (t, t.desc, d)); t.desc <- d end; t' let repr t = match t.desc with Tlink t' as d -> repr_link false t d t' | Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent -> repr_link false t d t' | _ -> t let rec commu_repr = function Clink r when !r <> Cunknown -> commu_repr !r | c -> c let rec row_field_repr_aux tl = function Reither(_, tl', _, {contents = Some fi}) -> row_field_repr_aux (tl@tl') fi | Reither(c, tl', m, r) -> Reither(c, tl@tl', m, r) | Rpresent (Some _) when tl <> [] -> Rpresent (Some (List.hd tl)) | fi -> fi let row_field_repr fi = row_field_repr_aux [] fi let rec rev_concat l ll = match ll with [] -> l | l'::ll -> rev_concat (l'@l) ll let rec row_repr_aux ll row = match (repr row.row_more).desc with | Tvariant row' -> let f = row.row_fields in row_repr_aux (if f = [] then ll else f::ll) row' | _ -> if ll = [] then row else {row with row_fields = rev_concat row.row_fields ll} let row_repr row = row_repr_aux [] row let rec row_field tag row = let rec find = function | (tag',f) :: fields -> if tag = tag' then row_field_repr f else find fields | [] -> match repr row.row_more with | {desc=Tvariant row'} -> row_field tag row' | _ -> Rabsent in find row.row_fields let rec row_more row = match repr row.row_more with | {desc=Tvariant row'} -> row_more row' | ty -> ty let row_fixed row = let row = row_repr row in row.row_fixed || match (repr row.row_more).desc with Tvar _ | Tnil -> false | Tunivar _ | Tconstr _ -> true | _ -> assert false let static_row row = let row = row_repr row in row.row_closed && List.for_all (fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true) row.row_fields let hash_variant s = let accu = ref 0 in for i = 0 to String.length s - 1 do accu := 223 * !accu + Char.code s.[i] done; reduce to 31 bits accu := !accu land (1 lsl 31 - 1); make it signed for 64 bits architectures if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu let proxy ty = let ty0 = repr ty in match ty0.desc with | Tvariant row when not (static_row row) -> row_more row | Tobject (ty, _) -> let rec proxy_obj ty = match ty.desc with Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty | Tvar _ | Tunivar _ | Tconstr _ -> ty | Tnil -> ty0 | _ -> assert false in proxy_obj ty | _ -> ty0 (**** Utilities for fixed row private types ****) let row_of_type t = match (repr t).desc with Tobject(t,_) -> let rec get_row t = let t = repr t in match t.desc with Tfield(_,_,_,t) -> get_row t | _ -> t in get_row t | Tvariant row -> row_more row | _ -> t let has_constr_row t = not (is_Tconstr t) && is_Tconstr (row_of_type t) let is_row_name s = let l = String.length s in if l < 4 then false else String.sub s (l-4) 4 = "#row" let is_constr_row ~allow_ident t = match t.desc with Tconstr (Path.Pident id, _, _) when allow_ident -> is_row_name (Ident.name id) | Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s | _ -> false (**********************************) Utilities for type traversal (**********************************) let rec iter_row f row = List.iter (fun (_, fi) -> match row_field_repr fi with | Rpresent(Some ty) -> f ty | Reither(_, tl, _, _) -> List.iter f tl | _ -> ()) row.row_fields; match (repr row.row_more).desc with Tvariant row -> iter_row f row | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil -> Misc.may (fun (_,l) -> List.iter f l) row.row_name | _ -> assert false let iter_type_expr f ty = match ty.desc with Tvar _ -> () | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2 | Ttuple l -> List.iter f l | Tconstr (_, l, _) -> List.iter f l | Tobject(ty, {contents = Some (_, p)}) -> f ty; List.iter f p | Tobject (ty, _) -> f ty | Tvariant row -> iter_row f row; f (row_more row) | Tfield (_, _, ty1, ty2) -> f ty1; f ty2 | Tnil -> () | Tlink ty -> f ty | Tsubst ty -> f ty | Tunivar _ -> () | Tpoly (ty, tyl) -> f ty; List.iter f tyl | Tpackage (_, _, l) -> List.iter f l let rec iter_abbrev f = function Mnil -> () | Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem | Mlink rem -> iter_abbrev f !rem type type_iterators = { it_signature: type_iterators -> signature -> unit; it_signature_item: type_iterators -> signature_item -> unit; it_value_description: type_iterators -> value_description -> unit; it_type_declaration: type_iterators -> type_declaration -> unit; it_extension_constructor: type_iterators -> extension_constructor -> unit; it_module_declaration: type_iterators -> module_declaration -> unit; it_modtype_declaration: type_iterators -> modtype_declaration -> unit; it_class_declaration: type_iterators -> class_declaration -> unit; it_class_type_declaration: type_iterators -> class_type_declaration -> unit; it_module_type: type_iterators -> module_type -> unit; it_class_type: type_iterators -> class_type -> unit; it_type_kind: type_iterators -> type_kind -> unit; it_do_type_expr: type_iterators -> type_expr -> unit; it_type_expr: type_iterators -> type_expr -> unit; it_path: Path.t -> unit; } let iter_type_expr_cstr_args f = function | Cstr_tuple tl -> List.iter f tl | Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls let map_type_expr_cstr_args f = function | Cstr_tuple tl -> Cstr_tuple (List.map f tl) | Cstr_record lbls -> Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls) let iter_type_expr_kind f = function | Type_abstract -> () | Type_variant cstrs -> List.iter (fun cd -> iter_type_expr_cstr_args f cd.cd_args; Misc.may f cd.cd_res ) cstrs | Type_record(lbls, _) -> List.iter (fun d -> f d.ld_type) lbls | Type_open -> () let type_iterators = let it_signature it = List.iter (it.it_signature_item it) and it_signature_item it = function Sig_value (_, vd) -> it.it_value_description it vd | Sig_type (_, td, _) -> it.it_type_declaration it td | Sig_typext (_, td, _) -> it.it_extension_constructor it td | Sig_module (_, md, _) -> it.it_module_declaration it md | Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd | Sig_class (_, cd, _) -> it.it_class_declaration it cd | Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd and it_value_description it vd = it.it_type_expr it vd.val_type and it_type_declaration it td = List.iter (it.it_type_expr it) td.type_params; may (it.it_type_expr it) td.type_manifest; it.it_type_kind it td.type_kind and it_extension_constructor it td = it.it_path td.ext_type_path; List.iter (it.it_type_expr it) td.ext_type_params; iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args; may (it.it_type_expr it) td.ext_ret_type and it_module_declaration it md = it.it_module_type it md.md_type and it_modtype_declaration it mtd = may (it.it_module_type it) mtd.mtd_type and it_class_declaration it cd = List.iter (it.it_type_expr it) cd.cty_params; it.it_class_type it cd.cty_type; may (it.it_type_expr it) cd.cty_new; it.it_path cd.cty_path and it_class_type_declaration it ctd = List.iter (it.it_type_expr it) ctd.clty_params; it.it_class_type it ctd.clty_type; it.it_path ctd.clty_path and it_module_type it = function Mty_ident p | Mty_alias(_, p) -> it.it_path p | Mty_signature sg -> it.it_signature it sg | Mty_functor (_, mto, mt) -> may (it.it_module_type it) mto; it.it_module_type it mt and it_class_type it = function Cty_constr (p, tyl, cty) -> it.it_path p; List.iter (it.it_type_expr it) tyl; it.it_class_type it cty | Cty_signature cs -> it.it_type_expr it cs.csig_self; Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars; List.iter (fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl) cs.csig_inher | Cty_arrow (_, ty, cty) -> it.it_type_expr it ty; it.it_class_type it cty and it_type_kind it kind = iter_type_expr_kind (it.it_type_expr it) kind and it_do_type_expr it ty = iter_type_expr (it.it_type_expr it) ty; match ty.desc with Tconstr (p, _, _) | Tobject (_, {contents=Some (p, _)}) | Tpackage (p, _, _) -> it.it_path p | Tvariant row -> may (fun (p,_) -> it.it_path p) (row_repr row).row_name | _ -> () and it_path _p = () in { it_path; it_type_expr = it_do_type_expr; it_do_type_expr; it_type_kind; it_class_type; it_module_type; it_signature; it_class_type_declaration; it_class_declaration; it_modtype_declaration; it_module_declaration; it_extension_constructor; it_type_declaration; it_value_description; it_signature_item; } let copy_row f fixed row keep more = let fields = List.map (fun (l, fi) -> l, match row_field_repr fi with | Rpresent(Some ty) -> Rpresent(Some(f ty)) | Reither(c, tl, m, e) -> let e = if keep then e else ref None in let m = if row.row_fixed then fixed else m in let tl = List.map f tl in Reither(c, tl, m, e) | _ -> fi) row.row_fields in let name = match row.row_name with None -> None | Some (path, tl) -> Some (path, List.map f tl) in { row_fields = fields; row_more = more; row_bound = (); row_fixed = row.row_fixed && fixed; row_closed = row.row_closed; row_name = name; } let rec copy_kind = function Fvar{contents = Some k} -> copy_kind k | Fvar _ -> Fvar (ref None) | Fpresent -> Fpresent | Fabsent -> assert false let copy_commu c = if commu_repr c = Cok then Cok else Clink (ref Cunknown) (* Since univars may be used as row variables, we need to do some encoding during substitution *) let rec norm_univar ty = match ty.desc with Tunivar _ | Tsubst _ -> ty | Tlink ty -> norm_univar ty | Ttuple (ty :: _) -> norm_univar ty | _ -> assert false let rec copy_type_desc ?(keep_names=false) f = function Tvar _ as ty -> if keep_names then ty else Tvar None | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c) | Ttuple l -> Ttuple (List.map f l) | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil) | Tobject(ty, {contents = Some (p, tl)}) -> Tobject (f ty, ref (Some(p, List.map f tl))) | Tobject (ty, _) -> Tobject (f ty, ref None) | Tvariant _ -> assert false (* too ambiguous *) | Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *) Tfield (p, field_kind_repr k, f ty1, f ty2) | Tnil -> Tnil | Tlink ty -> copy_type_desc f ty.desc | Tsubst _ -> assert false | Tunivar _ as ty -> ty (* always keep the name *) | Tpoly (ty, tyl) -> let tyl = List.map (fun x -> norm_univar (f x)) tyl in Tpoly (f ty, tyl) | Tpackage (p, n, l) -> Tpackage (p, n, List.map f l) Utilities for copying let saved_desc = ref [] (* Saved association of generic nodes with their description. *) let save_desc ty desc = saved_desc := (ty, desc)::!saved_desc let saved_kinds = ref [] (* duplicated kind variables *) let new_kinds = ref [] (* new kind variables *) let dup_kind r = (match !r with None -> () | Some _ -> assert false); if not (List.memq r !new_kinds) then begin saved_kinds := r :: !saved_kinds; let r' = ref None in new_kinds := r' :: !new_kinds; r := Some (Fvar r') end (* Restored type descriptions. *) let cleanup_types () = List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc; List.iter (fun r -> r := None) !saved_kinds; saved_desc := []; saved_kinds := []; new_kinds := [] (* Mark a type. *) let rec mark_type ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr mark_type ty end let mark_type_node ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; end let mark_type_params ty = iter_type_expr mark_type ty let type_iterators = let it_type_expr it ty = let ty = repr ty in if ty.level >= lowest_level then begin mark_type_node ty; it.it_do_type_expr it ty; end in {type_iterators with it_type_expr} (* Remove marks from a type. *) let rec unmark_type ty = let ty = repr ty in if ty.level < lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr unmark_type ty end let unmark_iterators = let it_type_expr _it ty = unmark_type ty in {type_iterators with it_type_expr} let unmark_type_decl decl = unmark_iterators.it_type_declaration unmark_iterators decl let unmark_extension_constructor ext = List.iter unmark_type ext.ext_type_params; iter_type_expr_cstr_args unmark_type ext.ext_args; Misc.may unmark_type ext.ext_ret_type let unmark_class_signature sign = unmark_type sign.csig_self; Vars.iter (fun _l (_m, _v, t) -> unmark_type t) sign.csig_vars let unmark_class_type cty = unmark_iterators.it_class_type unmark_iterators cty (*******************************************) (* Memorization of abbreviation expansion *) (*******************************************) (* Search whether the expansion has been memorized. *) let lte_public p1 p2 = (* Private <= Public *) match p1, p2 with | Private, _ | _, Public -> true | Public, Private -> false let rec find_expans priv p1 = function Mnil -> None | Mcons (priv', p2, _ty0, ty, _) when lte_public priv priv' && Path.same p1 p2 -> Some ty | Mcons (_, _, _, _, rem) -> find_expans priv p1 rem | Mlink {contents = rem} -> find_expans priv p1 rem debug : check for cycles in abbreviation . only works with -principal let rec check_expans visited ty = let ty = repr ty in assert ( not ( visited ) ) ; match ty.desc with Tconstr ( path , args , abbrev ) - > begin match find_expans path ! abbrev with Some ty ' - > check_expans ( ty : : visited ) ty ' | None - > ( ) end | _ - > ( ) let rec check_expans visited ty = let ty = repr ty in assert (not (List.memq ty visited)); match ty.desc with Tconstr (path, args, abbrev) -> begin match find_expans path !abbrev with Some ty' -> check_expans (ty :: visited) ty' | None -> () end | _ -> () *) let memo = ref [] (* Contains the list of saved abbreviation expansions. *) let cleanup_abbrev () = (* Remove all memorized abbreviation expansions. *) List.iter (fun abbr -> abbr := Mnil) !memo; memo := [] let memorize_abbrev mem priv path v v' = (* Memorize the expansion of an abbreviation. *) mem := Mcons (priv, path, v, v', !mem); check_expans [ ] v ; memo := mem :: !memo let rec forget_abbrev_rec mem path = match mem with Mnil -> mem | Mcons (_, path', _, _, rem) when Path.same path path' -> rem | Mcons (priv, path', v, v', rem) -> Mcons (priv, path', v, v', forget_abbrev_rec rem path) | Mlink mem' -> mem' := forget_abbrev_rec !mem' path; raise Exit let forget_abbrev mem path = try mem := forget_abbrev_rec !mem path with Exit -> () debug : check for invalid abbreviations let rec check_abbrev_rec = function Mnil - > true | Mcons ( _ , , ty2 , rem ) - > repr ! = repr ty2 | Mlink mem ' - > check_abbrev_rec ! ' let ( ) = List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo let rec check_abbrev_rec = function Mnil -> true | Mcons (_, ty1, ty2, rem) -> repr ty1 != repr ty2 | Mlink mem' -> check_abbrev_rec !mem' let check_memorized_abbrevs () = List.for_all (fun mem -> check_abbrev_rec !mem) !memo *) (**********************************) Utilities for labels (**********************************) let is_optional = function Optional _ -> true | _ -> false let label_name = function Nolabel -> "" | Labelled s | Optional s -> s let prefixed_label_name = function Nolabel -> "" | Labelled s -> "~" ^ s | Optional s -> "?" ^ s let rec extract_label_aux hd l = function [] -> raise Not_found | (l',t as p) :: ls -> if label_name l' = l then (l', t, List.rev hd, ls) else extract_label_aux (p::hd) l ls let extract_label l ls = extract_label_aux [] l ls (**********************************) Utilities for backtracking (**********************************) let undo_change = function Ctype (ty, desc) -> ty.desc <- desc | Ccompress (ty, desc, _) -> ty.desc <- desc | Clevel (ty, level) -> ty.level <- level | Cscope (ty, scope) -> ty.scope <- scope | Cname (r, v) -> r := v | Crow (r, v) -> r := v | Ckind (r, v) -> r := v | Ccommu (r, v) -> r := v | Cuniv (r, v) -> r := v | Ctypeset (r, v) -> r := v type snapshot = changes ref * int let last_snapshot = ref 0 let log_type ty = if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc)) let link_type ty ty' = log_type ty; let desc = ty.desc in ty.desc <- Tlink ty'; (* Name is a user-supplied name for this unification variable (obtained * through a type annotation for instance). *) match desc, ty'.desc with Tvar name, Tvar name' -> begin match name, name' with | Some _, None -> log_type ty'; ty'.desc <- Tvar name | None, Some _ -> () | Some _, Some _ -> if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name) | None, None -> () end | _ -> () ; assert ( ( ) ) ; check_expans [ ] ty ' let set_level ty level = if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level)); ty.level <- level let set_scope ty scope = if ty.id <= !last_snapshot then log_change (Cscope (ty, ty.scope)); ty.scope <- scope let set_univar rty ty = log_change (Cuniv (rty, !rty)); rty := Some ty let set_name nm v = log_change (Cname (nm, !nm)); nm := v let set_row_field e v = log_change (Crow (e, !e)); e := Some v let set_kind rk k = log_change (Ckind (rk, !rk)); rk := Some k let set_commu rc c = log_change (Ccommu (rc, !rc)); rc := c let set_typeset rs s = log_change (Ctypeset (rs, !rs)); rs := s let snapshot () = let old = !last_snapshot in last_snapshot := !new_id; match Weak.get trail 0 with Some r -> (r, old) | None -> let r = ref Unchanged in Weak.set trail 0 (Some r); (r, old) let rec rev_log accu = function Unchanged -> accu | Invalid -> assert false | Change (ch, next) -> let d = !next in next := Invalid; rev_log (ch::accu) d let backtrack (changes, old) = match !changes with Unchanged -> last_snapshot := old | Invalid -> failwith "Btype.backtrack" | Change _ as change -> cleanup_abbrev (); let backlog = rev_log [] change in List.iter undo_change backlog; changes := Unchanged; last_snapshot := old; Weak.set trail 0 (Some changes) let rec rev_compress_log log r = match !r with Unchanged | Invalid -> log | Change (Ccompress _, next) -> rev_compress_log (r::log) next | Change (_, next) -> rev_compress_log log next let undo_compress (changes, _old) = match !changes with Unchanged | Invalid -> () | Change _ -> let log = rev_compress_log [] changes in List.iter (fun r -> match !r with Change (Ccompress (ty, desc, d), next) when ty.desc == d -> ty.desc <- desc; r := !next | _ -> ()) log
null
https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/407/btype.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Basic operations on core types *** Sets, maps and hashtables of types *** *** Forward declarations *** *** Type level management *** Used to mark a type during a traversal. pivot_level - lowest_level < lowest_level *** Some type creators *** *** Check some types *** *** Definitions for backtracking *** *** Representative of a type *** *** Utilities for fixed row private types *** ******************************** ******************************** Since univars may be used as row variables, we need to do some encoding during substitution too ambiguous the kind is kept shared always keep the name Saved association of generic nodes with their description. duplicated kind variables new kind variables Restored type descriptions. Mark a type. Remove marks from a type. ***************************************** Memorization of abbreviation expansion ***************************************** Search whether the expansion has been memorized. Private <= Public Contains the list of saved abbreviation expansions. Remove all memorized abbreviation expansions. Memorize the expansion of an abbreviation. ******************************** ******************************** ******************************** ******************************** Name is a user-supplied name for this unification variable (obtained * through a type annotation for instance).
and , projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Misc open Asttypes open Types module TypeSet = Set.Make(TypeOps) module TypeMap = Map.Make (TypeOps) module TypeHash = Hashtbl.Make(TypeOps) let print_raw = ref (fun _ -> assert false : Format.formatter -> type_expr -> unit) let generic_level = 100000000 let lowest_level = 0 let pivot_level = 2 * lowest_level - 1 let new_id = ref (-1) let newty2 level desc = incr new_id; { desc; level; scope = None; id = !new_id } let newgenty desc = newty2 generic_level desc let newgenvar ?name () = newgenty (Tvar name) let newmarkedvar level = incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id } let ( ) = incr new_id ; { desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id } let newmarkedvar level = incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id } let newmarkedgenvar () = incr new_id; { desc = Tvar; level = pivot_level - generic_level; id = !new_id } *) let is_Tvar = function {desc=Tvar _} -> true | _ -> false let is_Tunivar = function {desc=Tunivar _} -> true | _ -> false let is_Tconstr = function {desc=Tconstr _} -> true | _ -> false let dummy_method = "*dummy method*" let default_mty = function Some mty -> mty | None -> Mty_signature [] type change = Ctype of type_expr * type_desc | Ccompress of type_expr * type_desc * type_desc | Clevel of type_expr * int | Cscope of type_expr * int option | Cname of (Path.t * type_expr list) option ref * (Path.t * type_expr list) option | Crow of row_field option ref * row_field option | Ckind of field_kind option ref * field_kind option | Ccommu of commutable ref * commutable | Cuniv of type_expr option ref * type_expr option | Ctypeset of TypeSet.t ref * TypeSet.t type changes = Change of change * changes ref | Unchanged | Invalid let trail = Weak.create 1 let log_change ch = match Weak.get trail 0 with None -> () | Some r -> let r' = ref Unchanged in r := Change (ch, r'); Weak.set trail 0 (Some r') let rec field_kind_repr = function Fvar {contents = Some kind} -> field_kind_repr kind | kind -> kind let rec repr_link compress t d = function {desc = Tlink t' as d'} -> repr_link true t d' t' | {desc = Tfield (_, k, _, t') as d'} when field_kind_repr k = Fabsent -> repr_link true t d' t' | t' -> if compress then begin log_change (Ccompress (t, t.desc, d)); t.desc <- d end; t' let repr t = match t.desc with Tlink t' as d -> repr_link false t d t' | Tfield (_, k, _, t') as d when field_kind_repr k = Fabsent -> repr_link false t d t' | _ -> t let rec commu_repr = function Clink r when !r <> Cunknown -> commu_repr !r | c -> c let rec row_field_repr_aux tl = function Reither(_, tl', _, {contents = Some fi}) -> row_field_repr_aux (tl@tl') fi | Reither(c, tl', m, r) -> Reither(c, tl@tl', m, r) | Rpresent (Some _) when tl <> [] -> Rpresent (Some (List.hd tl)) | fi -> fi let row_field_repr fi = row_field_repr_aux [] fi let rec rev_concat l ll = match ll with [] -> l | l'::ll -> rev_concat (l'@l) ll let rec row_repr_aux ll row = match (repr row.row_more).desc with | Tvariant row' -> let f = row.row_fields in row_repr_aux (if f = [] then ll else f::ll) row' | _ -> if ll = [] then row else {row with row_fields = rev_concat row.row_fields ll} let row_repr row = row_repr_aux [] row let rec row_field tag row = let rec find = function | (tag',f) :: fields -> if tag = tag' then row_field_repr f else find fields | [] -> match repr row.row_more with | {desc=Tvariant row'} -> row_field tag row' | _ -> Rabsent in find row.row_fields let rec row_more row = match repr row.row_more with | {desc=Tvariant row'} -> row_more row' | ty -> ty let row_fixed row = let row = row_repr row in row.row_fixed || match (repr row.row_more).desc with Tvar _ | Tnil -> false | Tunivar _ | Tconstr _ -> true | _ -> assert false let static_row row = let row = row_repr row in row.row_closed && List.for_all (fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true) row.row_fields let hash_variant s = let accu = ref 0 in for i = 0 to String.length s - 1 do accu := 223 * !accu + Char.code s.[i] done; reduce to 31 bits accu := !accu land (1 lsl 31 - 1); make it signed for 64 bits architectures if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu let proxy ty = let ty0 = repr ty in match ty0.desc with | Tvariant row when not (static_row row) -> row_more row | Tobject (ty, _) -> let rec proxy_obj ty = match ty.desc with Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty | Tvar _ | Tunivar _ | Tconstr _ -> ty | Tnil -> ty0 | _ -> assert false in proxy_obj ty | _ -> ty0 let row_of_type t = match (repr t).desc with Tobject(t,_) -> let rec get_row t = let t = repr t in match t.desc with Tfield(_,_,_,t) -> get_row t | _ -> t in get_row t | Tvariant row -> row_more row | _ -> t let has_constr_row t = not (is_Tconstr t) && is_Tconstr (row_of_type t) let is_row_name s = let l = String.length s in if l < 4 then false else String.sub s (l-4) 4 = "#row" let is_constr_row ~allow_ident t = match t.desc with Tconstr (Path.Pident id, _, _) when allow_ident -> is_row_name (Ident.name id) | Tconstr (Path.Pdot (_, s, _), _, _) -> is_row_name s | _ -> false Utilities for type traversal let rec iter_row f row = List.iter (fun (_, fi) -> match row_field_repr fi with | Rpresent(Some ty) -> f ty | Reither(_, tl, _, _) -> List.iter f tl | _ -> ()) row.row_fields; match (repr row.row_more).desc with Tvariant row -> iter_row f row | Tvar _ | Tunivar _ | Tsubst _ | Tconstr _ | Tnil -> Misc.may (fun (_,l) -> List.iter f l) row.row_name | _ -> assert false let iter_type_expr f ty = match ty.desc with Tvar _ -> () | Tarrow (_, ty1, ty2, _) -> f ty1; f ty2 | Ttuple l -> List.iter f l | Tconstr (_, l, _) -> List.iter f l | Tobject(ty, {contents = Some (_, p)}) -> f ty; List.iter f p | Tobject (ty, _) -> f ty | Tvariant row -> iter_row f row; f (row_more row) | Tfield (_, _, ty1, ty2) -> f ty1; f ty2 | Tnil -> () | Tlink ty -> f ty | Tsubst ty -> f ty | Tunivar _ -> () | Tpoly (ty, tyl) -> f ty; List.iter f tyl | Tpackage (_, _, l) -> List.iter f l let rec iter_abbrev f = function Mnil -> () | Mcons(_, _, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem | Mlink rem -> iter_abbrev f !rem type type_iterators = { it_signature: type_iterators -> signature -> unit; it_signature_item: type_iterators -> signature_item -> unit; it_value_description: type_iterators -> value_description -> unit; it_type_declaration: type_iterators -> type_declaration -> unit; it_extension_constructor: type_iterators -> extension_constructor -> unit; it_module_declaration: type_iterators -> module_declaration -> unit; it_modtype_declaration: type_iterators -> modtype_declaration -> unit; it_class_declaration: type_iterators -> class_declaration -> unit; it_class_type_declaration: type_iterators -> class_type_declaration -> unit; it_module_type: type_iterators -> module_type -> unit; it_class_type: type_iterators -> class_type -> unit; it_type_kind: type_iterators -> type_kind -> unit; it_do_type_expr: type_iterators -> type_expr -> unit; it_type_expr: type_iterators -> type_expr -> unit; it_path: Path.t -> unit; } let iter_type_expr_cstr_args f = function | Cstr_tuple tl -> List.iter f tl | Cstr_record lbls -> List.iter (fun d -> f d.ld_type) lbls let map_type_expr_cstr_args f = function | Cstr_tuple tl -> Cstr_tuple (List.map f tl) | Cstr_record lbls -> Cstr_record (List.map (fun d -> {d with ld_type=f d.ld_type}) lbls) let iter_type_expr_kind f = function | Type_abstract -> () | Type_variant cstrs -> List.iter (fun cd -> iter_type_expr_cstr_args f cd.cd_args; Misc.may f cd.cd_res ) cstrs | Type_record(lbls, _) -> List.iter (fun d -> f d.ld_type) lbls | Type_open -> () let type_iterators = let it_signature it = List.iter (it.it_signature_item it) and it_signature_item it = function Sig_value (_, vd) -> it.it_value_description it vd | Sig_type (_, td, _) -> it.it_type_declaration it td | Sig_typext (_, td, _) -> it.it_extension_constructor it td | Sig_module (_, md, _) -> it.it_module_declaration it md | Sig_modtype (_, mtd) -> it.it_modtype_declaration it mtd | Sig_class (_, cd, _) -> it.it_class_declaration it cd | Sig_class_type (_, ctd, _) -> it.it_class_type_declaration it ctd and it_value_description it vd = it.it_type_expr it vd.val_type and it_type_declaration it td = List.iter (it.it_type_expr it) td.type_params; may (it.it_type_expr it) td.type_manifest; it.it_type_kind it td.type_kind and it_extension_constructor it td = it.it_path td.ext_type_path; List.iter (it.it_type_expr it) td.ext_type_params; iter_type_expr_cstr_args (it.it_type_expr it) td.ext_args; may (it.it_type_expr it) td.ext_ret_type and it_module_declaration it md = it.it_module_type it md.md_type and it_modtype_declaration it mtd = may (it.it_module_type it) mtd.mtd_type and it_class_declaration it cd = List.iter (it.it_type_expr it) cd.cty_params; it.it_class_type it cd.cty_type; may (it.it_type_expr it) cd.cty_new; it.it_path cd.cty_path and it_class_type_declaration it ctd = List.iter (it.it_type_expr it) ctd.clty_params; it.it_class_type it ctd.clty_type; it.it_path ctd.clty_path and it_module_type it = function Mty_ident p | Mty_alias(_, p) -> it.it_path p | Mty_signature sg -> it.it_signature it sg | Mty_functor (_, mto, mt) -> may (it.it_module_type it) mto; it.it_module_type it mt and it_class_type it = function Cty_constr (p, tyl, cty) -> it.it_path p; List.iter (it.it_type_expr it) tyl; it.it_class_type it cty | Cty_signature cs -> it.it_type_expr it cs.csig_self; Vars.iter (fun _ (_,_,ty) -> it.it_type_expr it ty) cs.csig_vars; List.iter (fun (p, tl) -> it.it_path p; List.iter (it.it_type_expr it) tl) cs.csig_inher | Cty_arrow (_, ty, cty) -> it.it_type_expr it ty; it.it_class_type it cty and it_type_kind it kind = iter_type_expr_kind (it.it_type_expr it) kind and it_do_type_expr it ty = iter_type_expr (it.it_type_expr it) ty; match ty.desc with Tconstr (p, _, _) | Tobject (_, {contents=Some (p, _)}) | Tpackage (p, _, _) -> it.it_path p | Tvariant row -> may (fun (p,_) -> it.it_path p) (row_repr row).row_name | _ -> () and it_path _p = () in { it_path; it_type_expr = it_do_type_expr; it_do_type_expr; it_type_kind; it_class_type; it_module_type; it_signature; it_class_type_declaration; it_class_declaration; it_modtype_declaration; it_module_declaration; it_extension_constructor; it_type_declaration; it_value_description; it_signature_item; } let copy_row f fixed row keep more = let fields = List.map (fun (l, fi) -> l, match row_field_repr fi with | Rpresent(Some ty) -> Rpresent(Some(f ty)) | Reither(c, tl, m, e) -> let e = if keep then e else ref None in let m = if row.row_fixed then fixed else m in let tl = List.map f tl in Reither(c, tl, m, e) | _ -> fi) row.row_fields in let name = match row.row_name with None -> None | Some (path, tl) -> Some (path, List.map f tl) in { row_fields = fields; row_more = more; row_bound = (); row_fixed = row.row_fixed && fixed; row_closed = row.row_closed; row_name = name; } let rec copy_kind = function Fvar{contents = Some k} -> copy_kind k | Fvar _ -> Fvar (ref None) | Fpresent -> Fpresent | Fabsent -> assert false let copy_commu c = if commu_repr c = Cok then Cok else Clink (ref Cunknown) let rec norm_univar ty = match ty.desc with Tunivar _ | Tsubst _ -> ty | Tlink ty -> norm_univar ty | Ttuple (ty :: _) -> norm_univar ty | _ -> assert false let rec copy_type_desc ?(keep_names=false) f = function Tvar _ as ty -> if keep_names then ty else Tvar None | Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c) | Ttuple l -> Ttuple (List.map f l) | Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil) | Tobject(ty, {contents = Some (p, tl)}) -> Tobject (f ty, ref (Some(p, List.map f tl))) | Tobject (ty, _) -> Tobject (f ty, ref None) Tfield (p, field_kind_repr k, f ty1, f ty2) | Tnil -> Tnil | Tlink ty -> copy_type_desc f ty.desc | Tsubst _ -> assert false | Tpoly (ty, tyl) -> let tyl = List.map (fun x -> norm_univar (f x)) tyl in Tpoly (f ty, tyl) | Tpackage (p, n, l) -> Tpackage (p, n, List.map f l) Utilities for copying let saved_desc = ref [] let save_desc ty desc = saved_desc := (ty, desc)::!saved_desc let dup_kind r = (match !r with None -> () | Some _ -> assert false); if not (List.memq r !new_kinds) then begin saved_kinds := r :: !saved_kinds; let r' = ref None in new_kinds := r' :: !new_kinds; r := Some (Fvar r') end let cleanup_types () = List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc; List.iter (fun r -> r := None) !saved_kinds; saved_desc := []; saved_kinds := []; new_kinds := [] let rec mark_type ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr mark_type ty end let mark_type_node ty = let ty = repr ty in if ty.level >= lowest_level then begin ty.level <- pivot_level - ty.level; end let mark_type_params ty = iter_type_expr mark_type ty let type_iterators = let it_type_expr it ty = let ty = repr ty in if ty.level >= lowest_level then begin mark_type_node ty; it.it_do_type_expr it ty; end in {type_iterators with it_type_expr} let rec unmark_type ty = let ty = repr ty in if ty.level < lowest_level then begin ty.level <- pivot_level - ty.level; iter_type_expr unmark_type ty end let unmark_iterators = let it_type_expr _it ty = unmark_type ty in {type_iterators with it_type_expr} let unmark_type_decl decl = unmark_iterators.it_type_declaration unmark_iterators decl let unmark_extension_constructor ext = List.iter unmark_type ext.ext_type_params; iter_type_expr_cstr_args unmark_type ext.ext_args; Misc.may unmark_type ext.ext_ret_type let unmark_class_signature sign = unmark_type sign.csig_self; Vars.iter (fun _l (_m, _v, t) -> unmark_type t) sign.csig_vars let unmark_class_type cty = unmark_iterators.it_class_type unmark_iterators cty match p1, p2 with | Private, _ | _, Public -> true | Public, Private -> false let rec find_expans priv p1 = function Mnil -> None | Mcons (priv', p2, _ty0, ty, _) when lte_public priv priv' && Path.same p1 p2 -> Some ty | Mcons (_, _, _, _, rem) -> find_expans priv p1 rem | Mlink {contents = rem} -> find_expans priv p1 rem debug : check for cycles in abbreviation . only works with -principal let rec check_expans visited ty = let ty = repr ty in assert ( not ( visited ) ) ; match ty.desc with Tconstr ( path , args , abbrev ) - > begin match find_expans path ! abbrev with Some ty ' - > check_expans ( ty : : visited ) ty ' | None - > ( ) end | _ - > ( ) let rec check_expans visited ty = let ty = repr ty in assert (not (List.memq ty visited)); match ty.desc with Tconstr (path, args, abbrev) -> begin match find_expans path !abbrev with Some ty' -> check_expans (ty :: visited) ty' | None -> () end | _ -> () *) let memo = ref [] let cleanup_abbrev () = List.iter (fun abbr -> abbr := Mnil) !memo; memo := [] let memorize_abbrev mem priv path v v' = mem := Mcons (priv, path, v, v', !mem); check_expans [ ] v ; memo := mem :: !memo let rec forget_abbrev_rec mem path = match mem with Mnil -> mem | Mcons (_, path', _, _, rem) when Path.same path path' -> rem | Mcons (priv, path', v, v', rem) -> Mcons (priv, path', v, v', forget_abbrev_rec rem path) | Mlink mem' -> mem' := forget_abbrev_rec !mem' path; raise Exit let forget_abbrev mem path = try mem := forget_abbrev_rec !mem path with Exit -> () debug : check for invalid abbreviations let rec check_abbrev_rec = function Mnil - > true | Mcons ( _ , , ty2 , rem ) - > repr ! = repr ty2 | Mlink mem ' - > check_abbrev_rec ! ' let ( ) = List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo let rec check_abbrev_rec = function Mnil -> true | Mcons (_, ty1, ty2, rem) -> repr ty1 != repr ty2 | Mlink mem' -> check_abbrev_rec !mem' let check_memorized_abbrevs () = List.for_all (fun mem -> check_abbrev_rec !mem) !memo *) Utilities for labels let is_optional = function Optional _ -> true | _ -> false let label_name = function Nolabel -> "" | Labelled s | Optional s -> s let prefixed_label_name = function Nolabel -> "" | Labelled s -> "~" ^ s | Optional s -> "?" ^ s let rec extract_label_aux hd l = function [] -> raise Not_found | (l',t as p) :: ls -> if label_name l' = l then (l', t, List.rev hd, ls) else extract_label_aux (p::hd) l ls let extract_label l ls = extract_label_aux [] l ls Utilities for backtracking let undo_change = function Ctype (ty, desc) -> ty.desc <- desc | Ccompress (ty, desc, _) -> ty.desc <- desc | Clevel (ty, level) -> ty.level <- level | Cscope (ty, scope) -> ty.scope <- scope | Cname (r, v) -> r := v | Crow (r, v) -> r := v | Ckind (r, v) -> r := v | Ccommu (r, v) -> r := v | Cuniv (r, v) -> r := v | Ctypeset (r, v) -> r := v type snapshot = changes ref * int let last_snapshot = ref 0 let log_type ty = if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc)) let link_type ty ty' = log_type ty; let desc = ty.desc in ty.desc <- Tlink ty'; match desc, ty'.desc with Tvar name, Tvar name' -> begin match name, name' with | Some _, None -> log_type ty'; ty'.desc <- Tvar name | None, Some _ -> () | Some _, Some _ -> if ty.level < ty'.level then (log_type ty'; ty'.desc <- Tvar name) | None, None -> () end | _ -> () ; assert ( ( ) ) ; check_expans [ ] ty ' let set_level ty level = if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level)); ty.level <- level let set_scope ty scope = if ty.id <= !last_snapshot then log_change (Cscope (ty, ty.scope)); ty.scope <- scope let set_univar rty ty = log_change (Cuniv (rty, !rty)); rty := Some ty let set_name nm v = log_change (Cname (nm, !nm)); nm := v let set_row_field e v = log_change (Crow (e, !e)); e := Some v let set_kind rk k = log_change (Ckind (rk, !rk)); rk := Some k let set_commu rc c = log_change (Ccommu (rc, !rc)); rc := c let set_typeset rs s = log_change (Ctypeset (rs, !rs)); rs := s let snapshot () = let old = !last_snapshot in last_snapshot := !new_id; match Weak.get trail 0 with Some r -> (r, old) | None -> let r = ref Unchanged in Weak.set trail 0 (Some r); (r, old) let rec rev_log accu = function Unchanged -> accu | Invalid -> assert false | Change (ch, next) -> let d = !next in next := Invalid; rev_log (ch::accu) d let backtrack (changes, old) = match !changes with Unchanged -> last_snapshot := old | Invalid -> failwith "Btype.backtrack" | Change _ as change -> cleanup_abbrev (); let backlog = rev_log [] change in List.iter undo_change backlog; changes := Unchanged; last_snapshot := old; Weak.set trail 0 (Some changes) let rec rev_compress_log log r = match !r with Unchanged | Invalid -> log | Change (Ccompress _, next) -> rev_compress_log (r::log) next | Change (_, next) -> rev_compress_log log next let undo_compress (changes, _old) = match !changes with Unchanged | Invalid -> () | Change _ -> let log = rev_compress_log [] changes in List.iter (fun r -> match !r with Change (Ccompress (ty, desc, d), next) when ty.desc == d -> ty.desc <- desc; r := !next | _ -> ()) log
e470d1a41cf9708b87a621c294a54ace87284960ddbcf1aa1d327ccd6a16cea7
frenetic-lang/netkat-automata
TermSize.ml
open Core.Std open Async.Std module Ast = Frenetic_Decide_Ast module Deriv = Frenetic_Decide_Deriv module DerivTerm = Deriv.BDDDeriv module Measurement = Frenetic_Decide_Measurement module Util = Frenetic_Decide_Util (* [base f] returns the basename of [f] without any file extensions. *) let base (filename: string) : string = Filename.basename filename |> Filename.split_extension |> fst let p_main (p_files: string list) : unit Deferred.t = let p_size (p_file: string) : unit Deferred.t = Reader.file_contents p_file >>| fun policy_string -> Frenetic_NetKAT_Json.policy_from_json_string policy_string |> Frenetic_NetKAT_Semantics.size |> printf "%s, %d\n" (base p_file) in Deferred.List.iter ~f:p_size p_files let t_main (t_files: string list) : unit Deferred.t = let t_size (t_file: string) : unit Deferred.t = failwith "TODO" in Deferred.List.iter ~f:t_size t_files let p = Command.async ~summary:"Prints term size of policies." Command.Spec.( empty +> anon (sequence ("ps" %: file)) ) (fun p_files () -> p_main p_files) let t = Command.async ~summary:"Prints term size of topologies." Command.Spec.( empty +> anon (sequence ("ts" %: file)) ) (fun t_files () -> t_main t_files) let () = Command.group ~summary:"Prints term sizes of policies and topologies." [ ("p", p); ("t", t); ] |> Command.run
null
https://raw.githubusercontent.com/frenetic-lang/netkat-automata/a4c3809e40e7c2ce500182043a74131ac9c19579/src/TermSize.ml
ocaml
[base f] returns the basename of [f] without any file extensions.
open Core.Std open Async.Std module Ast = Frenetic_Decide_Ast module Deriv = Frenetic_Decide_Deriv module DerivTerm = Deriv.BDDDeriv module Measurement = Frenetic_Decide_Measurement module Util = Frenetic_Decide_Util let base (filename: string) : string = Filename.basename filename |> Filename.split_extension |> fst let p_main (p_files: string list) : unit Deferred.t = let p_size (p_file: string) : unit Deferred.t = Reader.file_contents p_file >>| fun policy_string -> Frenetic_NetKAT_Json.policy_from_json_string policy_string |> Frenetic_NetKAT_Semantics.size |> printf "%s, %d\n" (base p_file) in Deferred.List.iter ~f:p_size p_files let t_main (t_files: string list) : unit Deferred.t = let t_size (t_file: string) : unit Deferred.t = failwith "TODO" in Deferred.List.iter ~f:t_size t_files let p = Command.async ~summary:"Prints term size of policies." Command.Spec.( empty +> anon (sequence ("ps" %: file)) ) (fun p_files () -> p_main p_files) let t = Command.async ~summary:"Prints term size of topologies." Command.Spec.( empty +> anon (sequence ("ts" %: file)) ) (fun t_files () -> t_main t_files) let () = Command.group ~summary:"Prints term sizes of policies and topologies." [ ("p", p); ("t", t); ] |> Command.run
f8e9259008f01cb0a970767cd371ada3a0514c8ff72646be3898009abae7abb2
VincentToups/racket-lib
rmatch-let.rkt
#lang racket (require racket/match (for-syntax syntax/parse) (for-syntax racket/match) syntax/parse) (define-syntax (rmatch-let stx) (define (positive-integer? n) (and (number? n) (> n 0))) (define (gen-ids seed n) (let loop ((ids '()) (n n)) (match n [0 (reverse ids)] [(? positive-integer?) (loop (cons (datum->syntax seed (gensym "match-let/loop-dummy-")) ids) (- n 1))]))) (define-syntax-class binder (pattern [pat:expr val:expr])) (syntax-parse stx [(rmatch-let point:id [binder:binder ...] body:expr ...) (let* ((n (length (syntax->datum #'(binder ...)))) (ids (gen-ids #'point n)) (pats (map (lambda (s) (car (syntax-e s))) (syntax-e #'(binder ...)))) (inits (map (lambda (s) (cadr (syntax-e s))) (syntax-e #'(binder ...))))) (with-syntax (((arg ...) (datum->syntax #'point ids)) ((pat ...) (datum->syntax (car pats) pats)) ((init ...) (datum->syntax (car inits) inits))) #'(letrec [(point (lambda (arg ...) (match* (arg ...) [(pat ...) body ...])))] (point init ...))))])) (provide rmatch-let)
null
https://raw.githubusercontent.com/VincentToups/racket-lib/d8aed0959fd148615b000ceecd7b8a6128cfcfa8/utilities/rmatch-let.rkt
racket
#lang racket (require racket/match (for-syntax syntax/parse) (for-syntax racket/match) syntax/parse) (define-syntax (rmatch-let stx) (define (positive-integer? n) (and (number? n) (> n 0))) (define (gen-ids seed n) (let loop ((ids '()) (n n)) (match n [0 (reverse ids)] [(? positive-integer?) (loop (cons (datum->syntax seed (gensym "match-let/loop-dummy-")) ids) (- n 1))]))) (define-syntax-class binder (pattern [pat:expr val:expr])) (syntax-parse stx [(rmatch-let point:id [binder:binder ...] body:expr ...) (let* ((n (length (syntax->datum #'(binder ...)))) (ids (gen-ids #'point n)) (pats (map (lambda (s) (car (syntax-e s))) (syntax-e #'(binder ...)))) (inits (map (lambda (s) (cadr (syntax-e s))) (syntax-e #'(binder ...))))) (with-syntax (((arg ...) (datum->syntax #'point ids)) ((pat ...) (datum->syntax (car pats) pats)) ((init ...) (datum->syntax (car inits) inits))) #'(letrec [(point (lambda (arg ...) (match* (arg ...) [(pat ...) body ...])))] (point init ...))))])) (provide rmatch-let)
0ec4df40027bfad6e304cf171e15f0f87303333f89a87a6b7649f8fb1050e29f
antoniogarrote/egearmand-server
jobs_queue_server.erl
-module(jobs_queue_server) . %% @doc %% Module with functions handling the queues with job requests %% for different priority levels. -author("Antonio Garrote Hernandez") . -behaviour(gen_server) . -include_lib("states.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([start_link/0, submit_job/5, lookup_job/1, reeschedule_job/1, check_option_for_job/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, update_job_options/2]). -export([submit_job_from_client_proxy/5]) . %% Public API start_link() -> gen_server:start_link({local, jobs_queue_server}, jobs_queue_server, job_request, []) . %% @doc Creates a new job request for a certain FunctionName , and Level from a %% client connection established from ClientSocket. submit_job(Background, FunctionName, [UniqueId, OpaqueData], ClientSocket, Level) -> Identifier = lists:flatten(io_lib:format("H:~p:~p",[node(),make_ref()])), {ok, {Adress,Port}} = inet:peername(ClientSocket), ClientProxyId = list_to_atom(lists:flatten(io_lib:format("client@~p:~p:~p",[node(),Adress,Port]))), case global:whereis_name(ClientProxyId) of undefined -> client_proxy:start_link(ClientProxyId, ClientSocket) ; _PID -> dont_care end, JobRequest = #job_request{ identifier = Identifier, function = FunctionName, unique_id = UniqueId, opaque_data = OpaqueData, level = Level, background = Background, client_socket_id = ClientProxyId }, gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . %% @doc Creates a new job request for a certain FunctionName , and Level from a %% client connection established from ClientSocket. submit_job_from_client_proxy(ClientProxyId, Background, FunctionName, [UniqueId, OpaqueData], Level) -> Identifier = lists:flatten(io_lib:format("H:~p:~p",[node(),make_ref()])), JobRequest = #job_request{ identifier = Identifier, function = FunctionName, unique_id = UniqueId, opaque_data = OpaqueData, level = Level, background = Background, client_socket_id = ClientProxyId }, gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . %% @doc Inserts again an existent JobRequest in the queue of jobs reeschedule_job(#job_request{ level=Level } = JobRequest) -> gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . %% @doc Updates the options of a scheduled job identified by JobHandle %% inserting the provided Option. update_job_options(JobHandle, Option) -> gen_server:call(jobs_queue_server, {update_options, JobHandle, Option}) . %% @doc %% Searches for some job associated to the function identified byFunctionName in the queues %% of jobs for all the priorities: high, normal and low. The first job request associated to FunctionName in the queue of higher returned . -spec(lookup_job(atom()) -> {ok, (not_found | #job_request{})}) . lookup_job(FunctionName) -> gen_server:call(jobs_queue_server, {lookup_job, FunctionName}) . %% @doc Checks if an option is set for a ceratin JobRequest -spec(check_option_for_job(binary(), #job_request{}) -> (true | false)) . check_option_for_job(Option, JobRequest) -> lists:any(fun(X) -> X =:= Option end, JobRequest#job_request.options) . %% Callbacks init(State) -> {ok, State}. handle_call({submit_job, JobRequest, Level}, _From, _State) -> {reply, {ok, JobRequest#job_request.identifier}, mnesia_store:insert(JobRequest#job_request{queue_key = {JobRequest#job_request.function, Level}}, job_request)} ; handle_call({update_options, JobHandle, Option}, _From, _State) -> Res = mnesia_store:update(fun(#job_request{ options = Options } = Job) -> Job#job_request{ options = [Option | Options] } end, JobHandle, job_request), {reply, Res, _State} ; handle_call({lookup_job, FunctionName}, _From, State) -> Found = do_lookup_job(FunctionName, State, [high, normal, low]), case Found of {not_found, StateP} -> {reply, {ok, not_found}, StateP} ; {Result, StateP} -> {reply, {ok, Result}, StateP} end . %% dummy callbacks so no warning are shown at compile time handle_cast(_Msg, State) -> {noreply, State} . handle_info(_Msg, State) -> {noreply, State}. terminate(shutdown, #connections_state{ socket = _ServerSock }) -> ok. %% Private functions do_lookup_job(_FunctionName, Queues, []) -> {not_found, Queues} ; do_lookup_job(FunctionName, Queues, [Level | Levels]) -> Result = mnesia_store:dequeue(fun(X) -> X#job_request.queue_key == {FunctionName, Level} end, job_request), case Result of {not_found, _QueueP} -> do_lookup_job(FunctionName, Queues, Levels) ; _Else -> Result end . %% tests check_option_for_job_test() -> Job = #job_request{ options = [<<"tests">>] }, ?assertEqual(true, check_option_for_job(<<"tests">>, Job)), ?assertEqual(false, check_option_for_job(<<"foo">>, Job)) .
null
https://raw.githubusercontent.com/antoniogarrote/egearmand-server/45296fb40e3ddb77f71225121188545a371d2237/src/jobs_queue_server.erl
erlang
@doc Module with functions handling the queues with job requests for different priority levels. Public API @doc client connection established from ClientSocket. @doc client connection established from ClientSocket. @doc @doc inserting the provided Option. @doc Searches for some job associated to the function identified byFunctionName in the queues of jobs for all the priorities: high, normal and low. @doc Callbacks dummy callbacks so no warning are shown at compile time Private functions tests
-module(jobs_queue_server) . -author("Antonio Garrote Hernandez") . -behaviour(gen_server) . -include_lib("states.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([start_link/0, submit_job/5, lookup_job/1, reeschedule_job/1, check_option_for_job/2]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, update_job_options/2]). -export([submit_job_from_client_proxy/5]) . start_link() -> gen_server:start_link({local, jobs_queue_server}, jobs_queue_server, job_request, []) . Creates a new job request for a certain FunctionName , and Level from a submit_job(Background, FunctionName, [UniqueId, OpaqueData], ClientSocket, Level) -> Identifier = lists:flatten(io_lib:format("H:~p:~p",[node(),make_ref()])), {ok, {Adress,Port}} = inet:peername(ClientSocket), ClientProxyId = list_to_atom(lists:flatten(io_lib:format("client@~p:~p:~p",[node(),Adress,Port]))), case global:whereis_name(ClientProxyId) of undefined -> client_proxy:start_link(ClientProxyId, ClientSocket) ; _PID -> dont_care end, JobRequest = #job_request{ identifier = Identifier, function = FunctionName, unique_id = UniqueId, opaque_data = OpaqueData, level = Level, background = Background, client_socket_id = ClientProxyId }, gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . Creates a new job request for a certain FunctionName , and Level from a submit_job_from_client_proxy(ClientProxyId, Background, FunctionName, [UniqueId, OpaqueData], Level) -> Identifier = lists:flatten(io_lib:format("H:~p:~p",[node(),make_ref()])), JobRequest = #job_request{ identifier = Identifier, function = FunctionName, unique_id = UniqueId, opaque_data = OpaqueData, level = Level, background = Background, client_socket_id = ClientProxyId }, gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . Inserts again an existent JobRequest in the queue of jobs reeschedule_job(#job_request{ level=Level } = JobRequest) -> gen_server:call(jobs_queue_server, {submit_job, JobRequest, Level}) . Updates the options of a scheduled job identified by JobHandle update_job_options(JobHandle, Option) -> gen_server:call(jobs_queue_server, {update_options, JobHandle, Option}) . The first job request associated to FunctionName in the queue of higher returned . -spec(lookup_job(atom()) -> {ok, (not_found | #job_request{})}) . lookup_job(FunctionName) -> gen_server:call(jobs_queue_server, {lookup_job, FunctionName}) . Checks if an option is set for a ceratin JobRequest -spec(check_option_for_job(binary(), #job_request{}) -> (true | false)) . check_option_for_job(Option, JobRequest) -> lists:any(fun(X) -> X =:= Option end, JobRequest#job_request.options) . init(State) -> {ok, State}. handle_call({submit_job, JobRequest, Level}, _From, _State) -> {reply, {ok, JobRequest#job_request.identifier}, mnesia_store:insert(JobRequest#job_request{queue_key = {JobRequest#job_request.function, Level}}, job_request)} ; handle_call({update_options, JobHandle, Option}, _From, _State) -> Res = mnesia_store:update(fun(#job_request{ options = Options } = Job) -> Job#job_request{ options = [Option | Options] } end, JobHandle, job_request), {reply, Res, _State} ; handle_call({lookup_job, FunctionName}, _From, State) -> Found = do_lookup_job(FunctionName, State, [high, normal, low]), case Found of {not_found, StateP} -> {reply, {ok, not_found}, StateP} ; {Result, StateP} -> {reply, {ok, Result}, StateP} end . handle_cast(_Msg, State) -> {noreply, State} . handle_info(_Msg, State) -> {noreply, State}. terminate(shutdown, #connections_state{ socket = _ServerSock }) -> ok. do_lookup_job(_FunctionName, Queues, []) -> {not_found, Queues} ; do_lookup_job(FunctionName, Queues, [Level | Levels]) -> Result = mnesia_store:dequeue(fun(X) -> X#job_request.queue_key == {FunctionName, Level} end, job_request), case Result of {not_found, _QueueP} -> do_lookup_job(FunctionName, Queues, Levels) ; _Else -> Result end . check_option_for_job_test() -> Job = #job_request{ options = [<<"tests">>] }, ?assertEqual(true, check_option_for_job(<<"tests">>, Job)), ?assertEqual(false, check_option_for_job(<<"foo">>, Job)) .
e15e6a8488307b289692da12f89d1b40af0616278d5ea7e98360bfc10de51682
ocamllabs/ocaml-modular-implicits
listLabels.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , Kyoto University RIMS (* *) Copyright 2001 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) (* Module [ListLabels]: labelled List module *) include List
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/stdlib/listLabels.ml
ocaml
********************************************************************* OCaml the special exception on linking described in file ../LICENSE. ********************************************************************* Module [ListLabels]: labelled List module
, Kyoto University RIMS Copyright 2001 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with include List
f17faa7f7a87f2855f68318b794c983cd9906446105bd40e1835d5a4275fc2ed
kovasb/gamma-driver
program.cljs
(ns gamma.webgl.model.program (:require [gamma.webgl.model.core :as m] [gamma.webgl.shader :as shader] [gamma.webgl.model.attributes :as attributes] [gamma.webgl.model.uniforms :as uniforms])) (defrecord Program [root parts] m/IModel (resolve [this val] (@parts val)) (conform [this val] (m/delegate m/conform @parts val))) (defn variable-locations [gl shader obj] (reduce (fn [x y] (assoc x y (if (= :attribute (:storage y)) (.getAttribLocation gl obj (:name y)) (.getUniformLocation gl obj (:name y))))) {} (:inputs shader))) (defn create-program [root val] (let [o (shader/install-shader (:gl root) val) variable-locations (variable-locations (:gl root) val o)] (Program. root (atom {:attributes (attributes/->Attributes root (atom {}) variable-locations) :uniforms (uniforms/uniforms root variable-locations) :object o}))))
null
https://raw.githubusercontent.com/kovasb/gamma-driver/abe0e1dd01365404342f4e8e04263e48c4648b6e/src/gamma/webgl/model/program.cljs
clojure
(ns gamma.webgl.model.program (:require [gamma.webgl.model.core :as m] [gamma.webgl.shader :as shader] [gamma.webgl.model.attributes :as attributes] [gamma.webgl.model.uniforms :as uniforms])) (defrecord Program [root parts] m/IModel (resolve [this val] (@parts val)) (conform [this val] (m/delegate m/conform @parts val))) (defn variable-locations [gl shader obj] (reduce (fn [x y] (assoc x y (if (= :attribute (:storage y)) (.getAttribLocation gl obj (:name y)) (.getUniformLocation gl obj (:name y))))) {} (:inputs shader))) (defn create-program [root val] (let [o (shader/install-shader (:gl root) val) variable-locations (variable-locations (:gl root) val o)] (Program. root (atom {:attributes (attributes/->Attributes root (atom {}) variable-locations) :uniforms (uniforms/uniforms root variable-locations) :object o}))))
60483311a86744ac12e55f4810410bbc8928997467bdea9b1129012a6940747e
racehub/om-bootstrap
components.cljs
(ns om-bootstrap.docs.components "All components for the om-bootstrap documentation project." (:require [om.core :as om :include-macros true] [om-bootstrap.docs.example :refer [->example TODO]] [om-bootstrap.docs.shared :refer [page-header]] [om-bootstrap.button :as b] [om-bootstrap.grid :as g] [om-bootstrap.input :as i] [om-bootstrap.mixins :as m] [om-bootstrap.modal :as md] [om-bootstrap.nav :as n] [om-bootstrap.pagination :as pg] [om-bootstrap.panel :as p] [om-bootstrap.progress-bar :as pb] [om-bootstrap.random :as r] [om-bootstrap.table :refer [table]] [om-tools.core :refer-macros [defcomponentk]] [om-tools.dom :as d :include-macros true]) (:require-macros [om-bootstrap.macros :refer [slurp-example]])) ;; ## Helpers (defn info-callout [title content] (d/div {:class "bs-callout bs-callout-info"} (d/h4 title) content)) (defn warning [title content] (d/div {:class "bs-callout bs-callout-warning"} (d/h4 title) content)) (defn section [id title & children] (d/div {:class "bs-docs-section"} (d/h1 {:id id :class "page-header"} title) children)) # # Button (defn button-options [] [(d/h2 {:id "button-options"} "Options") (d/p "Use any of the available button style types to quickly create a styled button. Just modify the " (d/code ":bs-style") " prop.") (->example (slurp-example "button/types")) (warning "Button Spacing" (d/p "Because React doesn't output newlines between elements, buttons on the same line are displayed flush against each other. To preserve the spacing between multiple inline buttons, wrap your button group in " (d/code "b/toolbar") "."))]) (defn button-sizing [] [(d/h2 "Sizes") (d/p "Fancy larger or smaller buttons? Add " (d/code ":bs-size large") ", " (d/code ":bs-size small") ", or " (d/code ":bs-size xsmall") " for additional sizes.") (->example (slurp-example "button/sizes")) (d/p "Create block level buttons — those that span the full width of a parent — by adding the " (d/code ":block? true") " prop.") (->example (slurp-example "button/block"))]) (defn button-states [] [(d/h2 "Active state") (d/p "To set a button's active state, simply set the component's " (d/code ":active? true") " prop.") (->example (slurp-example "button/active")) (d/h2 "Disabled state") (d/p "Make buttons look unclickable by fading them back 50%. To do this, add the " (d/code ":disabled? true") "attribute to buttons.") (->example (slurp-example "button/disabled")) (warning "Event handler functionality not impacted" (d/p "This option will only change the button's appearance, not its functionality. Use custom logic to disable the effect of the " (d/code ":on-click") "handlers."))]) (defn button-groups [] (section "btn-groups" ["Button groups " (d/small "button.cljs")] (d/p {:class "lead"} "Group a series of buttons together on a single line with the button group.") (d/h3 "Basic example") (d/p "Wrap a series of " (d/code "b/button") "s together in a " (d/code "b/button-group") ".") (->example (slurp-example "button/group_basic")) (d/h3 "Button toolbar") (d/p "Combine sets of " (d/code "b/button-group") "s into a " (d/code "b/toolbar") " for more complex components.") (->example (slurp-example "button/toolbar_basic")) (d/h3 "Sizing") (d/p "Instead of applying button sizing props to every button in a group, add the " (d/code ":bs-size") " prop to the " (d/code "b/button-group") ".") (->example (slurp-example "button/group_sizes")) (d/h3 "Nesting") (d/p "You can place other button types within the " (d/code "b/button-group") ", like " (d/code "b/dropdown") "s.") (->example (slurp-example "button/group_nested")) (d/h3 "Vertical variation") (d/p "Make a set of buttons appear vertically stacked rather than horizontally. " (d/strong {:class "text-danger"} "Split button dropdowns are not supported here.")) (d/p "Just add " (d/code ":vertical? true") " to the " (d/code "b/button-group")) (->example (slurp-example "button/group_vertical")) (d/h3 "Justified button groups") (d/p "Make a group of buttons stretch at equal sizes to span the entire width of its parent. Also works with button dropdowns within the button group.") (warning "Style issues" (d/p "There are some issues and workarounds required when using this property, please see " (d/a {:href "/#btn-groups-justified"} "bootstrap's button group docs") " for more specifics.")) (d/p "Just add " (d/code ":justified? true") " to the " (d/code "b/button-group") ".") (->example (slurp-example "button/group_justified")))) (defn button-dropdowns [] (section "btn-dropdowns" "Button dropdowns" (d/p {:class "lead"} "Use " (d/code "b/dropdown") " or " (d/code "b/split") " components to display a button with a dropdown menu.") (d/h3 "Single button dropdowns") (d/p "Create a dropdown button with the " (d/code "b/dropdown") " component.") (->example (slurp-example "button/dropdown_basic")) (d/h3 "Split button dropdowns") (d/p "Similarly, create split button dropdowns with the " (d/code "b/split") " component.") (->example (slurp-example "button/split_basic")) (d/h3 "Sizing") (d/p "Button dropdowns work with buttons of all sizes.") (->example (slurp-example "button/dropdown_sizes")) (d/h3 "Dropup variation") (d/p "Trigger dropdown menus that site above the button by adding the " (d/code ":dropup? true") " option.") (->example (slurp-example "button/split_dropup")) (d/h3 "Dropdown right variation") (d/p "Trigger dropdown menus that align to the right of the button using the " (d/code ":pull-right? true") " option.") (->example (slurp-example "button/split_right")))) (defn button-main [] (section "buttons" ["Buttons " (d/small "button.cljs")] (button-options) (button-sizing) (button-states) (d/h2 "Button tags") (d/p "The DOM element tag is chosen automatically for you based on the options you supply. Passing " (d/code ":href") " will result in the button using a " (d/code "<a />") " element. Otherwise, a " (d/code "<button />") " element will be used.") (->example (slurp-example "button/tag_types")) (d/h2 "Button loading state") (d/p "When activating an asynchronous action from a button it is a good UX pattern to give the user feedback as to the loading state. This can easily be done by updating your button's props from a state change like below.") (->example (slurp-example "button/loading")))) (defn button-block [] [(button-main) (button-groups) (button-dropdowns)]) ;; ## Panel (defn panel-block [] (section "panels" ["Panels " (d/small "panel.cljs")] (d/h3 "Basic example") (d/p "By default, all the " (d/code "p/panel") " does is apply some basic border and padding to contain some content.") (->example (slurp-example "panel/basic")) (d/h3 "Panel with heading") (d/p "Easily add a heading container to your panel with the " (d/code ":header") " option.") (->example (slurp-example "panel/heading")) (d/h3 "Panel with footer") (d/p "Pass buttons or secondary text with the" (d/code ":footer") "option. Note that panel footers do not inherit colors and borders when using contextual variations as they are not meant to be in the foreground.") (->example (slurp-example "panel/footer")) (d/h3 "Panel with list group") (d/p "Put full-width list-groups in your panel with the " (d/code ":list-group") "option.") (->example (slurp-example "panel/list-group")) (d/h3 "Contextual alternatives") (d/p "Like other components, make a panel more meaningful to a particular context by adding a " (d/code ":bs-style") " prop.") (->example (slurp-example "panel/contextual")) (d/h3 "Collapsible panels") (d/p "This panel is collapsed by default and can be extended by clicking on the title") (->example (slurp-example "panel/collapsible")) (d/h3 "Controlled PanelGroups") (d/p (d/code "p/panel-group") "s can be controlled by a parent component. The " (d/code ":active-key") " prop dictates which panel is open.") (TODO) (d/h3 "Accordions") (d/p (d/code "p/accordion") " aliases " (d/code "(d/panel-group {:accordion? true} ,,,)") ".") (TODO))) # # Modal (defn modal-block [] (section "modals" ["Modals " (d/small "modal.cljs (IN PROGRESS)")] (d/h3 "A static example") (d/p "A rendered modal with header, body, and set of actions in the footer.") (d/p "The header is added automatically if you pass in a " (d/code ":title") " option.") (->example (slurp-example "modal/static")) (d/h3 "Live Demo") (d/p "Build your own component to trigger a modal") (->example (slurp-example "modal/live")))) # # Tooltips (defn tooltip-block [] (section "tooltips" ["Tooltips " (d/small "random.cljs")] (d/h3 "Example tooltips") (d/p "Tooltip component.") (->example (slurp-example "tooltip/basic")) (d/p "Positioned tooltip component.") (TODO) (d/p "Positioned tooltip in copy.") (TODO))) (comment (def positioned-tooltip-example "Positioned tooltip component. (TODO: Needs overlay trigger to finish!)" (let [tooltip (r/tooltip {} (d/strong "Holy guacamole!") "Check this info.")] (b/toolbar {} (overlay-trigger {:placement "left" :overlay tooltip}) (overlay-trigger {:placement "top" :overlay tooltip}) (overlay-trigger {:placement "bottom" :overlay tooltip}) (overlay-trigger {:placement "right" :overlay tooltip})))) (defn link-with-tooltip [{:keys [tooltip href]} & children] (overlay-trigger {:placement "top" :overlay (r/tooltip {} tooltip) :delay-show 300 :delay-hide 150} (d/a {:href href} children))) (def positioned-tooltip-with-copy (d/p {:class "muted" :style {:margin-bottom 0}} "Call me Ishmael. Some years ago - never mind how long " (link-with-tooltip {:tooltip "Probably about two." :href "#"} "precisely") " - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly " (link-with-tooltip {:tooltip "The eleventh month!" :href "#"} "November") " in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the " (link-with-tooltip {:tooltip "A large alley or a small avenue." :href "#"} "street") "m and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in " (link-with-tooltip {:tooltip "The ship, that is." :href "#"} "this") ". If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me."))) ;; ## Popovers (defn popover-block [] (section "popovers" ["Popovers " (d/small "random.cljs")] (d/h3 "Example popovers") (d/p "Popovers component.") (->example (slurp-example "popover/basic")) (d/p "Popovers component.") (TODO) (d/p "Popovers scrolling.") (TODO))) # # Progress Bars (defn progress-bar-block [] (section "progress" ["Progress bars " (d/small "progress_bar.cljs (IN PROGRESS)")] (d/p {:class "lead"} "Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.") (d/h3 "Basic example") (d/p "Default progress bar.") (->example (slurp-example "progressbar/basic")) (d/h3 "With label") (d/p "Add a " (d/code ":label") " prop to show a visible percentage. For low percentages, consider adding a" (d/code ":min-width") " to ensure the label's text is fully visible.") (->example (slurp-example "progressbar/label")) (d/h3 "Screenreader only label") (d/p "Add the " (d/code ":sr-only? true") " option to hide the label visually.") (->example (slurp-example "progressbar/sr_only_label")) (d/h3 "Contextual alternatives") (d/p "Progress bars use some of the same button and alert classes for consistent styles.") (->example (slurp-example "progressbar/contextual")) (d/h3 "Striped") (d/p "Uses a gradient to create a striped effect. Not available in IE8.") (->example (slurp-example "progressbar/striped")) (d/h3 "Animated") (d/p "Add the " (d/code ":active? true") " option to animate the stripes right to left. Not available in IE9 and below.") (->example (slurp-example "progressbar/active")) (d/h3 "Stacked") (d/p "Nest " (d/code "pb/progress-bar") "s to stack them.") (->example (slurp-example "progressbar/stacked")))) # # Navs (defn nav-block [] (section "navs" ["Navs " (d/small "nav.cljs")] (d/h3 "Example navs") (d/p "Navs come in two styles, pills:") (->example (slurp-example "nav/pills")) (d/p "And tabs:") (->example (slurp-example "nav/tabs")))) # # Navbars (defn navbar-block [] (section "navbars" ["Navbars " (d/small "nav.cljs")] (d/h3 "Example navbars") (->example (slurp-example "nav/bar_basic")))) # # Toggleable Tabs (defn tab-block [] (section "tabs" ["Toggleable tabs " (d/small "(In Progress)")] (d/h2 "Example tabs") (d/p "Add quick, dynamic tab functionality to transition through panes of local content, even via dropdown menus.") (d/h3 "Uncontrolled") (d/p "Allow the component to control its own state.") (TODO) (d/h3 "Controlled") (d/p "Pass down the active state on render via props.") (TODO) (d/h3 "No animation") (d/p "Set the " (d/code ":animation?") " property to " (d/code "false") ".") (TODO) (info-callout "Extends tabbed navigation" ["This plugin extends the " (d/a {:href "#navs"} "tabbed navigation component") " to add tabbable areas."]))) ;; ## Pagination (defn pagination-block [] (section "pagination" ["Pagination " (d/small "basic.cljs")] (d/p "Creates pages that can have " (d/code ":href") " or " (d/code ":on-click") " set to navigate between pages") (d/h3 "Basic Pagination") (->example (slurp-example "pagination/basic")) (d/h3 "Pagination with previous and next") (->example (slurp-example "pagination/navigation")) (d/h3 "Pages can be disabled") (->example (slurp-example "pagination/disabled")) (d/h3 "Pages can be marked as active") (->example (slurp-example "pagination/active")) (d/h3 "Pages can be centered") (->example (slurp-example "pagination/centered")))) # # Pager (defn pager-block [] (section "pager" ["Pager " (d/small "In Progress")] (d/p "Quick previous and next links.") (d/h3 "Default") (d/p "Centers by default.") (TODO) (d/h3 "Aligned") (d/p "Set the " (d/code ":previous?") " or " (d/code ":next?") " to " (d/code "true") " to align left or right.") (TODO) (d/h3 "Disabled") (d/p "Set the " (d/code ":disabled?") " prop to " (d/code "true") " to disabled the link.") (TODO))) ;; ## Alerts (defn alert-block [] (section "alerts" ["Alert messages " (d/small "random.cljs")] (d/h3 "Example alerts") (d/p "Basic alert styles.") (->example (slurp-example "alert/basic")) (d/p "For closeable alerts, just pass an " (d/code ":on-dismiss") " function.") (TODO) (d/p "Auto close after a set time with the " (d/code ":dismiss-after") " option.") (TODO))) # # Carousels (defn carousel-block [] (section "carousels" ["Carousels " (d/small "In Progress")] (d/h2 "Example Carousels") (d/h3 "Uncontrolled") (d/p "Allow the component to control its own state.") (TODO) (d/h3 "Controlled") (d/p "Pass down the active state on render via props.") (TODO))) # # Grids (defn grid-block [] (section "grids" ["Grids " (d/small "grid.cljs")] (d/h3 "Example grids") (->example (slurp-example "grid")))) ;; ## Labels (defn label-block [] (section "labels" ["Labels " (d/small "random.cljs")] (d/h3 "Example") (d/p "Create " (d/code "(r/label {} \"label\")") " to show highlight information.") (->example (slurp-example "label/basic")) (d/h3 "Available variations") (d/p "Add any of the below mentioned modifier classes to change the appearance of a label.") (->example (slurp-example "label/variations")))) ;; ## Badges (defn badge-block [] (section "badges" ["Badges " (d/small "random.cljs")] (d/p "Easily highlight new or unread items by adding a " (d/code "r/badge") " to links, Bootstrap navs, and more.") (d/h3 "Example") (->example (slurp-example "badge")) (info-callout "Cross-browser compatibility" "Unlike regular Bootstrap, badges self-collapse even in Internet Explorer 8."))) # # Jumbotron (defn jumbotron-block [] (section "jumbotron" ["Jumbotron " (d/small "random.cljs")] (d/p "A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.") (d/h3 "Example") (->example (slurp-example "jumbotron/basic")))) # # Page Header (defn header-block [] (section "page-header" ["Page Header " (d/small "random.cljs")] (d/p "A simple shell for an " (d/code "h1") " to appropriately space out and segment sections of content on a page. It can utilize the " (d/code "h1") "’s default " (d/code "small") " small element, as well as most other components (with additional styles).") (d/h3 "Example") (->example (slurp-example "page_header")))) ;; ## Well (defn well-block [] (section "wells" ["Wells " (d/small "random.cljs")] (d/p "Use the well as a simple effect on an element to give it an inset effect.") (d/h3 "Default Wells") (->example (slurp-example "well/basic")) (d/h3 "Optional classes") (d/p "Control padding and rounded corners with two optional modifier classes.") (->example (slurp-example "well/sizes")))) # # Glyphicons (defn glyphicon-block [] (section "glyphicons" ["Glyphicons " (d/small "random.cljs")] (d/p "Use them in buttons, button groups for a toolbar, navigation, or prepended form inputs.") (d/h3 "Example") (->example (slurp-example "glyphicon")))) ;; ## Tables (defn table-block [] (section "tables" ["Tables " (d/small "table.cljs")] (d/h3 "Example") (d/p "Use the " (d/code ":striped? true") ", " (d/code ":bordered? true") ", " (d/code ":condensed? true") ", and " (d/code ":hover? true") " options to customize the table.") (->example (slurp-example "table/basic")) (d/h3 "Responsive") (d/p "Add the " (d/code ":responsive? true") " option to make them scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.") (->example (slurp-example "table/responsive")))) # # Input (defn input-block [] (section "input" ["Input " (d/small "input.cljs")] (d/p "Renders an input in bootstrap wrappers. Supports label, help, text input add-ons, validation and use as wrapper. om-bootstrap tags the " (d/code "input") " node with a " (d/code ":ref") " and " (d/code ":key") ", so you can access the internal input element with " (d/code "(om/get-node owner \"input\")") " as demonstrated in the snippet.") (->example (slurp-example "input/validation")) (d/h3 "Types") (d/p "Supports " (d/code "select") ", " (d/code "textarea") ", " (d/code "static") " as well as the standard HTML input types.") (->example (slurp-example "input/types")) (d/h3 "Add-ons") (d/p "Use " (d/code ":addon-before") ", " (d/code ":addon-after") ", " (d/code ":addon-button-before") " and " (d/code ":addon-button-after") ".") (->example (slurp-example "input/addons")) (d/h3 "Validation") (d/p "Set " (d/code ":bs-style") " to one of " (d/code "\"success\"") ", " (d/code "\"warning\"") ", or" (d/code "\"error\"") ". Add " (d/code ":has-feedback? true") " to show a glyphicon. Glyphicon may need additional styling if there is an add-on or no label.") (->example (slurp-example "input/feedback")) (d/h3 "Horizontal forms") (d/p "Use" (d/code ":label-classname") " and " (d/code ":wrapper-classname") (d/p " options to add col classes manually. Checkbox and radio types need special treatment because label wraps input.")) (->example (slurp-example "input/horizontal")) (d/h3 "Use as a wrapper") (d/p "If " (d/code ":type") " is not set, child element(s) will be rendered instead of an input element.") (->example (slurp-example "input/wrapper")))) ;; ## Final Page Loading (defn sidebar [] (d/div {:class "col-md-3"} (d/div {:class "bs-docs-sidebar hidden-print" :role "complementary"} (n/nav {:class "bs-docs-sidenav"} (n/nav-item {:href "#buttons"} "Buttons") (n/nav-item {:href "#panels"} "Panels") (n/nav-item {:href "#modals"} "Modals") (n/nav-item {:href "#tooltips"} "Tooltips") (n/nav-item {:href "#popovers"} "Popovers") (n/nav-item {:href "#progress"} "Progress bars") (n/nav-item {:href "#navs"} "Navs") (n/nav-item {:href "#navbars"} "Navbars") (n/nav-item {:href "#tabs"} "Toggleable Tabs") (n/nav-item {:href "#pagination"} "Pagination") (n/nav-item {:href "#pager"} "Pager") (n/nav-item {:href "#alerts"} "Alerts") (n/nav-item {:href "#carousels"} "Carousels") (n/nav-item {:href "#grids"} "Grids") (n/nav-item {:href "#listgroup"} "List group") (n/nav-item {:href "#labels"} "Labels") (n/nav-item {:href "#badges"} "Badges") (n/nav-item {:href "#jumbotron"} "Jumbotron") (n/nav-item {:href "#page-header"} "Page header") (n/nav-item {:href "#wells"} "Wells") (n/nav-item {:href "#glyphicons"} "Glyphicons") (n/nav-item {:href "#tables"} "Tables") (n/nav-item {:href "#input"} "Input")) (d/a {:class "back-to-top" :href "#top"} "Back to top")))) (defn lead [] (d/div {:class "lead"} "This page lists the Om-Bootstrap components. For each component, we provide:" (d/ul (d/li "Usage instructions") (d/li "An example code snippet") (d/li "The rendered result of the example snippet")) "Click \"show code\" below the rendered component to reveal the snippet.")) (defn components-page [] [(page-header {:title "Components"}) (d/div {:class "container bs-docs-container"} (d/div {:class "row"} (d/div {:class "col-md-9" :role "main"} (lead) (button-block) (panel-block) (modal-block) (tooltip-block) (popover-block) (progress-bar-block) (nav-block) (navbar-block) (tab-block) (pagination-block) (pager-block) (alert-block) (carousel-block) (grid-block) (label-block) (badge-block) (jumbotron-block) (header-block) (well-block) (glyphicon-block) (table-block) (input-block)) (sidebar)))])
null
https://raw.githubusercontent.com/racehub/om-bootstrap/18fb7f67c306d208bcb012a1b765ac1641d7a00b/docs/src/cljs/om_bootstrap/docs/components.cljs
clojure
## Helpers ## Panel ## Popovers ## Pagination ## Alerts ## Labels ## Badges ## Well ## Tables ## Final Page Loading
(ns om-bootstrap.docs.components "All components for the om-bootstrap documentation project." (:require [om.core :as om :include-macros true] [om-bootstrap.docs.example :refer [->example TODO]] [om-bootstrap.docs.shared :refer [page-header]] [om-bootstrap.button :as b] [om-bootstrap.grid :as g] [om-bootstrap.input :as i] [om-bootstrap.mixins :as m] [om-bootstrap.modal :as md] [om-bootstrap.nav :as n] [om-bootstrap.pagination :as pg] [om-bootstrap.panel :as p] [om-bootstrap.progress-bar :as pb] [om-bootstrap.random :as r] [om-bootstrap.table :refer [table]] [om-tools.core :refer-macros [defcomponentk]] [om-tools.dom :as d :include-macros true]) (:require-macros [om-bootstrap.macros :refer [slurp-example]])) (defn info-callout [title content] (d/div {:class "bs-callout bs-callout-info"} (d/h4 title) content)) (defn warning [title content] (d/div {:class "bs-callout bs-callout-warning"} (d/h4 title) content)) (defn section [id title & children] (d/div {:class "bs-docs-section"} (d/h1 {:id id :class "page-header"} title) children)) # # Button (defn button-options [] [(d/h2 {:id "button-options"} "Options") (d/p "Use any of the available button style types to quickly create a styled button. Just modify the " (d/code ":bs-style") " prop.") (->example (slurp-example "button/types")) (warning "Button Spacing" (d/p "Because React doesn't output newlines between elements, buttons on the same line are displayed flush against each other. To preserve the spacing between multiple inline buttons, wrap your button group in " (d/code "b/toolbar") "."))]) (defn button-sizing [] [(d/h2 "Sizes") (d/p "Fancy larger or smaller buttons? Add " (d/code ":bs-size large") ", " (d/code ":bs-size small") ", or " (d/code ":bs-size xsmall") " for additional sizes.") (->example (slurp-example "button/sizes")) (d/p "Create block level buttons — those that span the full width of a parent — by adding the " (d/code ":block? true") " prop.") (->example (slurp-example "button/block"))]) (defn button-states [] [(d/h2 "Active state") (d/p "To set a button's active state, simply set the component's " (d/code ":active? true") " prop.") (->example (slurp-example "button/active")) (d/h2 "Disabled state") (d/p "Make buttons look unclickable by fading them back 50%. To do this, add the " (d/code ":disabled? true") "attribute to buttons.") (->example (slurp-example "button/disabled")) (warning "Event handler functionality not impacted" (d/p "This option will only change the button's appearance, not its functionality. Use custom logic to disable the effect of the " (d/code ":on-click") "handlers."))]) (defn button-groups [] (section "btn-groups" ["Button groups " (d/small "button.cljs")] (d/p {:class "lead"} "Group a series of buttons together on a single line with the button group.") (d/h3 "Basic example") (d/p "Wrap a series of " (d/code "b/button") "s together in a " (d/code "b/button-group") ".") (->example (slurp-example "button/group_basic")) (d/h3 "Button toolbar") (d/p "Combine sets of " (d/code "b/button-group") "s into a " (d/code "b/toolbar") " for more complex components.") (->example (slurp-example "button/toolbar_basic")) (d/h3 "Sizing") (d/p "Instead of applying button sizing props to every button in a group, add the " (d/code ":bs-size") " prop to the " (d/code "b/button-group") ".") (->example (slurp-example "button/group_sizes")) (d/h3 "Nesting") (d/p "You can place other button types within the " (d/code "b/button-group") ", like " (d/code "b/dropdown") "s.") (->example (slurp-example "button/group_nested")) (d/h3 "Vertical variation") (d/p "Make a set of buttons appear vertically stacked rather than horizontally. " (d/strong {:class "text-danger"} "Split button dropdowns are not supported here.")) (d/p "Just add " (d/code ":vertical? true") " to the " (d/code "b/button-group")) (->example (slurp-example "button/group_vertical")) (d/h3 "Justified button groups") (d/p "Make a group of buttons stretch at equal sizes to span the entire width of its parent. Also works with button dropdowns within the button group.") (warning "Style issues" (d/p "There are some issues and workarounds required when using this property, please see " (d/a {:href "/#btn-groups-justified"} "bootstrap's button group docs") " for more specifics.")) (d/p "Just add " (d/code ":justified? true") " to the " (d/code "b/button-group") ".") (->example (slurp-example "button/group_justified")))) (defn button-dropdowns [] (section "btn-dropdowns" "Button dropdowns" (d/p {:class "lead"} "Use " (d/code "b/dropdown") " or " (d/code "b/split") " components to display a button with a dropdown menu.") (d/h3 "Single button dropdowns") (d/p "Create a dropdown button with the " (d/code "b/dropdown") " component.") (->example (slurp-example "button/dropdown_basic")) (d/h3 "Split button dropdowns") (d/p "Similarly, create split button dropdowns with the " (d/code "b/split") " component.") (->example (slurp-example "button/split_basic")) (d/h3 "Sizing") (d/p "Button dropdowns work with buttons of all sizes.") (->example (slurp-example "button/dropdown_sizes")) (d/h3 "Dropup variation") (d/p "Trigger dropdown menus that site above the button by adding the " (d/code ":dropup? true") " option.") (->example (slurp-example "button/split_dropup")) (d/h3 "Dropdown right variation") (d/p "Trigger dropdown menus that align to the right of the button using the " (d/code ":pull-right? true") " option.") (->example (slurp-example "button/split_right")))) (defn button-main [] (section "buttons" ["Buttons " (d/small "button.cljs")] (button-options) (button-sizing) (button-states) (d/h2 "Button tags") (d/p "The DOM element tag is chosen automatically for you based on the options you supply. Passing " (d/code ":href") " will result in the button using a " (d/code "<a />") " element. Otherwise, a " (d/code "<button />") " element will be used.") (->example (slurp-example "button/tag_types")) (d/h2 "Button loading state") (d/p "When activating an asynchronous action from a button it is a good UX pattern to give the user feedback as to the loading state. This can easily be done by updating your button's props from a state change like below.") (->example (slurp-example "button/loading")))) (defn button-block [] [(button-main) (button-groups) (button-dropdowns)]) (defn panel-block [] (section "panels" ["Panels " (d/small "panel.cljs")] (d/h3 "Basic example") (d/p "By default, all the " (d/code "p/panel") " does is apply some basic border and padding to contain some content.") (->example (slurp-example "panel/basic")) (d/h3 "Panel with heading") (d/p "Easily add a heading container to your panel with the " (d/code ":header") " option.") (->example (slurp-example "panel/heading")) (d/h3 "Panel with footer") (d/p "Pass buttons or secondary text with the" (d/code ":footer") "option. Note that panel footers do not inherit colors and borders when using contextual variations as they are not meant to be in the foreground.") (->example (slurp-example "panel/footer")) (d/h3 "Panel with list group") (d/p "Put full-width list-groups in your panel with the " (d/code ":list-group") "option.") (->example (slurp-example "panel/list-group")) (d/h3 "Contextual alternatives") (d/p "Like other components, make a panel more meaningful to a particular context by adding a " (d/code ":bs-style") " prop.") (->example (slurp-example "panel/contextual")) (d/h3 "Collapsible panels") (d/p "This panel is collapsed by default and can be extended by clicking on the title") (->example (slurp-example "panel/collapsible")) (d/h3 "Controlled PanelGroups") (d/p (d/code "p/panel-group") "s can be controlled by a parent component. The " (d/code ":active-key") " prop dictates which panel is open.") (TODO) (d/h3 "Accordions") (d/p (d/code "p/accordion") " aliases " (d/code "(d/panel-group {:accordion? true} ,,,)") ".") (TODO))) # # Modal (defn modal-block [] (section "modals" ["Modals " (d/small "modal.cljs (IN PROGRESS)")] (d/h3 "A static example") (d/p "A rendered modal with header, body, and set of actions in the footer.") (d/p "The header is added automatically if you pass in a " (d/code ":title") " option.") (->example (slurp-example "modal/static")) (d/h3 "Live Demo") (d/p "Build your own component to trigger a modal") (->example (slurp-example "modal/live")))) # # Tooltips (defn tooltip-block [] (section "tooltips" ["Tooltips " (d/small "random.cljs")] (d/h3 "Example tooltips") (d/p "Tooltip component.") (->example (slurp-example "tooltip/basic")) (d/p "Positioned tooltip component.") (TODO) (d/p "Positioned tooltip in copy.") (TODO))) (comment (def positioned-tooltip-example "Positioned tooltip component. (TODO: Needs overlay trigger to finish!)" (let [tooltip (r/tooltip {} (d/strong "Holy guacamole!") "Check this info.")] (b/toolbar {} (overlay-trigger {:placement "left" :overlay tooltip}) (overlay-trigger {:placement "top" :overlay tooltip}) (overlay-trigger {:placement "bottom" :overlay tooltip}) (overlay-trigger {:placement "right" :overlay tooltip})))) (defn link-with-tooltip [{:keys [tooltip href]} & children] (overlay-trigger {:placement "top" :overlay (r/tooltip {} tooltip) :delay-show 300 :delay-hide 150} (d/a {:href href} children))) (def positioned-tooltip-with-copy (d/p {:class "muted" :style {:margin-bottom 0}} "Call me Ishmael. Some years ago - never mind how long " (link-with-tooltip {:tooltip "Probably about two." :href "#"} "precisely") " - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly " (link-with-tooltip {:tooltip "The eleventh month!" :href "#"} "November") " in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the " (link-with-tooltip {:tooltip "A large alley or a small avenue." :href "#"} "street") "m and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in " (link-with-tooltip {:tooltip "The ship, that is." :href "#"} "this") ". If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me."))) (defn popover-block [] (section "popovers" ["Popovers " (d/small "random.cljs")] (d/h3 "Example popovers") (d/p "Popovers component.") (->example (slurp-example "popover/basic")) (d/p "Popovers component.") (TODO) (d/p "Popovers scrolling.") (TODO))) # # Progress Bars (defn progress-bar-block [] (section "progress" ["Progress bars " (d/small "progress_bar.cljs (IN PROGRESS)")] (d/p {:class "lead"} "Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.") (d/h3 "Basic example") (d/p "Default progress bar.") (->example (slurp-example "progressbar/basic")) (d/h3 "With label") (d/p "Add a " (d/code ":label") " prop to show a visible percentage. For low percentages, consider adding a" (d/code ":min-width") " to ensure the label's text is fully visible.") (->example (slurp-example "progressbar/label")) (d/h3 "Screenreader only label") (d/p "Add the " (d/code ":sr-only? true") " option to hide the label visually.") (->example (slurp-example "progressbar/sr_only_label")) (d/h3 "Contextual alternatives") (d/p "Progress bars use some of the same button and alert classes for consistent styles.") (->example (slurp-example "progressbar/contextual")) (d/h3 "Striped") (d/p "Uses a gradient to create a striped effect. Not available in IE8.") (->example (slurp-example "progressbar/striped")) (d/h3 "Animated") (d/p "Add the " (d/code ":active? true") " option to animate the stripes right to left. Not available in IE9 and below.") (->example (slurp-example "progressbar/active")) (d/h3 "Stacked") (d/p "Nest " (d/code "pb/progress-bar") "s to stack them.") (->example (slurp-example "progressbar/stacked")))) # # Navs (defn nav-block [] (section "navs" ["Navs " (d/small "nav.cljs")] (d/h3 "Example navs") (d/p "Navs come in two styles, pills:") (->example (slurp-example "nav/pills")) (d/p "And tabs:") (->example (slurp-example "nav/tabs")))) # # Navbars (defn navbar-block [] (section "navbars" ["Navbars " (d/small "nav.cljs")] (d/h3 "Example navbars") (->example (slurp-example "nav/bar_basic")))) # # Toggleable Tabs (defn tab-block [] (section "tabs" ["Toggleable tabs " (d/small "(In Progress)")] (d/h2 "Example tabs") (d/p "Add quick, dynamic tab functionality to transition through panes of local content, even via dropdown menus.") (d/h3 "Uncontrolled") (d/p "Allow the component to control its own state.") (TODO) (d/h3 "Controlled") (d/p "Pass down the active state on render via props.") (TODO) (d/h3 "No animation") (d/p "Set the " (d/code ":animation?") " property to " (d/code "false") ".") (TODO) (info-callout "Extends tabbed navigation" ["This plugin extends the " (d/a {:href "#navs"} "tabbed navigation component") " to add tabbable areas."]))) (defn pagination-block [] (section "pagination" ["Pagination " (d/small "basic.cljs")] (d/p "Creates pages that can have " (d/code ":href") " or " (d/code ":on-click") " set to navigate between pages") (d/h3 "Basic Pagination") (->example (slurp-example "pagination/basic")) (d/h3 "Pagination with previous and next") (->example (slurp-example "pagination/navigation")) (d/h3 "Pages can be disabled") (->example (slurp-example "pagination/disabled")) (d/h3 "Pages can be marked as active") (->example (slurp-example "pagination/active")) (d/h3 "Pages can be centered") (->example (slurp-example "pagination/centered")))) # # Pager (defn pager-block [] (section "pager" ["Pager " (d/small "In Progress")] (d/p "Quick previous and next links.") (d/h3 "Default") (d/p "Centers by default.") (TODO) (d/h3 "Aligned") (d/p "Set the " (d/code ":previous?") " or " (d/code ":next?") " to " (d/code "true") " to align left or right.") (TODO) (d/h3 "Disabled") (d/p "Set the " (d/code ":disabled?") " prop to " (d/code "true") " to disabled the link.") (TODO))) (defn alert-block [] (section "alerts" ["Alert messages " (d/small "random.cljs")] (d/h3 "Example alerts") (d/p "Basic alert styles.") (->example (slurp-example "alert/basic")) (d/p "For closeable alerts, just pass an " (d/code ":on-dismiss") " function.") (TODO) (d/p "Auto close after a set time with the " (d/code ":dismiss-after") " option.") (TODO))) # # Carousels (defn carousel-block [] (section "carousels" ["Carousels " (d/small "In Progress")] (d/h2 "Example Carousels") (d/h3 "Uncontrolled") (d/p "Allow the component to control its own state.") (TODO) (d/h3 "Controlled") (d/p "Pass down the active state on render via props.") (TODO))) # # Grids (defn grid-block [] (section "grids" ["Grids " (d/small "grid.cljs")] (d/h3 "Example grids") (->example (slurp-example "grid")))) (defn label-block [] (section "labels" ["Labels " (d/small "random.cljs")] (d/h3 "Example") (d/p "Create " (d/code "(r/label {} \"label\")") " to show highlight information.") (->example (slurp-example "label/basic")) (d/h3 "Available variations") (d/p "Add any of the below mentioned modifier classes to change the appearance of a label.") (->example (slurp-example "label/variations")))) (defn badge-block [] (section "badges" ["Badges " (d/small "random.cljs")] (d/p "Easily highlight new or unread items by adding a " (d/code "r/badge") " to links, Bootstrap navs, and more.") (d/h3 "Example") (->example (slurp-example "badge")) (info-callout "Cross-browser compatibility" "Unlike regular Bootstrap, badges self-collapse even in Internet Explorer 8."))) # # Jumbotron (defn jumbotron-block [] (section "jumbotron" ["Jumbotron " (d/small "random.cljs")] (d/p "A lightweight, flexible component that can optionally extend the entire viewport to showcase key content on your site.") (d/h3 "Example") (->example (slurp-example "jumbotron/basic")))) # # Page Header (defn header-block [] (section "page-header" ["Page Header " (d/small "random.cljs")] (d/p "A simple shell for an " (d/code "h1") " to appropriately space out and segment sections of content on a page. It can utilize the " (d/code "h1") "’s default " (d/code "small") " small element, as well as most other components (with additional styles).") (d/h3 "Example") (->example (slurp-example "page_header")))) (defn well-block [] (section "wells" ["Wells " (d/small "random.cljs")] (d/p "Use the well as a simple effect on an element to give it an inset effect.") (d/h3 "Default Wells") (->example (slurp-example "well/basic")) (d/h3 "Optional classes") (d/p "Control padding and rounded corners with two optional modifier classes.") (->example (slurp-example "well/sizes")))) # # Glyphicons (defn glyphicon-block [] (section "glyphicons" ["Glyphicons " (d/small "random.cljs")] (d/p "Use them in buttons, button groups for a toolbar, navigation, or prepended form inputs.") (d/h3 "Example") (->example (slurp-example "glyphicon")))) (defn table-block [] (section "tables" ["Tables " (d/small "table.cljs")] (d/h3 "Example") (d/p "Use the " (d/code ":striped? true") ", " (d/code ":bordered? true") ", " (d/code ":condensed? true") ", and " (d/code ":hover? true") " options to customize the table.") (->example (slurp-example "table/basic")) (d/h3 "Responsive") (d/p "Add the " (d/code ":responsive? true") " option to make them scroll horizontally up to small devices (under 768px). When viewing on anything larger than 768px wide, you will not see any difference in these tables.") (->example (slurp-example "table/responsive")))) # # Input (defn input-block [] (section "input" ["Input " (d/small "input.cljs")] (d/p "Renders an input in bootstrap wrappers. Supports label, help, text input add-ons, validation and use as wrapper. om-bootstrap tags the " (d/code "input") " node with a " (d/code ":ref") " and " (d/code ":key") ", so you can access the internal input element with " (d/code "(om/get-node owner \"input\")") " as demonstrated in the snippet.") (->example (slurp-example "input/validation")) (d/h3 "Types") (d/p "Supports " (d/code "select") ", " (d/code "textarea") ", " (d/code "static") " as well as the standard HTML input types.") (->example (slurp-example "input/types")) (d/h3 "Add-ons") (d/p "Use " (d/code ":addon-before") ", " (d/code ":addon-after") ", " (d/code ":addon-button-before") " and " (d/code ":addon-button-after") ".") (->example (slurp-example "input/addons")) (d/h3 "Validation") (d/p "Set " (d/code ":bs-style") " to one of " (d/code "\"success\"") ", " (d/code "\"warning\"") ", or" (d/code "\"error\"") ". Add " (d/code ":has-feedback? true") " to show a glyphicon. Glyphicon may need additional styling if there is an add-on or no label.") (->example (slurp-example "input/feedback")) (d/h3 "Horizontal forms") (d/p "Use" (d/code ":label-classname") " and " (d/code ":wrapper-classname") (d/p " options to add col classes manually. Checkbox and radio types need special treatment because label wraps input.")) (->example (slurp-example "input/horizontal")) (d/h3 "Use as a wrapper") (d/p "If " (d/code ":type") " is not set, child element(s) will be rendered instead of an input element.") (->example (slurp-example "input/wrapper")))) (defn sidebar [] (d/div {:class "col-md-3"} (d/div {:class "bs-docs-sidebar hidden-print" :role "complementary"} (n/nav {:class "bs-docs-sidenav"} (n/nav-item {:href "#buttons"} "Buttons") (n/nav-item {:href "#panels"} "Panels") (n/nav-item {:href "#modals"} "Modals") (n/nav-item {:href "#tooltips"} "Tooltips") (n/nav-item {:href "#popovers"} "Popovers") (n/nav-item {:href "#progress"} "Progress bars") (n/nav-item {:href "#navs"} "Navs") (n/nav-item {:href "#navbars"} "Navbars") (n/nav-item {:href "#tabs"} "Toggleable Tabs") (n/nav-item {:href "#pagination"} "Pagination") (n/nav-item {:href "#pager"} "Pager") (n/nav-item {:href "#alerts"} "Alerts") (n/nav-item {:href "#carousels"} "Carousels") (n/nav-item {:href "#grids"} "Grids") (n/nav-item {:href "#listgroup"} "List group") (n/nav-item {:href "#labels"} "Labels") (n/nav-item {:href "#badges"} "Badges") (n/nav-item {:href "#jumbotron"} "Jumbotron") (n/nav-item {:href "#page-header"} "Page header") (n/nav-item {:href "#wells"} "Wells") (n/nav-item {:href "#glyphicons"} "Glyphicons") (n/nav-item {:href "#tables"} "Tables") (n/nav-item {:href "#input"} "Input")) (d/a {:class "back-to-top" :href "#top"} "Back to top")))) (defn lead [] (d/div {:class "lead"} "This page lists the Om-Bootstrap components. For each component, we provide:" (d/ul (d/li "Usage instructions") (d/li "An example code snippet") (d/li "The rendered result of the example snippet")) "Click \"show code\" below the rendered component to reveal the snippet.")) (defn components-page [] [(page-header {:title "Components"}) (d/div {:class "container bs-docs-container"} (d/div {:class "row"} (d/div {:class "col-md-9" :role "main"} (lead) (button-block) (panel-block) (modal-block) (tooltip-block) (popover-block) (progress-bar-block) (nav-block) (navbar-block) (tab-block) (pagination-block) (pager-block) (alert-block) (carousel-block) (grid-block) (label-block) (badge-block) (jumbotron-block) (header-block) (well-block) (glyphicon-block) (table-block) (input-block)) (sidebar)))])
2c46e4816740174727c48f835d9d78868726a0e6cf438e50ef7b2ccae49653a6
the2pizza/authorizer
time_test.clj
(ns authorizer.time-test (:require [clojure.test :refer :all] [authorizer.account :as account] [authorizer.time :refer :all]) (:import (java.time LocalDateTime))) (def test-transaction-record {:transaction {:merchant "KFC" :amount 20, :time "2019-02-13T12:02:07.000Z"}}) (def test-account-record {:account {:available-limit 1000 :active-card true}}) (def test-account (account/init (:account test-account-record))) (def test-account-with-history (account/record->history test-account (:transaction test-transaction-record))) (deftest parse-time-is-ok? (testing "Time Record is not Ok." (let [t (parse-date-time "2019-02-13T12:03:07.000Z")] (is (instance? LocalDateTime t))))) (deftest record-in-interval-is-ok? (testing "Time Record in interval is not Ok." (is (true? (record-in-interval? (:time (first (:history test-account-with-history))) "2019-02-13T12:03:07.000Z" 1))))) (deftest record-not-in-interval-is-ok? (testing "Time Record not in interval is not Ok." (is (false? (record-in-interval? (:time (first (:history test-account-with-history))) "2019-02-13T12:03:08.000Z" 1)))))
null
https://raw.githubusercontent.com/the2pizza/authorizer/024f9760621a9187337b5ef326d9b51795a4bdee/test/authorizer/time_test.clj
clojure
(ns authorizer.time-test (:require [clojure.test :refer :all] [authorizer.account :as account] [authorizer.time :refer :all]) (:import (java.time LocalDateTime))) (def test-transaction-record {:transaction {:merchant "KFC" :amount 20, :time "2019-02-13T12:02:07.000Z"}}) (def test-account-record {:account {:available-limit 1000 :active-card true}}) (def test-account (account/init (:account test-account-record))) (def test-account-with-history (account/record->history test-account (:transaction test-transaction-record))) (deftest parse-time-is-ok? (testing "Time Record is not Ok." (let [t (parse-date-time "2019-02-13T12:03:07.000Z")] (is (instance? LocalDateTime t))))) (deftest record-in-interval-is-ok? (testing "Time Record in interval is not Ok." (is (true? (record-in-interval? (:time (first (:history test-account-with-history))) "2019-02-13T12:03:07.000Z" 1))))) (deftest record-not-in-interval-is-ok? (testing "Time Record not in interval is not Ok." (is (false? (record-in-interval? (:time (first (:history test-account-with-history))) "2019-02-13T12:03:08.000Z" 1)))))
c552fc55b78ad7922a8b574e7ba42797ea315ef379ea691f89bc869464de045a
DavidAlphaFox/RabbitMQ
rest_simple_resource.erl
-module(rest_simple_resource). -export([init/3, content_types_provided/2, get_text_plain/2]). init(_Transport, _Req, _Opts) -> {upgrade, protocol, cowboy_http_rest}. content_types_provided(Req, State) -> {[{{<<"text">>, <<"plain">>, []}, get_text_plain}], Req, State}. get_text_plain(Req, State) -> {<<"This is REST!">>, Req, State}.
null
https://raw.githubusercontent.com/DavidAlphaFox/RabbitMQ/0a64e6f0464a9a4ce85c6baa52fb1c584689f49a/plugins-src/cowboy-wrapper/cowboy-git/test/rest_simple_resource.erl
erlang
-module(rest_simple_resource). -export([init/3, content_types_provided/2, get_text_plain/2]). init(_Transport, _Req, _Opts) -> {upgrade, protocol, cowboy_http_rest}. content_types_provided(Req, State) -> {[{{<<"text">>, <<"plain">>, []}, get_text_plain}], Req, State}. get_text_plain(Req, State) -> {<<"This is REST!">>, Req, State}.
b13160b43a0dcb161071e451d4dba318aab2170156a050b20b226d9b3363aef4
tyage/tiny-c
Type.hs
module Type where import Control.Monad.Writer import Control.Monad.State data Program = ExDeclList [ExternalDeclaration] data ExternalDeclaration = Decl Declaration | FuncDef FunctionDefinition data Declaration = Declaration DeclaratorList | EmptyDeclaration data DeclaratorList = DeclaratorList [Declarator] data Declarator = Declarator Identifier data FunctionDefinition = FunctionDefinition Declarator ParameterTypeList CompoundStatement data ParameterTypeList = ParameterTypeList [ParameterDeclaration] data ParameterDeclaration = ParameterDeclaration Declarator data Statement = EmptyStatement | ExpressionStmt Expr | CompoundStmt CompoundStatement | If Expr Statement Statement | While Expr Statement | Return Expr data CompoundStatement = CompoundStatement DeclarationList StatementList data DeclarationList = DeclarationList [Declaration] data StatementList = StatementList [Statement] data Expr = ExprList [Expr] | Assign Identifier Expr | Or Expr Expr | And Expr Expr | Equal Expr Expr | NotEqual Expr Expr | Lt Expr Expr | Gt Expr Expr | Le Expr Expr | Ge Expr Expr | Plus Expr Expr | Minus Expr Expr | Multiple Expr Expr | Divide Expr Expr | UnaryMinus Expr | FunctionCall Identifier ArgumentExprList | Ident Identifier | Const Constant | Parens Expr data ArgumentExprList = ArgumentExprList [Expr] data Identifier = Identifier String | TokenIdentifier Token deriving (Eq) data Token = VariableToken Identifier Level Offset | ParameterToken Identifier Level Offset | FunctionToken Identifier Level ParameterLength | UndefinedFunctionToken Identifier Level ParameterLength | FreshToken deriving (Eq) type Offset = Int type ParameterLength = Int data Constant = Constant Integer type ErrorChecker a = StateT Environment (WriterT [ErrorMessage] Maybe) a data ErrorMessage = ErrorMessage String | WarningMessage String data Environment = Environment { tokensTable :: TokensTable } data TokensTable = TokensTable { parentTokensTable :: (Maybe TokensTable), tokensList :: [(Identifier, Token)] } type Level = Int -- Asm type Asm = State AsmEnvironment [AsmCode] data AsmEnvironment = AsmEnvironment { asmLabelCounter :: Int, returnLabel :: Label } data AsmCode = AsmGlobal Label | AsmLabel Label | AsmCommon Label Bytes | AsmOp Op type Label = String type Bytes = Int data Op = Op0 String | Op1 String String | Op2 String String String
null
https://raw.githubusercontent.com/tyage/tiny-c/92aed366ad4e610b3daf15c9fccf4d5b6f3ba6ad/task8/Type.hs
haskell
Asm
module Type where import Control.Monad.Writer import Control.Monad.State data Program = ExDeclList [ExternalDeclaration] data ExternalDeclaration = Decl Declaration | FuncDef FunctionDefinition data Declaration = Declaration DeclaratorList | EmptyDeclaration data DeclaratorList = DeclaratorList [Declarator] data Declarator = Declarator Identifier data FunctionDefinition = FunctionDefinition Declarator ParameterTypeList CompoundStatement data ParameterTypeList = ParameterTypeList [ParameterDeclaration] data ParameterDeclaration = ParameterDeclaration Declarator data Statement = EmptyStatement | ExpressionStmt Expr | CompoundStmt CompoundStatement | If Expr Statement Statement | While Expr Statement | Return Expr data CompoundStatement = CompoundStatement DeclarationList StatementList data DeclarationList = DeclarationList [Declaration] data StatementList = StatementList [Statement] data Expr = ExprList [Expr] | Assign Identifier Expr | Or Expr Expr | And Expr Expr | Equal Expr Expr | NotEqual Expr Expr | Lt Expr Expr | Gt Expr Expr | Le Expr Expr | Ge Expr Expr | Plus Expr Expr | Minus Expr Expr | Multiple Expr Expr | Divide Expr Expr | UnaryMinus Expr | FunctionCall Identifier ArgumentExprList | Ident Identifier | Const Constant | Parens Expr data ArgumentExprList = ArgumentExprList [Expr] data Identifier = Identifier String | TokenIdentifier Token deriving (Eq) data Token = VariableToken Identifier Level Offset | ParameterToken Identifier Level Offset | FunctionToken Identifier Level ParameterLength | UndefinedFunctionToken Identifier Level ParameterLength | FreshToken deriving (Eq) type Offset = Int type ParameterLength = Int data Constant = Constant Integer type ErrorChecker a = StateT Environment (WriterT [ErrorMessage] Maybe) a data ErrorMessage = ErrorMessage String | WarningMessage String data Environment = Environment { tokensTable :: TokensTable } data TokensTable = TokensTable { parentTokensTable :: (Maybe TokensTable), tokensList :: [(Identifier, Token)] } type Level = Int type Asm = State AsmEnvironment [AsmCode] data AsmEnvironment = AsmEnvironment { asmLabelCounter :: Int, returnLabel :: Label } data AsmCode = AsmGlobal Label | AsmLabel Label | AsmCommon Label Bytes | AsmOp Op type Label = String type Bytes = Int data Op = Op0 String | Op1 String String | Op2 String String String
d817af6760a8c31cf74736b69182fc4b02afd919e2dd5d8287d42cd39261949f
cmsc430/www
test-runner.rkt
#lang racket (provide test-runner test-runner-io) (require rackunit) (define (test-runner run) ;; Abscond examples (check-equal? (run 7) 7) (check-equal? (run -8) -8) examples (check-equal? (run '(add1 (add1 7))) 9) (check-equal? (run '(add1 (sub1 7))) 7) ;; Con examples (check-equal? (run '(if (zero? 0) 1 2)) 1) (check-equal? (run '(if (zero? 1) 1 2)) 2) (check-equal? (run '(if (zero? -7) 1 2)) 2) (check-equal? (run '(if (zero? 0) (if (zero? 1) 1 2) 7)) 2) (check-equal? (run '(if (zero? (if (zero? 0) 1 0)) (if (zero? 1) 1 2) 7)) 7) Dupe examples (check-equal? (run #t) #t) (check-equal? (run #f) #f) (check-equal? (run (if #t 1 2)) 1) (check-equal? (run (if #f 1 2)) 2) (check-equal? (run (if 0 1 2)) 1) (check-equal? (run '(if #t 3 4)) 3) (check-equal? (run '(if #f 3 4)) 4) (check-equal? (run '(if 0 3 4)) 3) (check-equal? (run '(zero? 4)) #f) (check-equal? (run '(zero? 0)) #t) Dodger examples (check-equal? (run #\a) #\a) (check-equal? (run #\b) #\b) (check-equal? (run '(char? #\a)) #t) (check-equal? (run '(char? #t)) #f) (check-equal? (run '(char? 8)) #f) (check-equal? (run '(char->integer #\a)) (char->integer #\a)) (check-equal? (run '(integer->char 955)) #\λ) Extort examples (check-equal? (run '(add1 #f)) 'err) (check-equal? (run '(sub1 #f)) 'err) (check-equal? (run '(zero? #f)) 'err) (check-equal? (run '(char->integer #f)) 'err) (check-equal? (run '(integer->char #f)) 'err) (check-equal? (run '(integer->char -1)) 'err) (check-equal? (run '(write-byte #f)) 'err) (check-equal? (run '(write-byte -1)) 'err) (check-equal? (run '(write-byte 256)) 'err) ;; Fraud examples (check-equal? (run '(let ((x 7)) x)) 7) (check-equal? (run '(let ((x 7)) 2)) 2) (check-equal? (run '(let ((x 7)) (add1 x))) 8) (check-equal? (run '(let ((x (add1 7))) x)) 8) (check-equal? (run '(let ((x 7)) (let ((y 2)) x))) 7) (check-equal? (run '(let ((x 7)) (let ((x 2)) x))) 2) (check-equal? (run '(let ((x 7)) (let ((x (add1 x))) x))) 8) (check-equal? (run '(let ((x 0)) (if (zero? x) 7 8))) 7) (check-equal? (run '(let ((x 1)) (add1 (if (zero? x) 7 8)))) 9) (check-equal? (run '(+ 3 4)) 7) (check-equal? (run '(- 3 4)) -1) (check-equal? (run '(+ (+ 2 1) 4)) 7) (check-equal? (run '(+ (+ 2 1) (+ 2 2))) 7) (check-equal? (run '(let ((x (+ 1 2))) (let ((z (- 4 x))) (+ (+ x x) z)))) 7) (check-equal? (run '(= 5 5)) #t) (check-equal? (run '(= 4 5)) #f) (check-equal? (run '(= (add1 4) 5)) #t) (check-equal? (run '(< 5 5)) #f) (check-equal? (run '(< 4 5)) #t) (check-equal? (run '(< (add1 4) 5)) #f) Hustle examples (check-equal? (run ''()) '()) (check-equal? (run '(box 1)) (box 1)) (check-equal? (run '(box -1)) (box -1)) (check-equal? (run '(cons 1 2)) (cons 1 2)) (check-equal? (run '(unbox (box 1))) 1) (check-equal? (run '(car (cons 1 2))) 1) (check-equal? (run '(cdr (cons 1 2))) 2) (check-equal? (run '(cons 1 '())) (list 1)) (check-equal? (run '(box? (box 7))) #t) (check-equal? (run '(cons? (box 7))) #f) (check-equal? (run '(box? (cons 7 8))) #f) (check-equal? (run '(cons? (cons 7 8))) #t) (check-equal? (run '(empty? '())) #t) (check-equal? (run '(empty? 7)) #f) (check-equal? (run '(let ((x (box 2))) (unbox x))) 2) (check-equal? (run '(let ((x (cons 2 '()))) (car x))) 2) (check-equal? (run '(let ((x (cons 1 2))) (begin (cdr x) (car x)))) 1) (check-equal? (run '(let ((x (cons 1 2))) (let ((y (box 3))) (unbox y)))) 3) (check-equal? (run '(eq? 1 1)) #t) (check-equal? (run '(eq? 1 2)) #f) (check-equal? (run '(eq? (cons 1 2) (cons 1 2))) #f) (check-equal? (run '(let ((x (cons 1 2))) (eq? x x))) #t) ;; Hoax examples (check-equal? (run '(make-vector 0 0)) #()) (check-equal? (run '(make-vector 1 0)) #(0)) (check-equal? (run '(make-vector 3 0)) #(0 0 0)) (check-equal? (run '(make-vector 3 5)) #(5 5 5)) (check-equal? (run '(vector? (make-vector 0 0))) #t) (check-equal? (run '(vector? (cons 0 0))) #f) (check-equal? (run '(vector-ref (make-vector 0 #f) 0)) 'err) (check-equal? (run '(vector-ref (make-vector 3 5) -1)) 'err) (check-equal? (run '(vector-ref (make-vector 3 5) 0)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 1)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 2)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 3)) 'err) (check-equal? (run '(let ((x (make-vector 3 5))) (begin (vector-set! x 0 4) x))) #(4 5 5)) (check-equal? (run '(let ((x (make-vector 3 5))) (begin (vector-set! x 1 4) x))) #(5 4 5)) (check-equal? (run '(vector-length (make-vector 3 #f))) 3) (check-equal? (run '(vector-length (make-vector 0 #f))) 0) (check-equal? (run '"") "") (check-equal? (run '"fred") "fred") (check-equal? (run '"wilma") "wilma") (check-equal? (run '(make-string 0 #\f)) "") (check-equal? (run '(make-string 3 #\f)) "fff") (check-equal? (run '(make-string 3 #\g)) "ggg") (check-equal? (run '(string-length "")) 0) (check-equal? (run '(string-length "fred")) 4) (check-equal? (run '(string-ref "" 0)) 'err) (check-equal? (run '(string-ref (make-string 0 #\a) 0)) 'err) (check-equal? (run '(string-ref "fred" 0)) #\f) (check-equal? (run '(string-ref "fred" 1)) #\r) (check-equal? (run '(string-ref "fred" 2)) #\e) (check-equal? (run '(string-ref "fred" 4)) 'err) (check-equal? (run '(string? "fred")) #t) (check-equal? (run '(string? (cons 1 2))) #f) (check-equal? (run '(begin (make-string 3 #\f) (make-string 3 #\f))) "fff")) (define (test-runner-io run) ;; Evildoer examples (check-equal? (run 7 "") (cons 7 "")) (check-equal? (run '(write-byte 97) "") (cons (void) "a")) (check-equal? (run '(read-byte) "a") (cons 97 "")) (check-equal? (run '(begin (write-byte 97) (read-byte)) "b") (cons 98 "a")) (check-equal? (run '(read-byte) "") (cons eof "")) (check-equal? (run '(eof-object? (read-byte)) "") (cons #t "")) (check-equal? (run '(eof-object? (read-byte)) "a") (cons #f "")) (check-equal? (run '(begin (write-byte 97) (write-byte 98)) "") (cons (void) "ab")) (check-equal? (run '(peek-byte) "ab") (cons 97 "")) (check-equal? (run '(begin (peek-byte) (read-byte)) "ab") (cons 97 "")) Extort examples (check-equal? (run '(write-byte #t) "") (cons 'err "")) ;; Fraud examples (check-equal? (run '(let ((x 97)) (write-byte x)) "") (cons (void) "a")) (check-equal? (run '(let ((x 97)) (begin (write-byte x) x)) "") (cons 97 "a")) (check-equal? (run '(let ((x 97)) (begin (read-byte) x)) "b") (cons 97 "")) (check-equal? (run '(let ((x 97)) (begin (peek-byte) x)) "b") (cons 97 "")) Hustle examples (check-equal? (run '(let ((x 1)) (begin (write-byte 97) 1)) "") (cons 1 "a")) (check-equal? (run '(let ((x 1)) (let ((y 2)) (begin (write-byte 97) 1))) "") (cons 1 "a")) (check-equal? (run '(let ((x (cons 1 2))) (begin (write-byte 97) (car x))) "") (cons 1 "a")))
null
https://raw.githubusercontent.com/cmsc430/www/be56bd3dfa05387a0b6250e3ee031f8dbd7d28bc/langs/hoax/test/test-runner.rkt
racket
Abscond examples Con examples Fraud examples Hoax examples Evildoer examples Fraud examples
#lang racket (provide test-runner test-runner-io) (require rackunit) (define (test-runner run) (check-equal? (run 7) 7) (check-equal? (run -8) -8) examples (check-equal? (run '(add1 (add1 7))) 9) (check-equal? (run '(add1 (sub1 7))) 7) (check-equal? (run '(if (zero? 0) 1 2)) 1) (check-equal? (run '(if (zero? 1) 1 2)) 2) (check-equal? (run '(if (zero? -7) 1 2)) 2) (check-equal? (run '(if (zero? 0) (if (zero? 1) 1 2) 7)) 2) (check-equal? (run '(if (zero? (if (zero? 0) 1 0)) (if (zero? 1) 1 2) 7)) 7) Dupe examples (check-equal? (run #t) #t) (check-equal? (run #f) #f) (check-equal? (run (if #t 1 2)) 1) (check-equal? (run (if #f 1 2)) 2) (check-equal? (run (if 0 1 2)) 1) (check-equal? (run '(if #t 3 4)) 3) (check-equal? (run '(if #f 3 4)) 4) (check-equal? (run '(if 0 3 4)) 3) (check-equal? (run '(zero? 4)) #f) (check-equal? (run '(zero? 0)) #t) Dodger examples (check-equal? (run #\a) #\a) (check-equal? (run #\b) #\b) (check-equal? (run '(char? #\a)) #t) (check-equal? (run '(char? #t)) #f) (check-equal? (run '(char? 8)) #f) (check-equal? (run '(char->integer #\a)) (char->integer #\a)) (check-equal? (run '(integer->char 955)) #\λ) Extort examples (check-equal? (run '(add1 #f)) 'err) (check-equal? (run '(sub1 #f)) 'err) (check-equal? (run '(zero? #f)) 'err) (check-equal? (run '(char->integer #f)) 'err) (check-equal? (run '(integer->char #f)) 'err) (check-equal? (run '(integer->char -1)) 'err) (check-equal? (run '(write-byte #f)) 'err) (check-equal? (run '(write-byte -1)) 'err) (check-equal? (run '(write-byte 256)) 'err) (check-equal? (run '(let ((x 7)) x)) 7) (check-equal? (run '(let ((x 7)) 2)) 2) (check-equal? (run '(let ((x 7)) (add1 x))) 8) (check-equal? (run '(let ((x (add1 7))) x)) 8) (check-equal? (run '(let ((x 7)) (let ((y 2)) x))) 7) (check-equal? (run '(let ((x 7)) (let ((x 2)) x))) 2) (check-equal? (run '(let ((x 7)) (let ((x (add1 x))) x))) 8) (check-equal? (run '(let ((x 0)) (if (zero? x) 7 8))) 7) (check-equal? (run '(let ((x 1)) (add1 (if (zero? x) 7 8)))) 9) (check-equal? (run '(+ 3 4)) 7) (check-equal? (run '(- 3 4)) -1) (check-equal? (run '(+ (+ 2 1) 4)) 7) (check-equal? (run '(+ (+ 2 1) (+ 2 2))) 7) (check-equal? (run '(let ((x (+ 1 2))) (let ((z (- 4 x))) (+ (+ x x) z)))) 7) (check-equal? (run '(= 5 5)) #t) (check-equal? (run '(= 4 5)) #f) (check-equal? (run '(= (add1 4) 5)) #t) (check-equal? (run '(< 5 5)) #f) (check-equal? (run '(< 4 5)) #t) (check-equal? (run '(< (add1 4) 5)) #f) Hustle examples (check-equal? (run ''()) '()) (check-equal? (run '(box 1)) (box 1)) (check-equal? (run '(box -1)) (box -1)) (check-equal? (run '(cons 1 2)) (cons 1 2)) (check-equal? (run '(unbox (box 1))) 1) (check-equal? (run '(car (cons 1 2))) 1) (check-equal? (run '(cdr (cons 1 2))) 2) (check-equal? (run '(cons 1 '())) (list 1)) (check-equal? (run '(box? (box 7))) #t) (check-equal? (run '(cons? (box 7))) #f) (check-equal? (run '(box? (cons 7 8))) #f) (check-equal? (run '(cons? (cons 7 8))) #t) (check-equal? (run '(empty? '())) #t) (check-equal? (run '(empty? 7)) #f) (check-equal? (run '(let ((x (box 2))) (unbox x))) 2) (check-equal? (run '(let ((x (cons 2 '()))) (car x))) 2) (check-equal? (run '(let ((x (cons 1 2))) (begin (cdr x) (car x)))) 1) (check-equal? (run '(let ((x (cons 1 2))) (let ((y (box 3))) (unbox y)))) 3) (check-equal? (run '(eq? 1 1)) #t) (check-equal? (run '(eq? 1 2)) #f) (check-equal? (run '(eq? (cons 1 2) (cons 1 2))) #f) (check-equal? (run '(let ((x (cons 1 2))) (eq? x x))) #t) (check-equal? (run '(make-vector 0 0)) #()) (check-equal? (run '(make-vector 1 0)) #(0)) (check-equal? (run '(make-vector 3 0)) #(0 0 0)) (check-equal? (run '(make-vector 3 5)) #(5 5 5)) (check-equal? (run '(vector? (make-vector 0 0))) #t) (check-equal? (run '(vector? (cons 0 0))) #f) (check-equal? (run '(vector-ref (make-vector 0 #f) 0)) 'err) (check-equal? (run '(vector-ref (make-vector 3 5) -1)) 'err) (check-equal? (run '(vector-ref (make-vector 3 5) 0)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 1)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 2)) 5) (check-equal? (run '(vector-ref (make-vector 3 5) 3)) 'err) (check-equal? (run '(let ((x (make-vector 3 5))) (begin (vector-set! x 0 4) x))) #(4 5 5)) (check-equal? (run '(let ((x (make-vector 3 5))) (begin (vector-set! x 1 4) x))) #(5 4 5)) (check-equal? (run '(vector-length (make-vector 3 #f))) 3) (check-equal? (run '(vector-length (make-vector 0 #f))) 0) (check-equal? (run '"") "") (check-equal? (run '"fred") "fred") (check-equal? (run '"wilma") "wilma") (check-equal? (run '(make-string 0 #\f)) "") (check-equal? (run '(make-string 3 #\f)) "fff") (check-equal? (run '(make-string 3 #\g)) "ggg") (check-equal? (run '(string-length "")) 0) (check-equal? (run '(string-length "fred")) 4) (check-equal? (run '(string-ref "" 0)) 'err) (check-equal? (run '(string-ref (make-string 0 #\a) 0)) 'err) (check-equal? (run '(string-ref "fred" 0)) #\f) (check-equal? (run '(string-ref "fred" 1)) #\r) (check-equal? (run '(string-ref "fred" 2)) #\e) (check-equal? (run '(string-ref "fred" 4)) 'err) (check-equal? (run '(string? "fred")) #t) (check-equal? (run '(string? (cons 1 2))) #f) (check-equal? (run '(begin (make-string 3 #\f) (make-string 3 #\f))) "fff")) (define (test-runner-io run) (check-equal? (run 7 "") (cons 7 "")) (check-equal? (run '(write-byte 97) "") (cons (void) "a")) (check-equal? (run '(read-byte) "a") (cons 97 "")) (check-equal? (run '(begin (write-byte 97) (read-byte)) "b") (cons 98 "a")) (check-equal? (run '(read-byte) "") (cons eof "")) (check-equal? (run '(eof-object? (read-byte)) "") (cons #t "")) (check-equal? (run '(eof-object? (read-byte)) "a") (cons #f "")) (check-equal? (run '(begin (write-byte 97) (write-byte 98)) "") (cons (void) "ab")) (check-equal? (run '(peek-byte) "ab") (cons 97 "")) (check-equal? (run '(begin (peek-byte) (read-byte)) "ab") (cons 97 "")) Extort examples (check-equal? (run '(write-byte #t) "") (cons 'err "")) (check-equal? (run '(let ((x 97)) (write-byte x)) "") (cons (void) "a")) (check-equal? (run '(let ((x 97)) (begin (write-byte x) x)) "") (cons 97 "a")) (check-equal? (run '(let ((x 97)) (begin (read-byte) x)) "b") (cons 97 "")) (check-equal? (run '(let ((x 97)) (begin (peek-byte) x)) "b") (cons 97 "")) Hustle examples (check-equal? (run '(let ((x 1)) (begin (write-byte 97) 1)) "") (cons 1 "a")) (check-equal? (run '(let ((x 1)) (let ((y 2)) (begin (write-byte 97) 1))) "") (cons 1 "a")) (check-equal? (run '(let ((x (cons 1 2))) (begin (write-byte 97) (car x))) "") (cons 1 "a")))
217317c8a2c85ed6bd434f5986014fa8709b25e3737ff3325627ed028753daa4
wavewave/hoodle
Default.hs
# LANGUAGE CPP # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Hoodle.Coroutine.Default where import Control.Concurrent ( forkIO, forkOn, newEmptyMVar, putMVar, ) import qualified Control.Exception as E import Control.Lens (at, over, set, view, (.~), (?~), (^.), _2) import Control.Monad (void, when) import Control.Monad.State (evalStateT, get, gets, liftIO, modify, put) import Control.Monad.Trans.Crtn.Driver (driver) import Control.Monad.Trans.Crtn.Logger.Simple (simplelogger) import Control.Monad.Trans.Crtn.Object (Arg (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import qualified Data.ByteString.Char8 as B import Data.Foldable (mapM_) import Data.Hoodle.Generic ( gbackground, gdimension, ghoodleID, gpages, ) import Data.Hoodle.Simple (Background (..), Dimension (..)) import Data.IORef (writeIORef) import qualified Data.IntMap as M import qualified Data.List as L import Graphics.Hoodle.Render (cnstrctRBkgStateT) import Graphics.Hoodle.Render.Engine ( genRendererMain, pdfRendererMain, ) import Graphics.Hoodle.Render.Type (RBackground (..)) import qualified Graphics.UI.Gtk as Gtk hiding (get, set) import Hoodle.Accessor ( getHoodleFilePath, getPenType, lensSetToggleUIForFlag, pureUpdateUhdl, ) import Hoodle.Coroutine.Callback (eventHandler) import Hoodle.Coroutine.ContextMenu (processContextMenu) import Hoodle.Coroutine.Default.Menu (menuEventProcess) import Hoodle.Coroutine.Draw ( callRenderer, callRenderer_, defaultHandler, doIOaction_, invalidate, invalidateAll, invalidateInBBox, nextevent, waitSomeEvent, ) import Hoodle.Coroutine.Eraser (eraserStart) import Hoodle.Coroutine.File ( askIfSave, fileReload, getFileContent, ) --------- import Hoodle.Coroutine.Highlighter (highlighterStart) import Hoodle.Coroutine.Link ( gotLink, notifyLink, openLinkAction, ) import Hoodle.Coroutine.Mode ( modeChange, viewModeChange, ) import Hoodle.Coroutine.Page ( changePage, pageZoomChange, ) import Hoodle.Coroutine.Pen (penStart) import Hoodle.Coroutine.Scroll ( hscrollBarMoved, vscrollBarMoved, vscrollStart, ) import Hoodle.Coroutine.Select ( selectLassoStart, selectPenColorChanged, selectPenWidthChanged, selectRectStart, ) import Hoodle.Coroutine.TextInput (networkReceived) import Hoodle.Coroutine.VerticalSpace (verticalSpaceStart) import Hoodle.Coroutine.Window ( closeTab, doCanvasConfigure, findTab, paneMoveStart, switchTab, ) import Hoodle.Device ( DeviceList, PenButton (..), dev_touch_str, ) import Hoodle.GUI.Menu ( getMenuUI, int2Point, ) import Hoodle.GUI.Reflect ( reflectNewPageModeUI, reflectPenColorUI, reflectPenModeUI, reflectPenWidthUI, reflectUIToggle, reflectViewModeUI, ) import Hoodle.ModelAction.Page (getPageFromGHoodleMap) import Hoodle.ModelAction.Window ( constructFrame, createTab, eventConnect, ) import Hoodle.Script.Hook (Hook) import Hoodle.Type.Canvas ( CanvasId, CanvasInfoBox (CanvasSinglePage), canvasWidgets, currentPageNum, currentTool, defaultCvsInfoSinglePage, penColor, penType, penWidth, unboxLens, _canvasId, ) import Hoodle.Type.Coroutine ( EventVar, MainCoroutine, MainOp (DoEvent), doIOaction, world, ) import Hoodle.Type.Enum ( DrawFlag (Efficient), PenColor (..), PenType (..), SelectType (..), convertBackgroundStyleToByteString, selectType, ) import Hoodle.Type.Event ( AllEvent (..), NetworkEvent (..), RenderEvent (..), UserEvent (..), ) import Hoodle.Type.HoodleState ( FileStore (LocalDir), HoodleModeState (ViewAppendState), HoodleState, IsOneTimeSelectMode (YesBeforeSelect), backgroundStyle, callBack, currentCanvasInfo, currentUnit, cvsInfoMap, deviceList, doesUseTouch, doesUseVariableCursor, doesUseXInput, emptyHoodleState, frameState, genRenderQueue, getCurrentCanvasId, getHoodle, gtkUIManager, hoodleFileControl, hoodleFileName, hoodleModeState, hoodleModeStateEither, hookSet, isOneTimeSelectMode, isSaved, newPageMode, pdfRenderQueue, penInfo, renderCacheVar, resetHoodleModeStateBuffers, rootContainer, rootNotebook, rootOfRootWindow, rootWindow, selectInfo, settings, statusBar, switchTabSignal, uiComponentSignalHandler, undoTable, unitButton, unitHoodles, unitUUID, updateFromCanvasInfoAsCurrentCanvas, ) import Hoodle.Type.PageArrangement ( CanvasDimension (..), ZoomMode (FitWidth), ) import Hoodle.Type.Undo (emptyUndo) import Hoodle.Type.Widget ( doesUseLayerWidget, doesUsePanZoomWidget, widgetConfig, ) import Hoodle.Type.Window (WindowConfig (Node)) import Hoodle.Util (msgShout, (#)) import Hoodle.Widget.Dispatch (widgetCheckPen) import Hoodle.Widget.PanZoom (toggleTouch, touchStart) import System.Process (readProcess) import Prelude hiding (mapM_) -- | initCoroutine :: DeviceList -> Gtk.Window -> Maybe Hook -> -- | maxundo Int -> | ( xinputbool , usepz , uselyr , varcsr ) (Bool, Bool, Bool, Bool) -> IO (EventVar, HoodleState, Gtk.UIManager, Gtk.VBox) initCoroutine devlst window mhook maxundo (xinputbool, usepz, uselyr, varcsr) = do evar <- newEmptyMVar putMVar evar Nothing let callback = eventHandler evar st0new <- set deviceList devlst . set rootOfRootWindow window . set callBack callback <$> emptyHoodleState (ui, uicompsighdlr) <- getMenuUI evar let st1 = set gtkUIManager ui st0new initcvs = set (canvasWidgets . widgetConfig . doesUsePanZoomWidget) usepz . set (canvasWidgets . widgetConfig . doesUseLayerWidget) uselyr $ defaultCvsInfoSinglePage {_canvasId = 1} initcvsbox = CanvasSinglePage initcvs st2 = st1 # over (unitHoodles . currentUnit) ( set frameState (Node 1) . updateFromCanvasInfoAsCurrentCanvas initcvsbox . set cvsInfoMap M.empty ) uhdl2 = view (unitHoodles . currentUnit) st2 (uhdl3, rtwdw, _wconf) <- constructFrame st2 uhdl2 (view frameState uhdl2) (uhdl4, wconf') <- eventConnect st2 uhdl3 (view frameState uhdl3) notebook <- Gtk.notebookNew statusbar <- Gtk.statusbarNew let st4 = (unitHoodles . currentUnit .~ uhdl4) st2 st5 = st4 # over (unitHoodles . currentUnit) ( set undoTable (emptyUndo maxundo) . set frameState wconf' . set rootWindow rtwdw . set (hoodleFileControl . hoodleFileName) (LocalDir Nothing) ) . set (settings . doesUseXInput) xinputbool . set (settings . doesUseVariableCursor) varcsr . set hookSet mhook . set rootNotebook notebook . set uiComponentSignalHandler uicompsighdlr . set statusBar (Just statusbar) -- vbox <- Gtk.vBoxNew False 0 Gtk.containerAdd window vbox vboxcvs <- Gtk.vBoxNew False 0 (_, uuid, btn) <- createTab callback notebook vboxcvs Gtk.containerAdd vboxcvs (view (unitHoodles . currentUnit . rootWindow) st5) -- sigid <- notebook `Gtk.on` Gtk.switchPage $ \i -> callback (UsrEv (SwitchTab i)) let st6 = ( (unitHoodles . currentUnit . unitUUID .~ uuid) . (unitHoodles . currentUnit . unitButton .~ btn) . (uiComponentSignalHandler . switchTabSignal ?~ sigid) ) st5 startingXstate = (unitHoodles . currentUnit . rootContainer .~ Gtk.castToBox vboxcvs) st6 startworld = world startingXstate . ReaderT $ (\(Arg DoEvent ev) -> guiProcess ev) putMVar evar . Just $ driver simplelogger startworld return (evar, startingXstate, ui, vbox) -- | initialization according to the setting initialize :: Maybe (CanvasId, CanvasDimension) -> Bool -> AllEvent -> MainCoroutine (CanvasId, CanvasDimension) initialize cvs isInitialized ev = do case ev of UsrEv (Initialized mfname) -> do if isInitialized then do case cvs of Nothing -> nextevent >>= initialize Nothing True . UsrEv Just cvsi -> return cvsi else do -- additional initialization goes here xst1 <- get let ui = xst1 ^. gtkUIManager cachevar = xst1 ^. renderCacheVar tvarpdf = xst1 ^. pdfRenderQueue tvargen = xst1 ^. genRenderQueue doIOaction $ \evhandler -> do _ <- forkOn 2 $ pdfRendererMain (defaultHandler evhandler) tvarpdf _ <- forkIO $ E.catch (genRendererMain cachevar (defaultHandler evhandler) tvargen) (\e -> print (e :: E.SomeException)) return (UsrEv ActionOrdered) _ <- waitSomeEvent (\case ActionOrdered -> True; _ -> False) getFileContent (LocalDir mfname) -- xst2 <- get let uhdl = view (unitHoodles . currentUnit) xst2 hdlst = uhdl ^. hoodleModeState cid = getCurrentCanvasId uhdl callRenderer_ $ resetHoodleModeStateBuffers cid hdlst pureUpdateUhdl (hoodleModeState .~ hdlst) liftIO $ reflectUIToggle ui "SAVEA" False pureUpdateUhdl (isSaved .~ True) case cvs of Just cvsi -> return cvsi Nothing -> nextevent >>= initialize Nothing True . UsrEv UsrEv (CanvasConfigure cid w h) -> do nextevent >>= initialize (Just (cid, CanvasDimension (Dim w h))) isInitialized . UsrEv _ -> case (cvs, isInitialized) of (Just cvsi, True) -> return cvsi _ -> nextevent >>= initialize cvs isInitialized . UsrEv -- | guiProcess :: AllEvent -> MainCoroutine () guiProcess ev = do (cid, cdim) <- initialize Nothing False ev changePage (const 0) reflectViewModeUI reflectPenModeUI reflectPenColorUI reflectPenWidthUI reflectNewPageModeUI viewModeChange ToContSinglePage pageZoomChange FitWidth doCanvasConfigure cid cdim -- main loop sequence_ (repeat dispatchMode) -- | dispatchMode :: MainCoroutine () dispatchMode = gets (view (unitHoodles . currentUnit)) >>= either (const viewAppendMode) (const selectMode) . hoodleModeStateEither . view hoodleModeState -- | viewAppendMode :: MainCoroutine () viewAppendMode = do r1 <- nextevent case r1 of PenDown cid pbtn pcoord -> widgetCheckPen cid pcoord $ do ptype <- getPenType case (ptype, pbtn) of (PenWork, PenButton1) -> do r <- penStart cid pcoord case r of Just (Just Nothing) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord _ -> return () (PenWork, PenButton2) -> eraserStart cid pcoord (PenWork, PenButton3) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord (PenWork, EraserButton) -> eraserStart cid pcoord (PenWork, _) -> return () (EraserWork, _) -> eraserStart cid pcoord (HighlighterWork, _) -> do r <- highlighterStart cid pcoord case r of Just (Just Nothing) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord _ -> return () (VerticalSpaceWork, PenButton1) -> verticalSpaceStart cid pcoord (VerticalSpaceWork, _) -> return () TouchDown cid pcoord -> touchStart cid pcoord PenMove cid pcoord -> disableTouch >> notifyLink cid pcoord _ -> defaultEventProcess r1 disableTouch :: MainCoroutine () disableTouch = do xst <- get let devlst = view deviceList xst when (view (settings . doesUseTouch) xst) $ do let nxst = set (settings . doesUseTouch) False xst doIOaction_ $ do _ <- lensSetToggleUIForFlag "HANDA" (settings . doesUseTouch) nxst let touchstr = dev_touch_str devlst -- ad hoc when (touchstr /= "touch") $ void $ readProcess "xinput" ["disable", touchstr] "" put nxst -- | selectMode :: MainCoroutine () selectMode = do r1 <- nextevent case r1 of PenDown cid pbtn pcoord -> do ptype <- gets (view (selectInfo . selectType)) case ptype of SelectRectangleWork -> selectRectStart pbtn cid pcoord SelectLassoWork -> selectLassoStart pbtn cid pcoord _ -> return () PenMove cid pcoord -> disableTouch >> notifyLink cid pcoord TouchDown cid pcoord -> touchStart cid pcoord PenColorChanged c -> do modify (penInfo . currentTool . penColor .~ c) selectPenColorChanged c PenWidthChanged v -> do w <- gets (flip int2Point v . view (penInfo . penType)) modify (penInfo . currentTool . penWidth .~ w) selectPenWidthChanged w _ -> defaultEventProcess r1 -- | defaultEventProcess :: UserEvent -> MainCoroutine () defaultEventProcess (UpdateCanvas cid) = invalidate cid defaultEventProcess (UpdateCanvasEfficient cid) = invalidateInBBox Nothing Efficient cid defaultEventProcess (Menu m) = menuEventProcess m defaultEventProcess (HScrollBarMoved cid v) = hscrollBarMoved cid v defaultEventProcess (VScrollBarMoved cid v) = vscrollBarMoved cid v defaultEventProcess (VScrollBarStart cid v) = vscrollStart cid v defaultEventProcess PaneMoveStart = paneMoveStart defaultEventProcess (CanvasConfigure cid w' h') = doCanvasConfigure cid (CanvasDimension (Dim w' h')) defaultEventProcess ToViewAppendMode = modeChange ToViewAppendMode defaultEventProcess ToSelectMode = modeChange ToSelectMode defaultEventProcess ToSinglePage = viewModeChange ToSinglePage defaultEventProcess ToContSinglePage = viewModeChange ToContSinglePage defaultEventProcess (AssignPenMode t) = case t of Left pm -> do modify (penInfo . penType .~ pm) modeChange ToViewAppendMode Right sm -> do modify (selectInfo . selectType .~ sm) modeChange ToSelectMode defaultEventProcess (PenColorChanged c) = do modify (penInfo . currentTool . penColor .~ c) reflectPenColorUI defaultEventProcess (PenWidthChanged v) = do st <- get let ptype = view (penInfo . penType) st let w = int2Point ptype v let stNew = set (penInfo . currentTool . penWidth) w st put stNew reflectPenWidthUI defaultEventProcess (BackgroundStyleChanged bsty) = do modify (backgroundStyle .~ bsty) uhdl <- gets (view (unitHoodles . currentUnit)) let pgnum = view (currentCanvasInfo . unboxLens currentPageNum) uhdl hdl = getHoodle uhdl pgs = view gpages hdl cpage = getPageFromGHoodleMap pgnum hdl cbkg = view gbackground cpage bstystr = convertBackgroundStyleToByteString bsty -- for the time being, I replace any background to solid background dim = view gdimension cpage getnbkg' :: RBackground -> Background getnbkg' (RBkgSmpl c _ _) = Background "solid" c bstystr getnbkg' RBkgPDF {} = Background "solid" "white" bstystr getnbkg' RBkgEmbedPDF {} = Background "solid" "white" bstystr -- liftIO $ putStrLn " defaultEventProcess: BackgroundStyleChanged HERE/ " callRenderer $ GotRBackground <$> evalStateT (cnstrctRBkgStateT dim (getnbkg' cbkg)) Nothing RenderEv (GotRBackground nbkg) <- waitSomeEvent (\case RenderEv (GotRBackground _) -> True; _ -> False) let npage = set gbackground nbkg cpage npgs = set (at pgnum) (Just npage) pgs nhdl = set gpages npgs hdl modeChange ToViewAppendMode pureUpdateUhdl (hoodleModeState .~ ViewAppendState nhdl) invalidateAll defaultEventProcess (AssignNewPageMode nmod) = modify (settings . newPageMode .~ nmod) defaultEventProcess (GotContextMenuSignal ctxtmenu) = processContextMenu ctxtmenu defaultEventProcess (GetHoodleFileInfo ref) = do uhdl <- gets (view (unitHoodles . currentUnit)) let hdl = getHoodle uhdl uuid = B.unpack (view ghoodleID hdl) case getHoodleFilePath uhdl of Nothing -> liftIO $ writeIORef ref Nothing Just fp -> liftIO $ writeIORef ref (Just (uuid ++ "," ++ fp)) defaultEventProcess (GetHoodleFileInfoFromTab uuidtab ref) = do uhdlmap <- gets (view (unitHoodles . _2)) let muhdl = (L.lookup uuidtab . map (\x -> (view unitUUID x, x)) . M.elems) uhdlmap case muhdl of Nothing -> liftIO $ writeIORef ref Nothing Just uhdl -> do let hdl = getHoodle uhdl uuid = B.unpack (view ghoodleID hdl) case getHoodleFilePath uhdl of Nothing -> liftIO $ writeIORef ref Nothing Just fp -> liftIO $ writeIORef ref (Just (uuid ++ "," ++ fp)) defaultEventProcess (GotLink mstr (x, y)) = gotLink mstr (x, y) defaultEventProcess FileReloadOrdered = fileReload defaultEventProcess (CustomKeyEvent str) = do if | str == "[]:\"Super_L\"" -> do xst <- gets (over (settings . doesUseTouch) not) put xst doIOaction_ $ lensSetToggleUIForFlag "HANDA" (settings . doesUseTouch) xst toggleTouch | str == "[]:\"1\"" -> colorfunc ColorBlack | str == "[]:\"2\"" -> colorfunc ColorBlue | str == "[]:\"3\"" -> colorfunc ColorRed | str == "[]:\"4\"" -> colorfunc ColorGreen | str == "[]:\"5\"" -> colorfunc ColorGray | str == "[]:\"6\"" -> colorfunc ColorLightBlue | str == "[]:\"7\"" -> colorfunc ColorLightGreen | str == "[]:\"8\"" -> colorfunc ColorMagenta | str == "[]:\"9\"" -> colorfunc ColorOrange | str == "[]:\"0\"" -> colorfunc ColorYellow | str == "[]:\"minus\"" -> colorfunc ColorWhite | str == "[]:\"a\"" -> toolfunc PenWork | str == "[]:\"b\"" -> toolfunc HighlighterWork | str == "[]:\"c\"" -> toolfunc EraserWork | str == "[]:\"d\"" -> toolfunc VerticalSpaceWork | otherwise -> return () where colorfunc c = doIOaction $ \_evhandler -> return (UsrEv (PenColorChanged c)) toolfunc t = doIOaction $ \_evhandler -> return (UsrEv (AssignPenMode (Left t))) defaultEventProcess (SwitchTab i) = switchTab i defaultEventProcess (CloseTab uuid) = findTab uuid >>= mapM_ (\x -> switchTab x >> askIfSave closeTab) defaultEventProcess (OpenLink urlpath mid) = openLinkAction urlpath mid defaultEventProcess (NetworkProcess (NetworkReceived txt)) = networkReceived txt defaultEventProcess ev = -- for debugging do msgShout "--- no default ---" msgShout (show ev) msgShout "------------------"
null
https://raw.githubusercontent.com/wavewave/hoodle/fa7481d14a53733b2f6ae9debc95357d904a943c/core/src/Hoodle/Coroutine/Default.hs
haskell
# LANGUAGE GADTs # # LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # ------- | | maxundo | initialization according to the setting additional initialization goes here | main loop | | ad hoc | | for the time being, I replace any background to solid background for debugging
# LANGUAGE CPP # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module Hoodle.Coroutine.Default where import Control.Concurrent ( forkIO, forkOn, newEmptyMVar, putMVar, ) import qualified Control.Exception as E import Control.Lens (at, over, set, view, (.~), (?~), (^.), _2) import Control.Monad (void, when) import Control.Monad.State (evalStateT, get, gets, liftIO, modify, put) import Control.Monad.Trans.Crtn.Driver (driver) import Control.Monad.Trans.Crtn.Logger.Simple (simplelogger) import Control.Monad.Trans.Crtn.Object (Arg (..)) import Control.Monad.Trans.Reader (ReaderT (..)) import qualified Data.ByteString.Char8 as B import Data.Foldable (mapM_) import Data.Hoodle.Generic ( gbackground, gdimension, ghoodleID, gpages, ) import Data.Hoodle.Simple (Background (..), Dimension (..)) import Data.IORef (writeIORef) import qualified Data.IntMap as M import qualified Data.List as L import Graphics.Hoodle.Render (cnstrctRBkgStateT) import Graphics.Hoodle.Render.Engine ( genRendererMain, pdfRendererMain, ) import Graphics.Hoodle.Render.Type (RBackground (..)) import qualified Graphics.UI.Gtk as Gtk hiding (get, set) import Hoodle.Accessor ( getHoodleFilePath, getPenType, lensSetToggleUIForFlag, pureUpdateUhdl, ) import Hoodle.Coroutine.Callback (eventHandler) import Hoodle.Coroutine.ContextMenu (processContextMenu) import Hoodle.Coroutine.Default.Menu (menuEventProcess) import Hoodle.Coroutine.Draw ( callRenderer, callRenderer_, defaultHandler, doIOaction_, invalidate, invalidateAll, invalidateInBBox, nextevent, waitSomeEvent, ) import Hoodle.Coroutine.Eraser (eraserStart) import Hoodle.Coroutine.File ( askIfSave, fileReload, getFileContent, ) import Hoodle.Coroutine.Highlighter (highlighterStart) import Hoodle.Coroutine.Link ( gotLink, notifyLink, openLinkAction, ) import Hoodle.Coroutine.Mode ( modeChange, viewModeChange, ) import Hoodle.Coroutine.Page ( changePage, pageZoomChange, ) import Hoodle.Coroutine.Pen (penStart) import Hoodle.Coroutine.Scroll ( hscrollBarMoved, vscrollBarMoved, vscrollStart, ) import Hoodle.Coroutine.Select ( selectLassoStart, selectPenColorChanged, selectPenWidthChanged, selectRectStart, ) import Hoodle.Coroutine.TextInput (networkReceived) import Hoodle.Coroutine.VerticalSpace (verticalSpaceStart) import Hoodle.Coroutine.Window ( closeTab, doCanvasConfigure, findTab, paneMoveStart, switchTab, ) import Hoodle.Device ( DeviceList, PenButton (..), dev_touch_str, ) import Hoodle.GUI.Menu ( getMenuUI, int2Point, ) import Hoodle.GUI.Reflect ( reflectNewPageModeUI, reflectPenColorUI, reflectPenModeUI, reflectPenWidthUI, reflectUIToggle, reflectViewModeUI, ) import Hoodle.ModelAction.Page (getPageFromGHoodleMap) import Hoodle.ModelAction.Window ( constructFrame, createTab, eventConnect, ) import Hoodle.Script.Hook (Hook) import Hoodle.Type.Canvas ( CanvasId, CanvasInfoBox (CanvasSinglePage), canvasWidgets, currentPageNum, currentTool, defaultCvsInfoSinglePage, penColor, penType, penWidth, unboxLens, _canvasId, ) import Hoodle.Type.Coroutine ( EventVar, MainCoroutine, MainOp (DoEvent), doIOaction, world, ) import Hoodle.Type.Enum ( DrawFlag (Efficient), PenColor (..), PenType (..), SelectType (..), convertBackgroundStyleToByteString, selectType, ) import Hoodle.Type.Event ( AllEvent (..), NetworkEvent (..), RenderEvent (..), UserEvent (..), ) import Hoodle.Type.HoodleState ( FileStore (LocalDir), HoodleModeState (ViewAppendState), HoodleState, IsOneTimeSelectMode (YesBeforeSelect), backgroundStyle, callBack, currentCanvasInfo, currentUnit, cvsInfoMap, deviceList, doesUseTouch, doesUseVariableCursor, doesUseXInput, emptyHoodleState, frameState, genRenderQueue, getCurrentCanvasId, getHoodle, gtkUIManager, hoodleFileControl, hoodleFileName, hoodleModeState, hoodleModeStateEither, hookSet, isOneTimeSelectMode, isSaved, newPageMode, pdfRenderQueue, penInfo, renderCacheVar, resetHoodleModeStateBuffers, rootContainer, rootNotebook, rootOfRootWindow, rootWindow, selectInfo, settings, statusBar, switchTabSignal, uiComponentSignalHandler, undoTable, unitButton, unitHoodles, unitUUID, updateFromCanvasInfoAsCurrentCanvas, ) import Hoodle.Type.PageArrangement ( CanvasDimension (..), ZoomMode (FitWidth), ) import Hoodle.Type.Undo (emptyUndo) import Hoodle.Type.Widget ( doesUseLayerWidget, doesUsePanZoomWidget, widgetConfig, ) import Hoodle.Type.Window (WindowConfig (Node)) import Hoodle.Util (msgShout, (#)) import Hoodle.Widget.Dispatch (widgetCheckPen) import Hoodle.Widget.PanZoom (toggleTouch, touchStart) import System.Process (readProcess) import Prelude hiding (mapM_) initCoroutine :: DeviceList -> Gtk.Window -> Maybe Hook -> Int -> | ( xinputbool , usepz , uselyr , varcsr ) (Bool, Bool, Bool, Bool) -> IO (EventVar, HoodleState, Gtk.UIManager, Gtk.VBox) initCoroutine devlst window mhook maxundo (xinputbool, usepz, uselyr, varcsr) = do evar <- newEmptyMVar putMVar evar Nothing let callback = eventHandler evar st0new <- set deviceList devlst . set rootOfRootWindow window . set callBack callback <$> emptyHoodleState (ui, uicompsighdlr) <- getMenuUI evar let st1 = set gtkUIManager ui st0new initcvs = set (canvasWidgets . widgetConfig . doesUsePanZoomWidget) usepz . set (canvasWidgets . widgetConfig . doesUseLayerWidget) uselyr $ defaultCvsInfoSinglePage {_canvasId = 1} initcvsbox = CanvasSinglePage initcvs st2 = st1 # over (unitHoodles . currentUnit) ( set frameState (Node 1) . updateFromCanvasInfoAsCurrentCanvas initcvsbox . set cvsInfoMap M.empty ) uhdl2 = view (unitHoodles . currentUnit) st2 (uhdl3, rtwdw, _wconf) <- constructFrame st2 uhdl2 (view frameState uhdl2) (uhdl4, wconf') <- eventConnect st2 uhdl3 (view frameState uhdl3) notebook <- Gtk.notebookNew statusbar <- Gtk.statusbarNew let st4 = (unitHoodles . currentUnit .~ uhdl4) st2 st5 = st4 # over (unitHoodles . currentUnit) ( set undoTable (emptyUndo maxundo) . set frameState wconf' . set rootWindow rtwdw . set (hoodleFileControl . hoodleFileName) (LocalDir Nothing) ) . set (settings . doesUseXInput) xinputbool . set (settings . doesUseVariableCursor) varcsr . set hookSet mhook . set rootNotebook notebook . set uiComponentSignalHandler uicompsighdlr . set statusBar (Just statusbar) vbox <- Gtk.vBoxNew False 0 Gtk.containerAdd window vbox vboxcvs <- Gtk.vBoxNew False 0 (_, uuid, btn) <- createTab callback notebook vboxcvs Gtk.containerAdd vboxcvs (view (unitHoodles . currentUnit . rootWindow) st5) sigid <- notebook `Gtk.on` Gtk.switchPage $ \i -> callback (UsrEv (SwitchTab i)) let st6 = ( (unitHoodles . currentUnit . unitUUID .~ uuid) . (unitHoodles . currentUnit . unitButton .~ btn) . (uiComponentSignalHandler . switchTabSignal ?~ sigid) ) st5 startingXstate = (unitHoodles . currentUnit . rootContainer .~ Gtk.castToBox vboxcvs) st6 startworld = world startingXstate . ReaderT $ (\(Arg DoEvent ev) -> guiProcess ev) putMVar evar . Just $ driver simplelogger startworld return (evar, startingXstate, ui, vbox) initialize :: Maybe (CanvasId, CanvasDimension) -> Bool -> AllEvent -> MainCoroutine (CanvasId, CanvasDimension) initialize cvs isInitialized ev = do case ev of UsrEv (Initialized mfname) -> do if isInitialized then do case cvs of Nothing -> nextevent >>= initialize Nothing True . UsrEv Just cvsi -> return cvsi else do xst1 <- get let ui = xst1 ^. gtkUIManager cachevar = xst1 ^. renderCacheVar tvarpdf = xst1 ^. pdfRenderQueue tvargen = xst1 ^. genRenderQueue doIOaction $ \evhandler -> do _ <- forkOn 2 $ pdfRendererMain (defaultHandler evhandler) tvarpdf _ <- forkIO $ E.catch (genRendererMain cachevar (defaultHandler evhandler) tvargen) (\e -> print (e :: E.SomeException)) return (UsrEv ActionOrdered) _ <- waitSomeEvent (\case ActionOrdered -> True; _ -> False) getFileContent (LocalDir mfname) xst2 <- get let uhdl = view (unitHoodles . currentUnit) xst2 hdlst = uhdl ^. hoodleModeState cid = getCurrentCanvasId uhdl callRenderer_ $ resetHoodleModeStateBuffers cid hdlst pureUpdateUhdl (hoodleModeState .~ hdlst) liftIO $ reflectUIToggle ui "SAVEA" False pureUpdateUhdl (isSaved .~ True) case cvs of Just cvsi -> return cvsi Nothing -> nextevent >>= initialize Nothing True . UsrEv UsrEv (CanvasConfigure cid w h) -> do nextevent >>= initialize (Just (cid, CanvasDimension (Dim w h))) isInitialized . UsrEv _ -> case (cvs, isInitialized) of (Just cvsi, True) -> return cvsi _ -> nextevent >>= initialize cvs isInitialized . UsrEv guiProcess :: AllEvent -> MainCoroutine () guiProcess ev = do (cid, cdim) <- initialize Nothing False ev changePage (const 0) reflectViewModeUI reflectPenModeUI reflectPenColorUI reflectPenWidthUI reflectNewPageModeUI viewModeChange ToContSinglePage pageZoomChange FitWidth doCanvasConfigure cid cdim sequence_ (repeat dispatchMode) dispatchMode :: MainCoroutine () dispatchMode = gets (view (unitHoodles . currentUnit)) >>= either (const viewAppendMode) (const selectMode) . hoodleModeStateEither . view hoodleModeState viewAppendMode :: MainCoroutine () viewAppendMode = do r1 <- nextevent case r1 of PenDown cid pbtn pcoord -> widgetCheckPen cid pcoord $ do ptype <- getPenType case (ptype, pbtn) of (PenWork, PenButton1) -> do r <- penStart cid pcoord case r of Just (Just Nothing) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord _ -> return () (PenWork, PenButton2) -> eraserStart cid pcoord (PenWork, PenButton3) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord (PenWork, EraserButton) -> eraserStart cid pcoord (PenWork, _) -> return () (EraserWork, _) -> eraserStart cid pcoord (HighlighterWork, _) -> do r <- highlighterStart cid pcoord case r of Just (Just Nothing) -> do pureUpdateUhdl (isOneTimeSelectMode .~ YesBeforeSelect) modeChange ToSelectMode selectLassoStart PenButton3 cid pcoord _ -> return () (VerticalSpaceWork, PenButton1) -> verticalSpaceStart cid pcoord (VerticalSpaceWork, _) -> return () TouchDown cid pcoord -> touchStart cid pcoord PenMove cid pcoord -> disableTouch >> notifyLink cid pcoord _ -> defaultEventProcess r1 disableTouch :: MainCoroutine () disableTouch = do xst <- get let devlst = view deviceList xst when (view (settings . doesUseTouch) xst) $ do let nxst = set (settings . doesUseTouch) False xst doIOaction_ $ do _ <- lensSetToggleUIForFlag "HANDA" (settings . doesUseTouch) nxst let touchstr = dev_touch_str devlst when (touchstr /= "touch") $ void $ readProcess "xinput" ["disable", touchstr] "" put nxst selectMode :: MainCoroutine () selectMode = do r1 <- nextevent case r1 of PenDown cid pbtn pcoord -> do ptype <- gets (view (selectInfo . selectType)) case ptype of SelectRectangleWork -> selectRectStart pbtn cid pcoord SelectLassoWork -> selectLassoStart pbtn cid pcoord _ -> return () PenMove cid pcoord -> disableTouch >> notifyLink cid pcoord TouchDown cid pcoord -> touchStart cid pcoord PenColorChanged c -> do modify (penInfo . currentTool . penColor .~ c) selectPenColorChanged c PenWidthChanged v -> do w <- gets (flip int2Point v . view (penInfo . penType)) modify (penInfo . currentTool . penWidth .~ w) selectPenWidthChanged w _ -> defaultEventProcess r1 defaultEventProcess :: UserEvent -> MainCoroutine () defaultEventProcess (UpdateCanvas cid) = invalidate cid defaultEventProcess (UpdateCanvasEfficient cid) = invalidateInBBox Nothing Efficient cid defaultEventProcess (Menu m) = menuEventProcess m defaultEventProcess (HScrollBarMoved cid v) = hscrollBarMoved cid v defaultEventProcess (VScrollBarMoved cid v) = vscrollBarMoved cid v defaultEventProcess (VScrollBarStart cid v) = vscrollStart cid v defaultEventProcess PaneMoveStart = paneMoveStart defaultEventProcess (CanvasConfigure cid w' h') = doCanvasConfigure cid (CanvasDimension (Dim w' h')) defaultEventProcess ToViewAppendMode = modeChange ToViewAppendMode defaultEventProcess ToSelectMode = modeChange ToSelectMode defaultEventProcess ToSinglePage = viewModeChange ToSinglePage defaultEventProcess ToContSinglePage = viewModeChange ToContSinglePage defaultEventProcess (AssignPenMode t) = case t of Left pm -> do modify (penInfo . penType .~ pm) modeChange ToViewAppendMode Right sm -> do modify (selectInfo . selectType .~ sm) modeChange ToSelectMode defaultEventProcess (PenColorChanged c) = do modify (penInfo . currentTool . penColor .~ c) reflectPenColorUI defaultEventProcess (PenWidthChanged v) = do st <- get let ptype = view (penInfo . penType) st let w = int2Point ptype v let stNew = set (penInfo . currentTool . penWidth) w st put stNew reflectPenWidthUI defaultEventProcess (BackgroundStyleChanged bsty) = do modify (backgroundStyle .~ bsty) uhdl <- gets (view (unitHoodles . currentUnit)) let pgnum = view (currentCanvasInfo . unboxLens currentPageNum) uhdl hdl = getHoodle uhdl pgs = view gpages hdl cpage = getPageFromGHoodleMap pgnum hdl cbkg = view gbackground cpage bstystr = convertBackgroundStyleToByteString bsty dim = view gdimension cpage getnbkg' :: RBackground -> Background getnbkg' (RBkgSmpl c _ _) = Background "solid" c bstystr getnbkg' RBkgPDF {} = Background "solid" "white" bstystr getnbkg' RBkgEmbedPDF {} = Background "solid" "white" bstystr liftIO $ putStrLn " defaultEventProcess: BackgroundStyleChanged HERE/ " callRenderer $ GotRBackground <$> evalStateT (cnstrctRBkgStateT dim (getnbkg' cbkg)) Nothing RenderEv (GotRBackground nbkg) <- waitSomeEvent (\case RenderEv (GotRBackground _) -> True; _ -> False) let npage = set gbackground nbkg cpage npgs = set (at pgnum) (Just npage) pgs nhdl = set gpages npgs hdl modeChange ToViewAppendMode pureUpdateUhdl (hoodleModeState .~ ViewAppendState nhdl) invalidateAll defaultEventProcess (AssignNewPageMode nmod) = modify (settings . newPageMode .~ nmod) defaultEventProcess (GotContextMenuSignal ctxtmenu) = processContextMenu ctxtmenu defaultEventProcess (GetHoodleFileInfo ref) = do uhdl <- gets (view (unitHoodles . currentUnit)) let hdl = getHoodle uhdl uuid = B.unpack (view ghoodleID hdl) case getHoodleFilePath uhdl of Nothing -> liftIO $ writeIORef ref Nothing Just fp -> liftIO $ writeIORef ref (Just (uuid ++ "," ++ fp)) defaultEventProcess (GetHoodleFileInfoFromTab uuidtab ref) = do uhdlmap <- gets (view (unitHoodles . _2)) let muhdl = (L.lookup uuidtab . map (\x -> (view unitUUID x, x)) . M.elems) uhdlmap case muhdl of Nothing -> liftIO $ writeIORef ref Nothing Just uhdl -> do let hdl = getHoodle uhdl uuid = B.unpack (view ghoodleID hdl) case getHoodleFilePath uhdl of Nothing -> liftIO $ writeIORef ref Nothing Just fp -> liftIO $ writeIORef ref (Just (uuid ++ "," ++ fp)) defaultEventProcess (GotLink mstr (x, y)) = gotLink mstr (x, y) defaultEventProcess FileReloadOrdered = fileReload defaultEventProcess (CustomKeyEvent str) = do if | str == "[]:\"Super_L\"" -> do xst <- gets (over (settings . doesUseTouch) not) put xst doIOaction_ $ lensSetToggleUIForFlag "HANDA" (settings . doesUseTouch) xst toggleTouch | str == "[]:\"1\"" -> colorfunc ColorBlack | str == "[]:\"2\"" -> colorfunc ColorBlue | str == "[]:\"3\"" -> colorfunc ColorRed | str == "[]:\"4\"" -> colorfunc ColorGreen | str == "[]:\"5\"" -> colorfunc ColorGray | str == "[]:\"6\"" -> colorfunc ColorLightBlue | str == "[]:\"7\"" -> colorfunc ColorLightGreen | str == "[]:\"8\"" -> colorfunc ColorMagenta | str == "[]:\"9\"" -> colorfunc ColorOrange | str == "[]:\"0\"" -> colorfunc ColorYellow | str == "[]:\"minus\"" -> colorfunc ColorWhite | str == "[]:\"a\"" -> toolfunc PenWork | str == "[]:\"b\"" -> toolfunc HighlighterWork | str == "[]:\"c\"" -> toolfunc EraserWork | str == "[]:\"d\"" -> toolfunc VerticalSpaceWork | otherwise -> return () where colorfunc c = doIOaction $ \_evhandler -> return (UsrEv (PenColorChanged c)) toolfunc t = doIOaction $ \_evhandler -> return (UsrEv (AssignPenMode (Left t))) defaultEventProcess (SwitchTab i) = switchTab i defaultEventProcess (CloseTab uuid) = findTab uuid >>= mapM_ (\x -> switchTab x >> askIfSave closeTab) defaultEventProcess (OpenLink urlpath mid) = openLinkAction urlpath mid defaultEventProcess (NetworkProcess (NetworkReceived txt)) = networkReceived txt defaultEventProcess ev = do msgShout "--- no default ---" msgShout (show ev) msgShout "------------------"
556e8e24e4ba408f0a9ce185f0ad753b0c70a25dbbee5614bea895e6598ca610
VisionsGlobalEmpowerment/webchange
icon_align_left.cljs
(ns webchange.ui.components.icon.system.icon-align-left) (def data [:svg {:xmlns "" :width "26" :height "24" :viewBox "0 0 26 24" :class-name "stroke-colored" :fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-miterlimit "10"} [:path {:d "M4.21875 6.375H21.3299"}] [:path {:d "M4.21875 10.125H16.6632"}] [:path {:d "M4.21973 13.875H21.3302"}] [:path {:d "M4.21973 17.625H16.6636"}]])
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/07ab8bb00cf8fee60cbcf1ac1519e3409a7b681e/src/cljs/webchange/ui/components/icon/system/icon_align_left.cljs
clojure
(ns webchange.ui.components.icon.system.icon-align-left) (def data [:svg {:xmlns "" :width "26" :height "24" :viewBox "0 0 26 24" :class-name "stroke-colored" :fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-miterlimit "10"} [:path {:d "M4.21875 6.375H21.3299"}] [:path {:d "M4.21875 10.125H16.6632"}] [:path {:d "M4.21973 13.875H21.3302"}] [:path {:d "M4.21973 17.625H16.6636"}]])
d6e194e8a3037bf2482d527628b6c7a70ddd420c34dbfe39b11b9ce54ab4001e
goldfirere/singletons
T226.hs
module T226 where import Data.Singletons.TH $(singletons [d| class a ~> b |])
null
https://raw.githubusercontent.com/goldfirere/singletons/70d622645b960d60411ab8f31d16ffb91e69379e/singletons-base/tests/compile-and-dump/Singletons/T226.hs
haskell
module T226 where import Data.Singletons.TH $(singletons [d| class a ~> b |])
3b086f36ad696ce3a1c1f24156930ed63c4f3a5a6f694b14a4a526a00a734981
CSCfi/rems
config.cljs
(ns rems.config (:require [re-frame.core :as rf] [rems.common.util :refer [index-by]] [rems.flash-message :as flash-message] [rems.util :refer [fetch]])) ;; config (rf/reg-event-db ::loaded-config (fn [db [_ config]] (assoc db :config config :default-language (get config :default-language) :languages (get config :languages)))) (rf/reg-sub ::config (fn [db _] (:config db))) (defn ^:export fetch-config! [& [callback]] (fetch "/api/config" {:handler #(do (rf/dispatch-sync [::loaded-config %]) (when callback (callback %))) :error-handler (flash-message/default-error-handler :top "Fetch config")})) (defn dev-environment? [] (let [config @(rf/subscribe [::config])] (boolean (:dev config)))) (defn ^:export set-config! [js-config] (when (dev-environment?) (rf/dispatch-sync [::loaded-config (merge @(rf/subscribe [::config]) (js->clj js-config :keywordize-keys true))]))) ;; organizations (rf/reg-sub :organization-by-id (fn [db _] (:organization-by-id db {}))) (rf/reg-sub :organizations (fn [_db _] [(rf/subscribe [:organization-by-id]) (rf/subscribe [:language])]) (fn [[organization-by-id language]] (sort-by (comp language :organization/name) (vals organization-by-id)))) (rf/reg-sub :owned-organizations (fn [db _] (let [roles (get-in db [:identity :roles]) userid (get-in db [:identity :user :userid])] (for [org (vals (:organization-by-id db)) :let [owners (set (map :userid (:organization/owners org)))] :when (or (contains? roles :owner) (contains? owners userid))] org)))) (rf/reg-event-db :loaded-organizations (fn [db [_ organizations]] (assoc db :organization-by-id (index-by [:organization/id] organizations)))) (defn fetch-organizations! [] (fetch "/api/organizations" {:params {:disabled true :archived true} :handler #(rf/dispatch-sync [:loaded-organizations %]) :error-handler (flash-message/default-error-handler :top "Fetch organizations")}))
null
https://raw.githubusercontent.com/CSCfi/rems/567ce80d7b136d43570083380933d2907baba769/src/cljs/rems/config.cljs
clojure
config organizations
(ns rems.config (:require [re-frame.core :as rf] [rems.common.util :refer [index-by]] [rems.flash-message :as flash-message] [rems.util :refer [fetch]])) (rf/reg-event-db ::loaded-config (fn [db [_ config]] (assoc db :config config :default-language (get config :default-language) :languages (get config :languages)))) (rf/reg-sub ::config (fn [db _] (:config db))) (defn ^:export fetch-config! [& [callback]] (fetch "/api/config" {:handler #(do (rf/dispatch-sync [::loaded-config %]) (when callback (callback %))) :error-handler (flash-message/default-error-handler :top "Fetch config")})) (defn dev-environment? [] (let [config @(rf/subscribe [::config])] (boolean (:dev config)))) (defn ^:export set-config! [js-config] (when (dev-environment?) (rf/dispatch-sync [::loaded-config (merge @(rf/subscribe [::config]) (js->clj js-config :keywordize-keys true))]))) (rf/reg-sub :organization-by-id (fn [db _] (:organization-by-id db {}))) (rf/reg-sub :organizations (fn [_db _] [(rf/subscribe [:organization-by-id]) (rf/subscribe [:language])]) (fn [[organization-by-id language]] (sort-by (comp language :organization/name) (vals organization-by-id)))) (rf/reg-sub :owned-organizations (fn [db _] (let [roles (get-in db [:identity :roles]) userid (get-in db [:identity :user :userid])] (for [org (vals (:organization-by-id db)) :let [owners (set (map :userid (:organization/owners org)))] :when (or (contains? roles :owner) (contains? owners userid))] org)))) (rf/reg-event-db :loaded-organizations (fn [db [_ organizations]] (assoc db :organization-by-id (index-by [:organization/id] organizations)))) (defn fetch-organizations! [] (fetch "/api/organizations" {:params {:disabled true :archived true} :handler #(rf/dispatch-sync [:loaded-organizations %]) :error-handler (flash-message/default-error-handler :top "Fetch organizations")}))
cf921f84b21fe1d1a7e6fac04d2eb12c47a7820c3498d0fa78ca3583261296d9
foreverbell/project-euler-solutions
78.hs
import Data.Array.IArray modulo = 1000000 :: Int ways :: Array Int Int ways = listArray (0, 100000) [ dp n | n <- [0 .. 100000] ] where dp 0 = 1 dp n = helper 1 1 where helper j r = if val1 >= 0 then (acc + (helper (j + 1) (-r))) `mod` modulo else 0 where val1 = n - ((3 * j * j - j) `div` 2) val2 = n - ((3 * j * j + j) `div` 2) acc1 = r * (ways ! val1) acc2 = if (val2 >= 0) then r * (ways ! val2) else 0 acc = acc1 + acc2 find0 ((index, 0) : _) = index find0 (_ : xs) = find0 xs main = print $ find0 $ assocs ways
null
https://raw.githubusercontent.com/foreverbell/project-euler-solutions/c0bf2746aafce9be510892814e2d03e20738bf2b/src/78.hs
haskell
import Data.Array.IArray modulo = 1000000 :: Int ways :: Array Int Int ways = listArray (0, 100000) [ dp n | n <- [0 .. 100000] ] where dp 0 = 1 dp n = helper 1 1 where helper j r = if val1 >= 0 then (acc + (helper (j + 1) (-r))) `mod` modulo else 0 where val1 = n - ((3 * j * j - j) `div` 2) val2 = n - ((3 * j * j + j) `div` 2) acc1 = r * (ways ! val1) acc2 = if (val2 >= 0) then r * (ways ! val2) else 0 acc = acc1 + acc2 find0 ((index, 0) : _) = index find0 (_ : xs) = find0 xs main = print $ find0 $ assocs ways
bf9d9d4dc498e7c4bd9a0677dea826e866867aa44d73c47e168871d8e68864c8
cyverse-archive/DiscoveryEnvironmentBackend
element.clj
(ns metadactyl.routes.domain.app.element (:use [common-swagger-api.schema :only [describe]] [schema.core :only [defschema optional-key]]) (:import [java.util UUID])) (defschema DataSource {:id (describe UUID "A UUID that is used to identify the Data Source") :name (describe String "The Data Source's name") :description (describe String "The Data Source's description") :label (describe String "The Data Source's label")}) (defschema FileFormat {:id (describe UUID "A UUID that is used to identify the File Format") :name (describe String "The File Format's name") (optional-key :label) (describe String "The File Format's label")}) (defschema InfoType {:id (describe UUID "A UUID that is used to identify the Info Type") :name (describe String "The Info Type's name") (optional-key :label) (describe String "The Info Type's label")}) (defschema ParameterType {:id (describe UUID "A UUID that is used to identify the Parameter Type") :name (describe String "The Parameter Type's name") (optional-key :description) (describe String "The Parameter Type's description") :value_type (describe String "The Parameter Type's value type name")}) (defschema RuleType {:id (describe UUID "A UUID that is used to identify the Rule Type") :name (describe String "The Rule Type's name") (optional-key :description) (describe String "The Rule Type's description") :rule_description_format (describe String "The Rule Type's description format") :subtype (describe String "The Rule Type's subtype") :value_types (describe [String] "The Rule Type's value types")}) (defschema ToolType {:id (describe UUID "A UUID that is used to identify the Tool Type") :name (describe String "The Tool Type's name") (optional-key :description) (describe String "The Tool Type's description") :label (describe String "The Tool Type's label")}) (defschema ValueType {:id (describe UUID "A UUID that is used to identify the Value Type") :name (describe String "The Value Type's name") :description (describe String "The Value Type's description")}) (defschema DataSourceListing {:data_sources (describe [DataSource] "Listing of App File Parameter Data Sources")}) (defschema FileFormatListing {:formats (describe [FileFormat] "Listing of App Parameter File Formats")}) (defschema InfoTypeListing {:info_types (describe [InfoType] "Listing of Tool Info Types")}) (defschema ParameterTypeListing {:parameter_types (describe [ParameterType] "Listing of App Parameter Types")}) (defschema RuleTypeListing {:rule_types (describe [RuleType] "Listing of App Parameter Rule Types")}) (defschema ToolTypeListing {:tool_types (describe [ToolType] "Listing of App Tool Types")}) (defschema ValueTypeListing {:value_types (describe [ValueType] "Listing of App Parameter and Rule Value Types")})
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/routes/domain/app/element.clj
clojure
(ns metadactyl.routes.domain.app.element (:use [common-swagger-api.schema :only [describe]] [schema.core :only [defschema optional-key]]) (:import [java.util UUID])) (defschema DataSource {:id (describe UUID "A UUID that is used to identify the Data Source") :name (describe String "The Data Source's name") :description (describe String "The Data Source's description") :label (describe String "The Data Source's label")}) (defschema FileFormat {:id (describe UUID "A UUID that is used to identify the File Format") :name (describe String "The File Format's name") (optional-key :label) (describe String "The File Format's label")}) (defschema InfoType {:id (describe UUID "A UUID that is used to identify the Info Type") :name (describe String "The Info Type's name") (optional-key :label) (describe String "The Info Type's label")}) (defschema ParameterType {:id (describe UUID "A UUID that is used to identify the Parameter Type") :name (describe String "The Parameter Type's name") (optional-key :description) (describe String "The Parameter Type's description") :value_type (describe String "The Parameter Type's value type name")}) (defschema RuleType {:id (describe UUID "A UUID that is used to identify the Rule Type") :name (describe String "The Rule Type's name") (optional-key :description) (describe String "The Rule Type's description") :rule_description_format (describe String "The Rule Type's description format") :subtype (describe String "The Rule Type's subtype") :value_types (describe [String] "The Rule Type's value types")}) (defschema ToolType {:id (describe UUID "A UUID that is used to identify the Tool Type") :name (describe String "The Tool Type's name") (optional-key :description) (describe String "The Tool Type's description") :label (describe String "The Tool Type's label")}) (defschema ValueType {:id (describe UUID "A UUID that is used to identify the Value Type") :name (describe String "The Value Type's name") :description (describe String "The Value Type's description")}) (defschema DataSourceListing {:data_sources (describe [DataSource] "Listing of App File Parameter Data Sources")}) (defschema FileFormatListing {:formats (describe [FileFormat] "Listing of App Parameter File Formats")}) (defschema InfoTypeListing {:info_types (describe [InfoType] "Listing of Tool Info Types")}) (defschema ParameterTypeListing {:parameter_types (describe [ParameterType] "Listing of App Parameter Types")}) (defschema RuleTypeListing {:rule_types (describe [RuleType] "Listing of App Parameter Rule Types")}) (defschema ToolTypeListing {:tool_types (describe [ToolType] "Listing of App Tool Types")}) (defschema ValueTypeListing {:value_types (describe [ValueType] "Listing of App Parameter and Rule Value Types")})
eb6516b6ec8731781b614ad963e633f510e9df96fc95e92d08627c13cd29559b
silkapp/rest
Gen.hs
module Rest.Gen ( generate ) where import Data.Char import Data.Foldable import Data.Label import Data.Maybe import System.Directory import System.Exit import System.Process import qualified Language.Haskell.Exts.Syntax as H import Rest.Api (Api, Some1 (..), withVersion) import Rest.Gen.Config import Rest.Gen.Docs (DocsContext (DocsContext), writeDocs) import Rest.Gen.Haskell (HaskellContext (HaskellContext), mkHsApi) import Rest.Gen.JavaScript (mkJsApi) import Rest.Gen.Ruby (mkRbApi) import Rest.Gen.Types import Rest.Gen.Utils import qualified Rest.Gen.NoAnnotation as N generate :: Config -> String -> Api m -> [N.ModuleName] -> [N.ImportDecl] -> [(N.ModuleName, N.ModuleName)] -> IO () generate config name api sources imports rewrites = withVersion (get apiVersion config) api (putStrLn "Could not find api version" >> exitFailure) $ \ver (Some1 r) -> case get action config of Just (MakeDocs root) -> do loc <- getTargetDir config "./docs" setupTargetDir config loc let context = DocsContext root ver (fromMaybe "./templates" (getSourceLocation config)) writeDocs context r loc exitSuccess Just MakeJS -> mkJsApi (overModuleName (++ "Api") moduleName) (get apiPrivate config) ver r >>= toTarget config Just MakeRb -> mkRbApi (overModuleName (++ "Api") moduleName) (get apiPrivate config) ver r >>= toTarget config Just MakeHS -> do loc <- getTargetDir config "./client" setupTargetDir config loc let context = HaskellContext ver loc (packageName ++ "-client") (get apiPrivate config) sources imports rewrites [unModuleName moduleName, "Client"] mkHsApi context r exitSuccess Nothing -> return () where packageName = map toLower name moduleName = H.ModuleName () $ upFirst packageName getTargetDir :: Config -> String -> IO String getTargetDir config str = case get target config of Stream -> putStrLn ("Cannot generate documentation to stdOut, generating to " ++ str) >> return str Default -> putStrLn ("Generating to " ++ str) >> return str Location d -> putStrLn ("Generating to " ++ d) >> return d setupTargetDir :: Config -> String -> IO () setupTargetDir config t = do createDirectoryIfMissing True t forM_ (getSourceLocation config) $ \s -> system $ "cp -rf " ++ s ++ " " ++ t toTarget :: Config -> String -> IO () toTarget config code = do let outf = case get target config of Stream -> putStrLn Default -> putStrLn Location l -> writeFile l outf code exitSuccess getSourceLocation :: Config -> Maybe String getSourceLocation config = case get source config of Location s -> Just s _ -> Nothing
null
https://raw.githubusercontent.com/silkapp/rest/f0462fc36709407f236f57064d8e37c77bdf8a79/rest-gen/src/Rest/Gen.hs
haskell
module Rest.Gen ( generate ) where import Data.Char import Data.Foldable import Data.Label import Data.Maybe import System.Directory import System.Exit import System.Process import qualified Language.Haskell.Exts.Syntax as H import Rest.Api (Api, Some1 (..), withVersion) import Rest.Gen.Config import Rest.Gen.Docs (DocsContext (DocsContext), writeDocs) import Rest.Gen.Haskell (HaskellContext (HaskellContext), mkHsApi) import Rest.Gen.JavaScript (mkJsApi) import Rest.Gen.Ruby (mkRbApi) import Rest.Gen.Types import Rest.Gen.Utils import qualified Rest.Gen.NoAnnotation as N generate :: Config -> String -> Api m -> [N.ModuleName] -> [N.ImportDecl] -> [(N.ModuleName, N.ModuleName)] -> IO () generate config name api sources imports rewrites = withVersion (get apiVersion config) api (putStrLn "Could not find api version" >> exitFailure) $ \ver (Some1 r) -> case get action config of Just (MakeDocs root) -> do loc <- getTargetDir config "./docs" setupTargetDir config loc let context = DocsContext root ver (fromMaybe "./templates" (getSourceLocation config)) writeDocs context r loc exitSuccess Just MakeJS -> mkJsApi (overModuleName (++ "Api") moduleName) (get apiPrivate config) ver r >>= toTarget config Just MakeRb -> mkRbApi (overModuleName (++ "Api") moduleName) (get apiPrivate config) ver r >>= toTarget config Just MakeHS -> do loc <- getTargetDir config "./client" setupTargetDir config loc let context = HaskellContext ver loc (packageName ++ "-client") (get apiPrivate config) sources imports rewrites [unModuleName moduleName, "Client"] mkHsApi context r exitSuccess Nothing -> return () where packageName = map toLower name moduleName = H.ModuleName () $ upFirst packageName getTargetDir :: Config -> String -> IO String getTargetDir config str = case get target config of Stream -> putStrLn ("Cannot generate documentation to stdOut, generating to " ++ str) >> return str Default -> putStrLn ("Generating to " ++ str) >> return str Location d -> putStrLn ("Generating to " ++ d) >> return d setupTargetDir :: Config -> String -> IO () setupTargetDir config t = do createDirectoryIfMissing True t forM_ (getSourceLocation config) $ \s -> system $ "cp -rf " ++ s ++ " " ++ t toTarget :: Config -> String -> IO () toTarget config code = do let outf = case get target config of Stream -> putStrLn Default -> putStrLn Location l -> writeFile l outf code exitSuccess getSourceLocation :: Config -> Maybe String getSourceLocation config = case get source config of Location s -> Just s _ -> Nothing