_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 |
|---|---|---|---|---|---|---|---|---|
02fc5a50640403f824cf007161d14a74286071b41da668c9e8945bc57bf001e2 | cedlemo/OCaml-libmpdclient | mpd_lwt_status.ml |
* Copyright 2018 ,
* This file is part of .
*
* OCaml - libmpdclient 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
* any later version .
*
* OCaml - libmpdclient 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 . If not , see < / > .
* Copyright 2018 Cedric LE MOIGNE,
* This file is part of OCaml-libmpdclient.
*
* OCaml-libmpdclient 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
* any later version.
*
* OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>.
*)
open Lwt.Infix
let host = "127.0.0.1"
let port = 6600
let lwt_print_line str =
Lwt_io.write_line Lwt_io.stdout str
let main_thread =
let open Mpd in
Connection_lwt.initialize host port
>>= fun connection ->
Client_lwt.initialize connection
>>= fun client ->
Client_lwt.status client
>>= function
| Error (message) ->
lwt_print_line (Printf.sprintf "No response : %s" message)
| Ok status ->
let _ = lwt_print_line (Printf.sprintf "volume: %d" (Mpd.Status.volume status)) in
lwt_print_line (Printf.sprintf "state : %s"
(Mpd.Status.state status |> Mpd.Status.string_of_state))
let () =
Lwt_main.run main_thread
| null | https://raw.githubusercontent.com/cedlemo/OCaml-libmpdclient/49922f4fa0c1471324c613301675ffc06ff3147c/samples/mpd_lwt_status.ml | ocaml |
* Copyright 2018 ,
* This file is part of .
*
* OCaml - libmpdclient 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
* any later version .
*
* OCaml - libmpdclient 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 . If not , see < / > .
* Copyright 2018 Cedric LE MOIGNE,
* This file is part of OCaml-libmpdclient.
*
* OCaml-libmpdclient 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
* any later version.
*
* OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>.
*)
open Lwt.Infix
let host = "127.0.0.1"
let port = 6600
let lwt_print_line str =
Lwt_io.write_line Lwt_io.stdout str
let main_thread =
let open Mpd in
Connection_lwt.initialize host port
>>= fun connection ->
Client_lwt.initialize connection
>>= fun client ->
Client_lwt.status client
>>= function
| Error (message) ->
lwt_print_line (Printf.sprintf "No response : %s" message)
| Ok status ->
let _ = lwt_print_line (Printf.sprintf "volume: %d" (Mpd.Status.volume status)) in
lwt_print_line (Printf.sprintf "state : %s"
(Mpd.Status.state status |> Mpd.Status.string_of_state))
let () =
Lwt_main.run main_thread
| |
a433d4f96a619a5b762535f61eccab96863e76b148808bb2f06307f72a2342ba | elastic/eui-cljs | panel.cljs | (ns eui.panel
(:require ["@elastic/eui/lib/components/panel/panel.js" :as eui]))
(def EuiPanel eui/EuiPanel)
(def SIZES eui/SIZES)
(def BORDER_RADII eui/BORDER_RADII)
(def COLORS eui/COLORS)
| null | https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/panel.cljs | clojure | (ns eui.panel
(:require ["@elastic/eui/lib/components/panel/panel.js" :as eui]))
(def EuiPanel eui/EuiPanel)
(def SIZES eui/SIZES)
(def BORDER_RADII eui/BORDER_RADII)
(def COLORS eui/COLORS)
| |
8170b8cd6cf0a19d0a4818c37dcb939972cbb8e6319ff8ba2392bd4b91112cad | tsloughter/erlangdc2013 | estatsd_sup.erl | @author < >
2011
%% @doc The EStatsD main supervisor module.
-module (estatsd_sup).
This is an OPT supervisor .
-behaviour (supervisor).
%% Client API.
-export ([
start_link/0
]).
OTP supervisor callbacks .
-export ([
init/1
]).
= = = = = = = = = = = = = = = = = = = = = = \/ CLIENT API = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
%% @doc Starts EStatsD's main supervisor.
%% Registers a process named `estatsd_sup`.
start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).
% ====================== /\ CLIENT API =========================================
= = = = = = = = = = = = = = = = = = = = = = \/ SUPERVISOR CALLBACKS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
%% @doc Builds the supervisor and child-spec.
init([]) ->
ChildSpec = [
% Server handling metrics.
worker_spec_(estatsd_server),
UDP listener parsing packets and sending them to estatsd_server .
worker_spec_(estatsd_udp)
],
RestartStrategy = one_for_one,
If more than MaxRestarts number of restarts occur in the last
% RestartTimeframe seconds, then the supervisor terminates all the child
% processes and then itself.
MaxRestarts = 10000,
RestartTimeframe = 10,
% Final spec.
{ok, {{RestartStrategy, MaxRestarts, RestartTimeframe}, ChildSpec}}.
% ====================== /\ SUPERVISOR CALLBACKS ===============================
= = = = = = = = = = = = = = = = = = = = = = \/ HELPER FUNCTIONS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
%% @doc Builds a worker spec for the supervisor.
worker_spec_(Module) ->
Id = Module,
StartFunc = {Module, start_link, []},
RestartType = permanent,
ShutdownTimeout = 5000,
ChildType = worker,
Modules = [Module],
{Id, StartFunc, RestartType, ShutdownTimeout, ChildType, Modules}.
% ====================== /\ HELPER FUNCTIONS ===================================
| null | https://raw.githubusercontent.com/tsloughter/erlangdc2013/d08198526f903cf081f81cacef1cc82ee9e8575b/apps/estatsd/src/estatsd_sup.erl | erlang | @doc The EStatsD main supervisor module.
Client API.
@doc Starts EStatsD's main supervisor.
Registers a process named `estatsd_sup`.
====================== /\ CLIENT API =========================================
@doc Builds the supervisor and child-spec.
Server handling metrics.
RestartTimeframe seconds, then the supervisor terminates all the child
processes and then itself.
Final spec.
====================== /\ SUPERVISOR CALLBACKS ===============================
@doc Builds a worker spec for the supervisor.
====================== /\ HELPER FUNCTIONS =================================== | @author < >
2011
-module (estatsd_sup).
This is an OPT supervisor .
-behaviour (supervisor).
-export ([
start_link/0
]).
OTP supervisor callbacks .
-export ([
init/1
]).
= = = = = = = = = = = = = = = = = = = = = = \/ CLIENT API = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
start_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).
= = = = = = = = = = = = = = = = = = = = = = \/ SUPERVISOR CALLBACKS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
init([]) ->
ChildSpec = [
worker_spec_(estatsd_server),
UDP listener parsing packets and sending them to estatsd_server .
worker_spec_(estatsd_udp)
],
RestartStrategy = one_for_one,
If more than MaxRestarts number of restarts occur in the last
MaxRestarts = 10000,
RestartTimeframe = 10,
{ok, {{RestartStrategy, MaxRestarts, RestartTimeframe}, ChildSpec}}.
= = = = = = = = = = = = = = = = = = = = = = \/ HELPER FUNCTIONS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
worker_spec_(Module) ->
Id = Module,
StartFunc = {Module, start_link, []},
RestartType = permanent,
ShutdownTimeout = 5000,
ChildType = worker,
Modules = [Module],
{Id, StartFunc, RestartType, ShutdownTimeout, ChildType, Modules}.
|
a6c90aac0bb2595ef1c47d3e94a26edf9ba15a8dbc068a816ddaff2c72fb328f | TheLortex/mirage-monorepo | driver.ml |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
(* Stub generation driver for the callback lifetime tests. *)
let () = Tests_common.run Sys.argv (module Functions.Stubs)
| null | https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/ocaml-ctypes/tests/test-callback_lifetime/stub-generator/driver.ml | ocaml | Stub generation driver for the callback lifetime tests. |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
let () = Tests_common.run Sys.argv (module Functions.Stubs)
|
18f17ecd0958aeea0e3de045bf7588c43cae5bb65d339922b83b945786fa57c7 | robert-strandh/SICL | rewrite.lisp | (cl:in-package #:cleavir-path-replication)
;;; This rewrite rule is used as a preparation for moving INSTRUCTION
;;; past its predecessors, because in order to do that, INSTRUCTION
;;; must have a single predecessor. This function replicates
;;; INSTRUCTION for each predecessor P. It does that by creating a
;;; replica RP of INSTRUCTION, then it replaces INSTRUCTION with RP in
;;; the successors of P. Finally, it replaces INSTRUCTION by all the
;;; RPs in each successor of INSTRUCTION.
;;;
;;; We return a list of the copies that were created.
;;;
;;; Notice that we do NOT update the defining and using instructions
;;; of the inputs and outputs of INSTRUCTION. After this rewrite has
;;; been accomplished, this information must be updated explicitly if
;;; required.
(defun replicate-instruction (instruction)
(let ((copies
(loop for predecessor in (cleavir-ir:predecessors instruction)
for successors = (cleavir-ir:successors predecessor)
for copy = (make-instance (class-of instruction)
:policy (cleavir-ir:policy instruction)
:predecessors (list predecessor)
:successors (cleavir-ir:successors instruction)
:inputs (cleavir-ir:inputs instruction)
:outputs (cleavir-ir:outputs instruction))
do (nsubstitute copy instruction successors)
collect copy)))
(loop for successor in (cleavir-ir:successors instruction)
for predecessors = (cleavir-ir:predecessors successor)
do (setf (cleavir-ir:predecessors successor)
(loop for predecessor in predecessors
if (eq predecessor instruction)
append copies
else
collect predecessor)))
copies))
;;; This rewrite rule moves INSTRUCTION so that it precedes its
;;; current predecessor. INSTRUCTION must have a single predecessor.
;;; It accomplishes the rewrite rule by replicating its current
;;; predecessor between itself and each of its current successors.
(defun move-instruction (instruction)
(assert (= (length (cleavir-ir:predecessors instruction)) 1))
(loop with predecessor = (first (cleavir-ir:predecessors instruction))
for successors = (cleavir-ir:successors predecessor)
for remaining on (cleavir-ir:successors instruction)
for successor = (first remaining)
for copy = (make-instance (class-of predecessor)
:predecessors (list instruction)
:successors (substitute successor instruction successors)
:inputs (cleavir-ir:inputs predecessor)
:outputs (cleavir-ir:outputs predecessor))
do (assert (null (intersection (cleavir-ir:outputs predecessor)
(cleavir-ir:inputs instruction)
:test #'eq)))
(setf (first remaining) copy)
(nsubstitute copy instruction (cleavir-ir:predecessors successor))
(loop for pred in (cleavir-ir:predecessors predecessor)
do (nsubstitute instruction predecessor
(cleavir-ir:successors pred)))))
;;; This rewrite rule shortcuts every non-black predecessor P of
INSTRUCTION , so that instead of having as its
;;; successor it has either the red or the blue successor of
;;; INSTRUCTION as its new successor.
(defun shortcut-predecessors (instruction red-instructions blue-instructions)
(let* ((predecessors (cleavir-ir:predecessors instruction))
(successors (cleavir-ir:successors instruction))
(red-successor (first successors))
(blue-successor (second successors))
(red-predecessors (loop for predecessor in predecessors
when (gethash predecessor red-instructions)
collect predecessor))
(blue-predecessors (loop for predecessor in predecessors
when (gethash predecessor blue-instructions)
collect predecessor)))
;; Shortcut red predecessors to go to the red successor.
(loop for predecessor in red-predecessors
do (nsubstitute red-successor instruction
(cleavir-ir:successors predecessor))
(pushnew predecessor (cleavir-ir:predecessors red-successor)
:test #'eq))
;; Shortcut blue predecessors to go to the blue successor.
(loop for predecessor in blue-predecessors
do (nsubstitute blue-successor instruction
(cleavir-ir:successors predecessor))
(pushnew predecessor (cleavir-ir:predecessors blue-successor)
:test #'eq))
;; Keep only the black predecessors of INSTRUCTION.
(setf (cleavir-ir:predecessors instruction)
(loop for predecessor in predecessors
unless (or (gethash predecessor red-instructions)
(gethash predecessor blue-instructions))
collect predecessor))))
| null | https://raw.githubusercontent.com/robert-strandh/SICL/98dc580e961292ee0a6ad175c4b6ef30ec6ba3a7/Code/Cleavir/Path-replication/rewrite.lisp | lisp | This rewrite rule is used as a preparation for moving INSTRUCTION
past its predecessors, because in order to do that, INSTRUCTION
must have a single predecessor. This function replicates
INSTRUCTION for each predecessor P. It does that by creating a
replica RP of INSTRUCTION, then it replaces INSTRUCTION with RP in
the successors of P. Finally, it replaces INSTRUCTION by all the
RPs in each successor of INSTRUCTION.
We return a list of the copies that were created.
Notice that we do NOT update the defining and using instructions
of the inputs and outputs of INSTRUCTION. After this rewrite has
been accomplished, this information must be updated explicitly if
required.
This rewrite rule moves INSTRUCTION so that it precedes its
current predecessor. INSTRUCTION must have a single predecessor.
It accomplishes the rewrite rule by replicating its current
predecessor between itself and each of its current successors.
This rewrite rule shortcuts every non-black predecessor P of
successor it has either the red or the blue successor of
INSTRUCTION as its new successor.
Shortcut red predecessors to go to the red successor.
Shortcut blue predecessors to go to the blue successor.
Keep only the black predecessors of INSTRUCTION. | (cl:in-package #:cleavir-path-replication)
(defun replicate-instruction (instruction)
(let ((copies
(loop for predecessor in (cleavir-ir:predecessors instruction)
for successors = (cleavir-ir:successors predecessor)
for copy = (make-instance (class-of instruction)
:policy (cleavir-ir:policy instruction)
:predecessors (list predecessor)
:successors (cleavir-ir:successors instruction)
:inputs (cleavir-ir:inputs instruction)
:outputs (cleavir-ir:outputs instruction))
do (nsubstitute copy instruction successors)
collect copy)))
(loop for successor in (cleavir-ir:successors instruction)
for predecessors = (cleavir-ir:predecessors successor)
do (setf (cleavir-ir:predecessors successor)
(loop for predecessor in predecessors
if (eq predecessor instruction)
append copies
else
collect predecessor)))
copies))
(defun move-instruction (instruction)
(assert (= (length (cleavir-ir:predecessors instruction)) 1))
(loop with predecessor = (first (cleavir-ir:predecessors instruction))
for successors = (cleavir-ir:successors predecessor)
for remaining on (cleavir-ir:successors instruction)
for successor = (first remaining)
for copy = (make-instance (class-of predecessor)
:predecessors (list instruction)
:successors (substitute successor instruction successors)
:inputs (cleavir-ir:inputs predecessor)
:outputs (cleavir-ir:outputs predecessor))
do (assert (null (intersection (cleavir-ir:outputs predecessor)
(cleavir-ir:inputs instruction)
:test #'eq)))
(setf (first remaining) copy)
(nsubstitute copy instruction (cleavir-ir:predecessors successor))
(loop for pred in (cleavir-ir:predecessors predecessor)
do (nsubstitute instruction predecessor
(cleavir-ir:successors pred)))))
INSTRUCTION , so that instead of having as its
(defun shortcut-predecessors (instruction red-instructions blue-instructions)
(let* ((predecessors (cleavir-ir:predecessors instruction))
(successors (cleavir-ir:successors instruction))
(red-successor (first successors))
(blue-successor (second successors))
(red-predecessors (loop for predecessor in predecessors
when (gethash predecessor red-instructions)
collect predecessor))
(blue-predecessors (loop for predecessor in predecessors
when (gethash predecessor blue-instructions)
collect predecessor)))
(loop for predecessor in red-predecessors
do (nsubstitute red-successor instruction
(cleavir-ir:successors predecessor))
(pushnew predecessor (cleavir-ir:predecessors red-successor)
:test #'eq))
(loop for predecessor in blue-predecessors
do (nsubstitute blue-successor instruction
(cleavir-ir:successors predecessor))
(pushnew predecessor (cleavir-ir:predecessors blue-successor)
:test #'eq))
(setf (cleavir-ir:predecessors instruction)
(loop for predecessor in predecessors
unless (or (gethash predecessor red-instructions)
(gethash predecessor blue-instructions))
collect predecessor))))
|
34e113aa1d3c627666c3f60226a607d2c919f9c8e50ae54b2c00768125b73c8a | composewell/streamly | Zip.hs | # LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - deprecations #
-- |
Module : Streamly . Internal . Data . Stream . Zip
Copyright : ( c ) 2017 Composewell Technologies
--
-- License : BSD3
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
-- To run examples in this module:
--
> > > import qualified Streamly . Prelude as Stream
--
module Streamly.Internal.Data.Stream.Zip
(
ZipSerialM (..)
, ZipSerial
, consMZip
, zipWithK
, zipWithMK
-- * Deprecated
, ZipStream
)
where
import Control.Applicative (liftA2)
import Control.DeepSeq (NFData(..))
#if MIN_VERSION_deepseq(1,4,3)
import Control.DeepSeq (NFData1(..))
#endif
import Data.Foldable (Foldable(foldl'), fold)
import Data.Functor.Identity (Identity(..), runIdentity)
import Data.Maybe (fromMaybe)
import Data.Semigroup (Endo(..))
#if __GLASGOW_HASKELL__ < 808
import Data.Semigroup (Semigroup(..))
#endif
import GHC.Exts (IsList(..), IsString(..), oneShot)
import Text.Read
( Lexeme(Ident), lexP, parens, prec, readPrec, readListPrec
, readListPrecDefault)
import Streamly.Internal.BaseCompat ((#.))
import Streamly.Internal.Data.Maybe.Strict (Maybe'(..), toMaybe)
import Streamly.Internal.Data.Stream.Serial (SerialT(..))
import Streamly.Internal.Data.Stream.StreamK.Type (Stream)
import qualified Streamly.Internal.Data.Stream.Common as P
import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
import qualified Streamly.Internal.Data.Stream.StreamD as D
import qualified Streamly.Internal.Data.Stream.Serial as Serial
import Prelude hiding (map, repeat, zipWith)
#include "Instances.hs"
-- $setup
> > > import qualified Streamly . Prelude as Stream
-- >>> import Control.Concurrent (threadDelay)
-- >>> :{
-- delay n = do
threadDelay ( n * 1000000 ) -- sleep for n seconds
putStrLn ( show n + + " sec " ) -- print " n sec "
-- return n -- IO Int
-- :}
# INLINE zipWithMK #
zipWithMK :: Monad m =>
(a -> b -> m c) -> Stream m a -> Stream m b -> Stream m c
zipWithMK f m1 m2 =
D.toStreamK $ D.zipWithM f (D.fromStreamK m1) (D.fromStreamK m2)
# INLINE zipWithK #
zipWithK :: Monad m
=> (a -> b -> c) -> Stream m a -> Stream m b -> Stream m c
zipWithK f = zipWithMK (\a b -> return (f a b))
------------------------------------------------------------------------------
-- Serially Zipping Streams
------------------------------------------------------------------------------
-- | For 'ZipSerialM' streams:
--
-- @
-- (<>) = 'Streamly.Prelude.serial'
( < * > ) = ' Streamly . Prelude.serial.zipWith ' i d
-- @
--
-- Applicative evaluates the streams being zipped serially:
--
> > > s1 = Stream.fromFoldable [ 1 , 2 ]
> > > s2 = Stream.fromFoldable [ 3 , 4 ]
> > > s3 = Stream.fromFoldable [ 5 , 6 ]
> > > Stream.toList $ Stream.fromZipSerial $ ( , , ) < $ > s1 < * > s2 < * > s3
[ ( 1,3,5),(2,4,6 ) ]
--
-- /Since: 0.2.0 ("Streamly")/
--
@since 0.8.0
newtype ZipSerialM m a = ZipSerialM {getZipSerialM :: Stream m a}
deriving (Semigroup, Monoid)
-- |
@since 0.1.0
{-# DEPRECATED ZipStream "Please use 'ZipSerialM' instead." #-}
type ZipStream = ZipSerialM
-- | An IO stream whose applicative instance zips streams serially.
--
-- /Since: 0.2.0 ("Streamly")/
--
@since 0.8.0
type ZipSerial = ZipSerialM IO
consMZip :: Monad m => m a -> ZipSerialM m a -> ZipSerialM m a
consMZip m (ZipSerialM r) = ZipSerialM $ K.consM m r
LIST_INSTANCES(ZipSerialM)
NFDATA1_INSTANCE(ZipSerialM)
instance Monad m => Functor (ZipSerialM m) where
# INLINE fmap #
fmap f (ZipSerialM m) = ZipSerialM $ getSerialT $ fmap f (SerialT m)
instance Monad m => Applicative (ZipSerialM m) where
pure = ZipSerialM . getSerialT . Serial.repeat
{-# INLINE (<*>) #-}
ZipSerialM m1 <*> ZipSerialM m2 = ZipSerialM $ zipWithK id m1 m2
FOLDABLE_INSTANCE(ZipSerialM)
TRAVERSABLE_INSTANCE(ZipSerialM)
| null | https://raw.githubusercontent.com/composewell/streamly/8629a0e806f5eea87d23650c540aa04176f25c43/src/Streamly/Internal/Data/Stream/Zip.hs | haskell | |
License : BSD3
Maintainer :
Stability : experimental
To run examples in this module:
* Deprecated
$setup
>>> import Control.Concurrent (threadDelay)
>>> :{
delay n = do
sleep for n seconds
print " n sec "
return n -- IO Int
:}
----------------------------------------------------------------------------
Serially Zipping Streams
----------------------------------------------------------------------------
| For 'ZipSerialM' streams:
@
(<>) = 'Streamly.Prelude.serial'
@
Applicative evaluates the streams being zipped serially:
/Since: 0.2.0 ("Streamly")/
|
# DEPRECATED ZipStream "Please use 'ZipSerialM' instead." #
| An IO stream whose applicative instance zips streams serially.
/Since: 0.2.0 ("Streamly")/
# INLINE (<*>) # | # LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - deprecations #
Module : Streamly . Internal . Data . Stream . Zip
Copyright : ( c ) 2017 Composewell Technologies
Portability : GHC
> > > import qualified Streamly . Prelude as Stream
module Streamly.Internal.Data.Stream.Zip
(
ZipSerialM (..)
, ZipSerial
, consMZip
, zipWithK
, zipWithMK
, ZipStream
)
where
import Control.Applicative (liftA2)
import Control.DeepSeq (NFData(..))
#if MIN_VERSION_deepseq(1,4,3)
import Control.DeepSeq (NFData1(..))
#endif
import Data.Foldable (Foldable(foldl'), fold)
import Data.Functor.Identity (Identity(..), runIdentity)
import Data.Maybe (fromMaybe)
import Data.Semigroup (Endo(..))
#if __GLASGOW_HASKELL__ < 808
import Data.Semigroup (Semigroup(..))
#endif
import GHC.Exts (IsList(..), IsString(..), oneShot)
import Text.Read
( Lexeme(Ident), lexP, parens, prec, readPrec, readListPrec
, readListPrecDefault)
import Streamly.Internal.BaseCompat ((#.))
import Streamly.Internal.Data.Maybe.Strict (Maybe'(..), toMaybe)
import Streamly.Internal.Data.Stream.Serial (SerialT(..))
import Streamly.Internal.Data.Stream.StreamK.Type (Stream)
import qualified Streamly.Internal.Data.Stream.Common as P
import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
import qualified Streamly.Internal.Data.Stream.StreamD as D
import qualified Streamly.Internal.Data.Stream.Serial as Serial
import Prelude hiding (map, repeat, zipWith)
#include "Instances.hs"
> > > import qualified Streamly . Prelude as Stream
# INLINE zipWithMK #
zipWithMK :: Monad m =>
(a -> b -> m c) -> Stream m a -> Stream m b -> Stream m c
zipWithMK f m1 m2 =
D.toStreamK $ D.zipWithM f (D.fromStreamK m1) (D.fromStreamK m2)
# INLINE zipWithK #
zipWithK :: Monad m
=> (a -> b -> c) -> Stream m a -> Stream m b -> Stream m c
zipWithK f = zipWithMK (\a b -> return (f a b))
( < * > ) = ' Streamly . Prelude.serial.zipWith ' i d
> > > s1 = Stream.fromFoldable [ 1 , 2 ]
> > > s2 = Stream.fromFoldable [ 3 , 4 ]
> > > s3 = Stream.fromFoldable [ 5 , 6 ]
> > > Stream.toList $ Stream.fromZipSerial $ ( , , ) < $ > s1 < * > s2 < * > s3
[ ( 1,3,5),(2,4,6 ) ]
@since 0.8.0
newtype ZipSerialM m a = ZipSerialM {getZipSerialM :: Stream m a}
deriving (Semigroup, Monoid)
@since 0.1.0
type ZipStream = ZipSerialM
@since 0.8.0
type ZipSerial = ZipSerialM IO
consMZip :: Monad m => m a -> ZipSerialM m a -> ZipSerialM m a
consMZip m (ZipSerialM r) = ZipSerialM $ K.consM m r
LIST_INSTANCES(ZipSerialM)
NFDATA1_INSTANCE(ZipSerialM)
instance Monad m => Functor (ZipSerialM m) where
# INLINE fmap #
fmap f (ZipSerialM m) = ZipSerialM $ getSerialT $ fmap f (SerialT m)
instance Monad m => Applicative (ZipSerialM m) where
pure = ZipSerialM . getSerialT . Serial.repeat
ZipSerialM m1 <*> ZipSerialM m2 = ZipSerialM $ zipWithK id m1 m2
FOLDABLE_INSTANCE(ZipSerialM)
TRAVERSABLE_INSTANCE(ZipSerialM)
|
3c2adb34415ea9a462afa5994c8726400ae7796688bd78ced8bd50a32eae9327 | janestreet/universe | sexp_of.ml | module type S = sig
type t [@@deriving sexp_of]
end
module type S1 = sig
type 'a t [@@deriving sexp_of]
end
module type S2 = sig
type ('a, 'b) t [@@deriving sexp_of]
end
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/incremental/src/sexp_of.ml | ocaml | module type S = sig
type t [@@deriving sexp_of]
end
module type S1 = sig
type 'a t [@@deriving sexp_of]
end
module type S2 = sig
type ('a, 'b) t [@@deriving sexp_of]
end
| |
e1108e9d99d7140cfc2dbedaf97d593b6e4f83806ae7b69ea0c5e9253245a540 | GaloisInc/saw-script | CacheTests.hs |
Copyright : Galois , Inc. 2019
License : :
Stability : experimental
Portability : portable
Copyright : Galois, Inc. 2019
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Tests.CacheTests
( cacheTests
)
where
import Control.Monad
import Control.Monad.ST
import Data.Ref ( C )
import Test.Tasty
import Test.Tasty.HUnit
import Verifier.SAW.Cache
cacheTests :: [TestTree]
cacheTests =
[ cacheMapTestIO
, cacheMapTestST
, intMapTestIO
, intMapTestST
]
-- | Tests that a normal cache map can be used that will memoize
values in the IO monad .
cacheMapTestIO :: TestTree
cacheMapTestIO =
testGroup "normal map IO tests"
[
testCase "String->Bool small test" $
cTestA newCacheMap [ ("hello", True), ("world", False) ]
, testCase "String->String test" $
cTestA newCacheMap [ ("hello", "world"), ("world", "fair"), ("Goodbye", "!") ]
, testCase "Int->Char test" $
cTestA newCacheMap [ (9 :: Int, 'n'), (3, 't'), (-427, 'f'), (0, 'z') ]
]
cacheMapTestST :: TestTree
cacheMapTestST =
testGroup "normal map ST tests"
[
testCase "String->Bool small test" $
stToIO $ cTestA newCacheMap [ ("hello", True), ("world", False) ]
, testCase "String->String test" $
stToIO $ cTestA newCacheMap [ ("hello", "world"), ("world", "fair"), ("Goodbye", "!") ]
, testCase "Int->Char test" $
stToIO $ cTestA newCacheMap [ (9 :: Int, 'n'), (3, 't'), (-427, 'f'), (0, 'z') ]
]
-- | Tests that a normal cache map can be used that will memoize
values in the IO monad .
intMapTestIO :: TestTree
intMapTestIO =
testGroup "int map IO tests"
[
testCase "intmap Bool small test" $
cTestA newCacheIntMap [ (11, True), (0, False) ]
, testCase "intmap Int test" $
cTestA newCacheIntMap [ (1, 0 :: Int), (0, -5), (-5, 39) ]
, testCase "intmap String test" $
cTestA newCacheIntMap [ (1, "True"), (0, "not yet"), (-5, "negative"), (3248902, "big") ]
]
-- | Tests that a normal cache map can be used that will memoize
values in the IO monad .
intMapTestST :: TestTree
intMapTestST =
testGroup "int map IO tests"
[
testCase "intmap Bool small test" $
stToIO $ cTestA newCacheIntMap [ (11, True), (0, False) ]
, testCase "intmap Int test" $
stToIO $ cTestA newCacheIntMap [ (1, 0 :: Int), (0, -5), (-5, 39) ]
, testCase "intmap String test" $
stToIO $ cTestA newCacheIntMap [ (1, "True"), (0, "not yet"), (-5, "negative"), (3248902, "big") ]
]
Always pass at least 2 entries in the keyval array , keys and values should be independently unique
cTestA :: (C m, Eq k, Eq v, Show k, Show v) =>
m (Cache m k v) -> [(k,v)] -> m ()
cTestA mkCache keyvals = do
c1 <- mkCache -- will cache the keyvals
will separately cache all keys equal to the same val ( the first )
let (k0, v0) = head keyvals
let (kOmega, vOmega) = last keyvals
-- Verify a value can be added, and once it is added, it does not
-- need to be recomputed (i.e. it is memoized)
v0' <- useCache c1 k0 (return v0)
v0'' <- useCache c1 k0 (error "should not be called")
unless (v0 == v0') $ error "initial cache store failed"
unless (v0 == v0'') $ error "cached value retrieval failed"
vOmega' <- useCache c2 k0 (return vOmega)
vOmega'' <- useCache c2 k0 (return v0)
unless (vOmega == vOmega') $ error "second cache initial store failed"
unless (v0' /= vOmega') $ error "caches are not independent"
unless (vOmega == vOmega'') $ error "initial cache value is not persistent"
-- Verify all the other values can similarly be cached once, and
-- that they are distinct from the initial value.
forM_ (tail keyvals) $ \(k,v) -> do
vx <- useCache c1 k (return v)
unless (v == vx) $ error "incorrect value stored"
vy <- useCache c1 k (error "must not be called for vy")
unless (v == vy) $ error "incorrect value cached"
vo <- useCache c1 k0 (error "must not be called for vo")
when (vy == vo) $ error "value collision"
vz <- useCache c1 k (error "must not be called for vz")
unless (v == vz) $ error "correct value not still cached"
v2 <- useCache c2 k (return vOmega)
unless (vOmega == v2) $ error "incorrect stored in second cache"
if k == kOmega
then unless (v2 == vz) $ error "caches can share values"
else unless (v2 /= vz) $ error "caches are independent for all keys"
| null | https://raw.githubusercontent.com/GaloisInc/saw-script/fdb8987f09999439833d5cb573f69197bdf2cb7f/saw-core/tests/src/Tests/CacheTests.hs | haskell | | Tests that a normal cache map can be used that will memoize
| Tests that a normal cache map can be used that will memoize
| Tests that a normal cache map can be used that will memoize
will cache the keyvals
Verify a value can be added, and once it is added, it does not
need to be recomputed (i.e. it is memoized)
Verify all the other values can similarly be cached once, and
that they are distinct from the initial value. |
Copyright : Galois , Inc. 2019
License : :
Stability : experimental
Portability : portable
Copyright : Galois, Inc. 2019
License : BSD3
Maintainer :
Stability : experimental
Portability : portable
-}
module Tests.CacheTests
( cacheTests
)
where
import Control.Monad
import Control.Monad.ST
import Data.Ref ( C )
import Test.Tasty
import Test.Tasty.HUnit
import Verifier.SAW.Cache
cacheTests :: [TestTree]
cacheTests =
[ cacheMapTestIO
, cacheMapTestST
, intMapTestIO
, intMapTestST
]
values in the IO monad .
cacheMapTestIO :: TestTree
cacheMapTestIO =
testGroup "normal map IO tests"
[
testCase "String->Bool small test" $
cTestA newCacheMap [ ("hello", True), ("world", False) ]
, testCase "String->String test" $
cTestA newCacheMap [ ("hello", "world"), ("world", "fair"), ("Goodbye", "!") ]
, testCase "Int->Char test" $
cTestA newCacheMap [ (9 :: Int, 'n'), (3, 't'), (-427, 'f'), (0, 'z') ]
]
cacheMapTestST :: TestTree
cacheMapTestST =
testGroup "normal map ST tests"
[
testCase "String->Bool small test" $
stToIO $ cTestA newCacheMap [ ("hello", True), ("world", False) ]
, testCase "String->String test" $
stToIO $ cTestA newCacheMap [ ("hello", "world"), ("world", "fair"), ("Goodbye", "!") ]
, testCase "Int->Char test" $
stToIO $ cTestA newCacheMap [ (9 :: Int, 'n'), (3, 't'), (-427, 'f'), (0, 'z') ]
]
values in the IO monad .
intMapTestIO :: TestTree
intMapTestIO =
testGroup "int map IO tests"
[
testCase "intmap Bool small test" $
cTestA newCacheIntMap [ (11, True), (0, False) ]
, testCase "intmap Int test" $
cTestA newCacheIntMap [ (1, 0 :: Int), (0, -5), (-5, 39) ]
, testCase "intmap String test" $
cTestA newCacheIntMap [ (1, "True"), (0, "not yet"), (-5, "negative"), (3248902, "big") ]
]
values in the IO monad .
intMapTestST :: TestTree
intMapTestST =
testGroup "int map IO tests"
[
testCase "intmap Bool small test" $
stToIO $ cTestA newCacheIntMap [ (11, True), (0, False) ]
, testCase "intmap Int test" $
stToIO $ cTestA newCacheIntMap [ (1, 0 :: Int), (0, -5), (-5, 39) ]
, testCase "intmap String test" $
stToIO $ cTestA newCacheIntMap [ (1, "True"), (0, "not yet"), (-5, "negative"), (3248902, "big") ]
]
Always pass at least 2 entries in the keyval array , keys and values should be independently unique
cTestA :: (C m, Eq k, Eq v, Show k, Show v) =>
m (Cache m k v) -> [(k,v)] -> m ()
cTestA mkCache keyvals = do
will separately cache all keys equal to the same val ( the first )
let (k0, v0) = head keyvals
let (kOmega, vOmega) = last keyvals
v0' <- useCache c1 k0 (return v0)
v0'' <- useCache c1 k0 (error "should not be called")
unless (v0 == v0') $ error "initial cache store failed"
unless (v0 == v0'') $ error "cached value retrieval failed"
vOmega' <- useCache c2 k0 (return vOmega)
vOmega'' <- useCache c2 k0 (return v0)
unless (vOmega == vOmega') $ error "second cache initial store failed"
unless (v0' /= vOmega') $ error "caches are not independent"
unless (vOmega == vOmega'') $ error "initial cache value is not persistent"
forM_ (tail keyvals) $ \(k,v) -> do
vx <- useCache c1 k (return v)
unless (v == vx) $ error "incorrect value stored"
vy <- useCache c1 k (error "must not be called for vy")
unless (v == vy) $ error "incorrect value cached"
vo <- useCache c1 k0 (error "must not be called for vo")
when (vy == vo) $ error "value collision"
vz <- useCache c1 k (error "must not be called for vz")
unless (v == vz) $ error "correct value not still cached"
v2 <- useCache c2 k (return vOmega)
unless (vOmega == v2) $ error "incorrect stored in second cache"
if k == kOmega
then unless (v2 == vz) $ error "caches can share values"
else unless (v2 /= vz) $ error "caches are independent for all keys"
|
c87a8d692f92f9aa8e9d4d026cdb268426d44b2ce4003b185101e01a63132363 | gvannest/piscine_OCaml | gardening.ml | type 'a tree = Nil | Node of 'a * 'a tree * 'a tree
let rec size (tree:'a tree) = match tree with
| Nil -> 0
| Node (_, l, r) -> 1 + (size l) + (size r)
let height (tree:'a tree) =
let rec height_aux current_node height_acc = match current_node with
| Nil -> height_acc
| Node (v, l, r) -> begin
let height_left = height_aux l (height_acc + 1) in
let height_right = height_aux r (height_acc + 1) in
if height_left < height_right then height_right else height_left
end
in
height_aux tree 0
let draw_tree (tree:'a tree) =
let draw_square x y size =
if size > 0 then begin
Graphics.moveto (x - size/2) (y - size/2) ;
Graphics.lineto (x - size/2) (y + size/2) ;
Graphics.lineto (x + size/2) (y + size/2) ;
Graphics.lineto (x + size/2) (y - size/2) ;
Graphics.lineto (x - size/2) (y - size/2) ;
end
in
let height = height tree in
let rec draw_tree_aux current_node x y size factor = match current_node with
| Node (v, l, r) -> begin
draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5); Graphics.draw_string v ;
draw_tree_aux l (x - size * factor) (y - (size * 3)) size (factor - 1) ;
Graphics.moveto x (y - size/2) ;
Graphics.lineto (x - size * factor) (y - (size * 3- size / 2)) ;
draw_tree_aux r (x + size * factor) (y - (size * 3)) size (factor - 1);
Graphics.moveto x (y - size/2) ;
Graphics.lineto (x + size * factor) (y - (size * 3 - size / 2))
end
| Nil -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5) ; Graphics.draw_string "Nil" end
in
draw_tree_aux tree 900 1200 50 (height + 2)
let main () =
let tree = Node("Node", Node("Node", Node("Node", Nil, Node("Leaf", Nil, Nil)), Node("Node", Node("Leaf", Nil, Nil), Node("Leaf", Nil, Nil))), Node("Node", Nil, Node("Leaf", Nil, Nil))) in
let tree1 = Node("Node", Node("Node", Node("Leaf", Nil, Nil), Node("Node", Nil, Node("Leaf", Nil, Nil))), Nil) in
let tree2 = Node("Node", Node("Node", Node("Node", Node("Node", Node("Leaf", Nil, Nil),Nil),Nil), Nil), Node("Node", Node("Node", Node("Leaf", Nil, Nil), Node("Node", Node("Leaf", Nil, Nil), Nil)),Nil)) in
print_endline "********* tree **********" ;
print_string "size : " ; print_int (size tree) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree) ;
print_char '\n' ;
print_endline "********* tree1 **********" ;
print_string "size : " ; print_int (size tree1) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree1) ;
print_char '\n' ;
print_endline "********* tree2 **********" ;
print_string "size : " ; print_int (size tree2) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree2) ;
print_char '\n' ;
Graphics.open_graph " 2048x2048" ;
draw_tree tree ;
ignore(Graphics.read_key ())
let () = main ()
| null | https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d03/ex01/gardening.ml | ocaml | type 'a tree = Nil | Node of 'a * 'a tree * 'a tree
let rec size (tree:'a tree) = match tree with
| Nil -> 0
| Node (_, l, r) -> 1 + (size l) + (size r)
let height (tree:'a tree) =
let rec height_aux current_node height_acc = match current_node with
| Nil -> height_acc
| Node (v, l, r) -> begin
let height_left = height_aux l (height_acc + 1) in
let height_right = height_aux r (height_acc + 1) in
if height_left < height_right then height_right else height_left
end
in
height_aux tree 0
let draw_tree (tree:'a tree) =
let draw_square x y size =
if size > 0 then begin
Graphics.moveto (x - size/2) (y - size/2) ;
Graphics.lineto (x - size/2) (y + size/2) ;
Graphics.lineto (x + size/2) (y + size/2) ;
Graphics.lineto (x + size/2) (y - size/2) ;
Graphics.lineto (x - size/2) (y - size/2) ;
end
in
let height = height tree in
let rec draw_tree_aux current_node x y size factor = match current_node with
| Node (v, l, r) -> begin
draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5); Graphics.draw_string v ;
draw_tree_aux l (x - size * factor) (y - (size * 3)) size (factor - 1) ;
Graphics.moveto x (y - size/2) ;
Graphics.lineto (x - size * factor) (y - (size * 3- size / 2)) ;
draw_tree_aux r (x + size * factor) (y - (size * 3)) size (factor - 1);
Graphics.moveto x (y - size/2) ;
Graphics.lineto (x + size * factor) (y - (size * 3 - size / 2))
end
| Nil -> begin draw_square x y size ; Graphics.moveto (x - size/5) (y - size/5) ; Graphics.draw_string "Nil" end
in
draw_tree_aux tree 900 1200 50 (height + 2)
let main () =
let tree = Node("Node", Node("Node", Node("Node", Nil, Node("Leaf", Nil, Nil)), Node("Node", Node("Leaf", Nil, Nil), Node("Leaf", Nil, Nil))), Node("Node", Nil, Node("Leaf", Nil, Nil))) in
let tree1 = Node("Node", Node("Node", Node("Leaf", Nil, Nil), Node("Node", Nil, Node("Leaf", Nil, Nil))), Nil) in
let tree2 = Node("Node", Node("Node", Node("Node", Node("Node", Node("Leaf", Nil, Nil),Nil),Nil), Nil), Node("Node", Node("Node", Node("Leaf", Nil, Nil), Node("Node", Node("Leaf", Nil, Nil), Nil)),Nil)) in
print_endline "********* tree **********" ;
print_string "size : " ; print_int (size tree) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree) ;
print_char '\n' ;
print_endline "********* tree1 **********" ;
print_string "size : " ; print_int (size tree1) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree1) ;
print_char '\n' ;
print_endline "********* tree2 **********" ;
print_string "size : " ; print_int (size tree2) ;
print_char '\n' ;
print_string "height : " ; print_int (height tree2) ;
print_char '\n' ;
Graphics.open_graph " 2048x2048" ;
draw_tree tree ;
ignore(Graphics.read_key ())
let () = main ()
| |
ec10bd9acd1420da35eb430782bf3a6441efdcca377605ab84f76926e7c121ea | roryk/bcbio.rnaseq | simulate.clj | (ns bcbio.rnaseq.simulate
(:require [bcbio.rnaseq.compare :refer [compare-callers]]
[bcbio.rnaseq.simulator :as sim]
[bcbio.rnaseq.templates :as templates]
[bcbio.rnaseq.util :refer :all]
[clojure.java.shell :refer [sh]]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]
[clostache.parser :as stache]
[me.raynes.fs :as fs]))
(def compare-template "comparisons/compare-simulated.template")
(defn get-analysis-template [out-dir count-file sample-size]
{:de-out-dir out-dir
:count-file count-file
:comparison ["group1" "group2"]
:conditions (concat (repeat sample-size "group1") (repeat sample-size "group2"))
:condition-name "group1_vs_group2"
:project "simulated"})
(defn run-one-template [analysis-template template]
(let [analysis-config (templates/add-out-files-to-config template analysis-template)]
(templates/run-template template analysis-config)))
(defn compare-simulated-results [sim-dir in-files]
(let [out-file (swap-directory "concordant.pdf" sim-dir)
score-file (str (fs/file sim-dir "sim.scores"))
rfile (str (fs/file sim-dir "compare-simulated.R"))
template-config {:out-file (escape-quote out-file)
:score-file (escape-quote score-file)
:in-files (seq-to-rlist in-files)
:project (escape-quote "simulated")}]
(spit rfile (stache/render-resource compare-template template-config))
(apply sh ["Rscript" "--verbose" rfile])
out-file))
(defn run-simulation [out-dir num-genes sample-size library-size input-file]
(safe-makedir out-dir)
(let [count-file (sim/simulate out-dir num-genes sample-size library-size input-file)
analysis-template (get-analysis-template out-dir count-file sample-size)
out-files (map :out-file (map #(templates/run-template %1 analysis-template)
templates/templates))]
(compare-callers out-files)
(compare-simulated-results out-dir out-files)))
(def options
[["-h" "--help"]
["-d" "--out-dir OUT_DIR" "Output directory"
:default "simulate"]
["-c" "--count-file COUNT_FILE" "Optional count file for abudance distribution"
:default nil]
["-s" "--sample-size SAMPLE_SIZE" "Sample size of each group"
:default 3
:parse-fn #(Integer/parseInt %)]
["-n" "--num-genes NUM_GENES" "Number of genes to simulate."
:default 10000
:parse-fn #(Integer/parseInt %)]
["-l" "--library-size SIZE" "Library size in millions of reads"
:default 20
:parse-fn #(Float/parseFloat %)]])
(defn exit [status msg]
(println msg)
(System/exit status))
(defn usage [options-summary]
(->> [
""
"Usage: bcbio-rnaseq simulate [options]"
""
"Options:"
options-summary]
(string/join \newline)))
(defn simulate-cli [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args options)]
(cond
(:help options) (exit 0 (usage summary)))
(run-simulation (:out-dir options)
(:num-genes options)
(:sample-size options)
(:library-size options)
(:count-file options))))
| null | https://raw.githubusercontent.com/roryk/bcbio.rnaseq/66c629eb737c9a0096082d6683657bf9d89eb271/src/bcbio/rnaseq/simulate.clj | clojure | (ns bcbio.rnaseq.simulate
(:require [bcbio.rnaseq.compare :refer [compare-callers]]
[bcbio.rnaseq.simulator :as sim]
[bcbio.rnaseq.templates :as templates]
[bcbio.rnaseq.util :refer :all]
[clojure.java.shell :refer [sh]]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]
[clostache.parser :as stache]
[me.raynes.fs :as fs]))
(def compare-template "comparisons/compare-simulated.template")
(defn get-analysis-template [out-dir count-file sample-size]
{:de-out-dir out-dir
:count-file count-file
:comparison ["group1" "group2"]
:conditions (concat (repeat sample-size "group1") (repeat sample-size "group2"))
:condition-name "group1_vs_group2"
:project "simulated"})
(defn run-one-template [analysis-template template]
(let [analysis-config (templates/add-out-files-to-config template analysis-template)]
(templates/run-template template analysis-config)))
(defn compare-simulated-results [sim-dir in-files]
(let [out-file (swap-directory "concordant.pdf" sim-dir)
score-file (str (fs/file sim-dir "sim.scores"))
rfile (str (fs/file sim-dir "compare-simulated.R"))
template-config {:out-file (escape-quote out-file)
:score-file (escape-quote score-file)
:in-files (seq-to-rlist in-files)
:project (escape-quote "simulated")}]
(spit rfile (stache/render-resource compare-template template-config))
(apply sh ["Rscript" "--verbose" rfile])
out-file))
(defn run-simulation [out-dir num-genes sample-size library-size input-file]
(safe-makedir out-dir)
(let [count-file (sim/simulate out-dir num-genes sample-size library-size input-file)
analysis-template (get-analysis-template out-dir count-file sample-size)
out-files (map :out-file (map #(templates/run-template %1 analysis-template)
templates/templates))]
(compare-callers out-files)
(compare-simulated-results out-dir out-files)))
(def options
[["-h" "--help"]
["-d" "--out-dir OUT_DIR" "Output directory"
:default "simulate"]
["-c" "--count-file COUNT_FILE" "Optional count file for abudance distribution"
:default nil]
["-s" "--sample-size SAMPLE_SIZE" "Sample size of each group"
:default 3
:parse-fn #(Integer/parseInt %)]
["-n" "--num-genes NUM_GENES" "Number of genes to simulate."
:default 10000
:parse-fn #(Integer/parseInt %)]
["-l" "--library-size SIZE" "Library size in millions of reads"
:default 20
:parse-fn #(Float/parseFloat %)]])
(defn exit [status msg]
(println msg)
(System/exit status))
(defn usage [options-summary]
(->> [
""
"Usage: bcbio-rnaseq simulate [options]"
""
"Options:"
options-summary]
(string/join \newline)))
(defn simulate-cli [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args options)]
(cond
(:help options) (exit 0 (usage summary)))
(run-simulation (:out-dir options)
(:num-genes options)
(:sample-size options)
(:library-size options)
(:count-file options))))
| |
ddb49a054d21650728d520378c28258a519c22d8b2ed7810360f6fd635b63914 | aws-beam/aws-erlang | aws_cloudhsm.erl | %% WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
See -beam/aws-codegen for more details .
%% @doc AWS CloudHSM Service
%%
This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
-module(aws_cloudhsm).
-export([add_tags_to_resource/2,
add_tags_to_resource/3,
create_hapg/2,
create_hapg/3,
create_hsm/2,
create_hsm/3,
create_luna_client/2,
create_luna_client/3,
delete_hapg/2,
delete_hapg/3,
delete_hsm/2,
delete_hsm/3,
delete_luna_client/2,
delete_luna_client/3,
describe_hapg/2,
describe_hapg/3,
describe_hsm/2,
describe_hsm/3,
describe_luna_client/2,
describe_luna_client/3,
get_config/2,
get_config/3,
list_available_zones/2,
list_available_zones/3,
list_hapgs/2,
list_hapgs/3,
list_hsms/2,
list_hsms/3,
list_luna_clients/2,
list_luna_clients/3,
list_tags_for_resource/2,
list_tags_for_resource/3,
modify_hapg/2,
modify_hapg/3,
modify_hsm/2,
modify_hsm/3,
modify_luna_client/2,
modify_luna_client/3,
remove_tags_from_resource/2,
remove_tags_from_resource/3]).
-include_lib("hackney/include/hackney_lib.hrl").
%%====================================================================
%% API
%%====================================================================
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Adds or overwrites one or more tags for the specified AWS CloudHSM
%% resource.
%%
%% Each tag consists of a key and a value. Tag keys must be unique to each
%% resource.
add_tags_to_resource(Client, Input)
when is_map(Client), is_map(Input) ->
add_tags_to_resource(Client, Input, []).
add_tags_to_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"AddTagsToResource">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Creates a high-availability partition group. A high-availability partition
%% group is a group of partitions that spans multiple physical HSMs.
create_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
create_hapg(Client, Input, []).
create_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Creates an uninitialized HSM instance .
%%
There is an upfront fee charged for each HSM instance that you create with
the ` CreateHsm ' operation . If you accidentally provision an HSM and
%% want to request a refund, delete the instance using the `DeleteHsm'
operation , go to the AWS Support Center , create a new case , and select
%% Account and Billing Support.
%%
It can take up to 20 minutes to create and provision an HSM . You can
monitor the status of the HSM with the ` DescribeHsm ' operation . The
HSM is ready to be initialized when the status changes to ` RUNNING ' .
create_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
create_hsm(Client, Input, []).
create_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Creates an HSM client .
create_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
create_luna_client(Client, Input, []).
create_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Deletes a high-availability partition group.
delete_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
delete_hapg(Client, Input, []).
delete_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Deletes an HSM . After completion , this operation can not be undone and your
%% key material cannot be recovered.
delete_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
delete_hsm(Client, Input, []).
delete_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Deletes a client.
delete_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
delete_luna_client(Client, Input, []).
delete_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Retrieves information about a high-availability partition group.
describe_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
describe_hapg(Client, Input, []).
describe_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Retrieves information about an HSM . You can identify the HSM by its ARN or
%% its serial number.
describe_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
describe_hsm(Client, Input, []).
describe_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Retrieves information about an HSM client .
describe_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
describe_luna_client(Client, Input, []).
describe_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Gets the configuration files necessary to connect to all high availability
%% partition groups the client is associated with.
get_config(Client, Input)
when is_map(Client), is_map(Input) ->
get_config(Client, Input, []).
get_config(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"GetConfig">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Lists the Availability Zones that have available AWS CloudHSM capacity.
list_available_zones(Client, Input)
when is_map(Client), is_map(Input) ->
list_available_zones(Client, Input, []).
list_available_zones(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListAvailableZones">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Lists the high-availability partition groups for the account.
%%
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
%% response contains a token that you pass in the next call to
` ListHapgs ' to retrieve the next set of items .
list_hapgs(Client, Input)
when is_map(Client), is_map(Input) ->
list_hapgs(Client, Input, []).
list_hapgs(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListHapgs">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Retrieves the identifiers of all of the HSMs provisioned for the current
%% customer.
%%
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
response contains a token that you pass in the next call to ` ListHsms '
%% to retrieve the next set of items.
list_hsms(Client, Input)
when is_map(Client), is_map(Input) ->
list_hsms(Client, Input, []).
list_hsms(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListHsms">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Lists all of the clients.
%%
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
%% response contains a token that you pass in the next call to
%% `ListLunaClients' to retrieve the next set of items.
list_luna_clients(Client, Input)
when is_map(Client), is_map(Input) ->
list_luna_clients(Client, Input, []).
list_luna_clients(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListLunaClients">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Returns a list of all tags for the specified AWS CloudHSM resource.
list_tags_for_resource(Client, Input)
when is_map(Client), is_map(Input) ->
list_tags_for_resource(Client, Input, []).
list_tags_for_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListTagsForResource">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Modifies an existing high-availability partition group.
modify_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
modify_hapg(Client, Input, []).
modify_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Modifies an HSM .
%%
This operation can result in the HSM being offline for up to 15 minutes
%% while the AWS CloudHSM service is reconfigured. If you are modifying a
production HSM , you should ensure that your AWS CloudHSM service is
%% configured for high availability, and consider executing this operation
%% during a maintenance window.
modify_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
modify_hsm(Client, Input, []).
modify_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
%% Modifies the certificate used by the client.
%%
%% This action can potentially start a workflow to install the new
%% certificate on the client's HSMs.
modify_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
modify_luna_client(Client, Input, []).
modify_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
%%
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
%%
%% For information about the current version of AWS CloudHSM, see AWS
%% CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
%%
Removes one or more tags from the specified AWS CloudHSM resource .
%%
%% To remove a tag, specify only the tag key to remove (not the value). To
overwrite the value for an existing tag , use ` AddTagsToResource ' .
remove_tags_from_resource(Client, Input)
when is_map(Client), is_map(Input) ->
remove_tags_from_resource(Client, Input, []).
remove_tags_from_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"RemoveTagsFromResource">>, Input, Options).
%%====================================================================
Internal functions
%%====================================================================
-spec request(aws_client:aws_client(), binary(), map(), list()) ->
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map() | undefined,
Error :: map().
request(Client, Action, Input, Options) ->
RequestFun = fun() -> do_request(Client, Action, Input, Options) end,
aws_request:request(RequestFun, Options).
do_request(Client, Action, Input0, Options) ->
Client1 = Client#{service => <<"cloudhsm">>},
Host = build_host(<<"cloudhsm">>, Client1),
URL = build_url(Host, Client1),
Headers = [
{<<"Host">>, Host},
{<<"Content-Type">>, <<"application/x-amz-json-1.1">>},
{<<"X-Amz-Target">>, <<"CloudHsmFrontendService.", Action/binary>>}
],
Input = Input0,
Payload = jsx:encode(Input),
SignedHeaders = aws_request:sign_request(Client1, <<"POST">>, URL, Headers, Payload),
Response = hackney:request(post, URL, SignedHeaders, Payload, Options),
handle_response(Response).
handle_response({ok, 200, ResponseHeaders, Client}) ->
case hackney:body(Client) of
{ok, <<>>} ->
{ok, undefined, {200, ResponseHeaders, Client}};
{ok, Body} ->
Result = jsx:decode(Body),
{ok, Result, {200, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, ResponseHeaders, Client}) ->
{ok, Body} = hackney:body(Client),
Error = jsx:decode(Body),
{error, Error, {StatusCode, ResponseHeaders, Client}};
handle_response({error, Reason}) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Client) ->
Proto = aws_client:proto(Client),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, <<"/">>], <<"">>).
| null | https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_cloudhsm.erl | erlang | WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
@doc AWS CloudHSM Service
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
====================================================================
API
====================================================================
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
resource.
Each tag consists of a key and a value. Tag keys must be unique to each
resource.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Creates a high-availability partition group. A high-availability partition
group is a group of partitions that spans multiple physical HSMs.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
want to request a refund, delete the instance using the `DeleteHsm'
Account and Billing Support.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Deletes a high-availability partition group.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
key material cannot be recovered.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Deletes a client.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Retrieves information about a high-availability partition group.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
its serial number.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Gets the configuration files necessary to connect to all high availability
partition groups the client is associated with.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Lists the Availability Zones that have available AWS CloudHSM capacity.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Lists the high-availability partition groups for the account.
response contains a token that you pass in the next call to
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Retrieves the identifiers of all of the HSMs provisioned for the current
customer.
to retrieve the next set of items.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Lists all of the clients.
response contains a token that you pass in the next call to
`ListLunaClients' to retrieve the next set of items.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Returns a list of all tags for the specified AWS CloudHSM resource.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Modifies an existing high-availability partition group.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
while the AWS CloudHSM service is reconfigured. If you are modifying a
configured for high availability, and consider executing this operation
during a maintenance window.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
Modifies the certificate used by the client.
This action can potentially start a workflow to install the new
certificate on the client's HSMs.
For information about the current version of AWS CloudHSM, see AWS
CloudHSM, the AWS CloudHSM User Guide, and the AWS CloudHSM API Reference.
To remove a tag, specify only the tag key to remove (not the value). To
====================================================================
==================================================================== | See -beam/aws-codegen for more details .
This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
-module(aws_cloudhsm).
-export([add_tags_to_resource/2,
add_tags_to_resource/3,
create_hapg/2,
create_hapg/3,
create_hsm/2,
create_hsm/3,
create_luna_client/2,
create_luna_client/3,
delete_hapg/2,
delete_hapg/3,
delete_hsm/2,
delete_hsm/3,
delete_luna_client/2,
delete_luna_client/3,
describe_hapg/2,
describe_hapg/3,
describe_hsm/2,
describe_hsm/3,
describe_luna_client/2,
describe_luna_client/3,
get_config/2,
get_config/3,
list_available_zones/2,
list_available_zones/3,
list_hapgs/2,
list_hapgs/3,
list_hsms/2,
list_hsms/3,
list_luna_clients/2,
list_luna_clients/3,
list_tags_for_resource/2,
list_tags_for_resource/3,
modify_hapg/2,
modify_hapg/3,
modify_hsm/2,
modify_hsm/3,
modify_luna_client/2,
modify_luna_client/3,
remove_tags_from_resource/2,
remove_tags_from_resource/3]).
-include_lib("hackney/include/hackney_lib.hrl").
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Adds or overwrites one or more tags for the specified AWS CloudHSM
add_tags_to_resource(Client, Input)
when is_map(Client), is_map(Input) ->
add_tags_to_resource(Client, Input, []).
add_tags_to_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"AddTagsToResource">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
create_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
create_hapg(Client, Input, []).
create_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Creates an uninitialized HSM instance .
There is an upfront fee charged for each HSM instance that you create with
the ` CreateHsm ' operation . If you accidentally provision an HSM and
operation , go to the AWS Support Center , create a new case , and select
It can take up to 20 minutes to create and provision an HSM . You can
monitor the status of the HSM with the ` DescribeHsm ' operation . The
HSM is ready to be initialized when the status changes to ` RUNNING ' .
create_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
create_hsm(Client, Input, []).
create_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Creates an HSM client .
create_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
create_luna_client(Client, Input, []).
create_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"CreateLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
delete_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
delete_hapg(Client, Input, []).
delete_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Deletes an HSM . After completion , this operation can not be undone and your
delete_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
delete_hsm(Client, Input, []).
delete_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
delete_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
delete_luna_client(Client, Input, []).
delete_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DeleteLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
describe_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
describe_hapg(Client, Input, []).
describe_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Retrieves information about an HSM . You can identify the HSM by its ARN or
describe_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
describe_hsm(Client, Input, []).
describe_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Retrieves information about an HSM client .
describe_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
describe_luna_client(Client, Input, []).
describe_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"DescribeLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
get_config(Client, Input)
when is_map(Client), is_map(Input) ->
get_config(Client, Input, []).
get_config(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"GetConfig">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
list_available_zones(Client, Input)
when is_map(Client), is_map(Input) ->
list_available_zones(Client, Input, []).
list_available_zones(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListAvailableZones">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
` ListHapgs ' to retrieve the next set of items .
list_hapgs(Client, Input)
when is_map(Client), is_map(Input) ->
list_hapgs(Client, Input, []).
list_hapgs(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListHapgs">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
response contains a token that you pass in the next call to ` ListHsms '
list_hsms(Client, Input)
when is_map(Client), is_map(Input) ->
list_hsms(Client, Input, []).
list_hsms(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListHsms">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
This operation supports pagination with the use of the ` NextToken '
member . If more results are available , the ` NextToken ' member of the
list_luna_clients(Client, Input)
when is_map(Client), is_map(Input) ->
list_luna_clients(Client, Input, []).
list_luna_clients(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListLunaClients">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
list_tags_for_resource(Client, Input)
when is_map(Client), is_map(Input) ->
list_tags_for_resource(Client, Input, []).
list_tags_for_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ListTagsForResource">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
modify_hapg(Client, Input)
when is_map(Client), is_map(Input) ->
modify_hapg(Client, Input, []).
modify_hapg(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyHapg">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Modifies an HSM .
This operation can result in the HSM being offline for up to 15 minutes
production HSM , you should ensure that your AWS CloudHSM service is
modify_hsm(Client, Input)
when is_map(Client), is_map(Input) ->
modify_hsm(Client, Input, []).
modify_hsm(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyHsm">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
modify_luna_client(Client, Input)
when is_map(Client), is_map(Input) ->
modify_luna_client(Client, Input, []).
modify_luna_client(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"ModifyLunaClient">>, Input, Options).
@doc This is documentation for AWS CloudHSM Classic .
For more information , see AWS CloudHSM Classic FAQs , the AWS CloudHSM
Classic User Guide , and the AWS CloudHSM Classic API Reference .
Removes one or more tags from the specified AWS CloudHSM resource .
overwrite the value for an existing tag , use ` AddTagsToResource ' .
remove_tags_from_resource(Client, Input)
when is_map(Client), is_map(Input) ->
remove_tags_from_resource(Client, Input, []).
remove_tags_from_resource(Client, Input, Options)
when is_map(Client), is_map(Input), is_list(Options) ->
request(Client, <<"RemoveTagsFromResource">>, Input, Options).
Internal functions
-spec request(aws_client:aws_client(), binary(), map(), list()) ->
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map() | undefined,
Error :: map().
request(Client, Action, Input, Options) ->
RequestFun = fun() -> do_request(Client, Action, Input, Options) end,
aws_request:request(RequestFun, Options).
do_request(Client, Action, Input0, Options) ->
Client1 = Client#{service => <<"cloudhsm">>},
Host = build_host(<<"cloudhsm">>, Client1),
URL = build_url(Host, Client1),
Headers = [
{<<"Host">>, Host},
{<<"Content-Type">>, <<"application/x-amz-json-1.1">>},
{<<"X-Amz-Target">>, <<"CloudHsmFrontendService.", Action/binary>>}
],
Input = Input0,
Payload = jsx:encode(Input),
SignedHeaders = aws_request:sign_request(Client1, <<"POST">>, URL, Headers, Payload),
Response = hackney:request(post, URL, SignedHeaders, Payload, Options),
handle_response(Response).
handle_response({ok, 200, ResponseHeaders, Client}) ->
case hackney:body(Client) of
{ok, <<>>} ->
{ok, undefined, {200, ResponseHeaders, Client}};
{ok, Body} ->
Result = jsx:decode(Body),
{ok, Result, {200, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, ResponseHeaders, Client}) ->
{ok, Body} = hackney:body(Client),
Error = jsx:decode(Body),
{error, Error, {StatusCode, ResponseHeaders, Client}};
handle_response({error, Reason}) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Client) ->
Proto = aws_client:proto(Client),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, <<"/">>], <<"">>).
|
42a563a59ae3a738e7ef7334e00735afb66a7a3f2f204f515a02213920a5f0c9 | racket/math | mpfr-ffi-call-vs-racket.rkt | #lang racket/base
(require ffi/unsafe
tests/stress
math/private/bigfloat/mpfr)
(define mpfr-get-exp (get-mpfr-fun 'mpfr_get_exp (_fun _mpfr-pointer -> _exp_t)))
(define mpfr-get-prec (get-mpfr-fun 'mpfr_get_prec (_fun _mpfr-pointer -> _prec_t)))
(define mpfr-get-signbit (get-mpfr-fun 'mpfr_signbit (_fun _mpfr-pointer -> _int)))
(define (mpfr-signbit x)
(if ((mpfr-sign x) . < . 0) 1 0))
(define n 1000000)
(let ([x (bf 2)])
(stress
20
["mpfr-get-prec (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-prec x))]
["mpfr-prec (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-prec x))]))
(let ([x (bf 2)])
(stress
20
["mpfr-get-exp (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-exp x))]
["mpfr-exp (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-exp x))]))
(let ([x (bf 2)])
(stress
20
["mpfr-get-signbit (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-signbit x))]
["mpfr-signbit (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-signbit x))]))
| null | https://raw.githubusercontent.com/racket/math/dcd2ea1893dc5b45b26c8312997917a15fcd1c4a/math-test/math/tests/stress/mpfr-ffi-call-vs-racket.rkt | racket | #lang racket/base
(require ffi/unsafe
tests/stress
math/private/bigfloat/mpfr)
(define mpfr-get-exp (get-mpfr-fun 'mpfr_get_exp (_fun _mpfr-pointer -> _exp_t)))
(define mpfr-get-prec (get-mpfr-fun 'mpfr_get_prec (_fun _mpfr-pointer -> _prec_t)))
(define mpfr-get-signbit (get-mpfr-fun 'mpfr_signbit (_fun _mpfr-pointer -> _int)))
(define (mpfr-signbit x)
(if ((mpfr-sign x) . < . 0) 1 0))
(define n 1000000)
(let ([x (bf 2)])
(stress
20
["mpfr-get-prec (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-prec x))]
["mpfr-prec (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-prec x))]))
(let ([x (bf 2)])
(stress
20
["mpfr-get-exp (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-exp x))]
["mpfr-exp (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-exp x))]))
(let ([x (bf 2)])
(stress
20
["mpfr-get-signbit (FFI accessor)"
(for ([_ (in-range n)])
(mpfr-get-signbit x))]
["mpfr-signbit (Racket accessor)"
(for ([_ (in-range n)])
(mpfr-signbit x))]))
| |
35aed930a1904ea911fcb3cd2349a8468e7047798bd83a2e4e4aa86934e3de6f | padsproj/pads-haskell | GenPretty.hs | # LANGUAGE TypeSynonymInstances , TemplateHaskell , QuasiQuotes , MultiParamTypeClasses
, FlexibleInstances , DeriveDataTypeable , NamedFieldPuns , ScopedTypeVariables #
, FlexibleInstances, DeriveDataTypeable, NamedFieldPuns, ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK prune #-}
|
Module : Language . Pads . GenPretty
Description : Template haskell based pretty printing instances
Copyright : ( c ) 2011
< >
< >
License : MIT
Maintainer : < >
Stability : experimental
Module : Language.Pads.GenPretty
Description : Template haskell based pretty printing instances
Copyright : (c) 2011
Kathleen Fisher <>
John Launchbury <>
License : MIT
Maintainer : Karl Cronburg <>
Stability : experimental
-}
module Language.Pads.GenPretty where
import Language.Pads.Padsc
import Language.Pads.Errors
import Language.Pads.MetaData
import Language.Pads.TH
import Language.Haskell.TH as TH hiding (ppr)
import Text.PrettyPrint.Mainland
import Text.PrettyPrint.Mainland.Class
import qualified Data.List as L
import qualified Data.Set as S
import Control.Monad
import System.Posix.Types
import Data.Word
import Data.Int
import Data.Time
import Debug.Trace as D
pprE argE = AppE (VarE 'ppr) argE
pprListEs argEs = ListE (map pprE argEs)
pprCon1E argE = AppE (VarE 'pprCon1) argE
pprCon2E argE = AppE (VarE 'pprCon2) argE
pprCon1 arg = ppr (toList1 arg)
pprCon2 arg = ppr (toList2 arg)
| Get all the names of types referenced within the given ' TH.Type '
getTyNames :: TH.Type -> S.Set TH.Name
getTyNames ty = case ty of
ForallT tvb cxt ty' -> getTyNames ty'
VarT name -> S.empty
ConT name -> S.singleton name
TupleT i -> S.empty
ArrowT -> S.empty
ListT -> S.empty
AppT t1 t2 -> getTyNames t1 `S.union` getTyNames t2
SigT ty kind -> getTyNames ty
| Get all the types referenced within the given constructor .
getTyNamesFromCon :: TH.Con -> S.Set TH.Name
getTyNamesFromCon con = case con of
(NormalC name stys) -> S.unions (map (\(_,ty) -> getTyNames ty) stys)
(RecC name vstys) -> S.unions (map (\(_,_,ty) -> getTyNames ty) vstys)
(InfixC st1 name st2) -> getTyNames (snd st1) `S.union` getTyNames (snd st2)
(ForallC tvb cxt con) -> getTyNamesFromCon con
-- | Recursively reify types to get all the named types referenced by the given
-- name
getNamedTys :: TH.Name -> Q [TH.Name]
getNamedTys ty_name = S.toList <$> getNamedTys' S.empty (S.singleton ty_name)
-- | Helper for 'getNamedTys'
getNamedTys' :: S.Set TH.Name -> S.Set TH.Name -> Q (S.Set TH.Name)
getNamedTys' answers worklist =
if S.null worklist then return answers
else do
{ let (ty_name, worklist') = S.deleteFindMin worklist
; let answers' = S.insert ty_name answers
; info <- reify ty_name
; case info of
TyConI (NewtypeD [] ty_name' [] _ con derives) -> do
{ let all_nested = getTyNamesFromCon con
; let new_nested = all_nested `S.difference` answers'
; let new_worklist = worklist' `S.union` new_nested
; getNamedTys' answers' new_worklist
}
TyConI (DataD [] ty_name' [] _ cons derives) -> do
{ let all_nested = S.unions (map getTyNamesFromCon cons)
; let new_nested = all_nested `S.difference` answers'
; let new_worklist = worklist' `S.union` new_nested
; getNamedTys' answers' new_worklist
}
TyConI (TySynD _ _ _ ) -> do {reportError ("getTyNames: unimplemented TySynD case " ++ (nameBase ty_name)); return answers'}
TyConI (ForeignD _) -> do {reportError ("getTyNames: unimplemented ForeignD case " ++ (nameBase ty_name)); return answers'}
PrimTyConI _ _ _ -> return answers
otherwise -> do {reportError ("getTyNames: pattern didn't match for " ++ (nameBase ty_name)); return answers'}
}
-- | All the base types supported by Pads
baseTypeNames = S.fromList [ ''Int, ''Char, ''Digit, ''Text, ''String, ''StringFW, ''StringME
, ''StringSE, ''COff, ''EpochTime, ''FileMode, ''Int, ''Word, ''Int64
, ''Language.Pads.Errors.ErrInfo, ''Bool, ''Binary, ''Base_md, ''UTCTime, ''TimeZone
]
-- | Recursively make the pretty printing instance for a given named type by
-- also making instances for all nested types.
mkPrettyInstance :: TH.Name -> Q [TH.Dec]
mkPrettyInstance ty_name = mkPrettyInstance' (S.singleton ty_name) baseTypeNames []
mkMe :: TH.Name -> Q [TH.Dec]
mkMe n = do
D.traceM "HELLOOOOOOOOOO"
return []
-- | Helper for 'mkPrettyInstance'
mkPrettyInstance' :: S.Set TH.Name -> S.Set TH.Name -> [TH.Dec] -> Q [TH.Dec]
mkPrettyInstance' worklist done decls =
if S.null worklist then return decls
else do
let (ty_name, worklist') = S.deleteFindMin worklist
if ty_name `S.member` done then mkPrettyInstance' worklist' done decls
else do
let tyBaseName = nameBase ty_name
let baseStr = strToLower tyBaseName
let specificPprName = mkName (baseStr ++ "_ppr")
let funName = mkName (strToLower (tyBaseName ++ "_ppr"))
let inst = AppT (ConT ''Pretty) (ConT ty_name)
let genericPprName = mkName "ppr"
let ppr_method = ValD (VarP genericPprName) (NormalB (VarE specificPprName)) []
let instD = InstanceD Nothing [] inst [ppr_method]
let newDone = S.insert ty_name done
info <- reify ty_name
(nestedTyNames, decls') <- case info of
TyConI (NewtypeD [] ty_name' [] _ (NormalC ty_name'' [(Bang NoSourceUnpackedness NoSourceStrictness, AppT ListT ty)]) derives) -> do -- List
{ let nestedTyNames = getTyNames ty
-- ; reportError ("list case " ++ (nameBase ty_name))
; (itemsE,itemsP) <- doGenPE "list"
; let mapE = AppE (AppE (VarE 'map) (VarE 'ppr)) itemsE
; let bodyE = AppE (AppE (VarE 'namedlist_ppr) (nameToStrLit ty_name)) mapE
; let argP = ConP (mkName tyBaseName) [itemsP]
; let clause = Clause [argP] (NormalB bodyE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (NewtypeD [] ty_name' [] _ (NormalC ty_name'' [(Bang NoSourceUnpackedness NoSourceStrictness, AppT (AppT (ConT ty_con_name) ty_arg1) ty_arg2) ]) derives) -> do -- curry rep (Map)
{ let nestedTyNames = getTyNames ty_arg2
; (argP, body) <- mkPatBody tyBaseName pprCon2E
-- ; reportError ("curry rep case " ++ (nameBase ty_name))
; let clause = Clause [argP] body []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (NewtypeD [] ty_name' [] _ (NormalC ty_name'' [(Bang NoSourceUnpackedness NoSourceStrictness, AppT (ConT ty_con_name) ty_arg) ]) derives) -> do -- con rep (Set)
{ let nestedTyNames = getTyNames ty_arg
; (argP, body) <- mkPatBody tyBaseName pprCon1E
-- ; reportError ("con rep case " ++ (nameBase ty_name))
; let clause = Clause [argP] body []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
App , Typedef
{ (argP, body) <- mkPatBody tyBaseName pprE
-- ; reportError ("app, typedef case " ++ (nameBase ty_name))
; let clause = Clause [argP] body []
; return (S.singleton core_name, [instD, FunD specificPprName [clause]])
}
TyConI (NewtypeD [] ty_name' [] _ (NormalC ty_name'' [(Bang NoSourceUnpackedness NoSourceStrictness, ty)]) derives) | isTuple ty -> do -- Tuple
{ let nestedTyNames = getTyNames ty
-- ; reportError ("tuple case " ++ (nameBase ty_name))
; let (len, tys) = tupleTyToListofTys ty
; (exps, pats) <- doGenPEs len "tuple"
; let bodyE = AppE (AppE (VarE 'namedtuple_ppr) (LitE (StringL tyBaseName))) (pprListEs exps)
; let argP = ConP (mkName tyBaseName) [TupP pats]
; let clause = Clause [argP] (NormalB bodyE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (DataD [] ty_name' [] _ cons derives) | isDataType cons -> do
{ let nestedTyNames = S.unions (map getTyNamesFromCon cons)
; (exp, pat) <- doGenPE "case_arg"
; matches <- mapM mkClause cons
; let caseE = CaseE exp matches
; let clause = Clause [pat] (NormalB caseE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]] )
}
TyConI (DataD [] ty_name' [] _ cons derives) | isRecordType cons -> do
{ let nestedTyNames = S.unions (map getTyNamesFromCon cons)
; report ( length cons /= 1 ) ( " GenPretty : record " + + ( nameBase ty_name ' ) + + " did not have a single constructor . " )
; clause <- mkRecord (L.head cons)
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (DataD _ ty_name' _ _ cons derives) -> do
{
reportError ( " DataD pattern did n't match for"++(nameBase ty_name ) )
; return (S.empty, [])}
TyConI (TySynD ty_name' [] ty) -> do
{ let nestedTyNames = getTyNames ty
-- ; reportError ("tysyn for"++(nameBase ty_name))
; return (nestedTyNames, [])}
TyConI (TySynD ty_name' tyVarBndrs ty) -> do
{ let nestedTyNames = getTyNames ty
-- ; reportError ("tysyn for"++(nameBase ty_name))
; return (nestedTyNames, [])}
TyConI dec -> do {reportError ("otherwise; tyconI case "++(nameBase ty_name)) ; return (S.empty, [])}
otherwise -> do {reportError ("pattern didn't match for "++(nameBase ty_name)) ; return (S.empty, [])}
let newWorklist = worklist `S.union` nestedTyNames
let newDecls = decls'++decls
mkPrettyInstance' newWorklist newDone newDecls
-- | Is the given type a TupleT?
isTuple (TupleT n) = True
isTuple (AppT ty _) = isTuple ty
| Is the given constructor a normal constructor ?
isDataType [] = False
isDataType (NormalC _ _ : rest) = True
isDataType _ = False
| Is the given constructor a record constructor ?
isRecordType [] = False
isRecordType (RecC _ _ : rest) = True
isRecordType _ = False
-- | Make the pattern body of a pretty printer expression for a named Pads type
mkPatBody core_name_str pprE = do
(exp,pat) <- doGenPE "arg"
bodyE <- [| namedty_ppr $(litE $ stringL core_name_str) $(return $ pprE exp) |]
argP <- conP (mkName core_name_str) [return pat]
return (argP, NormalB bodyE)
-- | Make the pattern body of a pretty printer expression for a Pads type /
-- data constructor without arguments.
mkPatBodyNoArg core_name_str = do
bodyE <- [| text $(litE $ stringL core_name_str) |]
argP <- conP (mkName core_name_str) []
return (argP, NormalB bodyE)
-- | Make the clause for the data constructor of a data type based on whether or
-- not it has any arguments.
mkClause con = case con of
NormalC name [] -> do
{ (argP, body) <- mkPatBodyNoArg (nameBase name)
; return (Match argP body [])
}
NormalC name ty_args -> do
{ (argP, body) <- mkPatBody (nameBase name) pprE
; return (Match argP body [])
}
otherwise -> error "mkClause not implemented for this kind of constructor."
| Make the Haskell clause for a Pads record .
mkRecord (RecC rec_name fields) = do
fieldInfo <- mapM mkField fields
let (recPs, recEs) = unzip fieldInfo
let recP = RecP rec_name recPs
let bodyE = AppE (AppE (VarE 'record_ppr) (nameToStrLit rec_name)) (ListE recEs)
return (Clause [recP] (NormalB bodyE) [])
-- | Make the field pretty printer case.
mkField (field_name, _, ty) = do
(expE, pat) <- doGenPE (nameBase field_name)
fieldE <- [| field_ppr $(return $ nameToStrLit field_name) $(return $ pprE expE) |]
return ((field_name, pat), fieldE)
nameToStrLit name = LitE (StringL (nameBase name))
instance Pretty a = > Pretty ( a ) where
-- ppr PNothing = text ""
ppr ( PJust a ) = ppr a
--
-- instance Pretty a => Pretty (PMaybe_imd a) where
-- ppr (PNothing_imd _) = text ""
ppr ( PJust_imd a ) = ppr a
| null | https://raw.githubusercontent.com/padsproj/pads-haskell/8dce6b2b28bf7d98028e67f6faa2be753a6ad691/src/Language/Pads/GenPretty.hs | haskell | # OPTIONS_HADDOCK prune #
| Recursively reify types to get all the named types referenced by the given
name
| Helper for 'getNamedTys'
| All the base types supported by Pads
| Recursively make the pretty printing instance for a given named type by
also making instances for all nested types.
| Helper for 'mkPrettyInstance'
List
; reportError ("list case " ++ (nameBase ty_name))
curry rep (Map)
; reportError ("curry rep case " ++ (nameBase ty_name))
con rep (Set)
; reportError ("con rep case " ++ (nameBase ty_name))
; reportError ("app, typedef case " ++ (nameBase ty_name))
Tuple
; reportError ("tuple case " ++ (nameBase ty_name))
; reportError ("tysyn for"++(nameBase ty_name))
; reportError ("tysyn for"++(nameBase ty_name))
| Is the given type a TupleT?
| Make the pattern body of a pretty printer expression for a named Pads type
| Make the pattern body of a pretty printer expression for a Pads type /
data constructor without arguments.
| Make the clause for the data constructor of a data type based on whether or
not it has any arguments.
| Make the field pretty printer case.
ppr PNothing = text ""
instance Pretty a => Pretty (PMaybe_imd a) where
ppr (PNothing_imd _) = text "" | # LANGUAGE TypeSynonymInstances , TemplateHaskell , QuasiQuotes , MultiParamTypeClasses
, FlexibleInstances , DeriveDataTypeable , NamedFieldPuns , ScopedTypeVariables #
, FlexibleInstances, DeriveDataTypeable, NamedFieldPuns, ScopedTypeVariables #-}
|
Module : Language . Pads . GenPretty
Description : Template haskell based pretty printing instances
Copyright : ( c ) 2011
< >
< >
License : MIT
Maintainer : < >
Stability : experimental
Module : Language.Pads.GenPretty
Description : Template haskell based pretty printing instances
Copyright : (c) 2011
Kathleen Fisher <>
John Launchbury <>
License : MIT
Maintainer : Karl Cronburg <>
Stability : experimental
-}
module Language.Pads.GenPretty where
import Language.Pads.Padsc
import Language.Pads.Errors
import Language.Pads.MetaData
import Language.Pads.TH
import Language.Haskell.TH as TH hiding (ppr)
import Text.PrettyPrint.Mainland
import Text.PrettyPrint.Mainland.Class
import qualified Data.List as L
import qualified Data.Set as S
import Control.Monad
import System.Posix.Types
import Data.Word
import Data.Int
import Data.Time
import Debug.Trace as D
pprE argE = AppE (VarE 'ppr) argE
pprListEs argEs = ListE (map pprE argEs)
pprCon1E argE = AppE (VarE 'pprCon1) argE
pprCon2E argE = AppE (VarE 'pprCon2) argE
pprCon1 arg = ppr (toList1 arg)
pprCon2 arg = ppr (toList2 arg)
| Get all the names of types referenced within the given ' TH.Type '
getTyNames :: TH.Type -> S.Set TH.Name
getTyNames ty = case ty of
ForallT tvb cxt ty' -> getTyNames ty'
VarT name -> S.empty
ConT name -> S.singleton name
TupleT i -> S.empty
ArrowT -> S.empty
ListT -> S.empty
AppT t1 t2 -> getTyNames t1 `S.union` getTyNames t2
SigT ty kind -> getTyNames ty
| Get all the types referenced within the given constructor .
getTyNamesFromCon :: TH.Con -> S.Set TH.Name
getTyNamesFromCon con = case con of
(NormalC name stys) -> S.unions (map (\(_,ty) -> getTyNames ty) stys)
(RecC name vstys) -> S.unions (map (\(_,_,ty) -> getTyNames ty) vstys)
(InfixC st1 name st2) -> getTyNames (snd st1) `S.union` getTyNames (snd st2)
(ForallC tvb cxt con) -> getTyNamesFromCon con
getNamedTys :: TH.Name -> Q [TH.Name]
getNamedTys ty_name = S.toList <$> getNamedTys' S.empty (S.singleton ty_name)
getNamedTys' :: S.Set TH.Name -> S.Set TH.Name -> Q (S.Set TH.Name)
getNamedTys' answers worklist =
if S.null worklist then return answers
else do
{ let (ty_name, worklist') = S.deleteFindMin worklist
; let answers' = S.insert ty_name answers
; info <- reify ty_name
; case info of
TyConI (NewtypeD [] ty_name' [] _ con derives) -> do
{ let all_nested = getTyNamesFromCon con
; let new_nested = all_nested `S.difference` answers'
; let new_worklist = worklist' `S.union` new_nested
; getNamedTys' answers' new_worklist
}
TyConI (DataD [] ty_name' [] _ cons derives) -> do
{ let all_nested = S.unions (map getTyNamesFromCon cons)
; let new_nested = all_nested `S.difference` answers'
; let new_worklist = worklist' `S.union` new_nested
; getNamedTys' answers' new_worklist
}
TyConI (TySynD _ _ _ ) -> do {reportError ("getTyNames: unimplemented TySynD case " ++ (nameBase ty_name)); return answers'}
TyConI (ForeignD _) -> do {reportError ("getTyNames: unimplemented ForeignD case " ++ (nameBase ty_name)); return answers'}
PrimTyConI _ _ _ -> return answers
otherwise -> do {reportError ("getTyNames: pattern didn't match for " ++ (nameBase ty_name)); return answers'}
}
baseTypeNames = S.fromList [ ''Int, ''Char, ''Digit, ''Text, ''String, ''StringFW, ''StringME
, ''StringSE, ''COff, ''EpochTime, ''FileMode, ''Int, ''Word, ''Int64
, ''Language.Pads.Errors.ErrInfo, ''Bool, ''Binary, ''Base_md, ''UTCTime, ''TimeZone
]
mkPrettyInstance :: TH.Name -> Q [TH.Dec]
mkPrettyInstance ty_name = mkPrettyInstance' (S.singleton ty_name) baseTypeNames []
mkMe :: TH.Name -> Q [TH.Dec]
mkMe n = do
D.traceM "HELLOOOOOOOOOO"
return []
mkPrettyInstance' :: S.Set TH.Name -> S.Set TH.Name -> [TH.Dec] -> Q [TH.Dec]
mkPrettyInstance' worklist done decls =
if S.null worklist then return decls
else do
let (ty_name, worklist') = S.deleteFindMin worklist
if ty_name `S.member` done then mkPrettyInstance' worklist' done decls
else do
let tyBaseName = nameBase ty_name
let baseStr = strToLower tyBaseName
let specificPprName = mkName (baseStr ++ "_ppr")
let funName = mkName (strToLower (tyBaseName ++ "_ppr"))
let inst = AppT (ConT ''Pretty) (ConT ty_name)
let genericPprName = mkName "ppr"
let ppr_method = ValD (VarP genericPprName) (NormalB (VarE specificPprName)) []
let instD = InstanceD Nothing [] inst [ppr_method]
let newDone = S.insert ty_name done
info <- reify ty_name
(nestedTyNames, decls') <- case info of
{ let nestedTyNames = getTyNames ty
; (itemsE,itemsP) <- doGenPE "list"
; let mapE = AppE (AppE (VarE 'map) (VarE 'ppr)) itemsE
; let bodyE = AppE (AppE (VarE 'namedlist_ppr) (nameToStrLit ty_name)) mapE
; let argP = ConP (mkName tyBaseName) [itemsP]
; let clause = Clause [argP] (NormalB bodyE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
{ let nestedTyNames = getTyNames ty_arg2
; (argP, body) <- mkPatBody tyBaseName pprCon2E
; let clause = Clause [argP] body []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
{ let nestedTyNames = getTyNames ty_arg
; (argP, body) <- mkPatBody tyBaseName pprCon1E
; let clause = Clause [argP] body []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
App , Typedef
{ (argP, body) <- mkPatBody tyBaseName pprE
; let clause = Clause [argP] body []
; return (S.singleton core_name, [instD, FunD specificPprName [clause]])
}
{ let nestedTyNames = getTyNames ty
; let (len, tys) = tupleTyToListofTys ty
; (exps, pats) <- doGenPEs len "tuple"
; let bodyE = AppE (AppE (VarE 'namedtuple_ppr) (LitE (StringL tyBaseName))) (pprListEs exps)
; let argP = ConP (mkName tyBaseName) [TupP pats]
; let clause = Clause [argP] (NormalB bodyE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (DataD [] ty_name' [] _ cons derives) | isDataType cons -> do
{ let nestedTyNames = S.unions (map getTyNamesFromCon cons)
; (exp, pat) <- doGenPE "case_arg"
; matches <- mapM mkClause cons
; let caseE = CaseE exp matches
; let clause = Clause [pat] (NormalB caseE) []
; return (nestedTyNames, [instD, FunD specificPprName [clause]] )
}
TyConI (DataD [] ty_name' [] _ cons derives) | isRecordType cons -> do
{ let nestedTyNames = S.unions (map getTyNamesFromCon cons)
; report ( length cons /= 1 ) ( " GenPretty : record " + + ( nameBase ty_name ' ) + + " did not have a single constructor . " )
; clause <- mkRecord (L.head cons)
; return (nestedTyNames, [instD, FunD specificPprName [clause]])
}
TyConI (DataD _ ty_name' _ _ cons derives) -> do
{
reportError ( " DataD pattern did n't match for"++(nameBase ty_name ) )
; return (S.empty, [])}
TyConI (TySynD ty_name' [] ty) -> do
{ let nestedTyNames = getTyNames ty
; return (nestedTyNames, [])}
TyConI (TySynD ty_name' tyVarBndrs ty) -> do
{ let nestedTyNames = getTyNames ty
; return (nestedTyNames, [])}
TyConI dec -> do {reportError ("otherwise; tyconI case "++(nameBase ty_name)) ; return (S.empty, [])}
otherwise -> do {reportError ("pattern didn't match for "++(nameBase ty_name)) ; return (S.empty, [])}
let newWorklist = worklist `S.union` nestedTyNames
let newDecls = decls'++decls
mkPrettyInstance' newWorklist newDone newDecls
isTuple (TupleT n) = True
isTuple (AppT ty _) = isTuple ty
| Is the given constructor a normal constructor ?
isDataType [] = False
isDataType (NormalC _ _ : rest) = True
isDataType _ = False
| Is the given constructor a record constructor ?
isRecordType [] = False
isRecordType (RecC _ _ : rest) = True
isRecordType _ = False
mkPatBody core_name_str pprE = do
(exp,pat) <- doGenPE "arg"
bodyE <- [| namedty_ppr $(litE $ stringL core_name_str) $(return $ pprE exp) |]
argP <- conP (mkName core_name_str) [return pat]
return (argP, NormalB bodyE)
mkPatBodyNoArg core_name_str = do
bodyE <- [| text $(litE $ stringL core_name_str) |]
argP <- conP (mkName core_name_str) []
return (argP, NormalB bodyE)
mkClause con = case con of
NormalC name [] -> do
{ (argP, body) <- mkPatBodyNoArg (nameBase name)
; return (Match argP body [])
}
NormalC name ty_args -> do
{ (argP, body) <- mkPatBody (nameBase name) pprE
; return (Match argP body [])
}
otherwise -> error "mkClause not implemented for this kind of constructor."
| Make the Haskell clause for a Pads record .
mkRecord (RecC rec_name fields) = do
fieldInfo <- mapM mkField fields
let (recPs, recEs) = unzip fieldInfo
let recP = RecP rec_name recPs
let bodyE = AppE (AppE (VarE 'record_ppr) (nameToStrLit rec_name)) (ListE recEs)
return (Clause [recP] (NormalB bodyE) [])
mkField (field_name, _, ty) = do
(expE, pat) <- doGenPE (nameBase field_name)
fieldE <- [| field_ppr $(return $ nameToStrLit field_name) $(return $ pprE expE) |]
return ((field_name, pat), fieldE)
nameToStrLit name = LitE (StringL (nameBase name))
instance Pretty a = > Pretty ( a ) where
ppr ( PJust a ) = ppr a
ppr ( PJust_imd a ) = ppr a
|
1e2e4cf7a49270e4880412507145b8d4e84ea8faac8e6c049f08c5a11418a03a | kazu-yamamoto/http2 | HuffmanSpec.hs | # LANGUAGE OverloadedStrings , CPP #
module HPACK.HuffmanSpec where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import Data.Char (toLower)
import Network.HPACK
import Network.HPACK.Internal
import Test.Hspec
import Test.Hspec.QuickCheck
testData :: [(ByteString, ByteString)]
testData = [
("", "")
, ("www.example.com", "f1e3c2e5f23a6ba0ab90f4ff")
, ("no-cache", "a8eb10649cbf")
, ("custom-key", "25a849e95ba97d7f")
, ("custom-value", "25a849e95bb8e8b4bf")
, ("private", "aec3771a4b")
, ("Mon, 21 Oct 2013 20:13:21 GMT", "d07abe941054d444a8200595040b8166e082a62d1bff")
, ("", "9d29ad171863c78f0b97c8e9ae82ae43d3")
, ("Mon, 21 Oct 2013 20:13:22 GMT", "d07abe941054d444a8200595040b8166e084a62d1bff")
, ("gzip", "9bd9ab")
, ("foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007")
]
shouldBeEncoded :: ByteString -> ByteString -> Expectation
shouldBeEncoded inp out = do
out' <- BS.map toLower . B16.encode <$> encodeHuffman inp
out' `shouldBe` out
shouldBeDecoded :: ByteString -> ByteString -> Expectation
shouldBeDecoded inp out = do
out' <- decodeHuffman $ B16.decodeLenient inp
out' `shouldBe` out
tryDecode :: ByteString -> IO ByteString
tryDecode inp = decodeHuffman $ B16.decodeLenient inp
spec :: Spec
spec = do
describe "encode and decode" $ do
prop "duality" $ \cs -> do
let bs = BS.pack cs
es <- encodeHuffman bs
ds <- decodeHuffman es
ds `shouldBe` bs
describe "encode" $ do
it "encodes" $ do
mapM_ (\(x,y) -> x `shouldBeEncoded` y) testData
describe "decode" $ do
it "decodes" $ do
tryDecode "ff" `shouldThrow` (== TooLongEos)
tryDecode "ffffeaff" `shouldThrow` (== TooLongEos)
"ffffea" `shouldBeDecoded` "\9"
mapM_ (\(x,y) -> y `shouldBeDecoded` x) testData
| null | https://raw.githubusercontent.com/kazu-yamamoto/http2/3c29763be147a3d482eff28f427ad80f1d4df706/test/HPACK/HuffmanSpec.hs | haskell | # LANGUAGE OverloadedStrings , CPP #
module HPACK.HuffmanSpec where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BS
import Data.Char (toLower)
import Network.HPACK
import Network.HPACK.Internal
import Test.Hspec
import Test.Hspec.QuickCheck
testData :: [(ByteString, ByteString)]
testData = [
("", "")
, ("www.example.com", "f1e3c2e5f23a6ba0ab90f4ff")
, ("no-cache", "a8eb10649cbf")
, ("custom-key", "25a849e95ba97d7f")
, ("custom-value", "25a849e95bb8e8b4bf")
, ("private", "aec3771a4b")
, ("Mon, 21 Oct 2013 20:13:21 GMT", "d07abe941054d444a8200595040b8166e082a62d1bff")
, ("", "9d29ad171863c78f0b97c8e9ae82ae43d3")
, ("Mon, 21 Oct 2013 20:13:22 GMT", "d07abe941054d444a8200595040b8166e084a62d1bff")
, ("gzip", "9bd9ab")
, ("foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", "94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063d5007")
]
shouldBeEncoded :: ByteString -> ByteString -> Expectation
shouldBeEncoded inp out = do
out' <- BS.map toLower . B16.encode <$> encodeHuffman inp
out' `shouldBe` out
shouldBeDecoded :: ByteString -> ByteString -> Expectation
shouldBeDecoded inp out = do
out' <- decodeHuffman $ B16.decodeLenient inp
out' `shouldBe` out
tryDecode :: ByteString -> IO ByteString
tryDecode inp = decodeHuffman $ B16.decodeLenient inp
spec :: Spec
spec = do
describe "encode and decode" $ do
prop "duality" $ \cs -> do
let bs = BS.pack cs
es <- encodeHuffman bs
ds <- decodeHuffman es
ds `shouldBe` bs
describe "encode" $ do
it "encodes" $ do
mapM_ (\(x,y) -> x `shouldBeEncoded` y) testData
describe "decode" $ do
it "decodes" $ do
tryDecode "ff" `shouldThrow` (== TooLongEos)
tryDecode "ffffeaff" `shouldThrow` (== TooLongEos)
"ffffea" `shouldBeDecoded` "\9"
mapM_ (\(x,y) -> y `shouldBeDecoded` x) testData
| |
6c1898c4bbc2af501f73e71062359a1f7ca4ad295ff9f4866f35ac5eb4d7c1f9 | gethop-dev/hydrogen.duct-template | root.clj | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
;; file, You can obtain one at /
{{=<< >>=}}
(ns <<namespace>>.ssr.root
(:require [cognitect.transit :as transit]
[compojure.core :refer [context wrap-routes GET routes]]
[hiccup.util :refer [as-str]]
[hiccup.util :refer [escape-html as-str raw-string]]
[hiccup2.core :refer [html]]
[integrant.core :as ig]
[re-frame.core :as rf]
[re-frame.db :as rf.db]
[<<namespace>>.api.util :as api-util]
[<<namespace>>.client.breadcrumbs :as client.breadcrumbs]
[<<namespace>>.client.home :as client.home]
[<<namespace>>.client.hydrogen-demo.shop :as client.shop]
[<<namespace>>.client.hydrogen-demo.shop-item :as client.shop-item]<<#hydrogen-session?>>
[buddy.auth :refer [authenticated?]]
[<<namespace>>.client.landing :as client.landing]<</hydrogen-session?>>
[<<namespace>>.client.sidebar :as client.sidebar]
[<<namespace>>.client.theme :as client.theme]
[<<namespace>>.client.view :as client.view]
[<<namespace>>.service.shop :as srv.shop]
[<<namespace>>.util :as util]
[<<namespace>>.util.hiccup-parser :as hiccup-parser])
(:import [java.io ByteArrayOutputStream]))
(defonce default-app-db-ba-output-stream-buffer-size 4096)
(defn load-initial-app-db-script [app-db]
(with-open [app-db-output-stream (ByteArrayOutputStream. default-app-db-ba-output-stream-buffer-size)]
(let [app-db-writer (transit/writer app-db-output-stream :json)]
(transit/write app-db-writer app-db)
[:script
(raw-string (format "INITIAL_APP_DB=%s;"
(pr-str (.toString app-db-output-stream))))])))
(defn app
TODO it 's just a modified version of client.cljs 's app . Put it in a cljc namespace
[]
(let [theme (rf/subscribe [::client.theme/get-theme])]
(fn []
[:div.app-container
{:class (str "theme-" (name @theme))}
[client.sidebar/main]
[:div.app-container__main
{:id "app-container__main"}
[client.breadcrumbs/main]
[client.view/main]]])))
(defn- gen-html
[app-db]
(->
[:html {:lang "en"}
[:head
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
[:title <<front-page-title>>]
[:link {:href "-ssl.webflow.com/5a68a8bef9676b00011ad3be/5a8d32501a5b5000018eb866_favicon.png"
:rel "shortcut icon"
:type "image/x-icon"}]
[:link {:href ":400,700" :rel "stylesheet"}]
[:link {:rel "stylesheet" :href "/css/main.css"}]<<#hydrogen-session?>>
[:link {:rel "stylesheet" :href "/css/landing.css"}]<</hydrogen-session?>><<#hydrogen-session-cognito?>>
[:script {:src "-cognito-identity-js@2.0.6/dist/amazon-cognito-identity.min.js"
:integrity "sha256-pYn9Yh/mq4hWZBz8ZKuFWmTWBBAsAwEDx0TjRZHZozc="
:crossorigin "anonymous"}]<</hydrogen-session-cognito?>><<#hydrogen-session-keycloak?>>
[:script {:src "-js@9.0.0/dist/keycloak.min.js"
:integrity "sha256-cKzGXR7XoBTQp5rjJMHgTv72r1ERU266BypryyxzX2I="
:crossorigin "anonymous"}]<</hydrogen-session-keycloak?>>]
[:script "var INITIAL_APP_DB;"]
(some-> app-db (load-initial-app-db-script))
[:body
[:div#app
(hiccup-parser/parse-tag-content
[app])]
[:script {:src "/js/main.js"}]
[:script "<<js-namespace>>.client.init(true);"]]]
(html)
(as-str)))
TODO use 's fork to make it work on multiple threads
;(defn- handle-route*
; [app-db]
; (let [db-id (util/uuid)
; result (with-bindings {#'re-frame.db/app-db-id db-id}
; (swap! rf.db/db-atoms* assoc db-id app-db)
; (gen-html app-db))]
; (re-frame.db/clear-app-db db-id)
; result))
(defn- handle-route*
This solution will not work right with multiple clients asking for SSR as they will compete for the same resource .
;; Look at the solution above.
[app-db]
(reset! rf.db/app-db app-db)
(gen-html app-db))<<^hydrogen-session?>>
(defn- handle-route
[req {:keys [app-db]}]
(handle-route* app-db))
(defmethod ig/init-key :<<namespace>>.ssr/root [_ _]
NOTE : this routes registry needs to be a ONE TO ONE matching in regards to client 's app - routes
(context "/" []
(routes
(GET "/home" req
(handle-route
req
{:app-db
{:active-view [::client.home/view]
:breadcrumbs []}}))
(GET "/shop" req
(handle-route
req
{:appp-db
{:active-view [::client.shop/view]
:shop {:items [:apple :orange :banana]}
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop" :disabled true}]}}))
(GET "/shop/:id" [id :as req]
(handle-route
req
{:app-db
(let [shop-item (srv.shop/get-shop-item id)]
{:active-view [::client.shop-item/view]
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop"}
{:title (:name shop-item)
:url (str "/" id)
:disabled true}]
:shop-item shop-item})}))
(GET "*" req
(handle-route
req
{:app-db {:error "I don't know where I am"}})))))<</hydrogen-session?>><<#hydrogen-session?>>
(defn- handle-route
[req {:keys [app-db allow-unauthenticated? allow-authenticated?]
:or {allow-authenticated? true
allow-unauthenticated? false}}]
(let [authenticated? (buddy.auth/authenticated? req)
authorised? (or (and authenticated? allow-authenticated?)
(and (not authenticated?) allow-unauthenticated?))
app-db (if authorised?
app-db
{:error "Unauthorised"
:active-view [::client.landing/view]})]
(handle-route* app-db)))
(defmethod ig/init-key :<<namespace>>.ssr/root [_ {:keys [auth-middleware]}]
NOTE : this routes registry needs to be a ONE TO ONE matching in regards to client 's app - routes
(context "/" []
(->
(routes
(GET "/home" req
(handle-route
req
{:app-db
{:active-view [::client.home/view]
:breadcrumbs []}}))
(GET "/shop" req
(handle-route
req
{:app-db
{:active-view [::client.shop/view]
:shop {:items [:apple :orange :banana]}
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop" :disabled true}]}}))
(GET "/shop/:id" [id :as req]
(handle-route
req
{:app-db
(let [shop-item (srv.shop/get-shop-item id)]
{:active-view [::client.shop-item/view]
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop"}
{:title (:name shop-item)
:url (str "/" id)
:disabled true}]
:shop-item shop-item})}))
(GET "*" req
(handle-route
req
{:app-db {:error "I don't know where I am"}
:allow-unauthenticated? true})))
(api-util/wrap-authentication auth-middleware))))<</hydrogen-session?>>
| null | https://raw.githubusercontent.com/gethop-dev/hydrogen.duct-template/34d56aa499af1e673d9587b7da0cca2b126ff106/resources/ssr/ssr/root.clj | clojure | file, You can obtain one at /
(defn- handle-route*
[app-db]
(let [db-id (util/uuid)
result (with-bindings {#'re-frame.db/app-db-id db-id}
(swap! rf.db/db-atoms* assoc db-id app-db)
(gen-html app-db))]
(re-frame.db/clear-app-db db-id)
result))
Look at the solution above. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
{{=<< >>=}}
(ns <<namespace>>.ssr.root
(:require [cognitect.transit :as transit]
[compojure.core :refer [context wrap-routes GET routes]]
[hiccup.util :refer [as-str]]
[hiccup.util :refer [escape-html as-str raw-string]]
[hiccup2.core :refer [html]]
[integrant.core :as ig]
[re-frame.core :as rf]
[re-frame.db :as rf.db]
[<<namespace>>.api.util :as api-util]
[<<namespace>>.client.breadcrumbs :as client.breadcrumbs]
[<<namespace>>.client.home :as client.home]
[<<namespace>>.client.hydrogen-demo.shop :as client.shop]
[<<namespace>>.client.hydrogen-demo.shop-item :as client.shop-item]<<#hydrogen-session?>>
[buddy.auth :refer [authenticated?]]
[<<namespace>>.client.landing :as client.landing]<</hydrogen-session?>>
[<<namespace>>.client.sidebar :as client.sidebar]
[<<namespace>>.client.theme :as client.theme]
[<<namespace>>.client.view :as client.view]
[<<namespace>>.service.shop :as srv.shop]
[<<namespace>>.util :as util]
[<<namespace>>.util.hiccup-parser :as hiccup-parser])
(:import [java.io ByteArrayOutputStream]))
(defonce default-app-db-ba-output-stream-buffer-size 4096)
(defn load-initial-app-db-script [app-db]
(with-open [app-db-output-stream (ByteArrayOutputStream. default-app-db-ba-output-stream-buffer-size)]
(let [app-db-writer (transit/writer app-db-output-stream :json)]
(transit/write app-db-writer app-db)
[:script
(raw-string (format "INITIAL_APP_DB=%s;"
(pr-str (.toString app-db-output-stream))))])))
(defn app
TODO it 's just a modified version of client.cljs 's app . Put it in a cljc namespace
[]
(let [theme (rf/subscribe [::client.theme/get-theme])]
(fn []
[:div.app-container
{:class (str "theme-" (name @theme))}
[client.sidebar/main]
[:div.app-container__main
{:id "app-container__main"}
[client.breadcrumbs/main]
[client.view/main]]])))
(defn- gen-html
[app-db]
(->
[:html {:lang "en"}
[:head
[:meta {:charset "UTF-8"}]
[:meta {:name "viewport" :content "width=device-width, initial-scale=1"}]
[:title <<front-page-title>>]
[:link {:href "-ssl.webflow.com/5a68a8bef9676b00011ad3be/5a8d32501a5b5000018eb866_favicon.png"
:rel "shortcut icon"
:type "image/x-icon"}]
[:link {:href ":400,700" :rel "stylesheet"}]
[:link {:rel "stylesheet" :href "/css/main.css"}]<<#hydrogen-session?>>
[:link {:rel "stylesheet" :href "/css/landing.css"}]<</hydrogen-session?>><<#hydrogen-session-cognito?>>
[:script {:src "-cognito-identity-js@2.0.6/dist/amazon-cognito-identity.min.js"
:integrity "sha256-pYn9Yh/mq4hWZBz8ZKuFWmTWBBAsAwEDx0TjRZHZozc="
:crossorigin "anonymous"}]<</hydrogen-session-cognito?>><<#hydrogen-session-keycloak?>>
[:script {:src "-js@9.0.0/dist/keycloak.min.js"
:integrity "sha256-cKzGXR7XoBTQp5rjJMHgTv72r1ERU266BypryyxzX2I="
:crossorigin "anonymous"}]<</hydrogen-session-keycloak?>>]
[:script "var INITIAL_APP_DB;"]
(some-> app-db (load-initial-app-db-script))
[:body
[:div#app
(hiccup-parser/parse-tag-content
[app])]
[:script {:src "/js/main.js"}]
[:script "<<js-namespace>>.client.init(true);"]]]
(html)
(as-str)))
TODO use 's fork to make it work on multiple threads
(defn- handle-route*
This solution will not work right with multiple clients asking for SSR as they will compete for the same resource .
[app-db]
(reset! rf.db/app-db app-db)
(gen-html app-db))<<^hydrogen-session?>>
(defn- handle-route
[req {:keys [app-db]}]
(handle-route* app-db))
(defmethod ig/init-key :<<namespace>>.ssr/root [_ _]
NOTE : this routes registry needs to be a ONE TO ONE matching in regards to client 's app - routes
(context "/" []
(routes
(GET "/home" req
(handle-route
req
{:app-db
{:active-view [::client.home/view]
:breadcrumbs []}}))
(GET "/shop" req
(handle-route
req
{:appp-db
{:active-view [::client.shop/view]
:shop {:items [:apple :orange :banana]}
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop" :disabled true}]}}))
(GET "/shop/:id" [id :as req]
(handle-route
req
{:app-db
(let [shop-item (srv.shop/get-shop-item id)]
{:active-view [::client.shop-item/view]
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop"}
{:title (:name shop-item)
:url (str "/" id)
:disabled true}]
:shop-item shop-item})}))
(GET "*" req
(handle-route
req
{:app-db {:error "I don't know where I am"}})))))<</hydrogen-session?>><<#hydrogen-session?>>
(defn- handle-route
[req {:keys [app-db allow-unauthenticated? allow-authenticated?]
:or {allow-authenticated? true
allow-unauthenticated? false}}]
(let [authenticated? (buddy.auth/authenticated? req)
authorised? (or (and authenticated? allow-authenticated?)
(and (not authenticated?) allow-unauthenticated?))
app-db (if authorised?
app-db
{:error "Unauthorised"
:active-view [::client.landing/view]})]
(handle-route* app-db)))
(defmethod ig/init-key :<<namespace>>.ssr/root [_ {:keys [auth-middleware]}]
NOTE : this routes registry needs to be a ONE TO ONE matching in regards to client 's app - routes
(context "/" []
(->
(routes
(GET "/home" req
(handle-route
req
{:app-db
{:active-view [::client.home/view]
:breadcrumbs []}}))
(GET "/shop" req
(handle-route
req
{:app-db
{:active-view [::client.shop/view]
:shop {:items [:apple :orange :banana]}
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop" :disabled true}]}}))
(GET "/shop/:id" [id :as req]
(handle-route
req
{:app-db
(let [shop-item (srv.shop/get-shop-item id)]
{:active-view [::client.shop-item/view]
:breadcrumbs [{:title "Home" :url "/home"}
{:title "Shop" :url "/shop"}
{:title (:name shop-item)
:url (str "/" id)
:disabled true}]
:shop-item shop-item})}))
(GET "*" req
(handle-route
req
{:app-db {:error "I don't know where I am"}
:allow-unauthenticated? true})))
(api-util/wrap-authentication auth-middleware))))<</hydrogen-session?>>
|
6c39cd1dcb39c38a227de3125ca3eacee39604994eca711c9ddb9d56b8cd0dbd | johnlawrenceaspden/hobby-code | threads.clj | (import '(java.util.concurrent Executors))
(defn test-stm [nitems nthreads niters]
(let [refs (map ref (replicate nitems 0))
pool (Executors/newFixedThreadPool nthreads)
tasks (map (fn [t]
(fn []
(dotimes [n niters]
(dosync
(doseq [r refs]
(alter r + 1 t))))))
(range nthreads))]
(doseq [future (.invokeAll pool tasks)]
(.get future))
(.shutdown pool)
(map deref refs)))
| null | https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/threads.clj | clojure | (import '(java.util.concurrent Executors))
(defn test-stm [nitems nthreads niters]
(let [refs (map ref (replicate nitems 0))
pool (Executors/newFixedThreadPool nthreads)
tasks (map (fn [t]
(fn []
(dotimes [n niters]
(dosync
(doseq [r refs]
(alter r + 1 t))))))
(range nthreads))]
(doseq [future (.invokeAll pool tasks)]
(.get future))
(.shutdown pool)
(map deref refs)))
| |
a6edb44534bbbd25a03532e359187f758caac3ed560ac86c5ef133bb0abdcbb4 | 0xd34df00d/can-i-haz | Common.hs | # LANGUAGE DeriveGeneric , DeriveAnyClass #
{-# LANGUAGE Strict #-}
module Common where
import Control.DeepSeq
import GHC.Generics
import Control.Monad.Except.CoHas
import Control.Monad.Reader.Has
data FooEnv = FooEnv
{ fooInt :: Int
, fooStr :: String
} deriving (Eq, Ord, Show, Generic, NFData)
data BarEnv = BarEnv
{ barDouble :: Double
, barArr :: [Int]
} deriving (Eq, Ord, Show, Generic, NFData)
data AppEnv = AppEnv
{ fooEnv :: FooEnv
, barEnv :: BarEnv
} deriving (Eq, Ord, Show, Generic, NFData, Has FooEnv, Has BarEnv)
data AppErr = FooEnvErr FooEnv
| BarEnvErr BarEnv
deriving (Eq, Ord, Show, Generic, NFData, CoHas FooEnv, CoHas BarEnv)
| null | https://raw.githubusercontent.com/0xd34df00d/can-i-haz/da27c09b1380ee10b859152d542489bcb6296fed/test/Common.hs | haskell | # LANGUAGE Strict # | # LANGUAGE DeriveGeneric , DeriveAnyClass #
module Common where
import Control.DeepSeq
import GHC.Generics
import Control.Monad.Except.CoHas
import Control.Monad.Reader.Has
data FooEnv = FooEnv
{ fooInt :: Int
, fooStr :: String
} deriving (Eq, Ord, Show, Generic, NFData)
data BarEnv = BarEnv
{ barDouble :: Double
, barArr :: [Int]
} deriving (Eq, Ord, Show, Generic, NFData)
data AppEnv = AppEnv
{ fooEnv :: FooEnv
, barEnv :: BarEnv
} deriving (Eq, Ord, Show, Generic, NFData, Has FooEnv, Has BarEnv)
data AppErr = FooEnvErr FooEnv
| BarEnvErr BarEnv
deriving (Eq, Ord, Show, Generic, NFData, CoHas FooEnv, CoHas BarEnv)
|
d3f7737e68919c68515aae4bd4a382a6f3efe3a6c58fdb260400b53a40a599ca | ijp/guildhall | limited-write.scm | #!r6rs
(library (guildhall ext trc-testing limited-write)
(export limited-write)
(import (rnrs))
(define (write-string s port)
(put-string port s))
Code below taken from scheme48 1.8 , Copyright ( c ) 1993 - 2008
and . Licensed under the new - style BSD license .
(define (limited-write obj port max-depth max-length)
(let recur ((obj obj) (depth 0))
(if (and (= depth max-depth)
(not (or (boolean? obj)
(null? obj)
(number? obj)
(symbol? obj)
(char? obj)
(string? obj))))
(display "#" port)
(call-with-current-continuation
(lambda (escape)
(recurring-write obj port
(let ((count 0))
(lambda (sub)
(if (= count max-length)
(begin (display "---" port)
(write-char
(if (or (pair? obj) (vector? obj))
#\)
#\})
port)
(escape #t))
(begin (set! count (+ count 1))
(recur sub (+ depth 1))))))))))))
(define (recurring-write obj port recur)
(cond ((pair? obj) (write-list obj port recur))
((vector? obj) (write-vector obj port recur))
(else
(write obj port))))
(define (write-list obj port recur)
(cond ((quotation? obj)
(write-char #\' port)
(recur (cadr obj)))
(else
(write-char #\( port)
(recur (car obj))
(let loop ((l (cdr obj))
(n 1))
(cond ((not (pair? l))
(cond ((not (null? l))
(write-string " . " port)
(recur l))))
(else
(write-char #\space port)
(recur (car l))
(loop (cdr l) (+ n 1)))))
(write-char #\) port))))
(define (quotation? obj)
(and (pair? obj)
(eq? (car obj) 'quote)
(pair? (cdr obj))
(null? (cddr obj))))
(define (write-vector obj port recur)
(write-string "#(" port)
(let ((z (vector-length obj)))
(cond ((> z 0)
(recur (vector-ref obj 0))
(let loop ((i 1))
(cond ((>= i z))
(else
(write-char #\space port)
(recur (vector-ref obj i))
(loop (+ i 1))))))))
(write-char #\) port))
)
| null | https://raw.githubusercontent.com/ijp/guildhall/2fe2cc539f4b811bbcd69e58738db03eb5a2b778/guildhall/ext/trc-testing/limited-write.scm | scheme | #!r6rs
(library (guildhall ext trc-testing limited-write)
(export limited-write)
(import (rnrs))
(define (write-string s port)
(put-string port s))
Code below taken from scheme48 1.8 , Copyright ( c ) 1993 - 2008
and . Licensed under the new - style BSD license .
(define (limited-write obj port max-depth max-length)
(let recur ((obj obj) (depth 0))
(if (and (= depth max-depth)
(not (or (boolean? obj)
(null? obj)
(number? obj)
(symbol? obj)
(char? obj)
(string? obj))))
(display "#" port)
(call-with-current-continuation
(lambda (escape)
(recurring-write obj port
(let ((count 0))
(lambda (sub)
(if (= count max-length)
(begin (display "---" port)
(write-char
(if (or (pair? obj) (vector? obj))
#\)
#\})
port)
(escape #t))
(begin (set! count (+ count 1))
(recur sub (+ depth 1))))))))))))
(define (recurring-write obj port recur)
(cond ((pair? obj) (write-list obj port recur))
((vector? obj) (write-vector obj port recur))
(else
(write obj port))))
(define (write-list obj port recur)
(cond ((quotation? obj)
(write-char #\' port)
(recur (cadr obj)))
(else
(write-char #\( port)
(recur (car obj))
(let loop ((l (cdr obj))
(n 1))
(cond ((not (pair? l))
(cond ((not (null? l))
(write-string " . " port)
(recur l))))
(else
(write-char #\space port)
(recur (car l))
(loop (cdr l) (+ n 1)))))
(write-char #\) port))))
(define (quotation? obj)
(and (pair? obj)
(eq? (car obj) 'quote)
(pair? (cdr obj))
(null? (cddr obj))))
(define (write-vector obj port recur)
(write-string "#(" port)
(let ((z (vector-length obj)))
(cond ((> z 0)
(recur (vector-ref obj 0))
(let loop ((i 1))
(cond ((>= i z))
(else
(write-char #\space port)
(recur (vector-ref obj i))
(loop (+ i 1))))))))
(write-char #\) port))
)
| |
cdb4c67e2c027101ee684c1902bfef31075263e59752ebbc7f8570f9b2b038b7 | umutisik/mathvas | AboutSpec.hs | module Handler.AboutSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getAboutR" $ do
error "Spec not implemented: getAboutR"
| null | https://raw.githubusercontent.com/umutisik/mathvas/9f764cd4d54370262c70c7ec3eadae076a1eb489/test/Handler/AboutSpec.hs | haskell | module Handler.AboutSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getAboutR" $ do
error "Spec not implemented: getAboutR"
| |
8a59a48b5433db48b97a2bd1b591214b02f85b076694f189b8a9fcde0749d73d | CryptoKami/cryptokami-core | Message.hs | # LANGUAGE DataKinds #
| Messages used for communication in SSC .
module Pos.Ssc.Message
( MCCommitment (..)
, MCOpening (..)
, MCShares (..)
, MCVssCertificate (..)
, _MCCommitment
, _MCOpening
, _MCShares
, _MCVssCertificate
, HasSscTag (..)
, SscTag (..)
, SscMessageConstraints
) where
import Universum
import Control.Lens (makePrisms)
import Data.Tagged (Tagged)
import qualified Data.Text.Buildable as Buildable
import Formatting (bprint, build, (%))
import Node.Message.Class (Message)
import Pos.Communication.Limits.Types (MessageLimited)
import Pos.Communication.Types.Relay (DataMsg, InvOrData, ReqMsg, ReqOrRes)
import Pos.Core (HasConfiguration, StakeholderId, VssCertificate, addressHash, getCertId)
import Pos.Core.Ssc (InnerSharesMap, Opening, SignedCommitment)
import Pos.Ssc.Toss.Types (SscTag (..))
class HasSscTag a where
toSscTag :: a -> SscTag
data MCCommitment = MCCommitment !SignedCommitment
deriving (Show, Eq, Generic)
data MCOpening = MCOpening !StakeholderId !Opening
deriving (Show, Eq, Generic)
data MCShares = MCShares !StakeholderId !InnerSharesMap
deriving (Show, Eq, Generic)
data MCVssCertificate = MCVssCertificate !VssCertificate
deriving (Show, Eq, Generic)
makePrisms ''MCCommitment
makePrisms ''MCOpening
makePrisms ''MCShares
makePrisms ''MCVssCertificate
instance Buildable MCCommitment where
build (MCCommitment (pk, _, _)) =
bprint ("commitment contents from "%build) $ addressHash pk
instance Buildable MCOpening where
build (MCOpening k _) =
bprint ("opening contents from "%build) k
instance Buildable MCShares where
build (MCShares k _) =
bprint ("shares contents from "%build) k
instance Buildable MCVssCertificate where
build (MCVssCertificate c) =
bprint ("VSS certificate contents from "%build) $ getCertId c
instance HasSscTag MCCommitment where
toSscTag _ = CommitmentMsg
instance HasSscTag MCOpening where
toSscTag _ = OpeningMsg
instance HasSscTag MCShares where
toSscTag _ = SharesMsg
instance HasSscTag MCVssCertificate where
toSscTag _ = VssCertificateMsg
-- TODO: someone who knows networking should take a look because this really
-- doesn't look like something that anyone should ever have to write
type SscMessageConstraints m =
( MessageLimited (DataMsg MCCommitment) m
, MessageLimited (DataMsg MCCommitment) m
, MessageLimited (DataMsg MCOpening) m
, MessageLimited (DataMsg MCShares) m
, MessageLimited (DataMsg MCVssCertificate) m
, Each '[Message]
[ InvOrData (Tagged MCCommitment StakeholderId) MCCommitment
, InvOrData (Tagged MCOpening StakeholderId) MCOpening
, InvOrData (Tagged MCShares StakeholderId) MCShares
, InvOrData (Tagged MCVssCertificate StakeholderId) MCVssCertificate ]
, Each '[Message]
[ ReqMsg (Tagged MCCommitment StakeholderId)
, ReqMsg (Tagged MCOpening StakeholderId)
, ReqMsg (Tagged MCShares StakeholderId)
, ReqMsg (Tagged MCVssCertificate StakeholderId) ]
, Each '[Message]
[ ReqOrRes (Tagged MCCommitment StakeholderId)
, ReqOrRes (Tagged MCOpening StakeholderId)
, ReqOrRes (Tagged MCShares StakeholderId)
, ReqOrRes (Tagged MCVssCertificate StakeholderId) ]
, HasConfiguration
)
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/ssc/Pos/Ssc/Message.hs | haskell | TODO: someone who knows networking should take a look because this really
doesn't look like something that anyone should ever have to write | # LANGUAGE DataKinds #
| Messages used for communication in SSC .
module Pos.Ssc.Message
( MCCommitment (..)
, MCOpening (..)
, MCShares (..)
, MCVssCertificate (..)
, _MCCommitment
, _MCOpening
, _MCShares
, _MCVssCertificate
, HasSscTag (..)
, SscTag (..)
, SscMessageConstraints
) where
import Universum
import Control.Lens (makePrisms)
import Data.Tagged (Tagged)
import qualified Data.Text.Buildable as Buildable
import Formatting (bprint, build, (%))
import Node.Message.Class (Message)
import Pos.Communication.Limits.Types (MessageLimited)
import Pos.Communication.Types.Relay (DataMsg, InvOrData, ReqMsg, ReqOrRes)
import Pos.Core (HasConfiguration, StakeholderId, VssCertificate, addressHash, getCertId)
import Pos.Core.Ssc (InnerSharesMap, Opening, SignedCommitment)
import Pos.Ssc.Toss.Types (SscTag (..))
class HasSscTag a where
toSscTag :: a -> SscTag
data MCCommitment = MCCommitment !SignedCommitment
deriving (Show, Eq, Generic)
data MCOpening = MCOpening !StakeholderId !Opening
deriving (Show, Eq, Generic)
data MCShares = MCShares !StakeholderId !InnerSharesMap
deriving (Show, Eq, Generic)
data MCVssCertificate = MCVssCertificate !VssCertificate
deriving (Show, Eq, Generic)
makePrisms ''MCCommitment
makePrisms ''MCOpening
makePrisms ''MCShares
makePrisms ''MCVssCertificate
instance Buildable MCCommitment where
build (MCCommitment (pk, _, _)) =
bprint ("commitment contents from "%build) $ addressHash pk
instance Buildable MCOpening where
build (MCOpening k _) =
bprint ("opening contents from "%build) k
instance Buildable MCShares where
build (MCShares k _) =
bprint ("shares contents from "%build) k
instance Buildable MCVssCertificate where
build (MCVssCertificate c) =
bprint ("VSS certificate contents from "%build) $ getCertId c
instance HasSscTag MCCommitment where
toSscTag _ = CommitmentMsg
instance HasSscTag MCOpening where
toSscTag _ = OpeningMsg
instance HasSscTag MCShares where
toSscTag _ = SharesMsg
instance HasSscTag MCVssCertificate where
toSscTag _ = VssCertificateMsg
type SscMessageConstraints m =
( MessageLimited (DataMsg MCCommitment) m
, MessageLimited (DataMsg MCCommitment) m
, MessageLimited (DataMsg MCOpening) m
, MessageLimited (DataMsg MCShares) m
, MessageLimited (DataMsg MCVssCertificate) m
, Each '[Message]
[ InvOrData (Tagged MCCommitment StakeholderId) MCCommitment
, InvOrData (Tagged MCOpening StakeholderId) MCOpening
, InvOrData (Tagged MCShares StakeholderId) MCShares
, InvOrData (Tagged MCVssCertificate StakeholderId) MCVssCertificate ]
, Each '[Message]
[ ReqMsg (Tagged MCCommitment StakeholderId)
, ReqMsg (Tagged MCOpening StakeholderId)
, ReqMsg (Tagged MCShares StakeholderId)
, ReqMsg (Tagged MCVssCertificate StakeholderId) ]
, Each '[Message]
[ ReqOrRes (Tagged MCCommitment StakeholderId)
, ReqOrRes (Tagged MCOpening StakeholderId)
, ReqOrRes (Tagged MCShares StakeholderId)
, ReqOrRes (Tagged MCVssCertificate StakeholderId) ]
, HasConfiguration
)
|
9d67f0fa580b29e52c1b5951256f7d2f2fdf0700c318c8eb6ee7de54fd959401 | mlabs-haskell/bot-plutus-interface | Main.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE TemplateHaskell #
module Main (main) where
import BotPlutusInterface qualified
import BotPlutusInterface.Config qualified as BotPlutusInterface
import BotPlutusInterface.Types (
HasDefinitions (..),
SomeBuiltin (..),
endpointsToSchemas,
)
import Cardano.PlutusExample.NFT
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Playground.Types (FunctionSchema)
import Schema (FormSchema)
import Prelude
instance HasDefinitions MintNFTContracts where
getDefinitions :: [MintNFTContracts]
getDefinitions = []
getSchema :: MintNFTContracts -> [FunctionSchema FormSchema]
getSchema _ = endpointsToSchemas @NFTSchema
getContract :: (MintNFTContracts -> SomeBuiltin)
getContract = \case
MintNFT p ->
SomeBuiltin $
mintNft p
newtype MintNFTContracts = MintNFT MintParams
deriving stock (Show)
$(deriveJSON defaultOptions ''MintNFTContracts)
main :: IO ()
main = do
pabConf <-
either error id
<$> BotPlutusInterface.loadPABConfig "./pabConfig.value"
BotPlutusInterface.runPAB @MintNFTContracts pabConf
| null | https://raw.githubusercontent.com/mlabs-haskell/bot-plutus-interface/1ab405a131c4dea2fbc85873da38f85b7a08e229/examples/plutus-nft/app/Main.hs | haskell | # LANGUAGE DeriveAnyClass # | # LANGUAGE TemplateHaskell #
module Main (main) where
import BotPlutusInterface qualified
import BotPlutusInterface.Config qualified as BotPlutusInterface
import BotPlutusInterface.Types (
HasDefinitions (..),
SomeBuiltin (..),
endpointsToSchemas,
)
import Cardano.PlutusExample.NFT
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Playground.Types (FunctionSchema)
import Schema (FormSchema)
import Prelude
instance HasDefinitions MintNFTContracts where
getDefinitions :: [MintNFTContracts]
getDefinitions = []
getSchema :: MintNFTContracts -> [FunctionSchema FormSchema]
getSchema _ = endpointsToSchemas @NFTSchema
getContract :: (MintNFTContracts -> SomeBuiltin)
getContract = \case
MintNFT p ->
SomeBuiltin $
mintNft p
newtype MintNFTContracts = MintNFT MintParams
deriving stock (Show)
$(deriveJSON defaultOptions ''MintNFTContracts)
main :: IO ()
main = do
pabConf <-
either error id
<$> BotPlutusInterface.loadPABConfig "./pabConfig.value"
BotPlutusInterface.runPAB @MintNFTContracts pabConf
|
2de546a966563b557125e80c4243a819cc12ea73497af27e9e414ad3ac3cd1e1 | sharplispers/montezuma | tc-multiple-term-doc-pos-enum.lisp | (in-package #:montezuma)
(deftestfixture multiple-term-doc-pos-enum
(:vars ir dir)
(:setup
(let* ((dir (make-instance 'ram-directory))
(iw (make-instance 'index-writer
:directory dir
:analyzer (make-instance 'whitespace-analyzer)
:create-if-missing-p T))
(documents (index-test-helper-prepare-search-docs)))
(setf (fixture-var 'dir) dir
(fixture-var 'documents) documents)
(dosequence (doc documents)
(add-document-to-index-writer iw doc))
(close iw)
(setf (fixture-var 'ir) (open-index-reader dir :close-directory-p T))))
(:teardown
(close (fixture-var 'ir)))
(:testfun test-mtdpe
(let ((t1 (make-term "field" "red"))
(t2 (make-term "field" "brown"))
(t3 (make-term "field" "hairy")))
(let ((mtdpe (make-instance 'multiple-term-doc-pos-enum
:reader (fixture-var 'ir)
:terms (list t1 t2 t3))))
(test mtdpe-1 (next? mtdpe) T #'bool=)
(test mtdpe-2 (doc mtdpe) 1)
(test mtdpe-3 (freq mtdpe) 1)
(test mtdpe-4 (next-position mtdpe) 4)
(test mtdpe-5 (next? mtdpe) T #'bool=)
(test mtdpe-6 (doc mtdpe) 8)
(test mtdpe-7 (freq mtdpe) 1)
(test mtdpe-8 (next-position mtdpe) 5)
(test mtdpe-9 (next? mtdpe) T #'bool=)
(test mtdpe-10 (doc mtdpe) 11)
(test mtdpe-11 (freq mtdpe) 1)
(test mtdpe-12 (next-position mtdpe) 4)
(test mtdpe-13 (next? mtdpe) T #'bool=)
(test mtdpe-14 (doc mtdpe) 14)
(test mtdpe-15 (freq mtdpe) 1)
(test mtdpe-16 (next-position mtdpe) 4)
(test mtdpe-17 (next? mtdpe) T #'bool=)
(test mtdpe-18 (doc mtdpe) 16)
(test mtdpe-19 (freq mtdpe) 3)
(test mtdpe-20 (next-position mtdpe) 5)
(test mtdpe-21 (next-position mtdpe) 7)
(test mtdpe-22 (next-position mtdpe) 11)
(test mtdpe-23 (next? mtdpe) T #'bool=)
(test mtdpe-24 (doc mtdpe) 17)
(test mtdpe-25 (freq mtdpe) 2)
(test mtdpe-26 (next-position mtdpe) 2)
(test mtdpe-27 (next-position mtdpe) 7)
(test mtdpe-28 (next? mtdpe) NIL #'bool=)
(close mtdpe))))
)
| null | https://raw.githubusercontent.com/sharplispers/montezuma/ee2129eece7065760de4ebbaeffaadcb27644738/tests/unit/index/tc-multiple-term-doc-pos-enum.lisp | lisp | (in-package #:montezuma)
(deftestfixture multiple-term-doc-pos-enum
(:vars ir dir)
(:setup
(let* ((dir (make-instance 'ram-directory))
(iw (make-instance 'index-writer
:directory dir
:analyzer (make-instance 'whitespace-analyzer)
:create-if-missing-p T))
(documents (index-test-helper-prepare-search-docs)))
(setf (fixture-var 'dir) dir
(fixture-var 'documents) documents)
(dosequence (doc documents)
(add-document-to-index-writer iw doc))
(close iw)
(setf (fixture-var 'ir) (open-index-reader dir :close-directory-p T))))
(:teardown
(close (fixture-var 'ir)))
(:testfun test-mtdpe
(let ((t1 (make-term "field" "red"))
(t2 (make-term "field" "brown"))
(t3 (make-term "field" "hairy")))
(let ((mtdpe (make-instance 'multiple-term-doc-pos-enum
:reader (fixture-var 'ir)
:terms (list t1 t2 t3))))
(test mtdpe-1 (next? mtdpe) T #'bool=)
(test mtdpe-2 (doc mtdpe) 1)
(test mtdpe-3 (freq mtdpe) 1)
(test mtdpe-4 (next-position mtdpe) 4)
(test mtdpe-5 (next? mtdpe) T #'bool=)
(test mtdpe-6 (doc mtdpe) 8)
(test mtdpe-7 (freq mtdpe) 1)
(test mtdpe-8 (next-position mtdpe) 5)
(test mtdpe-9 (next? mtdpe) T #'bool=)
(test mtdpe-10 (doc mtdpe) 11)
(test mtdpe-11 (freq mtdpe) 1)
(test mtdpe-12 (next-position mtdpe) 4)
(test mtdpe-13 (next? mtdpe) T #'bool=)
(test mtdpe-14 (doc mtdpe) 14)
(test mtdpe-15 (freq mtdpe) 1)
(test mtdpe-16 (next-position mtdpe) 4)
(test mtdpe-17 (next? mtdpe) T #'bool=)
(test mtdpe-18 (doc mtdpe) 16)
(test mtdpe-19 (freq mtdpe) 3)
(test mtdpe-20 (next-position mtdpe) 5)
(test mtdpe-21 (next-position mtdpe) 7)
(test mtdpe-22 (next-position mtdpe) 11)
(test mtdpe-23 (next? mtdpe) T #'bool=)
(test mtdpe-24 (doc mtdpe) 17)
(test mtdpe-25 (freq mtdpe) 2)
(test mtdpe-26 (next-position mtdpe) 2)
(test mtdpe-27 (next-position mtdpe) 7)
(test mtdpe-28 (next? mtdpe) NIL #'bool=)
(close mtdpe))))
)
| |
6bffb44188df9db26774787fcc4bd3ed35d948501a423c64b9acef7e9a66c065 | kelsey-sorrels/robinson | renderutil.clj | ;; Utility functions for rendering state
(ns robinson.renderutil
(:require
[taoensso.timbre :as log]
[robinson.random :as rr]
[robinson.math :as rmath]
[robinson.color :as rcolor]))
(def items
{:knife [\)]
:obsidian-knife [\)]
:obsidian-axe [\)]
:obsidian-spear [\)]
:flint-knife [\)]
:flint-axe [\)]
:flint-spear [\)]
:sharpened-stick [\)]
:plant-fiber [\,]
:sword [\)]
:armor [\[]
:shoes [\!]
:fishing-pole [\/]
:match [\/]
:lantern [\,]
:bandage [\&]
:saw [\,]
:tarp [\,]
:tarp-corner [\| :brown :transparent :screen]
:tarp-hung [\▓ :blue :transparent :screen]
:tarp-hung-mid [\▓ :brilliant-blue :transparent :screen]
:tarp-hung-corner [\▓ :blue]
:sail-corner [\| :brown :transparent :screen]
:sail-hung [\▓ :gray :transparent :screen]
:sail-hung-mid [\▓ :light-gray :transparent :screen]
:sail-hung-corner [\▓ :gray]
:spellbook [\+]
:scroll [\?]
:rock [\*]
:obsidian [\*]
:coconut [\* :brown]
:unhusked-coconut
[\* :brown]
:empty-coconut [\* :brown]
:red-fruit [\* :red]
:orange-fruit [\* :orange]
:yellow-fruit [\* :yellow]
:green-fruit [\* :green]
:blue-fruit [\* :blue]
:purple-fruit [\* :purple]
:white-fruit [\* :white]
:black-fruit [\* :gray]
:bamboo [\/ :light-green]
:stick [\/ :brown]
:grass [\/ :green]
:rope [\, :green]
:log [\/ :brown]
:bedroll [\▓ :dark-green :dark-beige]
:$ [\$ :yellow]
:amulet [\" :blue]
:food [\%]
:fire-plough [\,]
:hand-drill [\,]
:bow-drill [\,]
:jack-o-lantern [\☻ :orange :black]
:door [\+]
pirate ship ite\s
:spices [\^]
:sail [\#]
:dice [\&]
:blanket [\#]
:cup [\&]
:silver-bar [\$]
:bowl [\&]
:fork [\/]
:spoon [\/]
:rag [\#]
:cutlass [\)]
:pistol [\)]
:paper-cartridge [\&]
:ale [\!]
:pirate-clothes [\[]
:navy-uniform [\[]
;; ruined temple items
:blowdart [\-]
:jewlery [\"]
:statue [\&]
:human-skull [\☻ :white]
:gong [\&]
:stone-tablet [\&]
:robe [\[]
:codex [\&]})
(defn item->char
[item]
(let [item-char-fg-bg (get items
(or (item :type)
(item :item/id)))]
(when-not item-char-fg-bg
(log/info item))
(or (first item-char-fg-bg) \?)))
(defn item->fg
[item]
(let [item-char-fg-bg (get items (or (item :type)
(item :item/id)))]
(or (second item-char-fg-bg)
:white)))
(defn item->bg
[item]
(let [[_ _ bg _] (get items (or (item :type)
(item :item/id)))]
(or bg
:black)))
(defn item->blend-mode
[item]
(let [[_ _ _ blend-mode](get items (or (item :type)
(item :item/id)))]
(or blend-mode
:normal)))
| null | https://raw.githubusercontent.com/kelsey-sorrels/robinson/337fd2646882708331257d1f3db78a3074ccc67a/src/robinson/renderutil.clj | clojure | Utility functions for rendering state
ruined temple items | (ns robinson.renderutil
(:require
[taoensso.timbre :as log]
[robinson.random :as rr]
[robinson.math :as rmath]
[robinson.color :as rcolor]))
(def items
{:knife [\)]
:obsidian-knife [\)]
:obsidian-axe [\)]
:obsidian-spear [\)]
:flint-knife [\)]
:flint-axe [\)]
:flint-spear [\)]
:sharpened-stick [\)]
:plant-fiber [\,]
:sword [\)]
:armor [\[]
:shoes [\!]
:fishing-pole [\/]
:match [\/]
:lantern [\,]
:bandage [\&]
:saw [\,]
:tarp [\,]
:tarp-corner [\| :brown :transparent :screen]
:tarp-hung [\▓ :blue :transparent :screen]
:tarp-hung-mid [\▓ :brilliant-blue :transparent :screen]
:tarp-hung-corner [\▓ :blue]
:sail-corner [\| :brown :transparent :screen]
:sail-hung [\▓ :gray :transparent :screen]
:sail-hung-mid [\▓ :light-gray :transparent :screen]
:sail-hung-corner [\▓ :gray]
:spellbook [\+]
:scroll [\?]
:rock [\*]
:obsidian [\*]
:coconut [\* :brown]
:unhusked-coconut
[\* :brown]
:empty-coconut [\* :brown]
:red-fruit [\* :red]
:orange-fruit [\* :orange]
:yellow-fruit [\* :yellow]
:green-fruit [\* :green]
:blue-fruit [\* :blue]
:purple-fruit [\* :purple]
:white-fruit [\* :white]
:black-fruit [\* :gray]
:bamboo [\/ :light-green]
:stick [\/ :brown]
:grass [\/ :green]
:rope [\, :green]
:log [\/ :brown]
:bedroll [\▓ :dark-green :dark-beige]
:$ [\$ :yellow]
:amulet [\" :blue]
:food [\%]
:fire-plough [\,]
:hand-drill [\,]
:bow-drill [\,]
:jack-o-lantern [\☻ :orange :black]
:door [\+]
pirate ship ite\s
:spices [\^]
:sail [\#]
:dice [\&]
:blanket [\#]
:cup [\&]
:silver-bar [\$]
:bowl [\&]
:fork [\/]
:spoon [\/]
:rag [\#]
:cutlass [\)]
:pistol [\)]
:paper-cartridge [\&]
:ale [\!]
:pirate-clothes [\[]
:navy-uniform [\[]
:blowdart [\-]
:jewlery [\"]
:statue [\&]
:human-skull [\☻ :white]
:gong [\&]
:stone-tablet [\&]
:robe [\[]
:codex [\&]})
(defn item->char
[item]
(let [item-char-fg-bg (get items
(or (item :type)
(item :item/id)))]
(when-not item-char-fg-bg
(log/info item))
(or (first item-char-fg-bg) \?)))
(defn item->fg
[item]
(let [item-char-fg-bg (get items (or (item :type)
(item :item/id)))]
(or (second item-char-fg-bg)
:white)))
(defn item->bg
[item]
(let [[_ _ bg _] (get items (or (item :type)
(item :item/id)))]
(or bg
:black)))
(defn item->blend-mode
[item]
(let [[_ _ _ blend-mode](get items (or (item :type)
(item :item/id)))]
(or blend-mode
:normal)))
|
637ddeb82ae8f29088b5bfde75f522f83639b3c97fa96b2a2cc4884009b9f1dd | scrintal/heroicons-reagent | folder_open.cljs | (ns com.scrintal.heroicons.solid.folder-open)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M19.906 9c.382 0 .749.057 1.094.162V9a3 3 0 00-3-3h-3.879a.75.75 0 01-.53-.22L11.47 3.66A2.25 2.25 0 009.879 3H6a3 3 0 00-3 3v3.162A3.756 3.756 0 014.094 9h15.812zM4.094 10.5a2.25 2.25 0 00-2.227 2.568l.857 6A2.25 2.25 0 004.951 21H19.05a2.25 2.25 0 002.227-1.932l.857-6a2.25 2.25 0 00-2.227-2.568H4.094z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/folder_open.cljs | clojure | (ns com.scrintal.heroicons.solid.folder-open)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:d "M19.906 9c.382 0 .749.057 1.094.162V9a3 3 0 00-3-3h-3.879a.75.75 0 01-.53-.22L11.47 3.66A2.25 2.25 0 009.879 3H6a3 3 0 00-3 3v3.162A3.756 3.756 0 014.094 9h15.812zM4.094 10.5a2.25 2.25 0 00-2.227 2.568l.857 6A2.25 2.25 0 004.951 21H19.05a2.25 2.25 0 002.227-1.932l.857-6a2.25 2.25 0 00-2.227-2.568H4.094z"}]]) | |
cd3795dee0f064cff2a8533e7fe63171508778ab86a027989778d5511a8ec116 | imandra-ai/catapult | catapult.ml | * - based tracing .
A nice profiling format based on json , useful for visualizing what goes on .
This library is the instrumentation part ; see catapult - client , catapult - file ,
or use a custom { ! BACKEND } to actually record traces .
If a trace is obtained in , say , the file " trace.json.gz " , it
can be opened in
chrome / chromium at " chrome " .
{ { : } can import ( uncompressed )
trace files with a nice native trace explorer .
See { { : -PhYUmn5OOQtYMH4h6I0nSsKchNAySU/ }
the documentation of TEF }
A nice profiling format based on json, useful for visualizing what goes on.
This library is the instrumentation part; see catapult-client, catapult-file,
or use a custom {!BACKEND} to actually record traces.
If a trace is obtained in, say, the file "trace.json.gz", it
can be opened in
chrome/chromium at "chrome".
{{: } Tracy} can import (uncompressed)
trace files with a nice native trace explorer.
See {{: -PhYUmn5OOQtYMH4h6I0nSsKchNAySU/}
the documentation of TEF}
*)
module type BACKEND = Backend.S
module type IMPL = Impl.S
module Event_type = Event_type
module Arg = Arg
module Tracing = Tracing
module Nil_impl = Nil_impl
module Control = Tracing.Control
module Endpoint_address = Endpoint_address
module Ser = Ser
(**/**)
module Atomic_shim_ = Atomic_shim_
module Bare_encoding = Bare_encoding
module Clock = Clock
(**/**)
| null | https://raw.githubusercontent.com/imandra-ai/catapult/4bc5444a8471c5d0d7cb9a376a5a895c0ab042e6/src/core/catapult.ml | ocaml | */*
*/* | * - based tracing .
A nice profiling format based on json , useful for visualizing what goes on .
This library is the instrumentation part ; see catapult - client , catapult - file ,
or use a custom { ! BACKEND } to actually record traces .
If a trace is obtained in , say , the file " trace.json.gz " , it
can be opened in
chrome / chromium at " chrome " .
{ { : } can import ( uncompressed )
trace files with a nice native trace explorer .
See { { : -PhYUmn5OOQtYMH4h6I0nSsKchNAySU/ }
the documentation of TEF }
A nice profiling format based on json, useful for visualizing what goes on.
This library is the instrumentation part; see catapult-client, catapult-file,
or use a custom {!BACKEND} to actually record traces.
If a trace is obtained in, say, the file "trace.json.gz", it
can be opened in
chrome/chromium at "chrome".
{{: } Tracy} can import (uncompressed)
trace files with a nice native trace explorer.
See {{: -PhYUmn5OOQtYMH4h6I0nSsKchNAySU/}
the documentation of TEF}
*)
module type BACKEND = Backend.S
module type IMPL = Impl.S
module Event_type = Event_type
module Arg = Arg
module Tracing = Tracing
module Nil_impl = Nil_impl
module Control = Tracing.Control
module Endpoint_address = Endpoint_address
module Ser = Ser
module Atomic_shim_ = Atomic_shim_
module Bare_encoding = Bare_encoding
module Clock = Clock
|
613d3c714ab4c6bd6a84aa2b3d41eb05be2114909afd447cfc5f7907ce270aeb | Denommus/monadic | result.mli | module MakeT : functor
(Wrapped : Monad.MONAD)
(E : sig
type t
end)
-> sig
type e = E.t
include
Monad.MAKE_T
with type 'a wrapped := 'a Wrapped.t
with type 'a actual_t := ('a, e) result Wrapped.t
val error : e -> 'a t
val ok : 'a -> 'a t
end
with type 'a t = ('a, E.t) result Wrapped.t
module Make : functor
(E : sig
type t
end)
-> sig
type e = E.t
include
Monad.MAKE_T
with type 'a wrapped := 'a
with type 'a actual_t := ('a, e) result
val error : e -> 'a t
val ok : 'a -> 'a t
end
with type 'a t = ('a, E.t) result
module MakePlusT : functor (Wrapped : Monad.MONAD) (E : Monad.MONOID) -> sig
type e = E.t
include
Monad.MAKE_PLUS_T
with type 'a wrapped := 'a Wrapped.t
with type 'a actual_t := ('a, e) result Wrapped.t
val error : e -> 'a t
val ok : 'a -> 'a t
end
module MakePlus : functor (E : Monad.MONOID) -> sig
type e = E.t
include
Monad.MAKE_PLUS_T
with type 'a wrapped := 'a
with type 'a actual_t := ('a, e) result
val run : 'a t -> ('a, e) result
val create : ('a, e) result -> 'a t
val error : e -> 'a t
val ok : 'a -> 'a t
end
| null | https://raw.githubusercontent.com/Denommus/monadic/7cbf9b309800303665a6712a9b57c1d9c66e75b8/library/result.mli | ocaml | module MakeT : functor
(Wrapped : Monad.MONAD)
(E : sig
type t
end)
-> sig
type e = E.t
include
Monad.MAKE_T
with type 'a wrapped := 'a Wrapped.t
with type 'a actual_t := ('a, e) result Wrapped.t
val error : e -> 'a t
val ok : 'a -> 'a t
end
with type 'a t = ('a, E.t) result Wrapped.t
module Make : functor
(E : sig
type t
end)
-> sig
type e = E.t
include
Monad.MAKE_T
with type 'a wrapped := 'a
with type 'a actual_t := ('a, e) result
val error : e -> 'a t
val ok : 'a -> 'a t
end
with type 'a t = ('a, E.t) result
module MakePlusT : functor (Wrapped : Monad.MONAD) (E : Monad.MONOID) -> sig
type e = E.t
include
Monad.MAKE_PLUS_T
with type 'a wrapped := 'a Wrapped.t
with type 'a actual_t := ('a, e) result Wrapped.t
val error : e -> 'a t
val ok : 'a -> 'a t
end
module MakePlus : functor (E : Monad.MONOID) -> sig
type e = E.t
include
Monad.MAKE_PLUS_T
with type 'a wrapped := 'a
with type 'a actual_t := ('a, e) result
val run : 'a t -> ('a, e) result
val create : ('a, e) result -> 'a t
val error : e -> 'a t
val ok : 'a -> 'a t
end
| |
93e5e83e17cdbb2d09cbcc2d14957810da2d1010afaec5869240c525eb84289e | anik545/OwlPPL | eval_complexity.ml | open Ppl
open Core
let root_dir = "/home/anik/Files/work/project/diss/data/perf/by_datasize"
let string_of_float f = sprintf "%.15f" f
let print_2d arr =
Array.iter
~f:(fun r ->
Array.iter ~f:(printf "%f,") r;
printf "\n")
arr
(* save a string matrix (2d array) as a csv file *)
let write_to_csv ~fname data =
let oc = Out_channel.create (sprintf "%s/%s" root_dir fname) in
Array.iter data ~f:(fun line ->
fprintf oc "%s" @@ String.concat ~sep:"," (Array.to_list line);
fprintf oc "\n");
Out_channel.close oc
let x_vals = Owl.Arr.(to_array (logspace ~base:10. 2. 4. 5))
let use_model m i () =
printf "doing model\n%!";
let n = 1000 in
let inf = infer m i in
let x = take_k_samples n inf in
x
let by_particles model inf =
let open Owl.Arr in
let header = [| "n"; print_infer_strat_short (inf 0) |] in
let particles = logspace ~base:10. 2. 4. 5 in
let x =
map
(fun n ->
printf "n: %f\n" n;
snd @@ time (use_model model (inf (int_of_float n))))
particles
|> to_array
|> Array.map ~f:string_of_float
in
let pstrs = Array.map ~f:string_of_float (to_array particles) in
Array.append [| header |] (Array.transpose_exn @@ [| x; pstrs |])
let map_2d arr ~f = Array.map arr ~f:(fun a -> Array.map a ~f)
(* generate data to condition on, memoise to ensure same lists are used *)
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
let by_data_length_linreg () =
(* lengths of data *)
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. 20 in
let infs = [| Rejection (100, Soft); Importance 100; MH 500; SMC 50 |] in
let header =
Array.append [| "n" |] (Array.map infs ~f:print_infer_strat_short)
in
(* generate data to condition on, memoise to ensure same lists are used *)
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
in
let model : (float * float) list -> (float * float * float) dist =
Models.linreg
in
let d =
Array.map infs ~f:(fun inf_strat ->
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n"
(print_infer_strat_short inf_strat)
n;
snd
@@ time (use_model (model (list_gen (int_of_float n))) inf_strat)))
in
let data = Array.transpose_exn @@ Array.append [| ns |] d in
Array.append [| header |] (map_2d data ~f:string_of_float)
let by_data_length_linreg_single_inf ?(num_times = 3) ?(num_x = 20) inf :
string array array =
(* lengths of data *)
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. num_x in
let header = [| "n"; print_infer_strat_short inf; "err" |] in
(* generate data to condition on, memoise to ensure same lists are used *)
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
in
let model : (float * float) list -> (float * float * float) dist =
Models.linreg
in
let mean_std_of_times n f =
let arr = Array.init n ~f:(fun _ -> snd @@ time f) in
let mean = Owl_stats.mean arr in
[| mean; 1.96 *. Owl_stats.std ~mean arr |]
in
let d =
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n" (print_infer_strat_short inf) n;
let f = use_model (model (list_gen (int_of_float n))) inf in
mean_std_of_times num_times f)
in
(print_2d @@ Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d));
let data = Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d) in
Array.append [| header |] (map_2d data ~f:string_of_float)
let by_data_length_dpmm_single_inf ?(num_times = 3) ?(num_x = 20) inf :
string array array =
(* lengths of data *)
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. num_x in
let header = [| "n"; print_infer_strat_short inf; "err" |] in
(* generate data to condition on, memoise to ensure same lists are used *)
let list_gen =
memo (fun n -> List.init n ~f:(fun _ -> Owl_stats.uniform_rvs ~a:0. ~b:10.))
in
let model : float list -> (float * float) list dist =
Models.cluster_parameters
in
let mean_std_of_times n f =
let arr = Array.init n ~f:(fun _ -> snd @@ time f) in
let mean = Owl_stats.mean arr in
[| mean; 1.96 *. Owl_stats.std ~mean arr |]
in
let d =
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n" (print_infer_strat_short inf) n;
let f = use_model (model (list_gen (int_of_float n))) inf in
mean_std_of_times num_times f)
in
(print_2d @@ Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d));
let data = Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d) in
Array.append [| header |] (map_2d data ~f:string_of_float)
let mh, imp, rej, smc, pc, pimh =
(MH 500, Importance 50, Rejection (100, Soft), SMC 50, PC 10, PIMH 10)
let str_to_inf = function
| "mh" -> mh
| "imp" -> imp
| "rej" -> rej
| "smc" -> smc
| "pc" -> pc
| "pimh" -> pimh
| s -> failwith (s ^ " is not an inference method")
let infs =
if Array.length @@ Sys.get_argv () > 1 then
Array.sub (Sys.get_argv ()) ~pos:1 ~len:(Array.length (Sys.get_argv ()) - 1)
|> Array.map ~f:str_to_inf
else [| mh; rej; imp; smc |]
let _ =
~f:(fun inf - >
by_data_length_linreg_single_inf inf ~num_times:10
| > write_to_csv
~fname :
( " linreg_by_data_length _ " ^ print_infer_strat_short ^ " .csv " ) )
Array.map infs ~f:(fun inf ->
by_data_length_linreg_single_inf inf ~num_times:10
|> write_to_csv
~fname:
("linreg_by_data_length_" ^ print_infer_strat_short inf ^ ".csv")) *)
let _ =
Array.map infs ~f:(fun inf ->
by_data_length_dpmm_single_inf inf ~num_times:2
|> write_to_csv
~fname:("dpmm_by_data_length_" ^ print_infer_strat_short inf ^ ".csv"))
| null | https://raw.githubusercontent.com/anik545/OwlPPL/ad650219769d5f32564cc771d63c9a52289043a5/ppl/test/eval_complexity.ml | ocaml | save a string matrix (2d array) as a csv file
generate data to condition on, memoise to ensure same lists are used
lengths of data
generate data to condition on, memoise to ensure same lists are used
lengths of data
generate data to condition on, memoise to ensure same lists are used
lengths of data
generate data to condition on, memoise to ensure same lists are used | open Ppl
open Core
let root_dir = "/home/anik/Files/work/project/diss/data/perf/by_datasize"
let string_of_float f = sprintf "%.15f" f
let print_2d arr =
Array.iter
~f:(fun r ->
Array.iter ~f:(printf "%f,") r;
printf "\n")
arr
let write_to_csv ~fname data =
let oc = Out_channel.create (sprintf "%s/%s" root_dir fname) in
Array.iter data ~f:(fun line ->
fprintf oc "%s" @@ String.concat ~sep:"," (Array.to_list line);
fprintf oc "\n");
Out_channel.close oc
let x_vals = Owl.Arr.(to_array (logspace ~base:10. 2. 4. 5))
let use_model m i () =
printf "doing model\n%!";
let n = 1000 in
let inf = infer m i in
let x = take_k_samples n inf in
x
let by_particles model inf =
let open Owl.Arr in
let header = [| "n"; print_infer_strat_short (inf 0) |] in
let particles = logspace ~base:10. 2. 4. 5 in
let x =
map
(fun n ->
printf "n: %f\n" n;
snd @@ time (use_model model (inf (int_of_float n))))
particles
|> to_array
|> Array.map ~f:string_of_float
in
let pstrs = Array.map ~f:string_of_float (to_array particles) in
Array.append [| header |] (Array.transpose_exn @@ [| x; pstrs |])
let map_2d arr ~f = Array.map arr ~f:(fun a -> Array.map a ~f)
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
let by_data_length_linreg () =
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. 20 in
let infs = [| Rejection (100, Soft); Importance 100; MH 500; SMC 50 |] in
let header =
Array.append [| "n" |] (Array.map infs ~f:print_infer_strat_short)
in
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
in
let model : (float * float) list -> (float * float * float) dist =
Models.linreg
in
let d =
Array.map infs ~f:(fun inf_strat ->
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n"
(print_infer_strat_short inf_strat)
n;
snd
@@ time (use_model (model (list_gen (int_of_float n))) inf_strat)))
in
let data = Array.transpose_exn @@ Array.append [| ns |] d in
Array.append [| header |] (map_2d data ~f:string_of_float)
let by_data_length_linreg_single_inf ?(num_times = 3) ?(num_x = 20) inf :
string array array =
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. num_x in
let header = [| "n"; print_infer_strat_short inf; "err" |] in
let list_gen =
memo (fun n ->
List.init n ~f:(fun n ->
let n = float_of_int n in
(n, (n *. 2.) +. 1.)))
in
let model : (float * float) list -> (float * float * float) dist =
Models.linreg
in
let mean_std_of_times n f =
let arr = Array.init n ~f:(fun _ -> snd @@ time f) in
let mean = Owl_stats.mean arr in
[| mean; 1.96 *. Owl_stats.std ~mean arr |]
in
let d =
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n" (print_infer_strat_short inf) n;
let f = use_model (model (list_gen (int_of_float n))) inf in
mean_std_of_times num_times f)
in
(print_2d @@ Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d));
let data = Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d) in
Array.append [| header |] (map_2d data ~f:string_of_float)
let by_data_length_dpmm_single_inf ?(num_times = 3) ?(num_x = 20) inf :
string array array =
let ns = Owl.Arr.to_array @@ Owl.Arr.linspace 1. 10000. num_x in
let header = [| "n"; print_infer_strat_short inf; "err" |] in
let list_gen =
memo (fun n -> List.init n ~f:(fun _ -> Owl_stats.uniform_rvs ~a:0. ~b:10.))
in
let model : float list -> (float * float) list dist =
Models.cluster_parameters
in
let mean_std_of_times n f =
let arr = Array.init n ~f:(fun _ -> snd @@ time f) in
let mean = Owl_stats.mean arr in
[| mean; 1.96 *. Owl_stats.std ~mean arr |]
in
let d =
Array.map ns ~f:(fun n ->
printf "inf: %s, datasize: %f\n" (print_infer_strat_short inf) n;
let f = use_model (model (list_gen (int_of_float n))) inf in
mean_std_of_times num_times f)
in
(print_2d @@ Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d));
let data = Array.(transpose_exn @@ append [| ns |] @@ transpose_exn d) in
Array.append [| header |] (map_2d data ~f:string_of_float)
let mh, imp, rej, smc, pc, pimh =
(MH 500, Importance 50, Rejection (100, Soft), SMC 50, PC 10, PIMH 10)
let str_to_inf = function
| "mh" -> mh
| "imp" -> imp
| "rej" -> rej
| "smc" -> smc
| "pc" -> pc
| "pimh" -> pimh
| s -> failwith (s ^ " is not an inference method")
let infs =
if Array.length @@ Sys.get_argv () > 1 then
Array.sub (Sys.get_argv ()) ~pos:1 ~len:(Array.length (Sys.get_argv ()) - 1)
|> Array.map ~f:str_to_inf
else [| mh; rej; imp; smc |]
let _ =
~f:(fun inf - >
by_data_length_linreg_single_inf inf ~num_times:10
| > write_to_csv
~fname :
( " linreg_by_data_length _ " ^ print_infer_strat_short ^ " .csv " ) )
Array.map infs ~f:(fun inf ->
by_data_length_linreg_single_inf inf ~num_times:10
|> write_to_csv
~fname:
("linreg_by_data_length_" ^ print_infer_strat_short inf ^ ".csv")) *)
let _ =
Array.map infs ~f:(fun inf ->
by_data_length_dpmm_single_inf inf ~num_times:2
|> write_to_csv
~fname:("dpmm_by_data_length_" ^ print_infer_strat_short inf ^ ".csv"))
|
088972f78daac745062e2f0871fba1f27087fc9b72e17d958b0ae34cfcd348b7 | jmtd/hwadtools | Util.hs | module Util(clean,pad,getHandle) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import System.IO (stdin, IOMode(..), hSetBinaryMode, openFile, Handle)
import System.Environment (getArgs)
clean :: B.ByteString -> String
clean bs = clean' bs 8 where
clean' _ 0 = ""
clean' bs n | bs == B.empty = replicate n ' '
| head == '\0' = replicate n ' '
| otherwise = head : (clean' tail (n-1))
where
head = C.head bs
tail = C.tail bs
pad :: String -> String
pad s = s ++ (replicate (8 - (length s)) ' ')
getHandle :: IO Handle
getHandle = do
args <- getArgs
handle <- if args == []
then return stdin
else openFile (head args) ReadMode
hSetBinaryMode handle True
return handle
| null | https://raw.githubusercontent.com/jmtd/hwadtools/e5639a068edf8d88f3e560cbc3708593223e3109/Util.hs | haskell | module Util(clean,pad,getHandle) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import System.IO (stdin, IOMode(..), hSetBinaryMode, openFile, Handle)
import System.Environment (getArgs)
clean :: B.ByteString -> String
clean bs = clean' bs 8 where
clean' _ 0 = ""
clean' bs n | bs == B.empty = replicate n ' '
| head == '\0' = replicate n ' '
| otherwise = head : (clean' tail (n-1))
where
head = C.head bs
tail = C.tail bs
pad :: String -> String
pad s = s ++ (replicate (8 - (length s)) ' ')
getHandle :: IO Handle
getHandle = do
args <- getArgs
handle <- if args == []
then return stdin
else openFile (head args) ReadMode
hSetBinaryMode handle True
return handle
| |
6272c4ac3f8a6bbdb364794abfb8332146e153e74c6c2a38fbd5e976b1a4c527 | c-cube/ocaml-chord | mixtbl.mli | (* This source code is released into the Public Domain *)
type 'a t
(** A hash table containing values of different types.
The type parameter ['a] represents the type of the keys. *)
and ('a, 'b) injection
val create : int -> 'a t
(** [create n] creates a hash table of initial size [n]. *)
val access : unit -> ('a, 'b) injection
(**
Return a value that works for a given type of values.
This function is normally called once for each type of value.
Several injections may be created for the same type,
but a value set with a given setter can only be retrieved with
the matching getter.
The same injection can be reused across multiple tables (although
not in a thread-safe way).
*)
val get : inj:('a, 'b) injection -> 'a t -> 'a -> 'b option
(** Get the value corresponding to this key, if it exists and
belongs to the same injection *)
val set : inj:('a, 'b) injection -> 'a t -> 'a -> 'b -> unit
(** Bind the key to the value, using [inj] *)
val length : 'a t -> int
(** Number of bindings *)
val clear : 'a t -> unit
(** Clear content of the hashtable *)
val remove : 'a t -> 'a -> unit
(** Remove the binding for this key *)
val copy : 'a t -> 'a t
(** Copy of the table *)
val mem : inj:('a, _) injection -> 'a t -> 'a -> bool
(** Is the given key in the table, with the right type? *)
val find : inj:('a, 'b) injection -> 'a t -> 'a -> 'b
(** Find the value for the given key, which must be of the right type.
raises Not_found if either the key is not found, or if its value
doesn't belong to the right type *)
val iter_keys : 'a t -> ('a -> unit) -> unit
(** Iterate on the keys of this table *)
val fold_keys : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b
(** Fold over the keys *)
val keys : 'a t -> 'a list
(** List of the keys *)
val bindings : inj:('a, 'b) injection -> 'a t -> ('a * 'b) list
(** All the bindings that come from the corresponding injection *)
| null | https://raw.githubusercontent.com/c-cube/ocaml-chord/74b25d2d5574291b7c37dc7f4c4f569c7bc4ccf4/src/mixtbl.mli | ocaml | This source code is released into the Public Domain
* A hash table containing values of different types.
The type parameter ['a] represents the type of the keys.
* [create n] creates a hash table of initial size [n].
*
Return a value that works for a given type of values.
This function is normally called once for each type of value.
Several injections may be created for the same type,
but a value set with a given setter can only be retrieved with
the matching getter.
The same injection can be reused across multiple tables (although
not in a thread-safe way).
* Get the value corresponding to this key, if it exists and
belongs to the same injection
* Bind the key to the value, using [inj]
* Number of bindings
* Clear content of the hashtable
* Remove the binding for this key
* Copy of the table
* Is the given key in the table, with the right type?
* Find the value for the given key, which must be of the right type.
raises Not_found if either the key is not found, or if its value
doesn't belong to the right type
* Iterate on the keys of this table
* Fold over the keys
* List of the keys
* All the bindings that come from the corresponding injection |
type 'a t
and ('a, 'b) injection
val create : int -> 'a t
val access : unit -> ('a, 'b) injection
val get : inj:('a, 'b) injection -> 'a t -> 'a -> 'b option
val set : inj:('a, 'b) injection -> 'a t -> 'a -> 'b -> unit
val length : 'a t -> int
val clear : 'a t -> unit
val remove : 'a t -> 'a -> unit
val copy : 'a t -> 'a t
val mem : inj:('a, _) injection -> 'a t -> 'a -> bool
val find : inj:('a, 'b) injection -> 'a t -> 'a -> 'b
val iter_keys : 'a t -> ('a -> unit) -> unit
val fold_keys : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b
val keys : 'a t -> 'a list
val bindings : inj:('a, 'b) injection -> 'a t -> ('a * 'b) list
|
bd09f566b6d4609427eae7380739eb5203613f3b0ec2a6a5216f1e78950cfc81 | Beyamor/ruin | helpers.cljs | (ns demo.helpers
(:require [ruin.scene :as s]
[ruin.level :as l]
[ruin.entities :as es]
[demo.tiles :as ts]))
(defn is-empty-floor?
[{:keys [level entities]} x y]
(and (= ts/floor-tile (l/get-tile level x y))
(not (es/at-position? entities x y))))
(defn kill
([{:keys [on-death] :as entity}]
(if on-death
(on-death entity)
[:remove entity]))
([entity message]
(let [result
(concat
[:send [entity message]]
(kill entity))]
result)))
(defn can-see?
[{:keys [x y sight-radius]} {target-x :x target-y :y} level]
(let [dx (- target-x x)
dy (- target-y y)]
(when (>= (* sight-radius sight-radius)
(+ (* dx dx) (* dy dy)))
(contains?
(l/visible-tiles level x y sight-radius)
[target-x target-y]))))
| null | https://raw.githubusercontent.com/Beyamor/ruin/50a6977430dcbbceecccadbf732298462165b049/src/demo/helpers.cljs | clojure | (ns demo.helpers
(:require [ruin.scene :as s]
[ruin.level :as l]
[ruin.entities :as es]
[demo.tiles :as ts]))
(defn is-empty-floor?
[{:keys [level entities]} x y]
(and (= ts/floor-tile (l/get-tile level x y))
(not (es/at-position? entities x y))))
(defn kill
([{:keys [on-death] :as entity}]
(if on-death
(on-death entity)
[:remove entity]))
([entity message]
(let [result
(concat
[:send [entity message]]
(kill entity))]
result)))
(defn can-see?
[{:keys [x y sight-radius]} {target-x :x target-y :y} level]
(let [dx (- target-x x)
dy (- target-y y)]
(when (>= (* sight-radius sight-radius)
(+ (* dx dx) (* dy dy)))
(contains?
(l/visible-tiles level x y sight-radius)
[target-x target-y]))))
| |
5a1db744c8644c79c78ded0928308217d4155730d68d560470e0bc5213fdd470 | sanette/bogue | b_time.ml |
Warning : ( from the SDL wiki )
SDL_GetTicks
This function is not recommended as of SDL 2.0.18 ; use SDL_GetTicks64 ( ) instead , where the value does n't wrap every ~49 days . There are places in SDL where we provide a 32 - bit timestamp that can not change without breaking binary compatibility , though , so this function is n't officially deprecated .
Warning: (from the SDL wiki)
SDL_GetTicks
This function is not recommended as of SDL 2.0.18; use SDL_GetTicks64() instead, where the value doesn't wrap every ~49 days. There are places in SDL where we provide a 32-bit timestamp that can not change without breaking binary compatibility, though, so this function isn't officially deprecated.
*)
open Tsdl
open B_utils
1/1000 sec
let (+) t1 t2 = t1 + t2
let (-) t1 t2 = t1 - t2
let add t1 t2 = t1 + t2
let length t1 t2 = t2 - t1
let compare (t1 : t) (t2 : t) =
Stdlib.compare t1 t2
let (>>) (t1 : t) (t2 : t) =
t1 > t2
let float t = float t
(* Do not use ! it is NOT nice to other threads *)
attention ça freeze
(* we use this instead *)
let delay x = Thread.delay (float x /. 1000.)
in principle one should use Int32.unsigned_to_int . This is ok until 2 ^ 31 -1 ,
ie . about 24 days . TODO change this ?
ie. about 24 days. TODO change this? *)
let now () : t = Int32.to_int (Sdl.get_ticks ())
let make_fps () =
let start = ref 0 in
fun fps ->
if !start = 0 then (delay 5; start := now ())
else
let round_trip = now () - !start in begin
let wait = max 5 ((1000 / fps) - round_trip) in
printd debug_graphics "FPS:%u (round_trip=%u)\n" (1000 / (round_trip + wait)) round_trip;
delay wait;
start := now ();
end
let adaptive_fps fps =
let start = ref 0 in
let frame = ref 1 in
let total_wait = ref 0 in (* only for debugging *)
(* the start function *)
(fun () ->
start := now ();
total_wait := 0;
frame := 1),
(* the main function *)
fun () ->
if !start = 0 then (delay 5; start := now (); assert(false))
else
let elapsed = now () - !start in
let theoric = 1000 * !frame / fps in (* theoric time after this number of frames *)
let wait = theoric - elapsed in
total_wait := !total_wait + wait;
let wait = if wait < 5
then (printd debug_graphics "Warning: cannot keep up required FPS=%u (wait=%d)" fps wait;
(* this can also happen when the animation was stopped; we reset
the counter *)
frame := 0;
total_wait := 0;
start := now ();
5)
else (printd debug_graphics "Wait=%u, Avg.=%u" wait (!total_wait / !frame);
wait) in
delay wait;
incr frame;
if !frame > 1000000 (* set lower? *)
then (printd debug_graphics "Reset FPS counter";
frame := 1;
total_wait := 0;
start := now ())
| null | https://raw.githubusercontent.com/sanette/bogue/1c572bc7f49a2af3cafa96dcc643c43406b990f7/lib/b_time.ml | ocaml | Do not use ! it is NOT nice to other threads
we use this instead
only for debugging
the start function
the main function
theoric time after this number of frames
this can also happen when the animation was stopped; we reset
the counter
set lower? |
Warning : ( from the SDL wiki )
SDL_GetTicks
This function is not recommended as of SDL 2.0.18 ; use SDL_GetTicks64 ( ) instead , where the value does n't wrap every ~49 days . There are places in SDL where we provide a 32 - bit timestamp that can not change without breaking binary compatibility , though , so this function is n't officially deprecated .
Warning: (from the SDL wiki)
SDL_GetTicks
This function is not recommended as of SDL 2.0.18; use SDL_GetTicks64() instead, where the value doesn't wrap every ~49 days. There are places in SDL where we provide a 32-bit timestamp that can not change without breaking binary compatibility, though, so this function isn't officially deprecated.
*)
open Tsdl
open B_utils
1/1000 sec
let (+) t1 t2 = t1 + t2
let (-) t1 t2 = t1 - t2
let add t1 t2 = t1 + t2
let length t1 t2 = t2 - t1
let compare (t1 : t) (t2 : t) =
Stdlib.compare t1 t2
let (>>) (t1 : t) (t2 : t) =
t1 > t2
let float t = float t
attention ça freeze
let delay x = Thread.delay (float x /. 1000.)
in principle one should use Int32.unsigned_to_int . This is ok until 2 ^ 31 -1 ,
ie . about 24 days . TODO change this ?
ie. about 24 days. TODO change this? *)
let now () : t = Int32.to_int (Sdl.get_ticks ())
let make_fps () =
let start = ref 0 in
fun fps ->
if !start = 0 then (delay 5; start := now ())
else
let round_trip = now () - !start in begin
let wait = max 5 ((1000 / fps) - round_trip) in
printd debug_graphics "FPS:%u (round_trip=%u)\n" (1000 / (round_trip + wait)) round_trip;
delay wait;
start := now ();
end
let adaptive_fps fps =
let start = ref 0 in
let frame = ref 1 in
(fun () ->
start := now ();
total_wait := 0;
frame := 1),
fun () ->
if !start = 0 then (delay 5; start := now (); assert(false))
else
let elapsed = now () - !start in
let wait = theoric - elapsed in
total_wait := !total_wait + wait;
let wait = if wait < 5
then (printd debug_graphics "Warning: cannot keep up required FPS=%u (wait=%d)" fps wait;
frame := 0;
total_wait := 0;
start := now ();
5)
else (printd debug_graphics "Wait=%u, Avg.=%u" wait (!total_wait / !frame);
wait) in
delay wait;
incr frame;
then (printd debug_graphics "Reset FPS counter";
frame := 1;
total_wait := 0;
start := now ())
|
377e2420aa6f1a33323c9437ed2480cbd6339ac4ddfe5595263fb79050d1ee92 | OCADml/OCADml | polyHoles.mli | val partition
: ?rev:bool
-> ?lift:(V2.t -> V3.t)
-> holes:V2.t list list
-> V2.t list
-> V3.t list * int list list
| null | https://raw.githubusercontent.com/OCADml/OCADml/ceed2bfce640667580f7286b46864a69cdc1d4d7/lib/polyHoles.mli | ocaml | val partition
: ?rev:bool
-> ?lift:(V2.t -> V3.t)
-> holes:V2.t list list
-> V2.t list
-> V3.t list * int list list
| |
742e83f7464a96a4df6f4bc624e4cb1c86c3eea7757d75e107df277873ba9050 | gebi/jungerl | edit_eval.erl | %%%----------------------------------------------------------------------
%%% File : edit_eval.erl
Author : < >
%%% Purpose : Erlang code evaluation
Created : 21 Jan 2001 by < >
%%%----------------------------------------------------------------------
-module(edit_eval).
-author('').
-include_lib("ermacs/include/edit.hrl").
-compile({parse_transform, edit_transform}).
-import(edit_lib, [buffer/1]).
-compile(export_all).
%%-export([Function/Arity, ...]).
-define(history, erlang_interaction_history).
eval_buffer(State) ->
B = buffer(State),
Text = edit_buf:get_text(B),
{ok, Scan, _} = erl_scan:string(Text), % safe ?
case erl_parse:parse_exprs(Scan) of
{ok, Parse} ->
case catch erl_eval:exprs(Parse, []) of
{value, V, _} ->
edit_util:status_msg(State, "~p", [V]);
{'EXIT', Reason} ->
edit_util:status_msg(State, "** exited: ~p **", [Reason])
end;
{error, {_, erl_parse, Err}} ->
edit_util:status_msg(State, "~p", [Err])
end.
eval_string(State, String) ->
{ok, Scan, _} = erl_scan:string(String), % safe ?
eval_tokens(State, Scan, []).
eval_tokens(Buf, Tokens, Bindings) ->
case erl_parse:parse_exprs(Tokens) of
{ok, Parse} ->
case erl_eval:exprs(Parse, Bindings, lf_handler(Buf)) of
{value, V, NewBs} ->
{ok, V, NewBs};
Error ->
{error, Error}
end;
{error, {_, erl_parse, Err}} ->
{error, fmt("~s", [Err])}
end.
lf_handler(Buf) ->
{eval, {?MODULE, local_func}, [Buf]}.
fmt(Fmt, Args) -> lists:flatten(io_lib:format(Fmt, Args)).
-command({eval_expression, [{erl_expr, "Eval:"}]}).
eval_expression(State, Expr) ->
Str = case eval_string(State, Expr) of
{ok, Val, NewBS} ->
fmt("~p", [Val]);
{error, Rsn} ->
fmt("~p", [Rsn])
end,
edit_util:popup_message(State, '*Eval*', Str).
region(Buffer) ->
{find_start(Buffer), edit_lib:end_of_line_pos(Buffer)}.
%% ----------------------------------------------------------------------
%% Interactive evaluation major mode
%% ----------------------------------------------------------------------
-define(keymap, erlang_interaction_map).
-define(output_mark, erlang_output).
-define(PROMPT, ">> ").
erlang_interaction_mode(State) ->
case edit_keymap:keymap_exists(?keymap) of
false ->
init_map();
true ->
ok
end,
Mode = #mode{name="Erlang Interaction",
id=erlang_interaction,
keymaps=[?keymap]},
Buf = buffer(State),
edit_buf:set_mode(Buf, Mode),
edit_buf:add_mark(Buf, ?output_mark, 1, forward),
ok.
init_map() ->
edit_keymap:new(?keymap),
edit_keymap:bind_each(?keymap, bindings()).
bindings() ->
[{"C-m", {?MODULE, interactive_eval, []}},
{"C-a", {?MODULE, beginning_of_prompt, []}}]
++ edit_history:bindings(?history, {?MODULE, region}).
interactive_eval(State) ->
P = find_start(buffer(State)),
interactive_eval1(State, P, P).
interactive_eval1(State, CodeStart, SearchStart) ->
Buf = buffer(State),
Max = edit_buf:point_max(Buf),
Pred = fun(C) -> C == $\n end,
CodeEnd = edit_lib:find_char_forward(Buf, Pred, SearchStart, Max),
Region = edit_buf:get_region(Buf, CodeStart, CodeEnd),
Bindings = edit_var:lookup(erlang_interaction_bindings, []),
case erl_scan:tokens([], Region ++ "\n", 1) of
{done, {ok, Tokens, _}, _} -> % ok - enough
%% Move point to the end
edit_buf:move_mark(Buf, point, CodeEnd),
%% eval
edit_util:spawn_with([Buf],
fun() ->
eval_async(Buf, Tokens, Bindings)
end),
edit_history:add(?history, Region);
{more, _} when CodeEnd == Max ->
edit_buf:insert(Buf, "\n", edit_buf:mark_pos(Buf, point));
{more, _} ->
interactive_eval1(State, CodeStart, CodeEnd + 1)
end.
eval_async(Buf, Tokens, Bindings) ->
ensure_serv_started(Buf),
%% update output marker
edit_buf:insert(Buf, "\n", edit_buf:mark_pos(Buf, point)),
InsertionPoint = edit_buf:mark_pos(Buf, point),
edit_buf:move_mark(Buf, ?output_mark, InsertionPoint),
%% eval
Str = case serv_eval(Buf, Tokens, Bindings) of
{ok, Value, NewBs} ->
%% FIXME: bindings
edit_var:set(erlang_interaction_bindings, NewBs),
fmt("=> ~p\n", [Value]);
{error, {'EXIT', Rsn}} ->
fmt("** exited: ~p **\n", [Rsn]);
{error, Rsn} ->
fmt("** ~s **\n", [Rsn])
end,
edit_buf:insert(Buf, Str, edit_buf:mark_pos(Buf, point)),
PromptPos = edit_buf:mark_pos(Buf, point),
edit_buf:insert(Buf, ?PROMPT, PromptPos),
edit_buf:move_mark(Buf, ?output_mark, PromptPos),
redraw(),
ok.
redraw() ->
edit:invoke_async(edit_lib, nop, []).
%% Go to the beginning of the line or directly after the prompt,
%% whichever is closer.
beginning_of_prompt(State) ->
Buf = buffer(State),
edit_buf:move_mark(Buf, point, beginning_of_prompt_pos(Buf)).
beginning_of_prompt_pos(Buf) ->
Point = edit_buf:mark_pos(Buf, point),
BOL = edit_lib:beginning_of_line_pos(Buf),
case find_start(Buf) of
Pos when Pos > BOL, Pos =< Point ->
Pos;
_ ->
BOL
end.
find_start(Buf) ->
case edit_lib:find_string_backward(Buf, ?PROMPT) of
not_found ->
1;
X ->
edit_lib:min(X + length(?PROMPT), edit_buf:point_max(Buf))
end.
local_func(Function , , Bindings , Shell ) - >
{ value , , Bs }
%% Evaluate local functions, including shell commands.
local_func(F, As0, Bs0, Buf) ->
{As,Bs} = erl_eval:expr_list(As0, Bs0, {eval,{?MODULE,local_func},[Buf]}),
case erlang:function_exported(user_default, F, length(As)) of
true ->
{value,apply(user_default, F, As),Bs};
false ->
{value,apply(shell_default, F, As),Bs}
end;
local_func(F, As0, Bs0, Buf) ->
{As,Bs} = erl_eval:expr_list(As0, Bs0, {eval,{?MODULE,local_func},[Buf]}),
{value,apply(F, As),Bs}.
%% ----------------------------------------------------------------------
%% Evaluation server API
%% ok | already_started
ensure_serv_started(Buffer) ->
case whereis(serv_name(Buffer)) of
undefined ->
Pid = spawn(?MODULE, eval_serv_init, [Buffer]),
register(serv_name(Buffer), Pid),
ok;
Pid ->
already_started
end.
serv_eval(Buffer, Tokens, Bindings) ->
Serv = whereis(serv_name(Buffer)),
erlang:monitor(process, Serv),
Serv ! {call, self(), {eval, Tokens, Bindings}},
receive
{reply, Result} ->
Result;
{'DOWN', _, process, Serv, Rsn} ->
{error, {'EXIT', Rsn}}
end.
%% serv_name(foo) -> 'foo:eval_serv'
serv_name(Buffer) -> list_to_atom(atom_to_list(Buffer) ++ ":eval_serv").
%% ----------------------------------------------------------------------
%% Eval server loop
eval_serv_init(Buffer) ->
erlang:monitor(process, whereis(Buffer)),
GL = gl_spawn_link(Buffer),
group_leader(GL, self()),
eval_serv_loop(Buffer, GL).
eval_serv_loop(Buffer, GL) ->
receive
{call, From, {eval, Tokens, Bindings}} ->
GL ! {got_shared_lock, self()},
Result = eval_tokens(Buffer, Tokens, Bindings),
GL ! {releasing_shared_lock, self()},
receive gl_ack -> ok end,
From ! {reply, Result},
eval_serv_loop(Buffer, GL);
{'DOWN', _, _, _, _} ->
exit(buffer_died)
end.
%% ----------------------------------------------------------------------
%% Group leader process for putting output into a buffer.
%%
%% The evaluation server sends us:
{ got_shared_lock , HolderPid }
%% followed by:
%% {releasing_shared_lock, HolderPid}
%% Between these messages, we informally share the lock on the buffer.
gl_spawn_link(Buffer) ->
spawn_link(?MODULE, gl_serv_init, [Buffer]).
gl_serv_init(Buffer) ->
gl_serv_without_lock(Buffer).
State : Nothing known about 's lock
gl_serv_without_lock(Buffer) ->
?debug("STATE: no lock~n", []),
receive
Msg = {io_request, From, ReplyAs, Req} ->
gl_serv_work(Buffer, Msg);
{got_shared_lock, Holder} ->
gl_serv_with_lock(Buffer)
end.
State : Buffer is locked by eval_server , so we can use it .
gl_serv_with_lock(Buffer) ->
receive
Msg = {io_request, From, ReplyAs, Req} ->
do_gl_request(Buffer, Msg),
gl_serv_with_lock(Buffer);
{releasing_shared_lock, Holder} ->
Holder ! gl_ack,
gl_serv_without_lock(Buffer)
end.
Action : Acquire the lock on , perform a request , and release .
gl_serv_work(Buffer, Req) ->
edit_buf:async_borrow(Buffer),
receive
{loan, Buffer} ->
do_gl_request(Buffer, Req),
edit_buf:async_return(Buffer),
gl_serv_without_lock(Buffer);
got_shared_lock ->
do_gl_request(Buffer, Req),
gl_serv_with_lock(Buffer)
end.
%% Perform an I/O request by writing the result into the buffer.
do_gl_request(Buffer, {io_request, From, ReplyAs, {put_chars, M, F, A}}) ->
case catch apply(M, F, A) of
{'EXIT', Reason} ->
exit(From, Reason);
IOList ->
do_gl_request(Buffer,
{io_request, From, ReplyAs, {put_chars, IOList}})
end;
do_gl_request(Buffer, {io_request, From, ReplyAs, {put_chars, IOList}}) ->
From ! {io_reply, ReplyAs, ok},
Bin = list_to_binary(IOList),
Pos = edit_buf:mark_pos(Buffer, ?output_mark),
edit_buf:insert(Buffer, Bin, Pos),
redraw();
do_gl_request(Buffer, {io_request, From, ReplyAs, {get_until, _, _, _}}) ->
From ! {io_reply, ReplyAs, eof}.
| null | https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/ermacs/src/edit_eval.erl | erlang | ----------------------------------------------------------------------
File : edit_eval.erl
Purpose : Erlang code evaluation
----------------------------------------------------------------------
-export([Function/Arity, ...]).
safe ?
safe ?
----------------------------------------------------------------------
Interactive evaluation major mode
----------------------------------------------------------------------
ok - enough
Move point to the end
eval
update output marker
eval
FIXME: bindings
Go to the beginning of the line or directly after the prompt,
whichever is closer.
Evaluate local functions, including shell commands.
----------------------------------------------------------------------
Evaluation server API
ok | already_started
serv_name(foo) -> 'foo:eval_serv'
----------------------------------------------------------------------
Eval server loop
----------------------------------------------------------------------
Group leader process for putting output into a buffer.
The evaluation server sends us:
followed by:
{releasing_shared_lock, HolderPid}
Between these messages, we informally share the lock on the buffer.
Perform an I/O request by writing the result into the buffer. | Author : < >
Created : 21 Jan 2001 by < >
-module(edit_eval).
-author('').
-include_lib("ermacs/include/edit.hrl").
-compile({parse_transform, edit_transform}).
-import(edit_lib, [buffer/1]).
-compile(export_all).
-define(history, erlang_interaction_history).
eval_buffer(State) ->
B = buffer(State),
Text = edit_buf:get_text(B),
case erl_parse:parse_exprs(Scan) of
{ok, Parse} ->
case catch erl_eval:exprs(Parse, []) of
{value, V, _} ->
edit_util:status_msg(State, "~p", [V]);
{'EXIT', Reason} ->
edit_util:status_msg(State, "** exited: ~p **", [Reason])
end;
{error, {_, erl_parse, Err}} ->
edit_util:status_msg(State, "~p", [Err])
end.
eval_string(State, String) ->
eval_tokens(State, Scan, []).
eval_tokens(Buf, Tokens, Bindings) ->
case erl_parse:parse_exprs(Tokens) of
{ok, Parse} ->
case erl_eval:exprs(Parse, Bindings, lf_handler(Buf)) of
{value, V, NewBs} ->
{ok, V, NewBs};
Error ->
{error, Error}
end;
{error, {_, erl_parse, Err}} ->
{error, fmt("~s", [Err])}
end.
lf_handler(Buf) ->
{eval, {?MODULE, local_func}, [Buf]}.
fmt(Fmt, Args) -> lists:flatten(io_lib:format(Fmt, Args)).
-command({eval_expression, [{erl_expr, "Eval:"}]}).
eval_expression(State, Expr) ->
Str = case eval_string(State, Expr) of
{ok, Val, NewBS} ->
fmt("~p", [Val]);
{error, Rsn} ->
fmt("~p", [Rsn])
end,
edit_util:popup_message(State, '*Eval*', Str).
region(Buffer) ->
{find_start(Buffer), edit_lib:end_of_line_pos(Buffer)}.
-define(keymap, erlang_interaction_map).
-define(output_mark, erlang_output).
-define(PROMPT, ">> ").
erlang_interaction_mode(State) ->
case edit_keymap:keymap_exists(?keymap) of
false ->
init_map();
true ->
ok
end,
Mode = #mode{name="Erlang Interaction",
id=erlang_interaction,
keymaps=[?keymap]},
Buf = buffer(State),
edit_buf:set_mode(Buf, Mode),
edit_buf:add_mark(Buf, ?output_mark, 1, forward),
ok.
init_map() ->
edit_keymap:new(?keymap),
edit_keymap:bind_each(?keymap, bindings()).
bindings() ->
[{"C-m", {?MODULE, interactive_eval, []}},
{"C-a", {?MODULE, beginning_of_prompt, []}}]
++ edit_history:bindings(?history, {?MODULE, region}).
interactive_eval(State) ->
P = find_start(buffer(State)),
interactive_eval1(State, P, P).
interactive_eval1(State, CodeStart, SearchStart) ->
Buf = buffer(State),
Max = edit_buf:point_max(Buf),
Pred = fun(C) -> C == $\n end,
CodeEnd = edit_lib:find_char_forward(Buf, Pred, SearchStart, Max),
Region = edit_buf:get_region(Buf, CodeStart, CodeEnd),
Bindings = edit_var:lookup(erlang_interaction_bindings, []),
case erl_scan:tokens([], Region ++ "\n", 1) of
edit_buf:move_mark(Buf, point, CodeEnd),
edit_util:spawn_with([Buf],
fun() ->
eval_async(Buf, Tokens, Bindings)
end),
edit_history:add(?history, Region);
{more, _} when CodeEnd == Max ->
edit_buf:insert(Buf, "\n", edit_buf:mark_pos(Buf, point));
{more, _} ->
interactive_eval1(State, CodeStart, CodeEnd + 1)
end.
eval_async(Buf, Tokens, Bindings) ->
ensure_serv_started(Buf),
edit_buf:insert(Buf, "\n", edit_buf:mark_pos(Buf, point)),
InsertionPoint = edit_buf:mark_pos(Buf, point),
edit_buf:move_mark(Buf, ?output_mark, InsertionPoint),
Str = case serv_eval(Buf, Tokens, Bindings) of
{ok, Value, NewBs} ->
edit_var:set(erlang_interaction_bindings, NewBs),
fmt("=> ~p\n", [Value]);
{error, {'EXIT', Rsn}} ->
fmt("** exited: ~p **\n", [Rsn]);
{error, Rsn} ->
fmt("** ~s **\n", [Rsn])
end,
edit_buf:insert(Buf, Str, edit_buf:mark_pos(Buf, point)),
PromptPos = edit_buf:mark_pos(Buf, point),
edit_buf:insert(Buf, ?PROMPT, PromptPos),
edit_buf:move_mark(Buf, ?output_mark, PromptPos),
redraw(),
ok.
redraw() ->
edit:invoke_async(edit_lib, nop, []).
beginning_of_prompt(State) ->
Buf = buffer(State),
edit_buf:move_mark(Buf, point, beginning_of_prompt_pos(Buf)).
beginning_of_prompt_pos(Buf) ->
Point = edit_buf:mark_pos(Buf, point),
BOL = edit_lib:beginning_of_line_pos(Buf),
case find_start(Buf) of
Pos when Pos > BOL, Pos =< Point ->
Pos;
_ ->
BOL
end.
find_start(Buf) ->
case edit_lib:find_string_backward(Buf, ?PROMPT) of
not_found ->
1;
X ->
edit_lib:min(X + length(?PROMPT), edit_buf:point_max(Buf))
end.
local_func(Function , , Bindings , Shell ) - >
{ value , , Bs }
local_func(F, As0, Bs0, Buf) ->
{As,Bs} = erl_eval:expr_list(As0, Bs0, {eval,{?MODULE,local_func},[Buf]}),
case erlang:function_exported(user_default, F, length(As)) of
true ->
{value,apply(user_default, F, As),Bs};
false ->
{value,apply(shell_default, F, As),Bs}
end;
local_func(F, As0, Bs0, Buf) ->
{As,Bs} = erl_eval:expr_list(As0, Bs0, {eval,{?MODULE,local_func},[Buf]}),
{value,apply(F, As),Bs}.
ensure_serv_started(Buffer) ->
case whereis(serv_name(Buffer)) of
undefined ->
Pid = spawn(?MODULE, eval_serv_init, [Buffer]),
register(serv_name(Buffer), Pid),
ok;
Pid ->
already_started
end.
serv_eval(Buffer, Tokens, Bindings) ->
Serv = whereis(serv_name(Buffer)),
erlang:monitor(process, Serv),
Serv ! {call, self(), {eval, Tokens, Bindings}},
receive
{reply, Result} ->
Result;
{'DOWN', _, process, Serv, Rsn} ->
{error, {'EXIT', Rsn}}
end.
serv_name(Buffer) -> list_to_atom(atom_to_list(Buffer) ++ ":eval_serv").
eval_serv_init(Buffer) ->
erlang:monitor(process, whereis(Buffer)),
GL = gl_spawn_link(Buffer),
group_leader(GL, self()),
eval_serv_loop(Buffer, GL).
eval_serv_loop(Buffer, GL) ->
receive
{call, From, {eval, Tokens, Bindings}} ->
GL ! {got_shared_lock, self()},
Result = eval_tokens(Buffer, Tokens, Bindings),
GL ! {releasing_shared_lock, self()},
receive gl_ack -> ok end,
From ! {reply, Result},
eval_serv_loop(Buffer, GL);
{'DOWN', _, _, _, _} ->
exit(buffer_died)
end.
{ got_shared_lock , HolderPid }
gl_spawn_link(Buffer) ->
spawn_link(?MODULE, gl_serv_init, [Buffer]).
gl_serv_init(Buffer) ->
gl_serv_without_lock(Buffer).
State : Nothing known about 's lock
gl_serv_without_lock(Buffer) ->
?debug("STATE: no lock~n", []),
receive
Msg = {io_request, From, ReplyAs, Req} ->
gl_serv_work(Buffer, Msg);
{got_shared_lock, Holder} ->
gl_serv_with_lock(Buffer)
end.
State : Buffer is locked by eval_server , so we can use it .
gl_serv_with_lock(Buffer) ->
receive
Msg = {io_request, From, ReplyAs, Req} ->
do_gl_request(Buffer, Msg),
gl_serv_with_lock(Buffer);
{releasing_shared_lock, Holder} ->
Holder ! gl_ack,
gl_serv_without_lock(Buffer)
end.
Action : Acquire the lock on , perform a request , and release .
gl_serv_work(Buffer, Req) ->
edit_buf:async_borrow(Buffer),
receive
{loan, Buffer} ->
do_gl_request(Buffer, Req),
edit_buf:async_return(Buffer),
gl_serv_without_lock(Buffer);
got_shared_lock ->
do_gl_request(Buffer, Req),
gl_serv_with_lock(Buffer)
end.
do_gl_request(Buffer, {io_request, From, ReplyAs, {put_chars, M, F, A}}) ->
case catch apply(M, F, A) of
{'EXIT', Reason} ->
exit(From, Reason);
IOList ->
do_gl_request(Buffer,
{io_request, From, ReplyAs, {put_chars, IOList}})
end;
do_gl_request(Buffer, {io_request, From, ReplyAs, {put_chars, IOList}}) ->
From ! {io_reply, ReplyAs, ok},
Bin = list_to_binary(IOList),
Pos = edit_buf:mark_pos(Buffer, ?output_mark),
edit_buf:insert(Buffer, Bin, Pos),
redraw();
do_gl_request(Buffer, {io_request, From, ReplyAs, {get_until, _, _, _}}) ->
From ! {io_reply, ReplyAs, eof}.
|
ba7ff370064368c1540d63566337d97106ea03fa4be1fccf4171dc8ae12839c1 | wdebeaum/step | brand.lisp | ;;;;
W::BRAND
;;;;
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::BRAND
(SENSES
((LF-PARENT ONT::name) (TEMPL gen-part-of-reln-TEMPL)
(META-DATA :ORIGIN CALO :ENTRY-DATE 20040204 :CHANGE-DATE NIL :wn ("brand%1:10:00")
:COMMENTS HTML-PURCHASING-CORPUS))))
))
(define-words :pos W::V :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::brand
(SENSES
((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090501 :comments nil :vn ("dub-29.3-1"))
(LF-PARENT ONT::naming)
;(TEMPL AGENT-NEUTRAL-FORMAL-2-XP-3-XP2-NP-OPTIONAL-TEMPL) ; like name
(TEMPL AGENT-NEUTRAL-NEUTRAL1-XP-TEMPL (XP (% W::NP)))
)
((meta-data :origin "verbnet-1.5" :entry-date 20051219 :change-date 20090501 :comments nil :vn ("dub-29.3-1"))
(LF-PARENT ONT::naming)
(TEMPL agent-neutral-xp-templ) ; like label
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/step/f38c07d9cd3a58d0e0183159d4445de9a0eafe26/src/LexiconManager/Data/new/brand.lisp | lisp |
(TEMPL AGENT-NEUTRAL-FORMAL-2-XP-3-XP2-NP-OPTIONAL-TEMPL) ; like name
like label | W::BRAND
(define-words :pos W::n :templ COUNT-PRED-TEMPL
:words (
(W::BRAND
(SENSES
((LF-PARENT ONT::name) (TEMPL gen-part-of-reln-TEMPL)
(META-DATA :ORIGIN CALO :ENTRY-DATE 20040204 :CHANGE-DATE NIL :wn ("brand%1:10:00")
:COMMENTS HTML-PURCHASING-CORPUS))))
))
(define-words :pos W::V :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::brand
(SENSES
((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090501 :comments nil :vn ("dub-29.3-1"))
(LF-PARENT ONT::naming)
(TEMPL AGENT-NEUTRAL-NEUTRAL1-XP-TEMPL (XP (% W::NP)))
)
((meta-data :origin "verbnet-1.5" :entry-date 20051219 :change-date 20090501 :comments nil :vn ("dub-29.3-1"))
(LF-PARENT ONT::naming)
)
)
)
))
|
6d690d84da5c6388f320e6c7bc7cf7af18275cce5e7376a199f31a67c8cf1635 | sgbj/MaximaSharp | idamax.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
;;; Using Lisp CMU Common Lisp 20d (20D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format double-float))
(in-package :blas)
(defun idamax (n dx incx)
(declare (type (array double-float (*)) dx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((dx double-float dx-%data% dx-%offset%))
(prog ((i 0) (ix 0) (dmax 0.0) (idamax 0))
(declare (type (double-float) dmax)
(type (f2cl-lib:integer4) idamax ix i))
(setf idamax 0)
(if (or (< n 1) (<= incx 0)) (go end_label))
(setf idamax 1)
(if (= n 1) (go end_label))
(if (= incx 1) (go label20))
(setf ix 1)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (1) ((1 *)) dx-%offset%)))
(setf ix (f2cl-lib:int-add ix incx))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<=
(f2cl-lib:dabs (f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%))
dmax)
(go label5))
(setf idamax i)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%)))
label5
(setf ix (f2cl-lib:int-add ix incx))
label10))
(go end_label)
label20
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (1) ((1 *)) dx-%offset%)))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<=
(f2cl-lib:dabs (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))
dmax)
(go label30))
(setf idamax i)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%)))
label30))
(go end_label)
end_label
(return (values idamax nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::idamax
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/lapack/blas/idamax.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp 20d (20D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format double-float)) | ( " f2cl1.l , v 2edcbd958861 2012/05/30 03:34:52 toy $ "
" f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 3fe93de3be82 2012/05/06 02:17:14 toy $ " )
(in-package :blas)
(defun idamax (n dx incx)
(declare (type (array double-float (*)) dx)
(type (f2cl-lib:integer4) incx n))
(f2cl-lib:with-multi-array-data
((dx double-float dx-%data% dx-%offset%))
(prog ((i 0) (ix 0) (dmax 0.0) (idamax 0))
(declare (type (double-float) dmax)
(type (f2cl-lib:integer4) idamax ix i))
(setf idamax 0)
(if (or (< n 1) (<= incx 0)) (go end_label))
(setf idamax 1)
(if (= n 1) (go end_label))
(if (= incx 1) (go label20))
(setf ix 1)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (1) ((1 *)) dx-%offset%)))
(setf ix (f2cl-lib:int-add ix incx))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<=
(f2cl-lib:dabs (f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%))
dmax)
(go label5))
(setf idamax i)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%)))
label5
(setf ix (f2cl-lib:int-add ix incx))
label10))
(go end_label)
label20
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (1) ((1 *)) dx-%offset%)))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i n) nil)
(tagbody
(if
(<=
(f2cl-lib:dabs (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%))
dmax)
(go label30))
(setf idamax i)
(setf dmax
(f2cl-lib:dabs
(f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%)))
label30))
(go end_label)
end_label
(return (values idamax nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::idamax
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4))
:return-values '(nil nil nil)
:calls 'nil)))
|
7f3af2c762baf90489d563a9b3381b7171c110ab0c549729bf3345e100a9e6fa | simmsb/calamity | Interaction.hs | # LANGUAGE TemplateHaskell #
{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
-- | Interaction endpoints
module Calamity.HTTP.Interaction (
InteractionRequest (..),
InteractionCallbackMessageOptions (..),
InteractionCallbackAutocomplete (..),
InteractionCallbackAutocompleteChoice (..),
InteractionCallbackModal (..),
) where
import Calamity.HTTP.Channel (AllowedMentions, CreateMessageAttachment (..))
import Calamity.HTTP.Internal.Request
import Calamity.HTTP.Internal.Route
import Calamity.Internal.Utils (CalamityToJSON (..), CalamityToJSON' (..), (.=), (.?=))
import Calamity.Types.Model.Channel.Component (Component, CustomID)
import Calamity.Types.Model.Channel.Embed (Embed)
import Calamity.Types.Model.Channel.Message (Message)
import Calamity.Types.Model.Interaction
import Calamity.Types.Snowflake
import Data.Aeson qualified as Aeson
import Data.Bits (shiftL, (.|.))
import Data.Default.Class
import Data.HashMap.Strict qualified as H
import Data.Maybe (fromMaybe)
import Data.Monoid (First (First, getFirst))
import Data.Text (Text)
import Data.Text qualified as T
import Network.HTTP.Client.MultipartFormData
import Network.HTTP.Req
import Network.Mime
import Optics
data InteractionCallback = InteractionCallback
{ type_ :: InteractionCallbackType
, data_ :: Maybe Aeson.Value
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallback
instance CalamityToJSON' InteractionCallback where
toPairs InteractionCallback {..} =
[ "type" .= type_
, "data" .?= data_
]
data InteractionCallbackMessageOptions = InteractionCallbackMessageOptions
{ tts :: Maybe Bool
, content :: Maybe Text
, embeds :: Maybe [Embed]
, allowedMentions :: Maybe AllowedMentions
, ephemeral :: Maybe Bool
, suppressEmbeds :: Maybe Bool
, components :: Maybe [Component]
, attachments :: Maybe [CreateMessageAttachment]
}
deriving (Show)
instance Default InteractionCallbackMessageOptions where
def = InteractionCallbackMessageOptions Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
data CreateMessageAttachmentJson = CreateMessageAttachmentJson
{ id :: Int
, filename :: Text
, description :: Maybe Text
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON CreateMessageAttachmentJson
instance CalamityToJSON' CreateMessageAttachmentJson where
toPairs CreateMessageAttachmentJson {..} =
[ "id" .= id
, "filename" .= filename
, "description" .?= description
]
data CreateResponseMessageJson = CreateResponseMessageJson
{ tts :: Maybe Bool
, content :: Maybe Text
, embeds :: Maybe [Embed]
, allowedMentions :: Maybe AllowedMentions
, flags :: Maybe Int
, components :: Maybe [Component]
, attachments :: Maybe [CreateMessageAttachmentJson]
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON CreateResponseMessageJson
instance CalamityToJSON' CreateResponseMessageJson where
toPairs CreateResponseMessageJson {..} =
[ "tts" .?= tts
, "content" .?= content
, "embeds" .?= embeds
, "allowed_mentions" .?= allowedMentions
, "flags" .?= flags
, "components" .?= components
, "attachments" .?= attachments
]
newtype InteractionCallbackAutocomplete = InteractionCallbackAutocomplete
{ choices :: [InteractionCallbackAutocompleteChoice]
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackAutocomplete
instance CalamityToJSON' InteractionCallbackAutocomplete where
toPairs InteractionCallbackAutocomplete {..} = ["choices" .= choices]
data InteractionCallbackAutocompleteChoice = InteractionCallbackAutocompleteChoice
{ name :: Text
, nameLocalizations :: H.HashMap Text Text
, value :: Aeson.Value
-- ^ Either text or numeric
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackAutocompleteChoice
instance CalamityToJSON' InteractionCallbackAutocompleteChoice where
toPairs InteractionCallbackAutocompleteChoice {..} =
[ "name" .= name
, "name_localizations" .= nameLocalizations
, "value" .= value
]
data InteractionCallbackModal = InteractionCallbackModal
{ customID :: CustomID
, title :: Text
, components :: [Component]
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackModal
instance CalamityToJSON' InteractionCallbackModal where
toPairs InteractionCallbackModal {..} =
[ "custom_id" .= customID
, "title" .= title
, "components" .= components
]
data InteractionCallbackType
= PongType
| ChannelMessageWithSourceType
| DeferredChannelMessageWithSourceType
| DeferredUpdateMessageType
| UpdateMessageType
| ApplicationCommandAutocompleteResultType
| ModalType
deriving (Show)
instance Aeson.ToJSON InteractionCallbackType where
toJSON ty = Aeson.toJSON @Int $ case ty of
PongType -> 1
ChannelMessageWithSourceType -> 4
DeferredChannelMessageWithSourceType -> 5
DeferredUpdateMessageType -> 6
UpdateMessageType -> 7
ApplicationCommandAutocompleteResultType -> 8
ModalType -> 9
toEncoding ty = Aeson.toEncoding @Int $ case ty of
PongType -> 1
ChannelMessageWithSourceType -> 4
DeferredChannelMessageWithSourceType -> 5
DeferredUpdateMessageType -> 6
UpdateMessageType -> 7
ApplicationCommandAutocompleteResultType -> 8
ModalType -> 9
$(makeFieldLabelsNoPrefix ''InteractionCallbackMessageOptions)
$(makeFieldLabelsNoPrefix ''InteractionCallbackAutocomplete)
$(makeFieldLabelsNoPrefix ''InteractionCallbackAutocompleteChoice)
$(makeFieldLabelsNoPrefix ''InteractionCallbackModal)
data InteractionRequest a where
CreateResponseMessage ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
-- | Ack an interaction and defer the response
--
-- This route triggers the 'thinking' message
CreateResponseDefer ::
(HasID Interaction i) =>
i ->
InteractionToken ->
-- | Ephemeral
Bool ->
InteractionRequest ()
-- | Ack an interaction and defer the response
--
-- This route is only usable by component interactions, and doesn't trigger a
-- 'thinking' message
CreateResponseDeferComponent ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionRequest ()
CreateResponseUpdate ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
CreateResponseAutocomplete ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackAutocomplete ->
InteractionRequest ()
CreateResponseModal ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackModal ->
InteractionRequest ()
GetOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionRequest Message
EditOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest Message
DeleteOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionRequest ()
CreateFollowupMessage ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
GetFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionRequest Message
EditFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
DeleteFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionRequest ()
baseRoute :: Snowflake Application -> InteractionToken -> RouteBuilder _
baseRoute id (InteractionToken token) =
mkRouteBuilder // S "webhooks" // ID @Application // S token
& giveID id
foo :: Maybe a -> Maybe a -> (a -> a -> a) -> Maybe a
foo (Just x) (Just y) f = Just (f x y)
foo x y _ = getFirst $ First x <> First y
instance Request (InteractionRequest a) where
type Result (InteractionRequest a) = a
route (CreateResponseDefer (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseDeferComponent (getID @Interaction -> iid) (InteractionToken token)) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseMessage (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseUpdate (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseAutocomplete (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseModal (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (GetOriginalInteractionResponse (getID @Application -> aid) token) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (EditOriginalInteractionResponse (getID @Application -> aid) token _) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (DeleteOriginalInteractionResponse (getID @Application -> aid) token) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (CreateFollowupMessage (getID @Application -> aid) token _) =
baseRoute aid token & buildRoute
route (GetFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
route (EditFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token _) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
route (DeleteFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
action (CreateResponseDefer _ _ ephemeral) =
let jsonBody =
InteractionCallback
{ type_ = DeferredChannelMessageWithSourceType
, data_ = if ephemeral then Just . Aeson.object $ [("flags", Aeson.Number 64)] else Nothing
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseDeferComponent _ _) =
let jsonBody =
InteractionCallback
{ type_ = DeferredUpdateMessageType
, data_ = Nothing
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseMessage _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = ChannelMessageWithSourceType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
postWith' body u o
action (CreateResponseUpdate _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = UpdateMessageType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
postWith' body u o
action (CreateResponseAutocomplete _ _ ao) =
let jsonBody =
InteractionCallback
{ type_ = ApplicationCommandAutocompleteResultType
, data_ = Just . Aeson.toJSON $ ao
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseModal _ _ mo) =
let jsonBody =
InteractionCallback
{ type_ = ModalType
, data_ = Just . Aeson.toJSON $ mo
}
in postWith' (ReqBodyJson jsonBody)
action (GetOriginalInteractionResponse _ _) = getWith
action (EditOriginalInteractionResponse _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = UpdateMessageType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
patchWith' body u o
action (DeleteOriginalInteractionResponse _ _) = deleteWith
action (CreateFollowupMessage _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonData) : files)
postWith' body u o
action GetFollowupMessage {} = getWith
action (EditFollowupMessage _ _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonData) : files)
patchWith' body u o
action DeleteFollowupMessage {} = deleteWith
| null | https://raw.githubusercontent.com/simmsb/calamity/be310255b446e87e7432673de1fbc67ef46de3ae/calamity/Calamity/HTTP/Interaction.hs | haskell | # OPTIONS_GHC -Wno-partial-type-signatures #
| Interaction endpoints
^ Either text or numeric
| Ack an interaction and defer the response
This route triggers the 'thinking' message
| Ephemeral
| Ack an interaction and defer the response
This route is only usable by component interactions, and doesn't trigger a
'thinking' message | # LANGUAGE TemplateHaskell #
module Calamity.HTTP.Interaction (
InteractionRequest (..),
InteractionCallbackMessageOptions (..),
InteractionCallbackAutocomplete (..),
InteractionCallbackAutocompleteChoice (..),
InteractionCallbackModal (..),
) where
import Calamity.HTTP.Channel (AllowedMentions, CreateMessageAttachment (..))
import Calamity.HTTP.Internal.Request
import Calamity.HTTP.Internal.Route
import Calamity.Internal.Utils (CalamityToJSON (..), CalamityToJSON' (..), (.=), (.?=))
import Calamity.Types.Model.Channel.Component (Component, CustomID)
import Calamity.Types.Model.Channel.Embed (Embed)
import Calamity.Types.Model.Channel.Message (Message)
import Calamity.Types.Model.Interaction
import Calamity.Types.Snowflake
import Data.Aeson qualified as Aeson
import Data.Bits (shiftL, (.|.))
import Data.Default.Class
import Data.HashMap.Strict qualified as H
import Data.Maybe (fromMaybe)
import Data.Monoid (First (First, getFirst))
import Data.Text (Text)
import Data.Text qualified as T
import Network.HTTP.Client.MultipartFormData
import Network.HTTP.Req
import Network.Mime
import Optics
data InteractionCallback = InteractionCallback
{ type_ :: InteractionCallbackType
, data_ :: Maybe Aeson.Value
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallback
instance CalamityToJSON' InteractionCallback where
toPairs InteractionCallback {..} =
[ "type" .= type_
, "data" .?= data_
]
data InteractionCallbackMessageOptions = InteractionCallbackMessageOptions
{ tts :: Maybe Bool
, content :: Maybe Text
, embeds :: Maybe [Embed]
, allowedMentions :: Maybe AllowedMentions
, ephemeral :: Maybe Bool
, suppressEmbeds :: Maybe Bool
, components :: Maybe [Component]
, attachments :: Maybe [CreateMessageAttachment]
}
deriving (Show)
instance Default InteractionCallbackMessageOptions where
def = InteractionCallbackMessageOptions Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
data CreateMessageAttachmentJson = CreateMessageAttachmentJson
{ id :: Int
, filename :: Text
, description :: Maybe Text
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON CreateMessageAttachmentJson
instance CalamityToJSON' CreateMessageAttachmentJson where
toPairs CreateMessageAttachmentJson {..} =
[ "id" .= id
, "filename" .= filename
, "description" .?= description
]
data CreateResponseMessageJson = CreateResponseMessageJson
{ tts :: Maybe Bool
, content :: Maybe Text
, embeds :: Maybe [Embed]
, allowedMentions :: Maybe AllowedMentions
, flags :: Maybe Int
, components :: Maybe [Component]
, attachments :: Maybe [CreateMessageAttachmentJson]
}
deriving (Show)
deriving (Aeson.ToJSON) via CalamityToJSON CreateResponseMessageJson
instance CalamityToJSON' CreateResponseMessageJson where
toPairs CreateResponseMessageJson {..} =
[ "tts" .?= tts
, "content" .?= content
, "embeds" .?= embeds
, "allowed_mentions" .?= allowedMentions
, "flags" .?= flags
, "components" .?= components
, "attachments" .?= attachments
]
newtype InteractionCallbackAutocomplete = InteractionCallbackAutocomplete
{ choices :: [InteractionCallbackAutocompleteChoice]
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackAutocomplete
instance CalamityToJSON' InteractionCallbackAutocomplete where
toPairs InteractionCallbackAutocomplete {..} = ["choices" .= choices]
data InteractionCallbackAutocompleteChoice = InteractionCallbackAutocompleteChoice
{ name :: Text
, nameLocalizations :: H.HashMap Text Text
, value :: Aeson.Value
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackAutocompleteChoice
instance CalamityToJSON' InteractionCallbackAutocompleteChoice where
toPairs InteractionCallbackAutocompleteChoice {..} =
[ "name" .= name
, "name_localizations" .= nameLocalizations
, "value" .= value
]
data InteractionCallbackModal = InteractionCallbackModal
{ customID :: CustomID
, title :: Text
, components :: [Component]
}
deriving stock (Show)
deriving (Aeson.ToJSON) via CalamityToJSON InteractionCallbackModal
instance CalamityToJSON' InteractionCallbackModal where
toPairs InteractionCallbackModal {..} =
[ "custom_id" .= customID
, "title" .= title
, "components" .= components
]
data InteractionCallbackType
= PongType
| ChannelMessageWithSourceType
| DeferredChannelMessageWithSourceType
| DeferredUpdateMessageType
| UpdateMessageType
| ApplicationCommandAutocompleteResultType
| ModalType
deriving (Show)
instance Aeson.ToJSON InteractionCallbackType where
toJSON ty = Aeson.toJSON @Int $ case ty of
PongType -> 1
ChannelMessageWithSourceType -> 4
DeferredChannelMessageWithSourceType -> 5
DeferredUpdateMessageType -> 6
UpdateMessageType -> 7
ApplicationCommandAutocompleteResultType -> 8
ModalType -> 9
toEncoding ty = Aeson.toEncoding @Int $ case ty of
PongType -> 1
ChannelMessageWithSourceType -> 4
DeferredChannelMessageWithSourceType -> 5
DeferredUpdateMessageType -> 6
UpdateMessageType -> 7
ApplicationCommandAutocompleteResultType -> 8
ModalType -> 9
$(makeFieldLabelsNoPrefix ''InteractionCallbackMessageOptions)
$(makeFieldLabelsNoPrefix ''InteractionCallbackAutocomplete)
$(makeFieldLabelsNoPrefix ''InteractionCallbackAutocompleteChoice)
$(makeFieldLabelsNoPrefix ''InteractionCallbackModal)
data InteractionRequest a where
CreateResponseMessage ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
CreateResponseDefer ::
(HasID Interaction i) =>
i ->
InteractionToken ->
Bool ->
InteractionRequest ()
CreateResponseDeferComponent ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionRequest ()
CreateResponseUpdate ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
CreateResponseAutocomplete ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackAutocomplete ->
InteractionRequest ()
CreateResponseModal ::
(HasID Interaction i) =>
i ->
InteractionToken ->
InteractionCallbackModal ->
InteractionRequest ()
GetOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionRequest Message
EditOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest Message
DeleteOriginalInteractionResponse ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionRequest ()
CreateFollowupMessage ::
(HasID Application i) =>
i ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
GetFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionRequest Message
EditFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionCallbackMessageOptions ->
InteractionRequest ()
DeleteFollowupMessage ::
(HasID Application i, HasID Message m) =>
i ->
m ->
InteractionToken ->
InteractionRequest ()
baseRoute :: Snowflake Application -> InteractionToken -> RouteBuilder _
baseRoute id (InteractionToken token) =
mkRouteBuilder // S "webhooks" // ID @Application // S token
& giveID id
foo :: Maybe a -> Maybe a -> (a -> a -> a) -> Maybe a
foo (Just x) (Just y) f = Just (f x y)
foo x y _ = getFirst $ First x <> First y
instance Request (InteractionRequest a) where
type Result (InteractionRequest a) = a
route (CreateResponseDefer (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseDeferComponent (getID @Interaction -> iid) (InteractionToken token)) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseMessage (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseUpdate (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseAutocomplete (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (CreateResponseModal (getID @Interaction -> iid) (InteractionToken token) _) =
mkRouteBuilder // S "interactions" // ID @Interaction // S token // S "callback"
& giveID iid
& buildRoute
route (GetOriginalInteractionResponse (getID @Application -> aid) token) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (EditOriginalInteractionResponse (getID @Application -> aid) token _) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (DeleteOriginalInteractionResponse (getID @Application -> aid) token) =
baseRoute aid token // S "messages" // S "@original" & buildRoute
route (CreateFollowupMessage (getID @Application -> aid) token _) =
baseRoute aid token & buildRoute
route (GetFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
route (EditFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token _) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
route (DeleteFollowupMessage (getID @Application -> aid) (getID @Message -> mid) token) =
baseRoute aid token // S "messages" // ID @Message & giveID mid & buildRoute
action (CreateResponseDefer _ _ ephemeral) =
let jsonBody =
InteractionCallback
{ type_ = DeferredChannelMessageWithSourceType
, data_ = if ephemeral then Just . Aeson.object $ [("flags", Aeson.Number 64)] else Nothing
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseDeferComponent _ _) =
let jsonBody =
InteractionCallback
{ type_ = DeferredUpdateMessageType
, data_ = Nothing
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseMessage _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = ChannelMessageWithSourceType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
postWith' body u o
action (CreateResponseUpdate _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = UpdateMessageType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
postWith' body u o
action (CreateResponseAutocomplete _ _ ao) =
let jsonBody =
InteractionCallback
{ type_ = ApplicationCommandAutocompleteResultType
, data_ = Just . Aeson.toJSON $ ao
}
in postWith' (ReqBodyJson jsonBody)
action (CreateResponseModal _ _ mo) =
let jsonBody =
InteractionCallback
{ type_ = ModalType
, data_ = Just . Aeson.toJSON $ mo
}
in postWith' (ReqBodyJson jsonBody)
action (GetOriginalInteractionResponse _ _) = getWith
action (EditOriginalInteractionResponse _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
jsonBody =
InteractionCallback
{ type_ = UpdateMessageType
, data_ = Just . Aeson.toJSON $ jsonData
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonBody) : files)
patchWith' body u o
action (DeleteOriginalInteractionResponse _ _) = deleteWith
action (CreateFollowupMessage _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonData) : files)
postWith' body u o
action GetFollowupMessage {} = getWith
action (EditFollowupMessage _ _ _ cm) = \u o -> do
let filePart CreateMessageAttachment {filename, content} n =
(partLBS @IO (T.pack $ "files[" <> show n <> "]") content)
{ partFilename = Just (T.unpack filename)
, partContentType = Just (defaultMimeLookup filename)
}
attachmentPart CreateMessageAttachment {filename, description} n =
CreateMessageAttachmentJson n filename description
files = zipWith filePart (fromMaybe [] $ cm ^. #attachments) [(0 :: Int) ..]
attachments = (\a -> zipWith attachmentPart a [0 ..]) <$> cm ^. #attachments
ephemeral = (\f -> if f then 1 `shiftL` 6 else 0) <$> cm ^. #ephemeral
suppressEmbeds = (\f -> if f then 1 `shiftL` 2 else 0) <$> cm ^. #suppressEmbeds
flags = foo ephemeral suppressEmbeds (.|.)
jsonData =
CreateResponseMessageJson
{ content = cm ^. #content
, tts = cm ^. #tts
, embeds = cm ^. #embeds
, allowedMentions = cm ^. #allowedMentions
, components = cm ^. #components
, attachments = attachments
, flags = flags
}
body <- reqBodyMultipart (partLBS "payload_json" (Aeson.encode jsonData) : files)
patchWith' body u o
action DeleteFollowupMessage {} = deleteWith
|
eb89179ce4a7eee7d04585a58a8efcba58defaf721d8d262558af6c02ae6d01d | mbj/stratosphere | HealthCheck.hs | module Stratosphere.Route53.HealthCheck (
module Exports, HealthCheck(..), mkHealthCheck
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import {-# SOURCE #-} Stratosphere.Route53.HealthCheck.HealthCheckConfigProperty as Exports
import {-# SOURCE #-} Stratosphere.Route53.HealthCheck.HealthCheckTagProperty as Exports
import Stratosphere.ResourceProperties
data HealthCheck
= HealthCheck {healthCheckConfig :: HealthCheckConfigProperty,
healthCheckTags :: (Prelude.Maybe [HealthCheckTagProperty])}
mkHealthCheck :: HealthCheckConfigProperty -> HealthCheck
mkHealthCheck healthCheckConfig
= HealthCheck
{healthCheckConfig = healthCheckConfig,
healthCheckTags = Prelude.Nothing}
instance ToResourceProperties HealthCheck where
toResourceProperties HealthCheck {..}
= ResourceProperties
{awsType = "AWS::Route53::HealthCheck",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["HealthCheckConfig" JSON..= healthCheckConfig]
(Prelude.catMaybes
[(JSON..=) "HealthCheckTags" Prelude.<$> healthCheckTags]))}
instance JSON.ToJSON HealthCheck where
toJSON HealthCheck {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["HealthCheckConfig" JSON..= healthCheckConfig]
(Prelude.catMaybes
[(JSON..=) "HealthCheckTags" Prelude.<$> healthCheckTags])))
instance Property "HealthCheckConfig" HealthCheck where
type PropertyType "HealthCheckConfig" HealthCheck = HealthCheckConfigProperty
set newValue HealthCheck {..}
= HealthCheck {healthCheckConfig = newValue, ..}
instance Property "HealthCheckTags" HealthCheck where
type PropertyType "HealthCheckTags" HealthCheck = [HealthCheckTagProperty]
set newValue HealthCheck {..}
= HealthCheck {healthCheckTags = Prelude.pure newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/route53/gen/Stratosphere/Route53/HealthCheck.hs | haskell | # SOURCE #
# SOURCE # | module Stratosphere.Route53.HealthCheck (
module Exports, HealthCheck(..), mkHealthCheck
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
data HealthCheck
= HealthCheck {healthCheckConfig :: HealthCheckConfigProperty,
healthCheckTags :: (Prelude.Maybe [HealthCheckTagProperty])}
mkHealthCheck :: HealthCheckConfigProperty -> HealthCheck
mkHealthCheck healthCheckConfig
= HealthCheck
{healthCheckConfig = healthCheckConfig,
healthCheckTags = Prelude.Nothing}
instance ToResourceProperties HealthCheck where
toResourceProperties HealthCheck {..}
= ResourceProperties
{awsType = "AWS::Route53::HealthCheck",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["HealthCheckConfig" JSON..= healthCheckConfig]
(Prelude.catMaybes
[(JSON..=) "HealthCheckTags" Prelude.<$> healthCheckTags]))}
instance JSON.ToJSON HealthCheck where
toJSON HealthCheck {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["HealthCheckConfig" JSON..= healthCheckConfig]
(Prelude.catMaybes
[(JSON..=) "HealthCheckTags" Prelude.<$> healthCheckTags])))
instance Property "HealthCheckConfig" HealthCheck where
type PropertyType "HealthCheckConfig" HealthCheck = HealthCheckConfigProperty
set newValue HealthCheck {..}
= HealthCheck {healthCheckConfig = newValue, ..}
instance Property "HealthCheckTags" HealthCheck where
type PropertyType "HealthCheckTags" HealthCheck = [HealthCheckTagProperty]
set newValue HealthCheck {..}
= HealthCheck {healthCheckTags = Prelude.pure newValue, ..} |
8635ad90659fa3ba249b657a4a9a5bcc14730f93b8f254452a6c4c91e908c831 | wdebeaum/DeepSemLex | throw.lisp | ;;;;
;;;; W::throw
;;;;
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::throw
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown :nom w::throw)))
(SENSES
((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090512 :comments nil :vn ("amuse-31.1") :wn ("throw%2:31:00" "throw%2:37:00"))
(LF-PARENT ONT::evoke-confusion)
(example "the detour threw them until they looked at the map")
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(PREFERENCE 0.96)
)
((LF-PARENT ONT::propel)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(example "he threw the ball")
(meta-data :origin step :entry-date 20080721 :change-date nil :comments nil)
)
)
)
))
(define-words :pos W::v
:words (
((W::throw (W::up))
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown)))
(SENSES
((LF-PARENT ONT::visual-display)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(example "throw up the map")
)
((EXAMPLE "The patient threw up")
(LF-PARENT ONT::vomit)
(TEMPL affected-TEMPL)
)
)
)
))
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
((W::throw (W::off))
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown)))
(SENSES
((EXAMPLE "My schedule is all thrown off ")
(LF-PARENT ONT::hindering)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
)
)
)
))
| null | https://raw.githubusercontent.com/wdebeaum/DeepSemLex/ce0e7523dd2b1ebd42b9e88ffbcfdb0fd339aaee/trips/src/LexiconManager/Data/new/throw.lisp | lisp |
W::throw
|
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
(W::throw
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown :nom w::throw)))
(SENSES
((meta-data :origin "verbnet-2.0" :entry-date 20060315 :change-date 20090512 :comments nil :vn ("amuse-31.1") :wn ("throw%2:31:00" "throw%2:37:00"))
(LF-PARENT ONT::evoke-confusion)
(example "the detour threw them until they looked at the map")
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(PREFERENCE 0.96)
)
((LF-PARENT ONT::propel)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(example "he threw the ball")
(meta-data :origin step :entry-date 20080721 :change-date nil :comments nil)
)
)
)
))
(define-words :pos W::v
:words (
((W::throw (W::up))
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown)))
(SENSES
((LF-PARENT ONT::visual-display)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
(example "throw up the map")
)
((EXAMPLE "The patient threw up")
(LF-PARENT ONT::vomit)
(TEMPL affected-TEMPL)
)
)
)
))
(define-words :pos W::v :TEMPL AGENT-FORMAL-XP-TEMPL
:words (
((W::throw (W::off))
(wordfeats (W::morph (:forms (-vb) :past W::threw :pastpart W::thrown)))
(SENSES
((EXAMPLE "My schedule is all thrown off ")
(LF-PARENT ONT::hindering)
(TEMPL AGENT-AFFECTED-XP-NP-TEMPL)
)
)
)
))
|
95f622c167981d9ffeeed9662d675317d147e604114df0ab7bb2d3abd7ad211d | privet-kitty/cl-competitive | mod-inverse.lisp | (defpackage :cp/mod-inverse
(:use :cl)
#+sbcl (:import-from #:sb-c #:defoptimizer #:lvar-type #:integer-type-numeric-bounds
#:derive-type #:flushable #:foldable)
#+sbcl (:import-from :sb-kernel #:specifier-type)
(:export #:mod-inverse))
(in-package :cp/mod-inverse)
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(sb-c:defknown %mod-inverse ((integer 0) (integer 1)) (integer 0)
(flushable foldable)
:overwrite-fndb-silently t)
(sb-c:defknown mod-inverse (integer (integer 1)) (integer 0)
(flushable foldable)
:overwrite-fndb-silently t)
(defun derive-mod (modulus)
(let ((high (nth-value 1 (integer-type-numeric-bounds (lvar-type modulus)))))
(specifier-type (if (integerp high)
`(integer 0 (,high))
`(integer 0)))))
(defoptimizer (%mod-inverse derive-type) ((integer modulus))
(declare (ignore integer))
(derive-mod modulus))
(defoptimizer (mod-inverse derive-type) ((integer modulus))
(declare (ignore integer))
(derive-mod modulus)))
(defun %mod-inverse (integer modulus)
(declare (optimize (speed 3) (safety 0))
#+sbcl (sb-ext:muffle-conditions sb-ext:compiler-note))
(macrolet ((frob (stype)
`(let ((a integer)
(b modulus)
(u 1)
(v 0))
(declare (,stype a b u v))
(loop until (zerop b)
for quot = (floor a b)
do (decf a (the ,stype (* quot b)))
(rotatef a b)
(decf u (the ,stype (* quot v)))
(rotatef u v))
(if (< u 0)
(+ u modulus)
u))))
(typecase modulus
((unsigned-byte 31) (frob (signed-byte 32)))
((unsigned-byte 62) (frob (signed-byte 63)))
(otherwise (frob integer)))))
(declaim (inline mod-inverse))
(defun mod-inverse (integer modulus)
"Solves ax = 1 mod m. Signals DIVISION-BY-ZERO when INTEGER and MODULUS are
not coprime."
(let* ((integer (mod integer modulus))
(result (%mod-inverse integer modulus)))
(unless (or (= 1 (mod (* integer result) modulus)) (= 1 modulus))
(error 'division-by-zero
:operands (list integer modulus)
:operation 'mod-inverse))
result))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/9c91901c2288b5d0de0f53aa039f96abb9b441b2/module/mod-inverse.lisp | lisp | (defpackage :cp/mod-inverse
(:use :cl)
#+sbcl (:import-from #:sb-c #:defoptimizer #:lvar-type #:integer-type-numeric-bounds
#:derive-type #:flushable #:foldable)
#+sbcl (:import-from :sb-kernel #:specifier-type)
(:export #:mod-inverse))
(in-package :cp/mod-inverse)
#+sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(sb-c:defknown %mod-inverse ((integer 0) (integer 1)) (integer 0)
(flushable foldable)
:overwrite-fndb-silently t)
(sb-c:defknown mod-inverse (integer (integer 1)) (integer 0)
(flushable foldable)
:overwrite-fndb-silently t)
(defun derive-mod (modulus)
(let ((high (nth-value 1 (integer-type-numeric-bounds (lvar-type modulus)))))
(specifier-type (if (integerp high)
`(integer 0 (,high))
`(integer 0)))))
(defoptimizer (%mod-inverse derive-type) ((integer modulus))
(declare (ignore integer))
(derive-mod modulus))
(defoptimizer (mod-inverse derive-type) ((integer modulus))
(declare (ignore integer))
(derive-mod modulus)))
(defun %mod-inverse (integer modulus)
(declare (optimize (speed 3) (safety 0))
#+sbcl (sb-ext:muffle-conditions sb-ext:compiler-note))
(macrolet ((frob (stype)
`(let ((a integer)
(b modulus)
(u 1)
(v 0))
(declare (,stype a b u v))
(loop until (zerop b)
for quot = (floor a b)
do (decf a (the ,stype (* quot b)))
(rotatef a b)
(decf u (the ,stype (* quot v)))
(rotatef u v))
(if (< u 0)
(+ u modulus)
u))))
(typecase modulus
((unsigned-byte 31) (frob (signed-byte 32)))
((unsigned-byte 62) (frob (signed-byte 63)))
(otherwise (frob integer)))))
(declaim (inline mod-inverse))
(defun mod-inverse (integer modulus)
"Solves ax = 1 mod m. Signals DIVISION-BY-ZERO when INTEGER and MODULUS are
not coprime."
(let* ((integer (mod integer modulus))
(result (%mod-inverse integer modulus)))
(unless (or (= 1 (mod (* integer result) modulus)) (= 1 modulus))
(error 'division-by-zero
:operands (list integer modulus)
:operation 'mod-inverse))
result))
| |
1cf42175645d8e60da073dabb4a284c73b43759d21df0a52d6d633544942f533 | probprog/anglican | bamc.cljc | (ns anglican.bamc
"Bayesian ascent Monte Carlo
Options:
:predict-candidates (false by default)
- output all samples rather than just those
with increasing log-weight"
(:refer-clojure :exclude [rand rand-int rand-nth])
(:require [anglican.state :refer [get-log-weight add-log-weight add-predict]])
(:use #?(:clj anglican.inference
:cljs [anglican.inference :only [infer checkpoint checkpoint-id exec
rand]])
[anglican.runtime :only [sample* observe* normal]]))
;;;;; Maximum a Posteriori Estimation through Sampling
(derive ::algorithm :anglican.inference/algorithm)
;;;; Particle state
(def initial-state
"initial state for MAP estimation"
(into anglican.state/initial-state
{::bandits {} ; multi-armed bandits
::trace [] ; random choices
::bandit-counts {} ; counts of occurences of `sample's
::bandit-last-id nil})) ; last sample id
Bayesian updating , for randomized probability matching
(defprotocol bayesian-belief
"Bayesian belief"
(bb-update [belief evidence]
"updates belief based on the evidence")
(bb-sample [belief]
"returns a random sample from the belief distribution")
(bb-sample-mean [belief]
"returns a random sample from the mean belief distribution")
(bb-as-prior [belief]
"returns a belief for use as a prior belief"))
;;;; Mean reward belief
(defn reward-belief
"returns reification of bayesian belief
about the mean reward of an arm"
[sum sum2 ^double cnt]
Bayesian belief about the reward ( log - weight ) .
(let [mean (/ sum cnt)
sd (Math/sqrt (- (/ sum2 cnt) (* mean mean)))
mean-sd (/ sd (Math/sqrt cnt))
dist (normal mean sd)
mean-dist (normal mean mean-sd)]
(reify bayesian-belief
(bb-update [rb reward]
(reward-belief
(+ sum reward) (+ sum2 (* reward reward)) (+ cnt 1.)))
(bb-sample [rb] (sample* dist))
(bb-sample-mean [rb] (sample* mean-dist))
(bb-as-prior [rb]
;; The current belief is converted to a prior belief
by setting the sample count to 1 and preserving
;; the mean and variance.
(if (<= cnt 1.) rb
(reward-belief (/ sum cnt) (/ sum2 cnt) 1.))))))
(def initial-reward-belief
"uninformative mean reward belief"
(reward-belief 0. 0. 0.))
;;;; Bandit
(defrecord multiarmed-bandit [arms
new-arm-belief
new-arm-count
new-arm-drawn])
(def fresh-bandit
"bandit with no arm pulls"
(map->multiarmed-bandit
{:arms {}
:new-arm-belief initial-reward-belief
:new-arm-count 0}))
An arm has two fields , : belief and : count . : count is the number
;; of times the arm was randomly selected from the prior as new.
;; Selects arms using open randomized probability matching.
(def ^:private +not-a-value+
"value of new arm"
::not-a-value)
(defn not-a-value?
"true when new value must be sampled"
[value]
(= value +not-a-value+))
(defn select-value
"selects value corresponding to the best arm"
[bandit log-p]
;; If the best arm happens to be a new arm,
;; return +not-a-value+. Checkpoint [::algorithm sample]
;; accounts for this and samples a new value
;; from the prior.
(if (empty? (seq (:arms bandit))) +not-a-value+
(loop [arms (:arms bandit)
best-reward (/ -1. 0.)
best-value +not-a-value+
best-belief nil]
First , we choose the new arm candidate proportional
;; to the probability that the reward drawn from the
;; arm is the maximum one.
(if-let [[[value {:keys [belief count]}] & arms] (seq arms)]
(let [reward (+ (log-p value)
(reduce max
(repeatedly
count #(bb-sample belief))))]
(if (>= reward best-reward)
(recur arms reward value belief)
(recur arms best-reward best-value best-belief)))
;; Then, we select an arm with the probability
;; that the arm has the highest *average* reward,
;; including the new arm candidate.
(loop [arms (:arms bandit)
best-reward (if (not-a-value? best-value)
(/ -1. 0.)
(+ (log-p best-value)
(bb-sample-mean best-belief)))
best-value +not-a-value+
parity 0.] ; number of
(if-let [[[value {:keys [belief count]}] & arms] (seq arms)]
(let [reward (+ (log-p value)
(reduce max
(repeatedly
count #(bb-sample-mean belief))))]
(cond
(> reward best-reward)
(recur arms reward value parity)
(= reward best-reward)
(let [parity (+ parity (double count))]
(if (> (/ parity) (rand))
(recur arms reward value parity)
(recur arms best-reward best-value parity)))
:else
(recur arms best-reward best-value parity)))
best-value))))))
(defn update-bandit
"updates bandit's belief"
[bandit value reward]
(let [bandit (if (:new-arm-drawn bandit)
;; A new arm was drawn, which may or may not
;; coincide with an existing arm.
(-> bandit
(update-in [:new-arm-belief] bb-update reward)
(update-in [:new-arm-count] inc)
(update-in [:arms value :count]
(fnil inc 0)))
bandit)]
;; Update the belief about the mean reward of the sampled arm.
(update-in bandit [:arms value :belief]
(fnil bb-update
;; If the arm is new, derive the belief from
;; the belief about a randomly drawn arm.
(bb-as-prior (:new-arm-belief bandit)))
reward)))
Trace
;; The trace is a vector of tuples
;; [bandit-id value past-reward]
;; where past reward is the reward accumulated before
;; reaching this random choice.
(defrecord entry [bandit-id value past-reward])
(defn bandit-id [smp state]
"returns bandit id for the checkpoint and the updated-state"
(checkpoint-id smp state ::bandit-counts ::bandit-last-id))
(defn record-choice
"records random choice in the state"
[state bandit-id value past-reward]
(update-in state [::trace]
conj (->entry bandit-id value past-reward)))
;;;; MAP inference
(defmethod checkpoint [::algorithm anglican.trap.sample] [algorithm smp]
(let [state (:state smp)
[bandit-id state] (bandit-id smp state)
bandit ((state ::bandits) bandit-id fresh-bandit)
;; Select value:
;; Select a value as a bandit arm.
value (select-value bandit #(observe* (:dist smp) %))
;; Remember whether a new arm was drawn;
;; new arm belief is updated during back-propagation.
bandit (assoc bandit :new-arm-drawn (not-a-value? value))
;; Sample a new value if a new arm was drawn.
value (if (not-a-value? value)
(sample* (:dist smp))
value)
;; Update state:
;; Insert an entry for the random choice into the trace.
state (record-choice
state bandit-id value (get-log-weight state))
;; Increment the log weight by the probability
;; of the sampled value.
state (add-log-weight state (observe* (:dist smp) value))
;; Re-insert the bandit; the bandit may be fresh,
;; and the new-arm-drawn flag may have been updated.
state (assoc-in state [::bandits bandit-id] bandit)]
;; Finally, continue the execution.
#((:cont smp) value state)))
;; Backpropagating rewards
(defn backpropagate
"back propagate reward to bandits"
[state]
(let [reward (get-log-weight state)]
(if (< (/ -1. 0.) reward (/ 1. 0.))
;; Detach the trace and the bandits from the existing
;; states, update the bandits and reattach them to
;; the initial state.
(loop [trace (state ::trace)
bandits (state ::bandits)]
(if (seq trace)
(let [[{:keys [bandit-id value past-reward]} & trace] trace]
(recur
trace
(update-in bandits [bandit-id]
;; Bandit arms grow incrementally.
update-bandit value (- reward past-reward))))
(assoc initial-state ::bandits bandits)))
;; If the reward is not meaningful, drop it and
;; carry over the bandits.
(assoc initial-state
::bandits (state ::bandits)))))
;;; Reporting the mode
(defn add-trace-predict
"adds trace as a predict"
[state]
(add-predict state '$trace
(map :value (::trace state))))
;;; Reporting the internal statistics
(defn add-bandit-predict
"add bandit arms and counts as a predict"
[state]
(add-predict state '$bandits
(sort-by
first
(map (fn [[bandit-id {:keys [arms new-arm-count]}]]
;; For each bandit, report the number of
;; arms and the number of times a new arm
;; was chosen.
[bandit-id {:arm-count (count arms)
:new-arm-count new-arm-count}])
(state ::bandits)))))
;;; Inference method
(defmethod infer :bamc
[_ prog value
& {:keys [;; Add the trace as a predict.
predict-trace
;; Output all states rather than just states
;; with increasing log-weight.
predict-candidates
;; Report internal statistics.
predict-bandits
;; Total number of samples to produce.
number-of-samples]
:or {predict-trace false
predict-candidates false
predict-bandits false}}]
The MAP inference consists of two chained transformations ,
;; `sample-seq', followed by `map-seq'.
(letfn
[(sample-seq [state]
(lazy-seq
(let [state (:state (exec ::algorithm prog value
(backpropagate state)))
state (if predict-trace
(add-trace-predict state)
state)
state (if predict-bandits
(add-bandit-predict state)
state)]
(cons state
(sample-seq state)))))
(map-seq [sample-seq max-log-weight]
;; Filters MAP estimates by increasing weight.
(lazy-seq
(when-let [[sample & sample-seq] (seq sample-seq)]
(if (or predict-candidates
(> (get-log-weight sample) max-log-weight))
(cons sample
(map-seq sample-seq (get-log-weight sample)))
(map-seq sample-seq max-log-weight)))))]
(let [sample-seq (sample-seq
(:state
(exec ::algorithm prog value initial-state)))
sample-seq (if number-of-samples
(take number-of-samples sample-seq)
sample-seq)]
(map-seq sample-seq (Math/log 0.)))))
| null | https://raw.githubusercontent.com/probprog/anglican/ab6111d7fa8f68f42ea046feab928ca3eedde1d7/src/anglican/bamc.cljc | clojure | Maximum a Posteriori Estimation through Sampling
Particle state
multi-armed bandits
random choices
counts of occurences of `sample's
last sample id
Mean reward belief
The current belief is converted to a prior belief
the mean and variance.
Bandit
of times the arm was randomly selected from the prior as new.
Selects arms using open randomized probability matching.
If the best arm happens to be a new arm,
return +not-a-value+. Checkpoint [::algorithm sample]
accounts for this and samples a new value
from the prior.
to the probability that the reward drawn from the
arm is the maximum one.
Then, we select an arm with the probability
that the arm has the highest *average* reward,
including the new arm candidate.
number of
A new arm was drawn, which may or may not
coincide with an existing arm.
Update the belief about the mean reward of the sampled arm.
If the arm is new, derive the belief from
the belief about a randomly drawn arm.
The trace is a vector of tuples
[bandit-id value past-reward]
where past reward is the reward accumulated before
reaching this random choice.
MAP inference
Select value:
Select a value as a bandit arm.
Remember whether a new arm was drawn;
new arm belief is updated during back-propagation.
Sample a new value if a new arm was drawn.
Update state:
Insert an entry for the random choice into the trace.
Increment the log weight by the probability
of the sampled value.
Re-insert the bandit; the bandit may be fresh,
and the new-arm-drawn flag may have been updated.
Finally, continue the execution.
Backpropagating rewards
Detach the trace and the bandits from the existing
states, update the bandits and reattach them to
the initial state.
Bandit arms grow incrementally.
If the reward is not meaningful, drop it and
carry over the bandits.
Reporting the mode
Reporting the internal statistics
For each bandit, report the number of
arms and the number of times a new arm
was chosen.
Inference method
Add the trace as a predict.
Output all states rather than just states
with increasing log-weight.
Report internal statistics.
Total number of samples to produce.
`sample-seq', followed by `map-seq'.
Filters MAP estimates by increasing weight. | (ns anglican.bamc
"Bayesian ascent Monte Carlo
Options:
:predict-candidates (false by default)
- output all samples rather than just those
with increasing log-weight"
(:refer-clojure :exclude [rand rand-int rand-nth])
(:require [anglican.state :refer [get-log-weight add-log-weight add-predict]])
(:use #?(:clj anglican.inference
:cljs [anglican.inference :only [infer checkpoint checkpoint-id exec
rand]])
[anglican.runtime :only [sample* observe* normal]]))
(derive ::algorithm :anglican.inference/algorithm)
(def initial-state
"initial state for MAP estimation"
(into anglican.state/initial-state
Bayesian updating , for randomized probability matching
(defprotocol bayesian-belief
"Bayesian belief"
(bb-update [belief evidence]
"updates belief based on the evidence")
(bb-sample [belief]
"returns a random sample from the belief distribution")
(bb-sample-mean [belief]
"returns a random sample from the mean belief distribution")
(bb-as-prior [belief]
"returns a belief for use as a prior belief"))
(defn reward-belief
"returns reification of bayesian belief
about the mean reward of an arm"
[sum sum2 ^double cnt]
Bayesian belief about the reward ( log - weight ) .
(let [mean (/ sum cnt)
sd (Math/sqrt (- (/ sum2 cnt) (* mean mean)))
mean-sd (/ sd (Math/sqrt cnt))
dist (normal mean sd)
mean-dist (normal mean mean-sd)]
(reify bayesian-belief
(bb-update [rb reward]
(reward-belief
(+ sum reward) (+ sum2 (* reward reward)) (+ cnt 1.)))
(bb-sample [rb] (sample* dist))
(bb-sample-mean [rb] (sample* mean-dist))
(bb-as-prior [rb]
by setting the sample count to 1 and preserving
(if (<= cnt 1.) rb
(reward-belief (/ sum cnt) (/ sum2 cnt) 1.))))))
(def initial-reward-belief
"uninformative mean reward belief"
(reward-belief 0. 0. 0.))
(defrecord multiarmed-bandit [arms
new-arm-belief
new-arm-count
new-arm-drawn])
(def fresh-bandit
"bandit with no arm pulls"
(map->multiarmed-bandit
{:arms {}
:new-arm-belief initial-reward-belief
:new-arm-count 0}))
An arm has two fields , : belief and : count . : count is the number
(def ^:private +not-a-value+
"value of new arm"
::not-a-value)
(defn not-a-value?
"true when new value must be sampled"
[value]
(= value +not-a-value+))
(defn select-value
"selects value corresponding to the best arm"
[bandit log-p]
(if (empty? (seq (:arms bandit))) +not-a-value+
(loop [arms (:arms bandit)
best-reward (/ -1. 0.)
best-value +not-a-value+
best-belief nil]
First , we choose the new arm candidate proportional
(if-let [[[value {:keys [belief count]}] & arms] (seq arms)]
(let [reward (+ (log-p value)
(reduce max
(repeatedly
count #(bb-sample belief))))]
(if (>= reward best-reward)
(recur arms reward value belief)
(recur arms best-reward best-value best-belief)))
(loop [arms (:arms bandit)
best-reward (if (not-a-value? best-value)
(/ -1. 0.)
(+ (log-p best-value)
(bb-sample-mean best-belief)))
best-value +not-a-value+
(if-let [[[value {:keys [belief count]}] & arms] (seq arms)]
(let [reward (+ (log-p value)
(reduce max
(repeatedly
count #(bb-sample-mean belief))))]
(cond
(> reward best-reward)
(recur arms reward value parity)
(= reward best-reward)
(let [parity (+ parity (double count))]
(if (> (/ parity) (rand))
(recur arms reward value parity)
(recur arms best-reward best-value parity)))
:else
(recur arms best-reward best-value parity)))
best-value))))))
(defn update-bandit
"updates bandit's belief"
[bandit value reward]
(let [bandit (if (:new-arm-drawn bandit)
(-> bandit
(update-in [:new-arm-belief] bb-update reward)
(update-in [:new-arm-count] inc)
(update-in [:arms value :count]
(fnil inc 0)))
bandit)]
(update-in bandit [:arms value :belief]
(fnil bb-update
(bb-as-prior (:new-arm-belief bandit)))
reward)))
Trace
(defrecord entry [bandit-id value past-reward])
(defn bandit-id [smp state]
"returns bandit id for the checkpoint and the updated-state"
(checkpoint-id smp state ::bandit-counts ::bandit-last-id))
(defn record-choice
"records random choice in the state"
[state bandit-id value past-reward]
(update-in state [::trace]
conj (->entry bandit-id value past-reward)))
(defmethod checkpoint [::algorithm anglican.trap.sample] [algorithm smp]
(let [state (:state smp)
[bandit-id state] (bandit-id smp state)
bandit ((state ::bandits) bandit-id fresh-bandit)
value (select-value bandit #(observe* (:dist smp) %))
bandit (assoc bandit :new-arm-drawn (not-a-value? value))
value (if (not-a-value? value)
(sample* (:dist smp))
value)
state (record-choice
state bandit-id value (get-log-weight state))
state (add-log-weight state (observe* (:dist smp) value))
state (assoc-in state [::bandits bandit-id] bandit)]
#((:cont smp) value state)))
(defn backpropagate
"back propagate reward to bandits"
[state]
(let [reward (get-log-weight state)]
(if (< (/ -1. 0.) reward (/ 1. 0.))
(loop [trace (state ::trace)
bandits (state ::bandits)]
(if (seq trace)
(let [[{:keys [bandit-id value past-reward]} & trace] trace]
(recur
trace
(update-in bandits [bandit-id]
update-bandit value (- reward past-reward))))
(assoc initial-state ::bandits bandits)))
(assoc initial-state
::bandits (state ::bandits)))))
(defn add-trace-predict
"adds trace as a predict"
[state]
(add-predict state '$trace
(map :value (::trace state))))
(defn add-bandit-predict
"add bandit arms and counts as a predict"
[state]
(add-predict state '$bandits
(sort-by
first
(map (fn [[bandit-id {:keys [arms new-arm-count]}]]
[bandit-id {:arm-count (count arms)
:new-arm-count new-arm-count}])
(state ::bandits)))))
(defmethod infer :bamc
[_ prog value
predict-trace
predict-candidates
predict-bandits
number-of-samples]
:or {predict-trace false
predict-candidates false
predict-bandits false}}]
The MAP inference consists of two chained transformations ,
(letfn
[(sample-seq [state]
(lazy-seq
(let [state (:state (exec ::algorithm prog value
(backpropagate state)))
state (if predict-trace
(add-trace-predict state)
state)
state (if predict-bandits
(add-bandit-predict state)
state)]
(cons state
(sample-seq state)))))
(map-seq [sample-seq max-log-weight]
(lazy-seq
(when-let [[sample & sample-seq] (seq sample-seq)]
(if (or predict-candidates
(> (get-log-weight sample) max-log-weight))
(cons sample
(map-seq sample-seq (get-log-weight sample)))
(map-seq sample-seq max-log-weight)))))]
(let [sample-seq (sample-seq
(:state
(exec ::algorithm prog value initial-state)))
sample-seq (if number-of-samples
(take number-of-samples sample-seq)
sample-seq)]
(map-seq sample-seq (Math/log 0.)))))
|
dcd07d4aaf79c87d8c5e704ec1e62cf61acff4fdc8b627396a1ddd69c9d04adb | mfp/extprot | conv.ml |
max_known , found
type ('a, 'hint, 'path) string_reader =
?hint:'hint -> ?level:int -> ?path:'path -> Reader.String_reader.t -> 'a
type ('a, 'hint, 'path) io_reader =
?hint:'hint -> ?level:int -> ?path:'path -> Reader.IO_reader.t -> 'a
type 'a writer = (Msg_buffer.t -> 'a -> unit)
let get_buf = function
None -> Msg_buffer.create ()
| Some b -> Msg_buffer.clear b; b
let serialize ?buf f x =
let b = get_buf buf in
f b x;
Msg_buffer.contents b
let dump f buf x =
Msg_buffer.clear buf;
f buf x
let deserialize (f : _ string_reader) ?hint ?(offset = 0) s =
f ?hint (Reader.String_reader.make s offset (String.length s - offset))
let serialize_versioned ?buf fs version x =
let buf = get_buf buf in
if version < 0 || version > 0xFFFF || version >= Array.length fs then
invalid_arg ("Extprot.Conv.serialize_versioned: bad version " ^
string_of_int version);
Msg_buffer.add_byte buf (version land 0xFF);
Msg_buffer.add_byte buf ((version lsr 8) land 0xFF);
fs.(version) buf x;
Msg_buffer.contents buf
let deserialize_versioned (fs : _ string_reader array) ?hint s =
let len = String.length s in
if len < 2 then
raise (Wrong_protocol_version (Array.length fs, -1));
let version = Char.code (s.[0]) + (Char.code s.[1] lsl 8) in
if version < Array.length fs then
fs.(version) ?hint (Reader.String_reader.make s 2 (len - 2))
else
raise (Wrong_protocol_version (Array.length fs, version))
let deserialize_versioned' (fs : _ string_reader array) ?hint version msg =
if version >= 0 && version < Array.length fs then
fs.(version) ?hint (Reader.String_reader.make msg 0 (String.length msg))
else
raise (Wrong_protocol_version (Array.length fs, version))
let read (f : _ io_reader) ?hint io = f ?hint (Reader.IO_reader.from_io io)
let write ?buf (f : Msg_buffer.t -> 'a -> unit) io (x : 'a) =
let buf = get_buf buf in
f buf x;
Msg_buffer.output_buffer_to_io io buf
let read_versioned (fs : _ io_reader array) ?hint rd =
let a = Reader.IO_reader.read_byte rd in
let b = Reader.IO_reader.read_byte rd in
let version = a + b lsl 8 in
if version < Array.length fs then
fs.(version) ?hint rd
else begin
let hd = Reader.IO_reader.read_prefix rd in
Reader.IO_reader.skip_value rd hd;
raise (Wrong_protocol_version ((Array.length fs), version))
end
let io_read_versioned fs ?hint io =
read_versioned fs ?hint (Reader.IO_reader.from_io io)
let write_versioned ?buf fs version io x =
let buf = get_buf buf in
if version < 0 || version > 0xFFFF || version >= Array.length fs then
invalid_arg ("Extprot.Conv.write_versioned: bad version " ^
string_of_int version);
fs.(version) buf x;
IO.write_ui16 io version;
Msg_buffer.output_buffer_to_io io buf
let read_frame io =
let rd = Reader.IO_reader.from_io io in
let a = Reader.IO_reader.read_byte rd in
let b = Reader.IO_reader.read_byte rd in
let version = a + b lsl 8 in
(version, Reader.IO_reader.read_message rd)
| null | https://raw.githubusercontent.com/mfp/extprot/c69eb66398e35b964c4232a7c3c85151fb5eddbe/runtime/conv.ml | ocaml |
max_known , found
type ('a, 'hint, 'path) string_reader =
?hint:'hint -> ?level:int -> ?path:'path -> Reader.String_reader.t -> 'a
type ('a, 'hint, 'path) io_reader =
?hint:'hint -> ?level:int -> ?path:'path -> Reader.IO_reader.t -> 'a
type 'a writer = (Msg_buffer.t -> 'a -> unit)
let get_buf = function
None -> Msg_buffer.create ()
| Some b -> Msg_buffer.clear b; b
let serialize ?buf f x =
let b = get_buf buf in
f b x;
Msg_buffer.contents b
let dump f buf x =
Msg_buffer.clear buf;
f buf x
let deserialize (f : _ string_reader) ?hint ?(offset = 0) s =
f ?hint (Reader.String_reader.make s offset (String.length s - offset))
let serialize_versioned ?buf fs version x =
let buf = get_buf buf in
if version < 0 || version > 0xFFFF || version >= Array.length fs then
invalid_arg ("Extprot.Conv.serialize_versioned: bad version " ^
string_of_int version);
Msg_buffer.add_byte buf (version land 0xFF);
Msg_buffer.add_byte buf ((version lsr 8) land 0xFF);
fs.(version) buf x;
Msg_buffer.contents buf
let deserialize_versioned (fs : _ string_reader array) ?hint s =
let len = String.length s in
if len < 2 then
raise (Wrong_protocol_version (Array.length fs, -1));
let version = Char.code (s.[0]) + (Char.code s.[1] lsl 8) in
if version < Array.length fs then
fs.(version) ?hint (Reader.String_reader.make s 2 (len - 2))
else
raise (Wrong_protocol_version (Array.length fs, version))
let deserialize_versioned' (fs : _ string_reader array) ?hint version msg =
if version >= 0 && version < Array.length fs then
fs.(version) ?hint (Reader.String_reader.make msg 0 (String.length msg))
else
raise (Wrong_protocol_version (Array.length fs, version))
let read (f : _ io_reader) ?hint io = f ?hint (Reader.IO_reader.from_io io)
let write ?buf (f : Msg_buffer.t -> 'a -> unit) io (x : 'a) =
let buf = get_buf buf in
f buf x;
Msg_buffer.output_buffer_to_io io buf
let read_versioned (fs : _ io_reader array) ?hint rd =
let a = Reader.IO_reader.read_byte rd in
let b = Reader.IO_reader.read_byte rd in
let version = a + b lsl 8 in
if version < Array.length fs then
fs.(version) ?hint rd
else begin
let hd = Reader.IO_reader.read_prefix rd in
Reader.IO_reader.skip_value rd hd;
raise (Wrong_protocol_version ((Array.length fs), version))
end
let io_read_versioned fs ?hint io =
read_versioned fs ?hint (Reader.IO_reader.from_io io)
let write_versioned ?buf fs version io x =
let buf = get_buf buf in
if version < 0 || version > 0xFFFF || version >= Array.length fs then
invalid_arg ("Extprot.Conv.write_versioned: bad version " ^
string_of_int version);
fs.(version) buf x;
IO.write_ui16 io version;
Msg_buffer.output_buffer_to_io io buf
let read_frame io =
let rd = Reader.IO_reader.from_io io in
let a = Reader.IO_reader.read_byte rd in
let b = Reader.IO_reader.read_byte rd in
let version = a + b lsl 8 in
(version, Reader.IO_reader.read_message rd)
| |
1468d96796deb2399c9d5ccff936c8737c0acf2d826cd50be36b2b80f5a98de8 | mstksg/tensor-ops | HMat.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE InstanceSigs #
{-# LANGUAGE KindSignatures #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE UndecidableInstances #
module TensorOps.BLAS.HMat
( HMat
, HMatD
) where
import Control.DeepSeq
import Data.Kind
import Data.Singletons
import Data.Singletons.TypeLits
import Data.Type.Combinator
import Data.Type.Vector (Vec, VecT(..))
import Data.Type.Vector.Util (curryV2', curryV3')
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Data as LA
import Numeric.LinearAlgebra.Devel
import TensorOps.BLAS
import Type.Class.Higher
import Type.Class.Higher.Util
import qualified Data.Finite as DF
import qualified Data.Finite.Internal as DF
import qualified Data.Vector.Storable as VS
type HMatD = HMat Double
data HMat :: Type -> BShape Nat -> Type where
HMV :: { unHMV :: !(Vector a) } -> HMat a ('BV n)
HMM :: { unHMM :: !(Matrix a) } -> HMat a ('BM n m)
instance (VS.Storable a, Show a, Element a) => Show (HMat a s) where
showsPrec p = \case
HMV x -> showParen (p > 10) $ showString "HMV "
. showsPrec 11 x
HMM x -> showParen (p > 10) $ showString "HMM "
. showsPrec 11 x
instance (VS.Storable a, Show a, Element a) => Show1 (HMat a)
instance (VS.Storable a, NFData a) => NFData (HMat a s) where
rnf = \case
HMV xs -> rnf xs
HMM xs -> rnf xs
# INLINE rnf #
instance (VS.Storable a, NFData a) => NFData1 (HMat a)
instance (SingI s, Container Vector a, Container Matrix a, Num a) => Num (HMat a s) where
(+) = unsafeZipH add add
(*) = unsafeZipH (VS.zipWith (*)) (liftMatrix2 (VS.zipWith (*)))
(-) = unsafeZipH (VS.zipWith (-)) (liftMatrix2 (VS.zipWith (-)))
negate = unsafeMapH (scale (-1)) (scale (-1))
abs = unsafeMapH (cmap abs) (cmap abs)
signum = unsafeMapH (cmap signum) (cmap signum)
fromInteger = case (sing :: Sing s) of
SBV n -> HMV . flip konst (fromIntegral (fromSing n)) . fromInteger
SBM n m -> HMM . flip konst (fromIntegral (fromSing n)
,fromIntegral (fromSing m)
) . fromInteger
-- | WARNING!! Functions should assume equal sized inputs and return
-- outputs of the same size! This is not checked!!!
unsafeZipH
:: (Vector a -> Vector a -> Vector a)
-> (Matrix a -> Matrix a -> Matrix a)
-> HMat a s -> HMat a s -> HMat a s
unsafeZipH f g = \case
HMV x -> \case
HMV y -> HMV $ f x y
HMM x -> \case
HMM y -> HMM $ g x y
-- | WARNING!! Functions should return outputs of the same size! This is
-- not checked!!!
unsafeMapH
:: (Vector a -> Vector a)
-> (Matrix a -> Matrix a)
-> HMat a s -> HMat a s
unsafeMapH f g = \case
HMV x -> HMV $ f x
HMM x -> HMM $ g x
liftB'
:: (Numeric a)
=> Sing s
-> (Vec n a -> a)
-> Vec n (HMat a s)
-> HMat a s
liftB' s f xs = bgen s $ \i -> f (indexB i <$> xs)
# INLINE liftB ' #
instance (Container Vector a, Numeric a) => BLAS (HMat a) where
type ElemB (HMat a) = a
TODO : rewrite rules
-- write in parallel?
liftB
:: forall n s. ()
=> Sing s
-> (Vec n a -> a)
-> Vec n (HMat a s)
-> HMat a s
liftB s f = \case
ØV -> case s of
SBV sN -> HMV $ konst (f ØV) ( fromIntegral (fromSing sN) )
SBM sN sM -> HMM $ konst (f ØV) ( fromIntegral (fromSing sN)
, fromIntegral (fromSing sM)
)
I x :* ØV -> case x of
HMV x' -> HMV (cmap (f . (:* ØV) . I) x')
HMM x' -> HMM (cmap (f . (:* ØV) . I) x')
I x :* I y :* ØV -> case x of
HMV x' -> case y of
HMV y' -> HMV $ VS.zipWith (curryV2' f) x' y'
HMM x' -> case y of
HMM y' -> HMM $ liftMatrix2 (VS.zipWith (curryV2' f)) x' y'
xs@(I x :* I y :* I z :* ØV) -> case x of
HMV x' -> case y of
HMV y' -> case z of
HMV z' -> HMV $ VS.zipWith3 (curryV3' f) x' y' z'
_ -> liftB' s f xs
xs@(_ :* _ :* _ :* _ :* _) -> liftB' s f xs
axpy α (HMV x) my
= HMV
. maybe id (add . unHMV) my
. scale α
$ x
# INLINE axpy #
dot (HMV x) (HMV y)
= x <.> y
# INLINE dot #
ger (HMV x) (HMV y)
= HMM $ x `outer` y
# INLINE ger #
gemv α (HMM a) (HMV x) mβy
= HMV
. maybe id (\(β, HMV y) -> add (scale β y)) mβy
. (a #>)
. scale α
$ x
# INLINE gemv #
gemm α (HMM a) (HMM b) mβc
= HMM
. maybe id (\(β, HMM c) -> add (scale β c)) mβc
. (a <>)
. scale α
$ b
# INLINE gemm #
scaleB α = unsafeMapH (scale α) (scale α)
# INLINE scaleB #
addB = unsafeZipH add add
# INLINE addB #
indexB = \case
PBV i -> \case
HMV x -> x `atIndex` fromInteger (DF.getFinite i)
PBM i j -> \case
HMM x -> x `atIndex` ( fromInteger (DF.getFinite i)
, fromInteger (DF.getFinite j)
)
# INLINE indexB #
indexRowB i (HMM x) = HMV (x ! fromInteger (DF.getFinite i))
# INLINE indexRowB #
transpB (HMM x) = HMM (tr x)
# INLINE transpB #
iRowsB f (HMM x) = fmap (HMM . fromRows)
. traverse (\(i,r) -> unHMV <$> f (DF.Finite i) (HMV r))
. zip [0..]
. toRows
$ x
# INLINE iRowsB #
iElemsB f = \case
HMV x -> fmap (HMV . fromList)
. traverse (\(i,e) -> f (PBV (DF.Finite i)) e)
. zip [0..]
. LA.toList
$ x
HMM x -> fmap (HMM . fromLists)
. traverse (\(i,rs) ->
traverse (\(j, e) -> f (PBM (DF.Finite i) (DF.Finite j)) e)
. zip [0..]
$ rs
)
. zip [0..]
. toLists
$ x
# INLINE iElemsB #
-- TODO: can be implemented in parallel maybe?
bgenA = \case
SBV sN -> \f -> fmap (HMV . fromList)
. traverse (\i -> f (PBV (DF.Finite i)))
$ [0 .. fromSing sN - 1]
SBM sN sM -> \f -> fmap (HMM . fromLists)
. traverse (\(i, js) ->
traverse (\j -> f (PBM (DF.Finite i) (DF.Finite j))) js
)
. zip [0 .. fromSing sN - 1]
$ repeat [0 .. fromSing sM - 1]
# INLINE bgenA #
bgenRowsA
:: forall f n m. (Applicative f, SingI n)
=> (DF.Finite n -> f (HMat a ('BV m)))
-> f (HMat a ('BM n m))
bgenRowsA f = fmap (HMM . fromRows)
. traverse (fmap unHMV . f . DF.Finite)
$ [0 .. fromSing (sing @Nat @n) - 1]
# INLINE bgenRowsA #
eye = HMM . ident . fromIntegral . fromSing
# INLINE eye #
diagB = HMM . diag . unHMV
# INLINE diagB #
getDiagB = HMV . takeDiag . unHMM
# INLINE getDiagB #
traceB = sumElements . takeDiag . unHMM
# INLINE traceB #
sumB = \case
HMV xs -> sumElements xs
HMM xs -> sumElements xs
# INLINE sumB #
| null | https://raw.githubusercontent.com/mstksg/tensor-ops/1958642d60d879e311da14469c3dd09c186b5fda/src/TensorOps/BLAS/HMat.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE GADTs #
# LANGUAGE KindSignatures #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
| WARNING!! Functions should assume equal sized inputs and return
outputs of the same size! This is not checked!!!
| WARNING!! Functions should return outputs of the same size! This is
not checked!!!
write in parallel?
TODO: can be implemented in parallel maybe? | # LANGUAGE FlexibleContexts #
# LANGUAGE InstanceSigs #
# LANGUAGE LambdaCase #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
module TensorOps.BLAS.HMat
( HMat
, HMatD
) where
import Control.DeepSeq
import Data.Kind
import Data.Singletons
import Data.Singletons.TypeLits
import Data.Type.Combinator
import Data.Type.Vector (Vec, VecT(..))
import Data.Type.Vector.Util (curryV2', curryV3')
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Data as LA
import Numeric.LinearAlgebra.Devel
import TensorOps.BLAS
import Type.Class.Higher
import Type.Class.Higher.Util
import qualified Data.Finite as DF
import qualified Data.Finite.Internal as DF
import qualified Data.Vector.Storable as VS
type HMatD = HMat Double
data HMat :: Type -> BShape Nat -> Type where
HMV :: { unHMV :: !(Vector a) } -> HMat a ('BV n)
HMM :: { unHMM :: !(Matrix a) } -> HMat a ('BM n m)
instance (VS.Storable a, Show a, Element a) => Show (HMat a s) where
showsPrec p = \case
HMV x -> showParen (p > 10) $ showString "HMV "
. showsPrec 11 x
HMM x -> showParen (p > 10) $ showString "HMM "
. showsPrec 11 x
instance (VS.Storable a, Show a, Element a) => Show1 (HMat a)
instance (VS.Storable a, NFData a) => NFData (HMat a s) where
rnf = \case
HMV xs -> rnf xs
HMM xs -> rnf xs
# INLINE rnf #
instance (VS.Storable a, NFData a) => NFData1 (HMat a)
instance (SingI s, Container Vector a, Container Matrix a, Num a) => Num (HMat a s) where
(+) = unsafeZipH add add
(*) = unsafeZipH (VS.zipWith (*)) (liftMatrix2 (VS.zipWith (*)))
(-) = unsafeZipH (VS.zipWith (-)) (liftMatrix2 (VS.zipWith (-)))
negate = unsafeMapH (scale (-1)) (scale (-1))
abs = unsafeMapH (cmap abs) (cmap abs)
signum = unsafeMapH (cmap signum) (cmap signum)
fromInteger = case (sing :: Sing s) of
SBV n -> HMV . flip konst (fromIntegral (fromSing n)) . fromInteger
SBM n m -> HMM . flip konst (fromIntegral (fromSing n)
,fromIntegral (fromSing m)
) . fromInteger
unsafeZipH
:: (Vector a -> Vector a -> Vector a)
-> (Matrix a -> Matrix a -> Matrix a)
-> HMat a s -> HMat a s -> HMat a s
unsafeZipH f g = \case
HMV x -> \case
HMV y -> HMV $ f x y
HMM x -> \case
HMM y -> HMM $ g x y
unsafeMapH
:: (Vector a -> Vector a)
-> (Matrix a -> Matrix a)
-> HMat a s -> HMat a s
unsafeMapH f g = \case
HMV x -> HMV $ f x
HMM x -> HMM $ g x
liftB'
:: (Numeric a)
=> Sing s
-> (Vec n a -> a)
-> Vec n (HMat a s)
-> HMat a s
liftB' s f xs = bgen s $ \i -> f (indexB i <$> xs)
# INLINE liftB ' #
instance (Container Vector a, Numeric a) => BLAS (HMat a) where
type ElemB (HMat a) = a
TODO : rewrite rules
liftB
:: forall n s. ()
=> Sing s
-> (Vec n a -> a)
-> Vec n (HMat a s)
-> HMat a s
liftB s f = \case
ØV -> case s of
SBV sN -> HMV $ konst (f ØV) ( fromIntegral (fromSing sN) )
SBM sN sM -> HMM $ konst (f ØV) ( fromIntegral (fromSing sN)
, fromIntegral (fromSing sM)
)
I x :* ØV -> case x of
HMV x' -> HMV (cmap (f . (:* ØV) . I) x')
HMM x' -> HMM (cmap (f . (:* ØV) . I) x')
I x :* I y :* ØV -> case x of
HMV x' -> case y of
HMV y' -> HMV $ VS.zipWith (curryV2' f) x' y'
HMM x' -> case y of
HMM y' -> HMM $ liftMatrix2 (VS.zipWith (curryV2' f)) x' y'
xs@(I x :* I y :* I z :* ØV) -> case x of
HMV x' -> case y of
HMV y' -> case z of
HMV z' -> HMV $ VS.zipWith3 (curryV3' f) x' y' z'
_ -> liftB' s f xs
xs@(_ :* _ :* _ :* _ :* _) -> liftB' s f xs
axpy α (HMV x) my
= HMV
. maybe id (add . unHMV) my
. scale α
$ x
# INLINE axpy #
dot (HMV x) (HMV y)
= x <.> y
# INLINE dot #
ger (HMV x) (HMV y)
= HMM $ x `outer` y
# INLINE ger #
gemv α (HMM a) (HMV x) mβy
= HMV
. maybe id (\(β, HMV y) -> add (scale β y)) mβy
. (a #>)
. scale α
$ x
# INLINE gemv #
gemm α (HMM a) (HMM b) mβc
= HMM
. maybe id (\(β, HMM c) -> add (scale β c)) mβc
. (a <>)
. scale α
$ b
# INLINE gemm #
scaleB α = unsafeMapH (scale α) (scale α)
# INLINE scaleB #
addB = unsafeZipH add add
# INLINE addB #
indexB = \case
PBV i -> \case
HMV x -> x `atIndex` fromInteger (DF.getFinite i)
PBM i j -> \case
HMM x -> x `atIndex` ( fromInteger (DF.getFinite i)
, fromInteger (DF.getFinite j)
)
# INLINE indexB #
indexRowB i (HMM x) = HMV (x ! fromInteger (DF.getFinite i))
# INLINE indexRowB #
transpB (HMM x) = HMM (tr x)
# INLINE transpB #
iRowsB f (HMM x) = fmap (HMM . fromRows)
. traverse (\(i,r) -> unHMV <$> f (DF.Finite i) (HMV r))
. zip [0..]
. toRows
$ x
# INLINE iRowsB #
iElemsB f = \case
HMV x -> fmap (HMV . fromList)
. traverse (\(i,e) -> f (PBV (DF.Finite i)) e)
. zip [0..]
. LA.toList
$ x
HMM x -> fmap (HMM . fromLists)
. traverse (\(i,rs) ->
traverse (\(j, e) -> f (PBM (DF.Finite i) (DF.Finite j)) e)
. zip [0..]
$ rs
)
. zip [0..]
. toLists
$ x
# INLINE iElemsB #
bgenA = \case
SBV sN -> \f -> fmap (HMV . fromList)
. traverse (\i -> f (PBV (DF.Finite i)))
$ [0 .. fromSing sN - 1]
SBM sN sM -> \f -> fmap (HMM . fromLists)
. traverse (\(i, js) ->
traverse (\j -> f (PBM (DF.Finite i) (DF.Finite j))) js
)
. zip [0 .. fromSing sN - 1]
$ repeat [0 .. fromSing sM - 1]
# INLINE bgenA #
bgenRowsA
:: forall f n m. (Applicative f, SingI n)
=> (DF.Finite n -> f (HMat a ('BV m)))
-> f (HMat a ('BM n m))
bgenRowsA f = fmap (HMM . fromRows)
. traverse (fmap unHMV . f . DF.Finite)
$ [0 .. fromSing (sing @Nat @n) - 1]
# INLINE bgenRowsA #
eye = HMM . ident . fromIntegral . fromSing
# INLINE eye #
diagB = HMM . diag . unHMV
# INLINE diagB #
getDiagB = HMV . takeDiag . unHMM
# INLINE getDiagB #
traceB = sumElements . takeDiag . unHMM
# INLINE traceB #
sumB = \case
HMV xs -> sumElements xs
HMM xs -> sumElements xs
# INLINE sumB #
|
42b51af6b2677d25664f83b1d793278020b1c63ba9f8f2817387cb2ff071a9aa | kayceesrk/Quelea | propTest.hs | import Codeec.Contract hiding (liftProp)
import qualified Codeec.Contract as C (liftProp)
liftProp :: Prop () -> Fol ()
liftProp = C.liftProp
tvis :: Fol ()
tvis = forall_ $ \a -> forall_ $ \b -> liftProp $ appRel ((^+) Vis) a b ⇒ vis a b
test :: Fol ()
test = forall_ $ \a -> forall_ $ \b -> forall_ $ \c -> liftProp $ (vis a b ∧ vis b c) ⇒ vis a c
main = do
r <- isValid "true" $ liftProp $ (Raw $ fol2Z3Ctrt tvis) ⇒ (Raw $ fol2Z3Ctrt test)
putStrLn $ show r
| null | https://raw.githubusercontent.com/kayceesrk/Quelea/73db79a5d5513b9aeeb475867a67bacb6a5313d0/scratch/propTest.hs | haskell | import Codeec.Contract hiding (liftProp)
import qualified Codeec.Contract as C (liftProp)
liftProp :: Prop () -> Fol ()
liftProp = C.liftProp
tvis :: Fol ()
tvis = forall_ $ \a -> forall_ $ \b -> liftProp $ appRel ((^+) Vis) a b ⇒ vis a b
test :: Fol ()
test = forall_ $ \a -> forall_ $ \b -> forall_ $ \c -> liftProp $ (vis a b ∧ vis b c) ⇒ vis a c
main = do
r <- isValid "true" $ liftProp $ (Raw $ fol2Z3Ctrt tvis) ⇒ (Raw $ fol2Z3Ctrt test)
putStrLn $ show r
| |
3c2a4381da2c08fa58e431b3e703592956ec51fef74eb180470acf10eeb9d1d1 | travelping/dike | dike_sup.erl | % __ __ _
% / /__________ __ _____ / /___ (_)___ ____ _
/ _ _ / _ _ _ / _ _ ` / | / / _ \/ / _ _ \/ / _ _ \/ _ _ ` /
% / /_/ / / /_/ /| |/ / __/ / /_/ / / / / / /_/ /
% \__/_/ \__,_/ |___/\___/_/ .___/_/_/ /_/\__, /
% /_/ /____/
%
Copyright ( c ) Travelping GmbH < >
-module(dike_sup).
-behaviour(supervisor).
%% API
-export([start_link/1]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
start_link(Masters) ->
% process_flag(trap_exit, true),
supervisor:start_link({local, ?SERVER}, ?MODULE, [Masters]).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
init([Masters]) ->
RestartStrategy = one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Restart = transient,%permanent,
Shutdown = 2000,
Type = worker,
Dispatcher = case length(Masters) of
1 ->
{dike_dispatcher, {dike_stub_dispatcher, start_link, [hd(Masters)]},
Restart, Shutdown, Type, [dike_stub_dispatcher]};
N when N == 3 orelse N == 5 ->
{dike_dispatcher, {dike_dispatcher, start_link, [Masters]},
Restart, Shutdown, Type, [dike_dispatcher]}
end,
{ok, {SupFlags, [Dispatcher]}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/travelping/dike/2849b9018b6fe5a4fa3f2df48ca9ed99204685ed/src/dike_sup.erl | erlang | __ __ _
/ /__________ __ _____ / /___ (_)___ ____ _
/ /_/ / / /_/ /| |/ / __/ / /_/ / / / / / /_/ /
\__/_/ \__,_/ |___/\___/_/ .___/_/_/ /_/\__, /
/_/ /____/
API
Supervisor callbacks
===================================================================
API functions
===================================================================
process_flag(trap_exit, true),
===================================================================
Supervisor callbacks
===================================================================
permanent,
===================================================================
=================================================================== | / _ _ / _ _ _ / _ _ ` / | / / _ \/ / _ _ \/ / _ _ \/ _ _ ` /
Copyright ( c ) Travelping GmbH < >
-module(dike_sup).
-behaviour(supervisor).
-export([start_link/1]).
-export([init/1]).
-define(SERVER, ?MODULE).
start_link(Masters) ->
supervisor:start_link({local, ?SERVER}, ?MODULE, [Masters]).
init([Masters]) ->
RestartStrategy = one_for_one,
MaxRestarts = 1000,
MaxSecondsBetweenRestarts = 3600,
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts},
Shutdown = 2000,
Type = worker,
Dispatcher = case length(Masters) of
1 ->
{dike_dispatcher, {dike_stub_dispatcher, start_link, [hd(Masters)]},
Restart, Shutdown, Type, [dike_stub_dispatcher]};
N when N == 3 orelse N == 5 ->
{dike_dispatcher, {dike_dispatcher, start_link, [Masters]},
Restart, Shutdown, Type, [dike_dispatcher]}
end,
{ok, {SupFlags, [Dispatcher]}}.
Internal functions
|
964b94fdff9dc7c8cd6958bc93b0ec481f6240039a76806771a508f9b7c5140c | facebook/pyre-check | locationTest.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open OUnit2
open Ast
open Test
let test_contains _ =
let contains ~location position =
Location.contains ~location:(parse_location location) (parse_position position)
in
let assert_contains ~location position = assert_true (contains ~location position) in
let assert_not_contains ~location position = assert_false (contains ~location position) in
assert_not_contains ~location:"1:3-2:14" "1:2";
assert_contains ~location:"1:3-2:14" "1:3";
assert_contains ~location:"1:3-2:14" "1:99";
assert_contains ~location:"1:3-2:14" "2:0";
assert_contains ~location:"1:3-2:14" "2:13";
assert_not_contains ~location:"1:3-2:14" "2:14";
()
let () = "location" >::: ["contains" >:: test_contains] |> Test.run
| null | https://raw.githubusercontent.com/facebook/pyre-check/958943f953a2e4dbca69741de51a3cd594ad12c5/source/ast/test/locationTest.ml | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open OUnit2
open Ast
open Test
let test_contains _ =
let contains ~location position =
Location.contains ~location:(parse_location location) (parse_position position)
in
let assert_contains ~location position = assert_true (contains ~location position) in
let assert_not_contains ~location position = assert_false (contains ~location position) in
assert_not_contains ~location:"1:3-2:14" "1:2";
assert_contains ~location:"1:3-2:14" "1:3";
assert_contains ~location:"1:3-2:14" "1:99";
assert_contains ~location:"1:3-2:14" "2:0";
assert_contains ~location:"1:3-2:14" "2:13";
assert_not_contains ~location:"1:3-2:14" "2:14";
()
let () = "location" >::: ["contains" >:: test_contains] |> Test.run
| |
d142bf08b89c81f166133147d1875a27c0a33f89247591a9cc50beb7bfe70442 | ericmoritz/wsdemo | wsdemo_bench_sup.erl |
-module(wsdemo_bench_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% Helper macro for declaring children of supervisor
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
{ok, { {one_for_one, 5, 60}, [
?CHILD(wsdemo_server_manager, worker),
?CHILD(wsdemo_master_fsm, worker)
]} }.
| null | https://raw.githubusercontent.com/ericmoritz/wsdemo/4b242ff56e8dc1d2af78b695d23b8c7eeb884682/src/wsdemo_bench_sup.erl | erlang | API
Supervisor callbacks
Helper macro for declaring children of supervisor
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== |
-module(wsdemo_bench_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 5, 60}, [
?CHILD(wsdemo_server_manager, worker),
?CHILD(wsdemo_master_fsm, worker)
]} }.
|
e56d372b2e8f64a473119a0d7ea0cde777940ed444c98ec15ebbf4800445ce08 | awakesecurity/spectacle | Spectacle.hs | {-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Language.Spectacle.Syntax
Copyright : ( c ) Arista Networks , 2022 - 2023
License : Apache License 2.0 , see LICENSE
--
-- Stability : stable
Portability : non - portable ( GHC extensions )
--
-- TODO: docs
--
-- @since 1.0.0
module Language.Spectacle
( -- * CLI Interaction
interaction,
-- * Model Checking
modelcheck,
modeltrace,
-- * Specification
Specification (Specification),
specInit,
specNext,
specProp,
ActionType (ActionSF, ActionWF, ActionUF),
TemporalType (PropF, PropG, PropGF, PropFG),
Fairness (StrongFair, WeakFair, Unfair),
Modality (Always, Eventually, Infinitely, Stays),
-- * Syntax
type Action,
type Temporal,
-- ** Variables
plain,
prime,
type (#),
-- ** Operators
(.=),
enabled,
throwE,
catchE,
-- ** Logic
forall,
exists,
oneOf,
conjunct,
(/\),
disjunct,
(\/),
complement,
(==>),
implies,
(<=>),
iff,
-- * Records
pattern ConF,
pattern NilF,
)
where
import Data.Type.Rec (RecF (ConF, NilF), type (#))
import Language.Spectacle.AST (Action, Temporal)
import Language.Spectacle.Fairness (Fairness (StrongFair, Unfair, WeakFair))
import Language.Spectacle.Interaction (interaction)
import Language.Spectacle.Model (modelcheck, modeltrace)
import Language.Spectacle.Specification
( ActionType (ActionSF, ActionUF, ActionWF),
Modality (Always, Eventually, Infinitely, Stays),
Specification (Specification),
TemporalType (PropF, PropFG, PropG, PropGF),
specInit,
specNext,
specProp,
)
import Language.Spectacle.Syntax
( catchE,
complement,
conjunct,
disjunct,
enabled,
exists,
forall,
iff,
implies,
oneOf,
plain,
prime,
throwE,
(.=),
(/\),
(<=>),
(==>),
(\/),
)
-- ---------------------------------------------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/awakesecurity/spectacle/430680c28b26dabb50f466948180eb59ba72fc8e/src/Language/Spectacle.hs | haskell | # OPTIONS_HADDOCK show-extensions #
|
Module : Language.Spectacle.Syntax
Stability : stable
TODO: docs
@since 1.0.0
* CLI Interaction
* Model Checking
* Specification
* Syntax
** Variables
** Operators
** Logic
* Records
--------------------------------------------------------------------------------------------------------------------- |
Copyright : ( c ) Arista Networks , 2022 - 2023
License : Apache License 2.0 , see LICENSE
Portability : non - portable ( GHC extensions )
module Language.Spectacle
interaction,
modelcheck,
modeltrace,
Specification (Specification),
specInit,
specNext,
specProp,
ActionType (ActionSF, ActionWF, ActionUF),
TemporalType (PropF, PropG, PropGF, PropFG),
Fairness (StrongFair, WeakFair, Unfair),
Modality (Always, Eventually, Infinitely, Stays),
type Action,
type Temporal,
plain,
prime,
type (#),
(.=),
enabled,
throwE,
catchE,
forall,
exists,
oneOf,
conjunct,
(/\),
disjunct,
(\/),
complement,
(==>),
implies,
(<=>),
iff,
pattern ConF,
pattern NilF,
)
where
import Data.Type.Rec (RecF (ConF, NilF), type (#))
import Language.Spectacle.AST (Action, Temporal)
import Language.Spectacle.Fairness (Fairness (StrongFair, Unfair, WeakFair))
import Language.Spectacle.Interaction (interaction)
import Language.Spectacle.Model (modelcheck, modeltrace)
import Language.Spectacle.Specification
( ActionType (ActionSF, ActionUF, ActionWF),
Modality (Always, Eventually, Infinitely, Stays),
Specification (Specification),
TemporalType (PropF, PropFG, PropG, PropGF),
specInit,
specNext,
specProp,
)
import Language.Spectacle.Syntax
( catchE,
complement,
conjunct,
disjunct,
enabled,
exists,
forall,
iff,
implies,
oneOf,
plain,
prime,
throwE,
(.=),
(/\),
(<=>),
(==>),
(\/),
)
|
b9ab0287b34da7293ecb0ce2d6d6f75e45ada023a468c39d21ff226f8d222c9b | plow-technologies/rescript-linter | rescript_linter_test.ml | open Rescript_parser
open Rescript_linter
module DisallowStringOfIntRule = DisallowedFunctionRule.Make (struct
type options = DisallowedFunctionRule.Options.options
let options =
{ DisallowedFunctionRule.Options.disallowed_function= "string_of_int"
; DisallowedFunctionRule.Options.suggested_function= Some "Belt.Int.fromString" }
end)
module DisallowInOfStringOptRule = DisallowedFunctionRule.Make (struct
type options = DisallowedFunctionRule.Options.options
let options =
{ DisallowedFunctionRule.Options.disallowed_function= "intOfStringOpt"
; DisallowedFunctionRule.Options.suggested_function= Some "Belt.Int.fromString" }
end)
module DisallowTriangleOperatorRule = DisallowedOperatorRule.Make (struct
type options = DisallowedOperatorRule.Options.options
let options =
{ DisallowedOperatorRule.Options.disallowed_operator= "|>"
; DisallowedOperatorRule.Options.suggested_operator= Some "->" }
end)
module NoInputComponentRule = NoReactComponentRule.Make (struct
type options = NoReactComponentRule.Options.options
let options =
{ NoReactComponentRule.Options.component_name= "input"
; NoReactComponentRule.Options.suggested_component_name= None }
end)
module NoInnerComponentRule = NoReactComponentRule.Make (struct
type options = NoReactComponentRule.Options.options
let options =
{ NoReactComponentRule.Options.component_name= "Inner"
; NoReactComponentRule.Options.suggested_component_name= Some "SafeInner" }
end)
module NoCSSModuleRule = DisallowModuleRule.Make (struct
type options = DisallowModuleRule.Options.options
let options =
{ DisallowModuleRule.Options.disallowed_module= "Css"
; DisallowModuleRule.Options.suggested_module= Some "CssJS" }
end)
type parseResult = {ast: Parsetree.structure; comments: Res_comment.t list}
let parseAst path =
let src = Linter.processFile path in
(* if you want to target the printer use: let mode = Res_parser.Default in*)
let p = Res_parser.make ~mode:Res_parser.Default src path in
{ast= Res_core.parseImplementation p; comments= p.comments}
module Tests = struct
(* The tests *)
let disallow_test_1 () =
let parseResult = parseAst "testData/disallowed_function_rule_test_1.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _); _] ->
Alcotest.(check string) "Same error message" DisallowStringOfIntRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should only have two lint errors"
let disallow_test_2 () =
let parseResult = parseAst "testData/disallowed_function_rule_test_2.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should not have any lint errors"
let disallow_operator_test () =
let parseResult = parseAst "testData/disallowed_operator_rule_test.res" in
let errors =
Linter.lint [(module DisallowTriangleOperatorRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check string) "Same error message" DisallowTriangleOperatorRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should not have any lint errors"
let no_jstring_interpolation_test () =
let parseResult = parseAst "testData/no_jstring_interpolation_test.res" in
let errors =
Linter.lint [(module NoJStringInterpolationRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check pass) "Same error message" NoJStringInterpolationRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should only return one error"
let disable_lint_test () =
let parseResult = parseAst "testData/disabled_lint_test_1.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only no lint errors"
let disable_lint_per_rule_test () =
let parseResult = parseAst "testData/disabled_lint_test_2.res" in
let errors =
Linter.lint
[(module DisallowStringOfIntRule : Rule.HASRULE); (module DisallowTriangleOperatorRule : Rule.HASRULE)]
parseResult.ast parseResult.comments
in
match errors with
| [_] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have one lint error"
let disable_lint_per_rule_specific_test () =
let parseResult = parseAst "testData/disabled_lint_test_3.res" in
let errors =
Linter.lint
[ (module DisallowStringOfIntRule : Rule.HASRULE)
; (module DisallowInOfStringOptRule : Rule.HASRULE)
; (module DisallowTriangleOperatorRule : Rule.HASRULE) ]
parseResult.ast parseResult.comments
in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disabled_multiple_lints_test () =
let parseResult = parseAst "testData/disabled_multiple_rules_test.res" in
let errors =
Linter.lint
[ (module DisallowStringOfIntRule : Rule.HASRULE)
; (module DisallowInOfStringOptRule : Rule.HASRULE)
; (module DisallowTriangleOperatorRule : Rule.HASRULE) ]
parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check string) "Same error message" msg DisallowTriangleOperatorRule.meta.ruleDescription
| _ -> Alcotest.fail "Should only have two lint error"
let no_react_component_test_1 () =
let parseResult = parseAst "testData/no_react_component_test_1.res" in
let errors =
Linter.lint [(module NoInputComponentRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let no_react_component_test_2 () =
let parseResult = parseAst "testData/no_react_component_test_2.res" in
let errors =
Linter.lint [(module NoInnerComponentRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [_] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_1 () =
let parseResult = parseAst "testData/disallow_module_test_1.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_2 () =
let parseResult = parseAst "testData/disallow_module_test_2.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_3 () =
let parseResult = parseAst "testData/disallow_module_test_3.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
end
(* Run it *)
let () =
let open Alcotest in
run "ReScript Linter"
[ ( "Disallow Function Rule"
, [ test_case "Lint only functions" `Quick Tests.disallow_test_1
; test_case "Does not lint variable with the same function name" `Quick Tests.disallow_test_2 ] )
; ( "No J String Interpolation Rule"
, [test_case "Lint j`` string" `Quick Tests.no_jstring_interpolation_test] )
; ("Disallow |> operator", [test_case "Lint |> operator" `Quick Tests.disallow_operator_test])
; ( "Disable lint test"
, [ test_case "Disable lint" `Quick Tests.disable_lint_test
; test_case "Disable lint per rule" `Quick Tests.disable_lint_per_rule_test
; test_case "Disable lint per specific" `Quick Tests.disable_lint_per_rule_specific_test
; test_case "Disable multiple lints" `Quick Tests.disabled_multiple_lints_test ] )
; ( "No react component"
, [ test_case "No input box" `Quick Tests.no_react_component_test_1
; test_case "No Inner component" `Quick Tests.no_react_component_test_2 ] )
; ( "Disallow module"
, [ test_case "open module" `Quick Tests.disallow_module_test_1
; test_case "alias module" `Quick Tests.disallow_module_test_2
; test_case "direct access module" `Quick Tests.disallow_module_test_3 ] ) ]
| null | https://raw.githubusercontent.com/plow-technologies/rescript-linter/8f7f144fb1b61f840a1269f2f55c5c6bd79706ad/test/rescript_linter_test.ml | ocaml | if you want to target the printer use: let mode = Res_parser.Default in
The tests
Run it | open Rescript_parser
open Rescript_linter
module DisallowStringOfIntRule = DisallowedFunctionRule.Make (struct
type options = DisallowedFunctionRule.Options.options
let options =
{ DisallowedFunctionRule.Options.disallowed_function= "string_of_int"
; DisallowedFunctionRule.Options.suggested_function= Some "Belt.Int.fromString" }
end)
module DisallowInOfStringOptRule = DisallowedFunctionRule.Make (struct
type options = DisallowedFunctionRule.Options.options
let options =
{ DisallowedFunctionRule.Options.disallowed_function= "intOfStringOpt"
; DisallowedFunctionRule.Options.suggested_function= Some "Belt.Int.fromString" }
end)
module DisallowTriangleOperatorRule = DisallowedOperatorRule.Make (struct
type options = DisallowedOperatorRule.Options.options
let options =
{ DisallowedOperatorRule.Options.disallowed_operator= "|>"
; DisallowedOperatorRule.Options.suggested_operator= Some "->" }
end)
module NoInputComponentRule = NoReactComponentRule.Make (struct
type options = NoReactComponentRule.Options.options
let options =
{ NoReactComponentRule.Options.component_name= "input"
; NoReactComponentRule.Options.suggested_component_name= None }
end)
module NoInnerComponentRule = NoReactComponentRule.Make (struct
type options = NoReactComponentRule.Options.options
let options =
{ NoReactComponentRule.Options.component_name= "Inner"
; NoReactComponentRule.Options.suggested_component_name= Some "SafeInner" }
end)
module NoCSSModuleRule = DisallowModuleRule.Make (struct
type options = DisallowModuleRule.Options.options
let options =
{ DisallowModuleRule.Options.disallowed_module= "Css"
; DisallowModuleRule.Options.suggested_module= Some "CssJS" }
end)
type parseResult = {ast: Parsetree.structure; comments: Res_comment.t list}
let parseAst path =
let src = Linter.processFile path in
let p = Res_parser.make ~mode:Res_parser.Default src path in
{ast= Res_core.parseImplementation p; comments= p.comments}
module Tests = struct
let disallow_test_1 () =
let parseResult = parseAst "testData/disallowed_function_rule_test_1.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _); _] ->
Alcotest.(check string) "Same error message" DisallowStringOfIntRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should only have two lint errors"
let disallow_test_2 () =
let parseResult = parseAst "testData/disallowed_function_rule_test_2.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should not have any lint errors"
let disallow_operator_test () =
let parseResult = parseAst "testData/disallowed_operator_rule_test.res" in
let errors =
Linter.lint [(module DisallowTriangleOperatorRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check string) "Same error message" DisallowTriangleOperatorRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should not have any lint errors"
let no_jstring_interpolation_test () =
let parseResult = parseAst "testData/no_jstring_interpolation_test.res" in
let errors =
Linter.lint [(module NoJStringInterpolationRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check pass) "Same error message" NoJStringInterpolationRule.meta.ruleDescription msg
| _ -> Alcotest.fail "Should only return one error"
let disable_lint_test () =
let parseResult = parseAst "testData/disabled_lint_test_1.res" in
let errors =
Linter.lint [(module DisallowStringOfIntRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only no lint errors"
let disable_lint_per_rule_test () =
let parseResult = parseAst "testData/disabled_lint_test_2.res" in
let errors =
Linter.lint
[(module DisallowStringOfIntRule : Rule.HASRULE); (module DisallowTriangleOperatorRule : Rule.HASRULE)]
parseResult.ast parseResult.comments
in
match errors with
| [_] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have one lint error"
let disable_lint_per_rule_specific_test () =
let parseResult = parseAst "testData/disabled_lint_test_3.res" in
let errors =
Linter.lint
[ (module DisallowStringOfIntRule : Rule.HASRULE)
; (module DisallowInOfStringOptRule : Rule.HASRULE)
; (module DisallowTriangleOperatorRule : Rule.HASRULE) ]
parseResult.ast parseResult.comments
in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disabled_multiple_lints_test () =
let parseResult = parseAst "testData/disabled_multiple_rules_test.res" in
let errors =
Linter.lint
[ (module DisallowStringOfIntRule : Rule.HASRULE)
; (module DisallowInOfStringOptRule : Rule.HASRULE)
; (module DisallowTriangleOperatorRule : Rule.HASRULE) ]
parseResult.ast parseResult.comments
in
match errors with
| [(msg, _)] ->
Alcotest.(check string) "Same error message" msg DisallowTriangleOperatorRule.meta.ruleDescription
| _ -> Alcotest.fail "Should only have two lint error"
let no_react_component_test_1 () =
let parseResult = parseAst "testData/no_react_component_test_1.res" in
let errors =
Linter.lint [(module NoInputComponentRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let no_react_component_test_2 () =
let parseResult = parseAst "testData/no_react_component_test_2.res" in
let errors =
Linter.lint [(module NoInnerComponentRule : Rule.HASRULE)] parseResult.ast parseResult.comments
in
match errors with
| [_] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_1 () =
let parseResult = parseAst "testData/disallow_module_test_1.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_2 () =
let parseResult = parseAst "testData/disallow_module_test_2.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
let disallow_module_test_3 () =
let parseResult = parseAst "testData/disallow_module_test_3.res" in
let errors = Linter.lint [(module NoCSSModuleRule : Rule.HASRULE)] parseResult.ast parseResult.comments in
match errors with
| [_; _] -> Alcotest.(check pass) "Same error message" [] []
| _ -> Alcotest.fail "Should only have two lint error"
end
let () =
let open Alcotest in
run "ReScript Linter"
[ ( "Disallow Function Rule"
, [ test_case "Lint only functions" `Quick Tests.disallow_test_1
; test_case "Does not lint variable with the same function name" `Quick Tests.disallow_test_2 ] )
; ( "No J String Interpolation Rule"
, [test_case "Lint j`` string" `Quick Tests.no_jstring_interpolation_test] )
; ("Disallow |> operator", [test_case "Lint |> operator" `Quick Tests.disallow_operator_test])
; ( "Disable lint test"
, [ test_case "Disable lint" `Quick Tests.disable_lint_test
; test_case "Disable lint per rule" `Quick Tests.disable_lint_per_rule_test
; test_case "Disable lint per specific" `Quick Tests.disable_lint_per_rule_specific_test
; test_case "Disable multiple lints" `Quick Tests.disabled_multiple_lints_test ] )
; ( "No react component"
, [ test_case "No input box" `Quick Tests.no_react_component_test_1
; test_case "No Inner component" `Quick Tests.no_react_component_test_2 ] )
; ( "Disallow module"
, [ test_case "open module" `Quick Tests.disallow_module_test_1
; test_case "alias module" `Quick Tests.disallow_module_test_2
; test_case "direct access module" `Quick Tests.disallow_module_test_3 ] ) ]
|
989ca493ec5b901694e30be37c543405b3c829a078ab1834cedc122c77dd311a | stchang/macrotypes | samc-define-lang.rkt | #lang turnstile
(provide Int →
+ #%datum (rename-out [λ+ λ]) #%app
require define define/broken
#%module-begin)
Example by : Adds local ` define ` to λ in stlc
(define-base-type Int)
(define-type-constructor → #:arity >= 1
#:arg-variances (λ (stx)
(syntax-parse stx
[(_ τ_in ... τ_out)
(append
(stx-map (λ _ contravariant) #'[τ_in ...])
(list covariant))])))
(define-primop + (→ Int Int Int))
(define-typed-syntax #%datum
[(_ . n:integer) ≫
--------
[⊢ (quote n) ⇒ #,Int+]]
[(_ . x) ≫
--------
[#:error (type-error #:src #'x #:msg "Unsupported literal: ~v" #'x)]])
(define-typed-syntax (#%app e_fn e_arg ...) ≫
[⊢ e_fn ≫ e_fn- ⇒ (~→ τ_in ... τ_out)]
#:fail-unless (stx-length=? #'[τ_in ...] #'[e_arg ...])
(num-args-fail-msg #'e_fn #'[τ_in ...] #'[e_arg ...])
[⊢ e_arg ≫ e_arg- ⇐ τ_in] ...
--------
[⊢ (#%plain-app- e_fn- e_arg- ...) ⇒ τ_out])
(define-typed-syntax (λ ([x:id (~datum :) τ_in:type] ...) e ...+) ≫
[[x ≫ x- : τ_in.norm] ... ⊢ (begin e ...) ≫ e- ⇒ τ_out]
-------
[⊢ (#%plain-lambda- (x- ...) e-) ⇒ (→ τ_in.norm ... τ_out)])
(define-typed-syntax (begin e ...+) ≫
[⊢ e ≫ e- ⇒ τ] ...
#:with τ-final (stx-last #'(τ ...))
--------------------
[⊢ (begin- e- ...) ⇒ τ-final])
(define-base-type Void)
(define- a-deep-dark-void (#%app- void-))
(define-typed-syntax define/broken
[(_ x:id e) ≫
[⊢ e ≫ e- ⇒ τ]
#:with x- (generate-temporary #'x)
-----------------------------------------------------
[⊢ (begin-
(define-typed-variable-rename x ≫ x- : τ)
(define- x- e-)
a-deep-dark-void)
⇒ Void]]
[(_ (f [x (~datum :) τ] ...) e ...+) ≫
-----------------------------------
[≻ (define/broken f (λ ([x : τ] ...) e ...))]])
(define-typed-syntax (λ+ ([x:id (~datum :) τ_in:type] ...) e ...+) ≫
[[x ≫ x- : τ_in.norm] ... ⊢ (begin/def e ...) ≫ e- ⇒ τ_out]
-------
[⊢ (#%plain-lambda- (x- ...) e-) ⇒ (→ τ_in.norm ... τ_out)])
(define-typed-syntax (begin/def e ...+) ≫
#:do [(define-values (e-... τ...) (walk/bind #'(e ...)))]
#:with τ-final (last τ...)
--------------------
[⊢ (begin- #,@e-...) ⇒ τ-final])
(define-syntax (define/intermediate stx)
(syntax-parse stx
[(_ x:id x-:id τ e)
#:with x-/τ (assign-type #'x- #'τ #:wrap? #f)
#'(begin-
(define-syntax x (make-variable-like-transformer #'x-/τ))
(define- x- e)
a-deep-dark-void)]))
(define-typed-syntax define
[(_ x:id e) ≫
[⊢ e ≫ e- ⇒ τ]
#:with x- (generate-temporary #'x)
#:with x+ (syntax-local-identifier-as-binding #'x)
-----------------------------------------------------
[⊢ (define/intermediate x+ x- τ e-) ⇒ Void]]
[(_ (f [x (~datum :) τ] ...) e ...+) ≫
-----------------------------------
[≻ (define f (λ+ ([x : τ] ...) e ...))]])
(define-for-syntax (int-def-ctx-bind-type-rename! x x- t ctx)
(syntax-local-bind-syntaxes (list x)
#`(make-rename-transformer
(add-orig (assign-type #'#,x- #'#,t #:wrap? #f) #'#,x))
ctx)
(syntax-local-bind-syntaxes (list x-) #f ctx))
(define-for-syntax (add-bindings-to-ctx! e- def-ctx)
(syntax-parse e-
#:literals (erased define/intermediate)
[(erased (define/intermediate x:id x-:id τ e-))
(int-def-ctx-bind-type-rename! #'x #'x- #'τ def-ctx)]
[_ (void)]))
(define-for-syntax (walk/bind e...)
(define def-ctx (syntax-local-make-definition-context))
(define unique (gensym 'walk/bind))
(define-values (rev-e-... rev-τ...)
(for/fold ([rev-e-... '()]
[rev-τ... '()])
([e (in-syntax e...)])
(define e- (local-expand e (list unique) (list #'erased) def-ctx))
(define τ (typeof e-))
(add-bindings-to-ctx! e- def-ctx)
(values (cons e- rev-e-...)
(cons τ rev-τ...))))
(values (reverse rev-e-...)
(reverse rev-τ...)))
Homework Assignment 1 - extend this for function definitions
Homework Assignment 2 - extend this for recursive function definitions
Homework Assignment 3 - extend this so that we can define forms that expand
;; to multiple definitions, such as define/memo
(define-syntax (define/memo stx)
(syntax-parse stx
[(_ (f [x (~datum :) τ] ...) e ...+)
#`(begin
(define memo 0)
(define (f [x : τ] ...)
;; referece to memo table
memo
e ...))]))
| null | https://raw.githubusercontent.com/stchang/macrotypes/05ec31f2e1fe0ddd653211e041e06c6c8071ffa6/turnstile-example/turnstile/examples/samc-define-lang.rkt | racket | to multiple definitions, such as define/memo
referece to memo table | #lang turnstile
(provide Int →
+ #%datum (rename-out [λ+ λ]) #%app
require define define/broken
#%module-begin)
Example by : Adds local ` define ` to λ in stlc
(define-base-type Int)
(define-type-constructor → #:arity >= 1
#:arg-variances (λ (stx)
(syntax-parse stx
[(_ τ_in ... τ_out)
(append
(stx-map (λ _ contravariant) #'[τ_in ...])
(list covariant))])))
(define-primop + (→ Int Int Int))
(define-typed-syntax #%datum
[(_ . n:integer) ≫
--------
[⊢ (quote n) ⇒ #,Int+]]
[(_ . x) ≫
--------
[#:error (type-error #:src #'x #:msg "Unsupported literal: ~v" #'x)]])
(define-typed-syntax (#%app e_fn e_arg ...) ≫
[⊢ e_fn ≫ e_fn- ⇒ (~→ τ_in ... τ_out)]
#:fail-unless (stx-length=? #'[τ_in ...] #'[e_arg ...])
(num-args-fail-msg #'e_fn #'[τ_in ...] #'[e_arg ...])
[⊢ e_arg ≫ e_arg- ⇐ τ_in] ...
--------
[⊢ (#%plain-app- e_fn- e_arg- ...) ⇒ τ_out])
(define-typed-syntax (λ ([x:id (~datum :) τ_in:type] ...) e ...+) ≫
[[x ≫ x- : τ_in.norm] ... ⊢ (begin e ...) ≫ e- ⇒ τ_out]
-------
[⊢ (#%plain-lambda- (x- ...) e-) ⇒ (→ τ_in.norm ... τ_out)])
(define-typed-syntax (begin e ...+) ≫
[⊢ e ≫ e- ⇒ τ] ...
#:with τ-final (stx-last #'(τ ...))
--------------------
[⊢ (begin- e- ...) ⇒ τ-final])
(define-base-type Void)
(define- a-deep-dark-void (#%app- void-))
(define-typed-syntax define/broken
[(_ x:id e) ≫
[⊢ e ≫ e- ⇒ τ]
#:with x- (generate-temporary #'x)
-----------------------------------------------------
[⊢ (begin-
(define-typed-variable-rename x ≫ x- : τ)
(define- x- e-)
a-deep-dark-void)
⇒ Void]]
[(_ (f [x (~datum :) τ] ...) e ...+) ≫
-----------------------------------
[≻ (define/broken f (λ ([x : τ] ...) e ...))]])
(define-typed-syntax (λ+ ([x:id (~datum :) τ_in:type] ...) e ...+) ≫
[[x ≫ x- : τ_in.norm] ... ⊢ (begin/def e ...) ≫ e- ⇒ τ_out]
-------
[⊢ (#%plain-lambda- (x- ...) e-) ⇒ (→ τ_in.norm ... τ_out)])
(define-typed-syntax (begin/def e ...+) ≫
#:do [(define-values (e-... τ...) (walk/bind #'(e ...)))]
#:with τ-final (last τ...)
--------------------
[⊢ (begin- #,@e-...) ⇒ τ-final])
(define-syntax (define/intermediate stx)
(syntax-parse stx
[(_ x:id x-:id τ e)
#:with x-/τ (assign-type #'x- #'τ #:wrap? #f)
#'(begin-
(define-syntax x (make-variable-like-transformer #'x-/τ))
(define- x- e)
a-deep-dark-void)]))
(define-typed-syntax define
[(_ x:id e) ≫
[⊢ e ≫ e- ⇒ τ]
#:with x- (generate-temporary #'x)
#:with x+ (syntax-local-identifier-as-binding #'x)
-----------------------------------------------------
[⊢ (define/intermediate x+ x- τ e-) ⇒ Void]]
[(_ (f [x (~datum :) τ] ...) e ...+) ≫
-----------------------------------
[≻ (define f (λ+ ([x : τ] ...) e ...))]])
(define-for-syntax (int-def-ctx-bind-type-rename! x x- t ctx)
(syntax-local-bind-syntaxes (list x)
#`(make-rename-transformer
(add-orig (assign-type #'#,x- #'#,t #:wrap? #f) #'#,x))
ctx)
(syntax-local-bind-syntaxes (list x-) #f ctx))
(define-for-syntax (add-bindings-to-ctx! e- def-ctx)
(syntax-parse e-
#:literals (erased define/intermediate)
[(erased (define/intermediate x:id x-:id τ e-))
(int-def-ctx-bind-type-rename! #'x #'x- #'τ def-ctx)]
[_ (void)]))
(define-for-syntax (walk/bind e...)
(define def-ctx (syntax-local-make-definition-context))
(define unique (gensym 'walk/bind))
(define-values (rev-e-... rev-τ...)
(for/fold ([rev-e-... '()]
[rev-τ... '()])
([e (in-syntax e...)])
(define e- (local-expand e (list unique) (list #'erased) def-ctx))
(define τ (typeof e-))
(add-bindings-to-ctx! e- def-ctx)
(values (cons e- rev-e-...)
(cons τ rev-τ...))))
(values (reverse rev-e-...)
(reverse rev-τ...)))
Homework Assignment 1 - extend this for function definitions
Homework Assignment 2 - extend this for recursive function definitions
Homework Assignment 3 - extend this so that we can define forms that expand
(define-syntax (define/memo stx)
(syntax-parse stx
[(_ (f [x (~datum :) τ] ...) e ...+)
#`(begin
(define memo 0)
(define (f [x : τ] ...)
memo
e ...))]))
|
3642434992955254ffc45387b00d52f7b575e7ff4bdf219781bd20e5d64666bf | karen/haskell-book | OuterInner.hs | module OuterInner where
embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded = return 1
embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded' = MaybeT $ ExceptT $ ReaderT $ const(return (Right (Just 1)))
| null | https://raw.githubusercontent.com/karen/haskell-book/90bb80ec3203fde68fc7fda1662d9fc8b509d179/src/ch26/OuterInner.hs | haskell | module OuterInner where
embedded :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded = return 1
embedded' :: MaybeT (ExceptT String (ReaderT () IO)) Int
embedded' = MaybeT $ ExceptT $ ReaderT $ const(return (Right (Just 1)))
| |
dd5fc211967ee4a9b4b824f2de8628e9816b396025457a6f43c0fab2fa0114ed | AvisoNovate/rook | gizmos.clj | (ns sample.gizmos
(:require [ring.util.response :refer [response]]))
(defn list-all
{:rook-route [:get ""]
:route-name ::index}
[]
(response []))
| null | https://raw.githubusercontent.com/AvisoNovate/rook/a752ce97f39a5c52301dd1866195f463817a1ed7/spec/sample/gizmos.clj | clojure | (ns sample.gizmos
(:require [ring.util.response :refer [response]]))
(defn list-all
{:rook-route [:get ""]
:route-name ::index}
[]
(response []))
| |
f0357c49200dd1162e4a84eeb3730def537d9899aed076da2f280d579c9617ca | cj1128/sicp-review | 3.67.scm | Exercise 3.67
;; Modify the pairs procedure so that (pairs integers integers) will procedure
;; the stream of all pairs of integers(i,j)(without the condition i <= j)
(load "../stream/utils.scm")
(define ints (integers-starting-from 1))
;; procedure (i, j) with i <= j
(define (pairs1 s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs1 (stream-cdr s) (stream-cdr t)))))
;; procedure (i, j) with i > j
(define (pairs2 s t)
(cons-stream
(list (stream-ref s 1) (stream-car t))
(interleave
(stream-map (lambda (x) (list x (stream-car t)))
(stream-cdr (stream-cdr s)))
(pairs2 (stream-cdr s) (stream-cdr t))))
)
(define int-pairs
(interleave
(pairs1 ints ints)
(pairs2 ints ints)))
(show-stream int-pairs 30)
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-3/3.5/3.67.scm | scheme | Modify the pairs procedure so that (pairs integers integers) will procedure
the stream of all pairs of integers(i,j)(without the condition i <= j)
procedure (i, j) with i <= j
procedure (i, j) with i > j | Exercise 3.67
(load "../stream/utils.scm")
(define ints (integers-starting-from 1))
(define (pairs1 s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs1 (stream-cdr s) (stream-cdr t)))))
(define (pairs2 s t)
(cons-stream
(list (stream-ref s 1) (stream-car t))
(interleave
(stream-map (lambda (x) (list x (stream-car t)))
(stream-cdr (stream-cdr s)))
(pairs2 (stream-cdr s) (stream-cdr t))))
)
(define int-pairs
(interleave
(pairs1 ints ints)
(pairs2 ints ints)))
(show-stream int-pairs 30)
|
c0d10d9e630f8962319b0994ef8408c1ec94361f26a4ab7d4118e844554fa9ff | acieroid/scala-am | fringe.scm | (define (atom? x)
(not (pair? x)))
(define (fringe l)
(cond ((null? l) '())
((atom? l) (list l))
(else (append (fringe (car l))
(fringe (cdr l))))))
(equal? (fringe '((1) ((((2)))) (3 (4 5) 6) ((7) 8 9))) '(1 2 3 4 5 6 7 8 9))
| null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/scp1/fringe.scm | scheme | (define (atom? x)
(not (pair? x)))
(define (fringe l)
(cond ((null? l) '())
((atom? l) (list l))
(else (append (fringe (car l))
(fringe (cdr l))))))
(equal? (fringe '((1) ((((2)))) (3 (4 5) 6) ((7) 8 9))) '(1 2 3 4 5 6 7 8 9))
| |
ce34f980019120ed499a2d359d2fd7d716ed0fba8608583b7344af0549c0a39e | GaloisInc/lumberjack | ExampleLog.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Reader
import Data.Functor.Contravariant
import Data.Text as T
import qualified Data.Text.IO as TIO
import qualified Control.Monad.Catch as X
import Lumberjack
import System.IO ( stderr )
----------------------------------------------------------------------
-- Base example:
instance HasLog T.Text IO where
The base IO monad does not have direct " storage " ability in the
-- monad itself, so it can really only support basic/default
-- operations which preclude some of the ancillary techniques such
as adding tags automatically . Lumberjack provides some default
functions to support logging directly in the IO monad if this is
-- desired.
getLogAction = return defaultGetIOLogAction
exampleTextLoggingInIO :: IO ()
exampleTextLoggingInIO = do
-- This function represents the main code that logging output should
-- be generated from. Here's an example of generating a log message:
writeLogM $ T.pack "This is a logged text message in base IO"
-- In situations where the current monad doesn't provide the log
-- action, it's possible to provide that directly:
let myLogAction = LogAction TIO.putStrLn
writeLog myLogAction $ T.pack "This is another text message, logged in IO with a custom action"
----------------------------------------------------------------------
Example 2 : Logging strings using a contramapped converter
instance HasLog [Char] IO where
-- The defaultGetIOLogAction logs Text, but if the code needed to
log , the contramap functionality can be used to simplify
-- the adaptation of the existing logger to a new input type.
getLogAction = return $ T.pack >$< defaultGetIOLogAction
exampleStringLoggingInIO :: IO ()
exampleStringLoggingInIO = do
writeLogM ("This is a logged string message in base IO" :: String)
----------------------------------------------------------------------
Example 3 : Storing the LogAction in a local monad stack
type ReaderEnv = LogAction MyMonad T.Text
newtype MyMonad a = MyMonad { runMyMonad :: ReaderT ReaderEnv IO a }
deriving ( Applicative, Functor, Monad, MonadReader ReaderEnv, MonadIO )
instance HasLog T.Text MyMonad where
getLogAction = ask
instance LoggingMonad T.Text MyMonad where
adjustLogAction a = local a
exampleStringLoggingInMyMonad :: MyMonad ()
exampleStringLoggingInMyMonad = do
writeLogM $ T.pack "This is a logged string message in MyMonad"
adjustLogAction (contramap (("LOG> " :: T.Text) <>)) $ do
writeLogM $ T.pack "The logger message can be adjusted"
----------------------------------------------------------------------
Example 4 : Logging information - rich message objects . Lumberjack
-- helpfully provides a common rich message object. Other message
objects can be defined and logged , but the Lumberjack LogMessage
-- attempts to provide a useful set of functionality so that a custom
-- msg type is frequently unnecessary.
type ReaderEnv2 = LogAction MyMonad2 LogMessage
newtype MyMonad2 a = MyMonad2 { runMyMonad2 :: ReaderT ReaderEnv2 IO a }
deriving ( Applicative, Functor, Monad, MonadReader ReaderEnv2
, X.MonadThrow, X.MonadCatch, MonadIO )
instance HasLog LogMessage MyMonad2 where
getLogAction = ask
instance LoggingMonad LogMessage MyMonad2 where
adjustLogAction a = local a
The above is sufficient to log LogMessage objects , but for
-- convenience, Text can be logged directly as well, using the
-- conversion builtin here.
instance HasLog T.Text MyMonad2 where
getLogAction = asks $ contramap textToLogMessage
where
textToLogMessage t = msgWith { logText = t, logLevel = Info }
exampleStringLoggingInMyMonad2 :: MyMonad2 ()
exampleStringLoggingInMyMonad2 = do
-- As noted above, this function represents the main body of code.
-- The logging messages would be interspersed in this code at
-- appropriate locations to generate the various logged information.
writeLogM $ msgWith { logText = "This is a logged string message in MyMonad" }
-- withLogTag is a helper to set the logTags field for subsequently logged messages
withLogTag "loc" "inner" $ do
writeLogM $ msgWith { logText = "doing stuff..." }
withLogTag "style" "(deep)" $ do
-- Tags accumulate and are applied to all messages logged.
writeLogM $ msgWith { logText = "deep thinking",
logLevel = Info
}
-- There's also a HasLog for simple messages in this monad
writeLogM $ ("Text messages can be logged as well" :: T.Text)
-- Calls to other functions can be logged on entry and exit by
-- simply using this wrapper. Note also that this is outside of
-- the inner withLogTag context, so only the outer tags are
-- applied, but the context for those tags extends to the logging
-- from the functions being called.
logFunctionCallM "invoking subFunction" $ subFunction
-- Helpers can be used to log various types of information. Here is
-- an indication of progress being made by the code.
logProgressM "making good progress"
writeLogM $ msgWith { logText = "Done now", logLevel = Warning }
subFunction :: (WithLog LogMessage m, Monad m) => m ()
subFunction =
-- An example of a monadic function called that can perform logging
with minimal constraints on the current Monad type .
writeLogM $ msgWith { logText = "subFunction executing" }
----------------------------------------------------------------------
main = do
exampleTextLoggingInIO
exampleStringLoggingInIO
The monad stack can just use the regular IO logging action
-- because the monad stack has MonadIO.
runReaderT (runMyMonad exampleStringLoggingInMyMonad) defaultGetIOLogAction
-- Or something different could be configured... without changing
-- the target code doing the logging
-- (e.g. exampleStringLoggingInMyMonad).
runReaderT (runMyMonad exampleStringLoggingInMyMonad) $
LogAction $ liftIO . \m -> do putStr "LOGMSG << "
TIO.putStr m
putStrLn " >>"
Richer messages allow for more detailed information . Of
-- particular interest, the target code identifies the information
-- relative to the code (like the severity of the message) but the
-- handler sets the time of log and performs the conversion from the
LogMessage to the Text that can be output by the base logger used .
let richStderrLogger = addLogActionTime $
cvtLogMessageToANSITermText >$< defaultGetIOLogAction
writeLogM ("** Example of rich message logging" :: String)
runReaderT (runMyMonad2 exampleStringLoggingInMyMonad2) richStderrLogger
-- Sometimes it's convenient to send log output to multiple sources.
-- In this example, warnings and above are logged to the console,
-- but all messages are logged to a file (without ANSI terminal
-- color codes). Again, note that the target code containing the
-- logging code does not change, only the logger configuration here.
--
-- Note that the `cvtLogMessage...` functions are provided by
Lumberjack for a standard method of formatting the LogMessage
supported by Lumberjack . It 's possible to write entirely
different formatting functions for the LogMessage and use those
-- instead.
--
-- It's also a good idea to use the `safeLogAction` wrapper to
-- ensure that exceptions generated by the Logger simply cause log
-- messages to be discarded rather than causing failure of the
-- entire application.
let consoleLogger = logFilter (\m -> Warning <= logLevel m ) $
cvtLogMessageToANSITermText >$<
defaultGetIOLogAction
fileLogger = safeLogAction $
addLogActionTime $
cvtLogMessageToPlainText >$<
LogAction (liftIO . TIO.appendFile "./example.log" . flip (<>) "\n")
failingLogger = safeLogAction $ -- remove this and the app will exit prematurely
addLogActionTime $
cvtLogMessageToPlainText >$<
LogAction (liftIO . TIO.appendFile "/bogus/location/to/log/to" . flip (<>) "\n")
writeLogM ("** Example of rich message logging to multiple outputs (see ./example.log)" :: String)
runReaderT (runMyMonad2 exampleStringLoggingInMyMonad2) $
consoleLogger <> failingLogger <> fileLogger
putStrLn "end of example"
| null | https://raw.githubusercontent.com/GaloisInc/lumberjack/47bfa2cafa62cdcc2fa09990c941c66f3fc137d5/example/ExampleLog.hs | haskell | # LANGUAGE OverloadedStrings #
--------------------------------------------------------------------
Base example:
monad itself, so it can really only support basic/default
operations which preclude some of the ancillary techniques such
desired.
This function represents the main code that logging output should
be generated from. Here's an example of generating a log message:
In situations where the current monad doesn't provide the log
action, it's possible to provide that directly:
--------------------------------------------------------------------
The defaultGetIOLogAction logs Text, but if the code needed to
the adaptation of the existing logger to a new input type.
--------------------------------------------------------------------
--------------------------------------------------------------------
helpfully provides a common rich message object. Other message
attempts to provide a useful set of functionality so that a custom
msg type is frequently unnecessary.
convenience, Text can be logged directly as well, using the
conversion builtin here.
As noted above, this function represents the main body of code.
The logging messages would be interspersed in this code at
appropriate locations to generate the various logged information.
withLogTag is a helper to set the logTags field for subsequently logged messages
Tags accumulate and are applied to all messages logged.
There's also a HasLog for simple messages in this monad
Calls to other functions can be logged on entry and exit by
simply using this wrapper. Note also that this is outside of
the inner withLogTag context, so only the outer tags are
applied, but the context for those tags extends to the logging
from the functions being called.
Helpers can be used to log various types of information. Here is
an indication of progress being made by the code.
An example of a monadic function called that can perform logging
--------------------------------------------------------------------
because the monad stack has MonadIO.
Or something different could be configured... without changing
the target code doing the logging
(e.g. exampleStringLoggingInMyMonad).
particular interest, the target code identifies the information
relative to the code (like the severity of the message) but the
handler sets the time of log and performs the conversion from the
Sometimes it's convenient to send log output to multiple sources.
In this example, warnings and above are logged to the console,
but all messages are logged to a file (without ANSI terminal
color codes). Again, note that the target code containing the
logging code does not change, only the logger configuration here.
Note that the `cvtLogMessage...` functions are provided by
instead.
It's also a good idea to use the `safeLogAction` wrapper to
ensure that exceptions generated by the Logger simply cause log
messages to be discarded rather than causing failure of the
entire application.
remove this and the app will exit prematurely | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
module Main where
import Control.Monad.Reader
import Data.Functor.Contravariant
import Data.Text as T
import qualified Data.Text.IO as TIO
import qualified Control.Monad.Catch as X
import Lumberjack
import System.IO ( stderr )
instance HasLog T.Text IO where
The base IO monad does not have direct " storage " ability in the
as adding tags automatically . Lumberjack provides some default
functions to support logging directly in the IO monad if this is
getLogAction = return defaultGetIOLogAction
exampleTextLoggingInIO :: IO ()
exampleTextLoggingInIO = do
writeLogM $ T.pack "This is a logged text message in base IO"
let myLogAction = LogAction TIO.putStrLn
writeLog myLogAction $ T.pack "This is another text message, logged in IO with a custom action"
Example 2 : Logging strings using a contramapped converter
instance HasLog [Char] IO where
log , the contramap functionality can be used to simplify
getLogAction = return $ T.pack >$< defaultGetIOLogAction
exampleStringLoggingInIO :: IO ()
exampleStringLoggingInIO = do
writeLogM ("This is a logged string message in base IO" :: String)
Example 3 : Storing the LogAction in a local monad stack
type ReaderEnv = LogAction MyMonad T.Text
newtype MyMonad a = MyMonad { runMyMonad :: ReaderT ReaderEnv IO a }
deriving ( Applicative, Functor, Monad, MonadReader ReaderEnv, MonadIO )
instance HasLog T.Text MyMonad where
getLogAction = ask
instance LoggingMonad T.Text MyMonad where
adjustLogAction a = local a
exampleStringLoggingInMyMonad :: MyMonad ()
exampleStringLoggingInMyMonad = do
writeLogM $ T.pack "This is a logged string message in MyMonad"
adjustLogAction (contramap (("LOG> " :: T.Text) <>)) $ do
writeLogM $ T.pack "The logger message can be adjusted"
Example 4 : Logging information - rich message objects . Lumberjack
objects can be defined and logged , but the Lumberjack LogMessage
type ReaderEnv2 = LogAction MyMonad2 LogMessage
newtype MyMonad2 a = MyMonad2 { runMyMonad2 :: ReaderT ReaderEnv2 IO a }
deriving ( Applicative, Functor, Monad, MonadReader ReaderEnv2
, X.MonadThrow, X.MonadCatch, MonadIO )
instance HasLog LogMessage MyMonad2 where
getLogAction = ask
instance LoggingMonad LogMessage MyMonad2 where
adjustLogAction a = local a
The above is sufficient to log LogMessage objects , but for
instance HasLog T.Text MyMonad2 where
getLogAction = asks $ contramap textToLogMessage
where
textToLogMessage t = msgWith { logText = t, logLevel = Info }
exampleStringLoggingInMyMonad2 :: MyMonad2 ()
exampleStringLoggingInMyMonad2 = do
writeLogM $ msgWith { logText = "This is a logged string message in MyMonad" }
withLogTag "loc" "inner" $ do
writeLogM $ msgWith { logText = "doing stuff..." }
withLogTag "style" "(deep)" $ do
writeLogM $ msgWith { logText = "deep thinking",
logLevel = Info
}
writeLogM $ ("Text messages can be logged as well" :: T.Text)
logFunctionCallM "invoking subFunction" $ subFunction
logProgressM "making good progress"
writeLogM $ msgWith { logText = "Done now", logLevel = Warning }
subFunction :: (WithLog LogMessage m, Monad m) => m ()
subFunction =
with minimal constraints on the current Monad type .
writeLogM $ msgWith { logText = "subFunction executing" }
main = do
exampleTextLoggingInIO
exampleStringLoggingInIO
The monad stack can just use the regular IO logging action
runReaderT (runMyMonad exampleStringLoggingInMyMonad) defaultGetIOLogAction
runReaderT (runMyMonad exampleStringLoggingInMyMonad) $
LogAction $ liftIO . \m -> do putStr "LOGMSG << "
TIO.putStr m
putStrLn " >>"
Richer messages allow for more detailed information . Of
LogMessage to the Text that can be output by the base logger used .
let richStderrLogger = addLogActionTime $
cvtLogMessageToANSITermText >$< defaultGetIOLogAction
writeLogM ("** Example of rich message logging" :: String)
runReaderT (runMyMonad2 exampleStringLoggingInMyMonad2) richStderrLogger
Lumberjack for a standard method of formatting the LogMessage
supported by Lumberjack . It 's possible to write entirely
different formatting functions for the LogMessage and use those
let consoleLogger = logFilter (\m -> Warning <= logLevel m ) $
cvtLogMessageToANSITermText >$<
defaultGetIOLogAction
fileLogger = safeLogAction $
addLogActionTime $
cvtLogMessageToPlainText >$<
LogAction (liftIO . TIO.appendFile "./example.log" . flip (<>) "\n")
addLogActionTime $
cvtLogMessageToPlainText >$<
LogAction (liftIO . TIO.appendFile "/bogus/location/to/log/to" . flip (<>) "\n")
writeLogM ("** Example of rich message logging to multiple outputs (see ./example.log)" :: String)
runReaderT (runMyMonad2 exampleStringLoggingInMyMonad2) $
consoleLogger <> failingLogger <> fileLogger
putStrLn "end of example"
|
0c498f8031d95a09c1d172b75b97b47b06dcc2caaea0ac03ca9f846089abf727 | ocaml-obuild/obuild | gtk.ml | external gtk_true : unit -> bool = "stub_gtk_true"
let () =
Printf.printf "gtk_true(): %b\n" (gtk_true ())
| null | https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/tests/simple/gtk.ml | ocaml | external gtk_true : unit -> bool = "stub_gtk_true"
let () =
Printf.printf "gtk_true(): %b\n" (gtk_true ())
| |
2c102a21e1d6a97f487fa3fd9df62836f4fbb8148677d977473e13ac2a06b28f | Shirakumo/kandria | creator.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass creator (alloy:dialog)
((entity :initform NIL :accessor entity))
(:default-initargs
:title "Create Entity"
:extent (alloy:size 400 500)))
(defmethod alloy:reject ((creator creator)))
(defmethod alloy:accept ((creator creator))
(let ((entity (entity creator)))
(when entity
(setf (location entity) (closest-acceptable-location entity (location entity)))
(edit (make-instance 'insert-entity :entity entity) T))))
(defmethod initialize-instance :after ((creator creator) &key)
(let* ((layout (make-instance 'alloy:grid-layout :col-sizes '(T) :row-sizes '(30 T) :layout-parent creator))
(focus (make-instance 'alloy:focus-list :focus-parent creator))
(class NIL)
(classes (sort (list-creatable-classes) #'string<))
(combo (alloy:represent class 'alloy:combo-set :value-set classes :layout-parent layout :focus-parent focus))
(inspector (make-instance 'alloy::inspector :object (entity creator)))
(scroll (make-instance 'alloy:scroll-view :scroll :y :focus inspector :layout inspector
:layout-parent layout :focus-parent focus)))
(alloy:on alloy:value (class combo)
(when class
(setf (entity creator) (make-instance class :location (vcopy (location (camera +world+)))))
(reinitialize-instance inspector :object (entity creator))))))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/458e21adec1088483f238565979cff2d58bbc3fe/editor/creator.lisp | lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass creator (alloy:dialog)
((entity :initform NIL :accessor entity))
(:default-initargs
:title "Create Entity"
:extent (alloy:size 400 500)))
(defmethod alloy:reject ((creator creator)))
(defmethod alloy:accept ((creator creator))
(let ((entity (entity creator)))
(when entity
(setf (location entity) (closest-acceptable-location entity (location entity)))
(edit (make-instance 'insert-entity :entity entity) T))))
(defmethod initialize-instance :after ((creator creator) &key)
(let* ((layout (make-instance 'alloy:grid-layout :col-sizes '(T) :row-sizes '(30 T) :layout-parent creator))
(focus (make-instance 'alloy:focus-list :focus-parent creator))
(class NIL)
(classes (sort (list-creatable-classes) #'string<))
(combo (alloy:represent class 'alloy:combo-set :value-set classes :layout-parent layout :focus-parent focus))
(inspector (make-instance 'alloy::inspector :object (entity creator)))
(scroll (make-instance 'alloy:scroll-view :scroll :y :focus inspector :layout inspector
:layout-parent layout :focus-parent focus)))
(alloy:on alloy:value (class combo)
(when class
(setf (entity creator) (make-instance class :location (vcopy (location (camera +world+)))))
(reinitialize-instance inspector :object (entity creator))))))
| |
3b7a178765174ec5f2686c3885a8a51587776d52f85094789ceed4516083d83d | terezka/cherry-core | Array.hs |
|
Module : Array
Description : Fast immutable arrays . The elements in an array must have the same type .
License : BSD 3
Maintainer :
Stability : experimental
Portability : POSIX
Fast immutable arrays . The elements in an array must have the same type .
Module : Array
Description : Fast immutable arrays. The elements in an array must have the same type.
License : BSD 3
Maintainer :
Stability : experimental
Portability : POSIX
Fast immutable arrays. The elements in an array must have the same type.
-}
module Array
( Array
-- * Creation
, empty, initialize, repeat, fromList
-- * Query
, isEmpty, length, get
-- * Manipulate
, set, push, append, slice
-- * Lists
, toList, toIndexedList
-- * Transform
, map, indexedMap, foldr, foldl, filter
) where
import Data.Foldable (foldl', product, sum)
import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, flip, fromIntegral, mappend, mconcat, otherwise, pure)
import Data.Vector ((!?), (++), (//))
import Basics ((&&), (+), (-), (<), (<=), (<|), (>>), Bool, Int, clamp)
import List (List)
import Maybe (Maybe (..))
import qualified Data.Vector
import qualified Data.Foldable
import qualified Data.Maybe as HM
import qualified List as List
import qualified Tuple as Tuple
{-| An array.
-}
newtype Array a
= Array (Data.Vector.Vector a)
deriving (Eq, Show)
{-| Return an empty array.
> length empty == 0
-}
empty :: Array a
empty =
Array Data.Vector.empty
{-| Determine if an array is empty.
> isEmpty empty == True
-}
isEmpty :: Array a -> Bool
isEmpty =
unwrap >> Data.Vector.null
| Return the length of an array .
> length ( fromList [ 1,2,3 ] ) = = 3
> length (fromList [1,2,3]) == 3
-}
length :: Array a -> Int
length =
unwrap
>> Data.Vector.length
>> fromIntegral
| Initialize an array . ` initialize n f ` creates an array of length ` n ` with
the element at index ` i ` initialized to the result of ` ( f i ) ` .
> initialize 4 identity = = fromList [ 0,1,2,3 ]
> initialize 4 ( \n - > n*n ) = = fromList [ 0,1,4,9 ]
> initialize 4 ( always 0 ) = = fromList [ 0,0,0,0 ]
the element at index `i` initialized to the result of `(f i)`.
> initialize 4 identity == fromList [0,1,2,3]
> initialize 4 (\n -> n*n) == fromList [0,1,4,9]
> initialize 4 (always 0) == fromList [0,0,0,0]
-}
initialize :: Int -> (Int -> a) -> Array a
initialize n f =
Array
<| Data.Vector.generate
(fromIntegral n)
(fromIntegral >> f)
| Creates an array with a given length , filled with a default element .
> repeat 5 0 = = fromList [ 0,0,0,0,0 ]
> repeat 3 " cat " = = fromList [ " cat","cat","cat " ]
Notice that ` repeat 3 x ` is the same as ` initialize 3 ( always x ) ` .
> repeat 5 0 == fromList [0,0,0,0,0]
> repeat 3 "cat" == fromList ["cat","cat","cat"]
Notice that `repeat 3 x` is the same as `initialize 3 (always x)`.
-}
repeat :: Int -> a -> Array a
repeat n e =
Array
<| Data.Vector.replicate (fromIntegral n) e
{-| Create an array from a `List`.
-}
fromList :: List a -> Array a
fromList =
Data.Vector.fromList >> Array
| Return ` Just ` the element at the index or ` Nothing ` if the index is out of
range .
> get 0 ( fromList [ 0,1,2 ] ) = = Just 0
> get 2 ( fromList [ 0,1,2 ] ) = = Just 2
> get 5 ( fromList [ 0,1,2 ] ) = = Nothing
> get -1 ( fromList [ 0,1,2 ] ) = = Nothing
range.
> get 0 (fromList [0,1,2]) == Just 0
> get 2 (fromList [0,1,2]) == Just 2
> get 5 (fromList [0,1,2]) == Nothing
> get -1 (fromList [0,1,2]) == Nothing
-}
get :: Int -> Array a -> Maybe a
get i array =
case unwrap array !? fromIntegral i of
HM.Just a -> Just a
HM.Nothing -> Nothing
| Set the element at a particular index . Returns an updated array .
If the index is out of range , the array is unaltered .
> set 1 7 ( fromList [ 1,2,3 ] ) = = fromList [ 1,7,3 ]
If the index is out of range, the array is unaltered.
> set 1 7 (fromList [1,2,3]) == fromList [1,7,3]
-}
set :: Int -> a -> Array a -> Array a
set i value array =
let len = length array
vector = unwrap array
result =
if 0 <= i && i < len
then vector // [(fromIntegral i, value)]
else vector
in
Array result
| Push an element onto the end of an array .
> push 3 ( fromList [ 1,2 ] ) = = fromList [ 1,2,3 ]
> push 3 (fromList [1,2]) == fromList [1,2,3]
-}
push :: a -> Array a -> Array a
push a (Array vector) =
Array (Data.Vector.snoc vector a)
| Create a list of elements from an array .
> toList ( fromList [ 3,5,8 ] ) = = [ 3,5,8 ]
> toList (fromList [3,5,8]) == [3,5,8]
-}
toList :: Array a -> List a
toList =
unwrap >> Data.Vector.toList
| Create an indexed list from an array . Each element of the array will be
paired with its index .
> toIndexedList ( fromList [ " cat","dog " ] ) = = [ ( 0,"cat " ) , ( 1,"dog " ) ]
paired with its index.
> toIndexedList (fromList ["cat","dog"]) == [(0,"cat"), (1,"dog")]
-}
toIndexedList :: Array a -> List (Int, a)
toIndexedList =
unwrap
>> Data.Vector.indexed
>> Data.Vector.toList
>> List.map (Tuple.mapFirst fromIntegral)
| Reduce an array from the right . Read ` foldr ` as fold from the right .
> foldr ( + ) 0 ( repeat 3 5 ) = = 15
> foldr (+) 0 (repeat 3 5) == 15
-}
foldr :: (a -> b -> b) -> b -> Array a -> b
foldr f value array =
Data.Foldable.foldr f value (unwrap array)
| Reduce an array from the left . Read ` foldl ` as fold from the left .
> foldl (: :) [ ] ( fromList [ 1,2,3 ] ) = = [ 3,2,1 ]
> foldl (::) [] (fromList [1,2,3]) == [3,2,1]
-}
foldl :: (a -> b -> b) -> b -> Array a -> b
foldl f value array =
foldl' (flip f) value (unwrap array)
| Keep elements that pass the test .
> filter isEven ( fromList [ 1,2,3,4,5,6 ] ) = = ( fromList [ 2,4,6 ] )
> filter isEven (fromList [1,2,3,4,5,6]) == (fromList [2,4,6])
-}
filter :: (a -> Bool) -> Array a -> Array a
filter f (Array vector) =
Array (Data.Vector.filter f vector)
| Apply a function on every element in an array .
> map sqrt ( fromList [ 1,4,9 ] ) = = fromList [ 1,2,3 ]
> map sqrt (fromList [1,4,9]) == fromList [1,2,3]
-}
map :: (a -> b) -> Array a -> Array b
map f (Array vector) =
Array (Data.Vector.map f vector)
| Apply a function on every element with its index as first argument .
> indexedMap ( * ) ( fromList [ 5,5,5 ] ) = = fromList [ 0,5,10 ]
> indexedMap (*) (fromList [5,5,5]) == fromList [0,5,10]
-}
indexedMap :: (Int -> a -> b) -> Array a -> Array b
indexedMap f (Array vector) =
Array (Data.Vector.imap (fromIntegral >> f) vector)
| Append two arrays to a new one .
> append ( repeat 2 42 ) ( repeat 3 81 ) = = fromList [ 42,42,81,81,81 ]
> append (repeat 2 42) (repeat 3 81) == fromList [42,42,81,81,81]
-}
append :: Array a -> Array a -> Array a
append (Array first) (Array second) =
Array (first ++ second)
| Get a sub - section of an array : ` ( slice start end array ) ` . The ` start ` is a
zero - based index where we will start our slice . The ` end ` is a zero - based index
that indicates the end of the slice . The slice extracts up to but not including
` end ` .
> slice 0 3 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 0,1,2 ]
> slice 1 4 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 1,2,3 ]
Both the ` start ` and ` end ` indexes can be negative , indicating an offset from
the end of the array .
> slice 1 -1 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 1,2,3 ]
> slice -2 5 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 3,4 ]
This makes it pretty easy to ` pop ` the last element off of an array :
` slice 0 -1 array `
zero-based index where we will start our slice. The `end` is a zero-based index
that indicates the end of the slice. The slice extracts up to but not including
`end`.
> slice 0 3 (fromList [0,1,2,3,4]) == fromList [0,1,2]
> slice 1 4 (fromList [0,1,2,3,4]) == fromList [1,2,3]
Both the `start` and `end` indexes can be negative, indicating an offset from
the end of the array.
> slice 1 -1 (fromList [0,1,2,3,4]) == fromList [1,2,3]
> slice -2 5 (fromList [0,1,2,3,4]) == fromList [3,4]
This makes it pretty easy to `pop` the last element off of an array:
`slice 0 -1 array`
-}
slice :: Int -> Int -> Array a -> Array a
slice from to (Array vector) =
let len = Data.Vector.length vector
handleNegative value = if value < 0 then len + value else value
normalize = fromIntegral >> handleNegative >> clamp 0 len
from' = normalize from
to' = normalize to
sliceLen = to' - from'
in
if sliceLen <= 0
then empty
else Array <| Data.Vector.slice from' sliceLen vector
-- INTERNAL
{-| Helper function to unwrap an array.
-}
unwrap :: Array a -> Data.Vector.Vector a
unwrap (Array v) =
v
| null | https://raw.githubusercontent.com/terezka/cherry-core/d9bd446e226fc9b04783532969fa670211a150c6/src/Array.hs | haskell | * Creation
* Query
* Manipulate
* Lists
* Transform
| An array.
| Return an empty array.
> length empty == 0
| Determine if an array is empty.
> isEmpty empty == True
| Create an array from a `List`.
INTERNAL
| Helper function to unwrap an array.
|
|
Module : Array
Description : Fast immutable arrays . The elements in an array must have the same type .
License : BSD 3
Maintainer :
Stability : experimental
Portability : POSIX
Fast immutable arrays . The elements in an array must have the same type .
Module : Array
Description : Fast immutable arrays. The elements in an array must have the same type.
License : BSD 3
Maintainer :
Stability : experimental
Portability : POSIX
Fast immutable arrays. The elements in an array must have the same type.
-}
module Array
( Array
, empty, initialize, repeat, fromList
, isEmpty, length, get
, set, push, append, slice
, toList, toIndexedList
, map, indexedMap, foldr, foldl, filter
) where
import Data.Foldable (foldl', product, sum)
import Prelude (Applicative, Char, Eq, Functor, Monad, Num, Ord, Show, flip, fromIntegral, mappend, mconcat, otherwise, pure)
import Data.Vector ((!?), (++), (//))
import Basics ((&&), (+), (-), (<), (<=), (<|), (>>), Bool, Int, clamp)
import List (List)
import Maybe (Maybe (..))
import qualified Data.Vector
import qualified Data.Foldable
import qualified Data.Maybe as HM
import qualified List as List
import qualified Tuple as Tuple
newtype Array a
= Array (Data.Vector.Vector a)
deriving (Eq, Show)
empty :: Array a
empty =
Array Data.Vector.empty
isEmpty :: Array a -> Bool
isEmpty =
unwrap >> Data.Vector.null
| Return the length of an array .
> length ( fromList [ 1,2,3 ] ) = = 3
> length (fromList [1,2,3]) == 3
-}
length :: Array a -> Int
length =
unwrap
>> Data.Vector.length
>> fromIntegral
| Initialize an array . ` initialize n f ` creates an array of length ` n ` with
the element at index ` i ` initialized to the result of ` ( f i ) ` .
> initialize 4 identity = = fromList [ 0,1,2,3 ]
> initialize 4 ( \n - > n*n ) = = fromList [ 0,1,4,9 ]
> initialize 4 ( always 0 ) = = fromList [ 0,0,0,0 ]
the element at index `i` initialized to the result of `(f i)`.
> initialize 4 identity == fromList [0,1,2,3]
> initialize 4 (\n -> n*n) == fromList [0,1,4,9]
> initialize 4 (always 0) == fromList [0,0,0,0]
-}
initialize :: Int -> (Int -> a) -> Array a
initialize n f =
Array
<| Data.Vector.generate
(fromIntegral n)
(fromIntegral >> f)
| Creates an array with a given length , filled with a default element .
> repeat 5 0 = = fromList [ 0,0,0,0,0 ]
> repeat 3 " cat " = = fromList [ " cat","cat","cat " ]
Notice that ` repeat 3 x ` is the same as ` initialize 3 ( always x ) ` .
> repeat 5 0 == fromList [0,0,0,0,0]
> repeat 3 "cat" == fromList ["cat","cat","cat"]
Notice that `repeat 3 x` is the same as `initialize 3 (always x)`.
-}
repeat :: Int -> a -> Array a
repeat n e =
Array
<| Data.Vector.replicate (fromIntegral n) e
fromList :: List a -> Array a
fromList =
Data.Vector.fromList >> Array
| Return ` Just ` the element at the index or ` Nothing ` if the index is out of
range .
> get 0 ( fromList [ 0,1,2 ] ) = = Just 0
> get 2 ( fromList [ 0,1,2 ] ) = = Just 2
> get 5 ( fromList [ 0,1,2 ] ) = = Nothing
> get -1 ( fromList [ 0,1,2 ] ) = = Nothing
range.
> get 0 (fromList [0,1,2]) == Just 0
> get 2 (fromList [0,1,2]) == Just 2
> get 5 (fromList [0,1,2]) == Nothing
> get -1 (fromList [0,1,2]) == Nothing
-}
get :: Int -> Array a -> Maybe a
get i array =
case unwrap array !? fromIntegral i of
HM.Just a -> Just a
HM.Nothing -> Nothing
| Set the element at a particular index . Returns an updated array .
If the index is out of range , the array is unaltered .
> set 1 7 ( fromList [ 1,2,3 ] ) = = fromList [ 1,7,3 ]
If the index is out of range, the array is unaltered.
> set 1 7 (fromList [1,2,3]) == fromList [1,7,3]
-}
set :: Int -> a -> Array a -> Array a
set i value array =
let len = length array
vector = unwrap array
result =
if 0 <= i && i < len
then vector // [(fromIntegral i, value)]
else vector
in
Array result
| Push an element onto the end of an array .
> push 3 ( fromList [ 1,2 ] ) = = fromList [ 1,2,3 ]
> push 3 (fromList [1,2]) == fromList [1,2,3]
-}
push :: a -> Array a -> Array a
push a (Array vector) =
Array (Data.Vector.snoc vector a)
| Create a list of elements from an array .
> toList ( fromList [ 3,5,8 ] ) = = [ 3,5,8 ]
> toList (fromList [3,5,8]) == [3,5,8]
-}
toList :: Array a -> List a
toList =
unwrap >> Data.Vector.toList
| Create an indexed list from an array . Each element of the array will be
paired with its index .
> toIndexedList ( fromList [ " cat","dog " ] ) = = [ ( 0,"cat " ) , ( 1,"dog " ) ]
paired with its index.
> toIndexedList (fromList ["cat","dog"]) == [(0,"cat"), (1,"dog")]
-}
toIndexedList :: Array a -> List (Int, a)
toIndexedList =
unwrap
>> Data.Vector.indexed
>> Data.Vector.toList
>> List.map (Tuple.mapFirst fromIntegral)
| Reduce an array from the right . Read ` foldr ` as fold from the right .
> foldr ( + ) 0 ( repeat 3 5 ) = = 15
> foldr (+) 0 (repeat 3 5) == 15
-}
foldr :: (a -> b -> b) -> b -> Array a -> b
foldr f value array =
Data.Foldable.foldr f value (unwrap array)
| Reduce an array from the left . Read ` foldl ` as fold from the left .
> foldl (: :) [ ] ( fromList [ 1,2,3 ] ) = = [ 3,2,1 ]
> foldl (::) [] (fromList [1,2,3]) == [3,2,1]
-}
foldl :: (a -> b -> b) -> b -> Array a -> b
foldl f value array =
foldl' (flip f) value (unwrap array)
| Keep elements that pass the test .
> filter isEven ( fromList [ 1,2,3,4,5,6 ] ) = = ( fromList [ 2,4,6 ] )
> filter isEven (fromList [1,2,3,4,5,6]) == (fromList [2,4,6])
-}
filter :: (a -> Bool) -> Array a -> Array a
filter f (Array vector) =
Array (Data.Vector.filter f vector)
| Apply a function on every element in an array .
> map sqrt ( fromList [ 1,4,9 ] ) = = fromList [ 1,2,3 ]
> map sqrt (fromList [1,4,9]) == fromList [1,2,3]
-}
map :: (a -> b) -> Array a -> Array b
map f (Array vector) =
Array (Data.Vector.map f vector)
| Apply a function on every element with its index as first argument .
> indexedMap ( * ) ( fromList [ 5,5,5 ] ) = = fromList [ 0,5,10 ]
> indexedMap (*) (fromList [5,5,5]) == fromList [0,5,10]
-}
indexedMap :: (Int -> a -> b) -> Array a -> Array b
indexedMap f (Array vector) =
Array (Data.Vector.imap (fromIntegral >> f) vector)
| Append two arrays to a new one .
> append ( repeat 2 42 ) ( repeat 3 81 ) = = fromList [ 42,42,81,81,81 ]
> append (repeat 2 42) (repeat 3 81) == fromList [42,42,81,81,81]
-}
append :: Array a -> Array a -> Array a
append (Array first) (Array second) =
Array (first ++ second)
| Get a sub - section of an array : ` ( slice start end array ) ` . The ` start ` is a
zero - based index where we will start our slice . The ` end ` is a zero - based index
that indicates the end of the slice . The slice extracts up to but not including
` end ` .
> slice 0 3 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 0,1,2 ]
> slice 1 4 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 1,2,3 ]
Both the ` start ` and ` end ` indexes can be negative , indicating an offset from
the end of the array .
> slice 1 -1 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 1,2,3 ]
> slice -2 5 ( fromList [ 0,1,2,3,4 ] ) = = fromList [ 3,4 ]
This makes it pretty easy to ` pop ` the last element off of an array :
` slice 0 -1 array `
zero-based index where we will start our slice. The `end` is a zero-based index
that indicates the end of the slice. The slice extracts up to but not including
`end`.
> slice 0 3 (fromList [0,1,2,3,4]) == fromList [0,1,2]
> slice 1 4 (fromList [0,1,2,3,4]) == fromList [1,2,3]
Both the `start` and `end` indexes can be negative, indicating an offset from
the end of the array.
> slice 1 -1 (fromList [0,1,2,3,4]) == fromList [1,2,3]
> slice -2 5 (fromList [0,1,2,3,4]) == fromList [3,4]
This makes it pretty easy to `pop` the last element off of an array:
`slice 0 -1 array`
-}
slice :: Int -> Int -> Array a -> Array a
slice from to (Array vector) =
let len = Data.Vector.length vector
handleNegative value = if value < 0 then len + value else value
normalize = fromIntegral >> handleNegative >> clamp 0 len
from' = normalize from
to' = normalize to
sliceLen = to' - from'
in
if sliceLen <= 0
then empty
else Array <| Data.Vector.slice from' sliceLen vector
unwrap :: Array a -> Data.Vector.Vector a
unwrap (Array v) =
v
|
3c5d634eb163bdade7b0901419bcaa4ba84fbc2d4de4f5ac299633d014e7c3c8 | weavejester/cljfmt | diff.clj | (ns cljfmt.diff
(:import [difflib DiffUtils]
[java.io File]
[java.util.regex Pattern])
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defn- lines [s]
(str/split s #"\n"))
(defn- unlines [ss]
(str/join "\n" ss))
(defn to-absolute-path [filename]
(->> (str/split filename (re-pattern (Pattern/quote File/separator)))
^java.io.File (apply io/file)
.getCanonicalPath))
(defn unified-diff
([filename original revised]
(unified-diff filename original revised 3))
([filename original revised context]
(unlines (DiffUtils/generateUnifiedDiff
(->> filename to-absolute-path (str "a"))
(->> filename to-absolute-path (str "b"))
(lines original)
(DiffUtils/diff (lines original) (lines revised))
context))))
(def ^:private ansi-colors
{:reset "[0m"
:red "[031m"
:green "[032m"
:cyan "[036m"})
(defn- colorize [s color]
(str \u001b (ansi-colors color) s \u001b (ansi-colors :reset)))
(defn colorize-diff [diff-text]
(-> diff-text
(str/replace #"(?m)^(@@.*@@)$" (colorize "$1" :cyan))
(str/replace #"(?m)^(\+(?!\+\+).*)$" (colorize "$1" :green))
(str/replace #"(?m)^(-(?!--).*)$" (colorize "$1" :red))))
| null | https://raw.githubusercontent.com/weavejester/cljfmt/d419b3809fe21b9c81c61b0440eb137cfeaaedcc/cljfmt/src/cljfmt/diff.clj | clojure | (ns cljfmt.diff
(:import [difflib DiffUtils]
[java.io File]
[java.util.regex Pattern])
(:require [clojure.java.io :as io]
[clojure.string :as str]))
(defn- lines [s]
(str/split s #"\n"))
(defn- unlines [ss]
(str/join "\n" ss))
(defn to-absolute-path [filename]
(->> (str/split filename (re-pattern (Pattern/quote File/separator)))
^java.io.File (apply io/file)
.getCanonicalPath))
(defn unified-diff
([filename original revised]
(unified-diff filename original revised 3))
([filename original revised context]
(unlines (DiffUtils/generateUnifiedDiff
(->> filename to-absolute-path (str "a"))
(->> filename to-absolute-path (str "b"))
(lines original)
(DiffUtils/diff (lines original) (lines revised))
context))))
(def ^:private ansi-colors
{:reset "[0m"
:red "[031m"
:green "[032m"
:cyan "[036m"})
(defn- colorize [s color]
(str \u001b (ansi-colors color) s \u001b (ansi-colors :reset)))
(defn colorize-diff [diff-text]
(-> diff-text
(str/replace #"(?m)^(@@.*@@)$" (colorize "$1" :cyan))
(str/replace #"(?m)^(\+(?!\+\+).*)$" (colorize "$1" :green))
(str/replace #"(?m)^(-(?!--).*)$" (colorize "$1" :red))))
| |
b0415fccb530135f1078cbf9fd68fa7797ecb834c05161f3abdf9e4f79ded9ae | channable/icepeak | stress_test.hs | #!/usr/bin/env stack
-- stack --stack-yaml ../../client-haskell/stack.yaml runghc --package QuickCheck --package quickcheck-text --package icepeak-client
# OPTIONS_GHC -Wall #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
import Prelude hiding (fail)
import Data.Foldable (traverse_)
import Data.Text (Text)
import Data.Text.Arbitrary ()
import Icepeak.Client (Client (..), Config (..), setAtLeaf, doNotRetry)
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Test.QuickCheck.Arbitrary (arbitrary)
import Text.Read (readEither)
import qualified Network.HTTP.Client as HTTP
import qualified Test.QuickCheck.Gen as Gen
main :: IO ()
main = do
args <- getArgs
print args
case args of
[count] -> either fail main' (readEither count)
_ -> fail "usage: stress_test.hs <count>"
where fail msg = do { hPutStrLn stderr msg; exitFailure }
main' :: Int -> IO ()
main' count = do
httpManager <- HTTP.newManager HTTP.defaultManagerSettings
let client = Client httpManager (Config "localhost" 3000 Nothing) doNotRetry
let putRandomPayload i = do
putStr $ "Test #" ++ show i ++ " ... "
path :: [Text] <- Gen.generate arbitrary
leaf :: Text <- Gen.generate arbitrary
status <- setAtLeaf client path leaf
print status
traverse_ putRandomPayload [1..count]
| null | https://raw.githubusercontent.com/channable/icepeak/19674df79c5c2c191367a87dff3a10588515044b/server/integration-tests/stress_test.hs | haskell | stack --stack-yaml ../../client-haskell/stack.yaml runghc --package QuickCheck --package quickcheck-text --package icepeak-client
# LANGUAGE OverloadedStrings # | #!/usr/bin/env stack
# OPTIONS_GHC -Wall #
# LANGUAGE ScopedTypeVariables #
import Prelude hiding (fail)
import Data.Foldable (traverse_)
import Data.Text (Text)
import Data.Text.Arbitrary ()
import Icepeak.Client (Client (..), Config (..), setAtLeaf, doNotRetry)
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (hPutStrLn, stderr)
import Test.QuickCheck.Arbitrary (arbitrary)
import Text.Read (readEither)
import qualified Network.HTTP.Client as HTTP
import qualified Test.QuickCheck.Gen as Gen
main :: IO ()
main = do
args <- getArgs
print args
case args of
[count] -> either fail main' (readEither count)
_ -> fail "usage: stress_test.hs <count>"
where fail msg = do { hPutStrLn stderr msg; exitFailure }
main' :: Int -> IO ()
main' count = do
httpManager <- HTTP.newManager HTTP.defaultManagerSettings
let client = Client httpManager (Config "localhost" 3000 Nothing) doNotRetry
let putRandomPayload i = do
putStr $ "Test #" ++ show i ++ " ... "
path :: [Text] <- Gen.generate arbitrary
leaf :: Text <- Gen.generate arbitrary
status <- setAtLeaf client path leaf
print status
traverse_ putRandomPayload [1..count]
|
4b8fb69a95c65903f64dc83e50d1fea0bf4ed3c2e5972d643d8b0a3c653318cd | input-output-hk/plutus-apps | AlwaysSucceeds.hs | # LANGUAGE DataKinds #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module PlutusExample.PlutusVersion1.AlwaysSucceeds
( alwaysSucceedsScript
, alwaysSucceedsScriptShortBs
) where
import Prelude hiding (($))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import Data.ByteString.Lazy qualified as LBS
import Data.ByteString.Short qualified as SBS
import Plutus.V1.Ledger.Api qualified as Plutus
import PlutusTx qualified
import PlutusTx.Prelude hiding (Semigroup (..), unless, (.))
# INLINABLE mkValidator #
mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator _ _ _ = ()
validator :: Plutus.Validator
validator = Plutus.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||])
script :: Plutus.Script
script = Plutus.unValidatorScript validator
alwaysSucceedsScriptShortBs :: SBS.ShortByteString
alwaysSucceedsScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
alwaysSucceedsScript :: PlutusScript PlutusScriptV1
alwaysSucceedsScript = PlutusScriptSerialised alwaysSucceedsScriptShortBs
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/c1269a7ab8806957cda93448a4637c485352cda5/plutus-example/src/PlutusExample/PlutusVersion1/AlwaysSucceeds.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module PlutusExample.PlutusVersion1.AlwaysSucceeds
( alwaysSucceedsScript
, alwaysSucceedsScriptShortBs
) where
import Prelude hiding (($))
import Cardano.Api.Shelley (PlutusScript (..), PlutusScriptV1)
import Codec.Serialise
import Data.ByteString.Lazy qualified as LBS
import Data.ByteString.Short qualified as SBS
import Plutus.V1.Ledger.Api qualified as Plutus
import PlutusTx qualified
import PlutusTx.Prelude hiding (Semigroup (..), unless, (.))
# INLINABLE mkValidator #
mkValidator :: BuiltinData -> BuiltinData -> BuiltinData -> ()
mkValidator _ _ _ = ()
validator :: Plutus.Validator
validator = Plutus.mkValidatorScript $$(PlutusTx.compile [|| mkValidator ||])
script :: Plutus.Script
script = Plutus.unValidatorScript validator
alwaysSucceedsScriptShortBs :: SBS.ShortByteString
alwaysSucceedsScriptShortBs = SBS.toShort . LBS.toStrict $ serialise script
alwaysSucceedsScript :: PlutusScript PlutusScriptV1
alwaysSucceedsScript = PlutusScriptSerialised alwaysSucceedsScriptShortBs
| |
97e7fce48fecacfaea159ca5ca26f0f1b682fcd5f228502f3e38ac92c59ccd5a | astrada/ocaml-extjs | ext_form_field_Text.ml | class type t =
object('self)
inherit Ext_form_field_Base.t
method afterComponentLayout : Js.number Js.t -> Js.number Js.t -> _ Js.t ->
_ Js.t -> unit Js.meth
method afterRender : unit Js.meth
method applyState : _ Js.t -> unit Js.meth
method autoSize : unit Js.meth
method beforeFocus : Ext_EventObject.t Js.t -> unit Js.meth
method getErrors : _ Js.t -> Js.js_string Js.t Js.js_array Js.t Js.meth
method getRawValue : Js.js_string Js.t Js.meth
method getState : _ Js.t Js.meth
method getSubTplData : _ Js.t Js.meth
method initComponent : unit Js.meth
method initEvents : unit Js.meth
method onDestroy : unit Js.meth
method onDisable : unit Js.meth
method onEnable : unit Js.meth
method postBlur : Ext_EventObject.t Js.t -> unit Js.meth
method processRawValue_str : Js.js_string Js.t -> Js.js_string Js.t Js.meth
method reset : unit Js.meth
method selectText : Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef ->
unit Js.meth
method setValue : _ Js.t -> 'self Js.t Js.meth
end
class type configs =
object('self)
inherit Ext_form_field_Base.configs
method allowBlank : bool Js.t Js.prop
method allowOnlyWhitespace : bool Js.t Js.prop
method blankText : Js.js_string Js.t Js.prop
method disableKeyFilter : bool Js.t Js.prop
method emptyCls : Js.js_string Js.t Js.prop
method emptyText : Js.js_string Js.t Js.prop
method enableKeyEvents : bool Js.t Js.prop
method enforceMaxLength : bool Js.t Js.prop
method grow : bool Js.t Js.prop
method growAppend : Js.js_string Js.t Js.prop
method growMax : Js.number Js.t Js.prop
method growMin : Js.number Js.t Js.prop
method maskRe : Regexp.regexp Js.t Js.prop
method maxLength : Js.number Js.t Js.prop
method maxLengthText : Js.js_string Js.t Js.prop
method minLength : Js.number Js.t Js.prop
method minLengthText : Js.js_string Js.t Js.prop
method regex : Regexp.regexp Js.t Js.prop
method regexText : Js.js_string Js.t Js.prop
method requiredCls : Js.js_string Js.t Js.prop
method selectOnFocus : bool Js.t Js.prop
method size : Js.number Js.t Js.prop
method stripCharsRe : Regexp.regexp Js.t Js.prop
method validateBlank : bool Js.t Js.prop
method validator : _ Js.callback Js.prop
method vtype : Js.js_string Js.t Js.prop
method vtypeText : Js.js_string Js.t Js.prop
method afterComponentLayout : ('self Js.t, Js.number Js.t -> Js.number Js.t
-> _ Js.t -> _ Js.t -> unit) Js.meth_callback Js.writeonly_prop
method afterRender : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method getSubTplData : ('self Js.t, unit -> _ Js.t) Js.meth_callback
Js.writeonly_prop
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onDisable : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onEnable : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
end
class type events =
object
inherit Ext_form_field_Base.events
method autosize : (t Js.t -> Js.number Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
method keydown : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
method keypress : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
method keyup : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
end
class type statics =
object
inherit Ext_form_field_Base.statics
end
let get_static () = Js.Unsafe.variable "Ext.form.field.Text"
let static = get_static ()
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_form_field_Text.ml | ocaml | class type t =
object('self)
inherit Ext_form_field_Base.t
method afterComponentLayout : Js.number Js.t -> Js.number Js.t -> _ Js.t ->
_ Js.t -> unit Js.meth
method afterRender : unit Js.meth
method applyState : _ Js.t -> unit Js.meth
method autoSize : unit Js.meth
method beforeFocus : Ext_EventObject.t Js.t -> unit Js.meth
method getErrors : _ Js.t -> Js.js_string Js.t Js.js_array Js.t Js.meth
method getRawValue : Js.js_string Js.t Js.meth
method getState : _ Js.t Js.meth
method getSubTplData : _ Js.t Js.meth
method initComponent : unit Js.meth
method initEvents : unit Js.meth
method onDestroy : unit Js.meth
method onDisable : unit Js.meth
method onEnable : unit Js.meth
method postBlur : Ext_EventObject.t Js.t -> unit Js.meth
method processRawValue_str : Js.js_string Js.t -> Js.js_string Js.t Js.meth
method reset : unit Js.meth
method selectText : Js.number Js.t Js.optdef -> Js.number Js.t Js.optdef ->
unit Js.meth
method setValue : _ Js.t -> 'self Js.t Js.meth
end
class type configs =
object('self)
inherit Ext_form_field_Base.configs
method allowBlank : bool Js.t Js.prop
method allowOnlyWhitespace : bool Js.t Js.prop
method blankText : Js.js_string Js.t Js.prop
method disableKeyFilter : bool Js.t Js.prop
method emptyCls : Js.js_string Js.t Js.prop
method emptyText : Js.js_string Js.t Js.prop
method enableKeyEvents : bool Js.t Js.prop
method enforceMaxLength : bool Js.t Js.prop
method grow : bool Js.t Js.prop
method growAppend : Js.js_string Js.t Js.prop
method growMax : Js.number Js.t Js.prop
method growMin : Js.number Js.t Js.prop
method maskRe : Regexp.regexp Js.t Js.prop
method maxLength : Js.number Js.t Js.prop
method maxLengthText : Js.js_string Js.t Js.prop
method minLength : Js.number Js.t Js.prop
method minLengthText : Js.js_string Js.t Js.prop
method regex : Regexp.regexp Js.t Js.prop
method regexText : Js.js_string Js.t Js.prop
method requiredCls : Js.js_string Js.t Js.prop
method selectOnFocus : bool Js.t Js.prop
method size : Js.number Js.t Js.prop
method stripCharsRe : Regexp.regexp Js.t Js.prop
method validateBlank : bool Js.t Js.prop
method validator : _ Js.callback Js.prop
method vtype : Js.js_string Js.t Js.prop
method vtypeText : Js.js_string Js.t Js.prop
method afterComponentLayout : ('self Js.t, Js.number Js.t -> Js.number Js.t
-> _ Js.t -> _ Js.t -> unit) Js.meth_callback Js.writeonly_prop
method afterRender : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method getSubTplData : ('self Js.t, unit -> _ Js.t) Js.meth_callback
Js.writeonly_prop
method initComponent : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onDestroy : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onDisable : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
method onEnable : ('self Js.t, unit -> unit) Js.meth_callback
Js.writeonly_prop
end
class type events =
object
inherit Ext_form_field_Base.events
method autosize : (t Js.t -> Js.number Js.t -> _ Js.t -> unit) Js.callback
Js.writeonly_prop
method keydown : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
method keypress : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
method keyup : (t Js.t -> Ext_EventObject.t Js.t -> _ Js.t -> unit)
Js.callback Js.writeonly_prop
end
class type statics =
object
inherit Ext_form_field_Base.statics
end
let get_static () = Js.Unsafe.variable "Ext.form.field.Text"
let static = get_static ()
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| |
6ca60fc088c54b0f5a2c689c99536d6acafc4d786b5f7d57ff151bd5409ac00a | bor0/soko-scheme | game.rkt | #lang racket
(define-struct posn (x y))
; Bounds checker
(define (bad-bounds? soko-map pos) (or (>= (posn-x pos) (length (car soko-map)))
(>= (posn-y pos) (length soko-map))
(< (posn-x pos) 0)
(< (posn-y pos) 0)))
; Get a value from the map given position
(define (get-soko-map-value soko-map pos)
(if (bad-bounds? soko-map pos)
#f
(list-ref (list-ref soko-map (posn-y pos)) (posn-x pos))))
(define (set-matrix xss i j x)
(cond
[(empty? xss) '()]
[(= j 0) (cons (list-set (car xss) i x)
(cdr xss))]
[else (cons (car xss)
(set-matrix (cdr xss) i (- j 1) x))]))
; Return a new updated map with new value at position
(define (set-soko-map-value soko-map pos val)
(if (bad-bounds? soko-map pos)
soko-map
(set-matrix soko-map (posn-x pos) (posn-y pos) val)))
Find the position of or LEVEL_SOKOBAN_BEACON
(define (get-soko-position soko-map)
(car (for*/list ([i (length (car soko-map))]
[j (length soko-map)]
#:when (member (get-soko-map-value soko-map (make-posn i j)) '(LEVEL_SOKOBAN LEVEL_SOKOBAN_BEACON)))
(make-posn i j))))
; Calculate new position given a position and direction
(define (get-new-position soko-map soko-position direction)
(cond ((eq? direction 'UP) (make-posn (posn-x soko-position)
(- (posn-y soko-position) 1)))
((eq? direction 'DOWN) (make-posn (posn-x soko-position)
(+ 1 (posn-y soko-position))))
((eq? direction 'LEFT) (make-posn (- (posn-x soko-position) 1)
(posn-y soko-position)))
((eq? direction 'RIGHT) (make-posn (+ 1 (posn-x soko-position))
(posn-y soko-position)))))
; Move box from a position to a new direction, maintaining beacon state
(define (update-box soko-map box-pos direction)
(letrec ([box-type (get-soko-map-value soko-map box-pos)]
[new-box-pos (get-new-position soko-map box-pos direction)]
[new-box-type (get-soko-map-value soko-map new-box-pos)])
(cond ((eq? new-box-type 'LEVEL_BEACON)
(set-soko-map-value (set-soko-map-value soko-map new-box-pos 'LEVEL_BOX_BEACON)
box-pos
(if (eq? box-type 'LEVEL_BOX_BEACON)
'LEVEL_BEACON
'LEVEL_TERRAIN)))
((eq? new-box-type 'LEVEL_TERRAIN)
(set-soko-map-value (set-soko-map-value soko-map new-box-pos 'LEVEL_BOX)
box-pos
(if (eq? box-type 'LEVEL_BOX_BEACON)
'LEVEL_BEACON
'LEVEL_TERRAIN)))
(else #f))))
; Move soko from a position to a new direction, maintaining beacon state
(define (update-soko soko-map soko-pos direction)
(letrec ([soko-type (get-soko-map-value soko-map soko-pos)]
[new-soko-pos (get-new-position soko-map soko-pos direction)]
[new-soko-type (get-soko-map-value soko-map new-soko-pos)]
[removed-soko-map (set-soko-map-value soko-map soko-pos (if (eq? soko-type 'LEVEL_SOKOBAN_BEACON) 'LEVEL_BEACON 'LEVEL_TERRAIN))])
(cond ((bad-bounds? soko-map new-soko-pos) soko-map)
((eq? new-soko-type 'LEVEL_BEACON)
(set-soko-map-value removed-soko-map new-soko-pos 'LEVEL_SOKOBAN_BEACON))
((eq? new-soko-type 'LEVEL_TERRAIN)
(set-soko-map-value removed-soko-map new-soko-pos 'LEVEL_SOKOBAN))
((eq? new-soko-type 'LEVEL_BOX)
(let ([new-box-map (update-box removed-soko-map new-soko-pos direction)])
(if new-box-map (set-soko-map-value new-box-map new-soko-pos 'LEVEL_SOKOBAN)
soko-map)))
((eq? new-soko-type 'LEVEL_BOX_BEACON)
(let ([new-box-map (update-box removed-soko-map new-soko-pos direction)])
(if new-box-map (set-soko-map-value new-box-map new-soko-pos 'LEVEL_SOKOBAN_BEACON)
soko-map)))
(else soko-map))))
(define (play soko-map direction)
(update-soko soko-map (get-soko-position soko-map) direction))
; It's a win only if there are no beacons
(define (check-win? soko-map)
(and
(not (member 'LEVEL_BEACON (flatten soko-map)))
(not (member 'LEVEL_SOKOBAN_BEACON (flatten soko-map)))))
(provide play posn posn-x posn-y set-soko-map-value get-soko-position get-soko-map-value check-win?)
| null | https://raw.githubusercontent.com/bor0/soko-scheme/2813fc1799be16e8f17ec9591cbd3aeb2ec2f3d2/src/game.rkt | racket | Bounds checker
Get a value from the map given position
Return a new updated map with new value at position
Calculate new position given a position and direction
Move box from a position to a new direction, maintaining beacon state
Move soko from a position to a new direction, maintaining beacon state
It's a win only if there are no beacons | #lang racket
(define-struct posn (x y))
(define (bad-bounds? soko-map pos) (or (>= (posn-x pos) (length (car soko-map)))
(>= (posn-y pos) (length soko-map))
(< (posn-x pos) 0)
(< (posn-y pos) 0)))
(define (get-soko-map-value soko-map pos)
(if (bad-bounds? soko-map pos)
#f
(list-ref (list-ref soko-map (posn-y pos)) (posn-x pos))))
(define (set-matrix xss i j x)
(cond
[(empty? xss) '()]
[(= j 0) (cons (list-set (car xss) i x)
(cdr xss))]
[else (cons (car xss)
(set-matrix (cdr xss) i (- j 1) x))]))
(define (set-soko-map-value soko-map pos val)
(if (bad-bounds? soko-map pos)
soko-map
(set-matrix soko-map (posn-x pos) (posn-y pos) val)))
Find the position of or LEVEL_SOKOBAN_BEACON
(define (get-soko-position soko-map)
(car (for*/list ([i (length (car soko-map))]
[j (length soko-map)]
#:when (member (get-soko-map-value soko-map (make-posn i j)) '(LEVEL_SOKOBAN LEVEL_SOKOBAN_BEACON)))
(make-posn i j))))
(define (get-new-position soko-map soko-position direction)
(cond ((eq? direction 'UP) (make-posn (posn-x soko-position)
(- (posn-y soko-position) 1)))
((eq? direction 'DOWN) (make-posn (posn-x soko-position)
(+ 1 (posn-y soko-position))))
((eq? direction 'LEFT) (make-posn (- (posn-x soko-position) 1)
(posn-y soko-position)))
((eq? direction 'RIGHT) (make-posn (+ 1 (posn-x soko-position))
(posn-y soko-position)))))
(define (update-box soko-map box-pos direction)
(letrec ([box-type (get-soko-map-value soko-map box-pos)]
[new-box-pos (get-new-position soko-map box-pos direction)]
[new-box-type (get-soko-map-value soko-map new-box-pos)])
(cond ((eq? new-box-type 'LEVEL_BEACON)
(set-soko-map-value (set-soko-map-value soko-map new-box-pos 'LEVEL_BOX_BEACON)
box-pos
(if (eq? box-type 'LEVEL_BOX_BEACON)
'LEVEL_BEACON
'LEVEL_TERRAIN)))
((eq? new-box-type 'LEVEL_TERRAIN)
(set-soko-map-value (set-soko-map-value soko-map new-box-pos 'LEVEL_BOX)
box-pos
(if (eq? box-type 'LEVEL_BOX_BEACON)
'LEVEL_BEACON
'LEVEL_TERRAIN)))
(else #f))))
(define (update-soko soko-map soko-pos direction)
(letrec ([soko-type (get-soko-map-value soko-map soko-pos)]
[new-soko-pos (get-new-position soko-map soko-pos direction)]
[new-soko-type (get-soko-map-value soko-map new-soko-pos)]
[removed-soko-map (set-soko-map-value soko-map soko-pos (if (eq? soko-type 'LEVEL_SOKOBAN_BEACON) 'LEVEL_BEACON 'LEVEL_TERRAIN))])
(cond ((bad-bounds? soko-map new-soko-pos) soko-map)
((eq? new-soko-type 'LEVEL_BEACON)
(set-soko-map-value removed-soko-map new-soko-pos 'LEVEL_SOKOBAN_BEACON))
((eq? new-soko-type 'LEVEL_TERRAIN)
(set-soko-map-value removed-soko-map new-soko-pos 'LEVEL_SOKOBAN))
((eq? new-soko-type 'LEVEL_BOX)
(let ([new-box-map (update-box removed-soko-map new-soko-pos direction)])
(if new-box-map (set-soko-map-value new-box-map new-soko-pos 'LEVEL_SOKOBAN)
soko-map)))
((eq? new-soko-type 'LEVEL_BOX_BEACON)
(let ([new-box-map (update-box removed-soko-map new-soko-pos direction)])
(if new-box-map (set-soko-map-value new-box-map new-soko-pos 'LEVEL_SOKOBAN_BEACON)
soko-map)))
(else soko-map))))
(define (play soko-map direction)
(update-soko soko-map (get-soko-position soko-map) direction))
(define (check-win? soko-map)
(and
(not (member 'LEVEL_BEACON (flatten soko-map)))
(not (member 'LEVEL_SOKOBAN_BEACON (flatten soko-map)))))
(provide play posn posn-x posn-y set-soko-map-value get-soko-position get-soko-map-value check-win?)
|
6b408e192668825dcb873549fa29b673e1f59e2f98ed61f94e5c0f9f657b1b3b | kowainik/treap | Update.hs | module Test.Rand.Update
( updateSpec
) where
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Common (describedAs, with, smallTreap)
import qualified Treap
updateSpec :: Spec
updateSpec = describe "Modification operations tests" $ do
insertSpec
deleteSpec
insertSpec :: Spec
insertSpec = describe "insert" $ do
it "insert negative inserts at the beginning" $
Treap.insert (-1) 42 smallTreap `describedAs` (42 : [1..5]) `with` 57
it "insert 0 inserts at the beginning" $
Treap.insert 0 42 smallTreap `describedAs` (42 : [1..5]) `with` 57
it "insert size inserts at the end" $
Treap.insert 5 42 smallTreap `describedAs` [1, 2, 3, 4, 5, 42] `with` 57
it "insert in the middle works" $
Treap.insert 2 42 smallTreap `describedAs` [1, 2, 42, 3, 4, 5] `with` 57
deleteSpec :: Spec
deleteSpec = describe "delete" $ do
it "delete negative does nothing" $
Treap.delete (-1) smallTreap `shouldBe` smallTreap
it "delete size does nothing" $
Treap.delete 5 smallTreap `shouldBe` smallTreap
it "delete 0 removes first element" $
Treap.delete 0 smallTreap `describedAs` [2..5] `with` 14
it "deletes from the middle works" $
Treap.delete 2 smallTreap `describedAs` [1, 2, 4, 5] `with` 12
| null | https://raw.githubusercontent.com/kowainik/treap/bd59f0ff0a938d7b67ebf5266427e100fce8e487/test/Test/Rand/Update.hs | haskell | module Test.Rand.Update
( updateSpec
) where
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Common (describedAs, with, smallTreap)
import qualified Treap
updateSpec :: Spec
updateSpec = describe "Modification operations tests" $ do
insertSpec
deleteSpec
insertSpec :: Spec
insertSpec = describe "insert" $ do
it "insert negative inserts at the beginning" $
Treap.insert (-1) 42 smallTreap `describedAs` (42 : [1..5]) `with` 57
it "insert 0 inserts at the beginning" $
Treap.insert 0 42 smallTreap `describedAs` (42 : [1..5]) `with` 57
it "insert size inserts at the end" $
Treap.insert 5 42 smallTreap `describedAs` [1, 2, 3, 4, 5, 42] `with` 57
it "insert in the middle works" $
Treap.insert 2 42 smallTreap `describedAs` [1, 2, 42, 3, 4, 5] `with` 57
deleteSpec :: Spec
deleteSpec = describe "delete" $ do
it "delete negative does nothing" $
Treap.delete (-1) smallTreap `shouldBe` smallTreap
it "delete size does nothing" $
Treap.delete 5 smallTreap `shouldBe` smallTreap
it "delete 0 removes first element" $
Treap.delete 0 smallTreap `describedAs` [2..5] `with` 14
it "deletes from the middle works" $
Treap.delete 2 smallTreap `describedAs` [1, 2, 4, 5] `with` 12
| |
01d9af3e0f24831c40f30786e3164d45533af7823471f5c47ad513dab2f25f04 | agentultra/rosby | Response.hs | module Rosby.Protocol.Response where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Rosby.Protocol.Serial
data Result
= Ok
| Fail ByteString
deriving (Eq, Show)
data Response
= Response
{ result :: Result
}
deriving (Eq, Show)
toPrim :: Response -> Primitive
toPrim (Response result) =
case result of
Ok -> Str 2 "Ok"
Fail msg ->
Array 2
[ Str 4 "Fail"
, Str (B.length msg) msg]
serializeResponse :: Response -> ByteString
serializeResponse = serialize . toPrim
| null | https://raw.githubusercontent.com/agentultra/rosby/8e81794e44f38d6e8676ef022c6ec15611571fd7/rosby-core/src/Rosby/Protocol/Response.hs | haskell | module Rosby.Protocol.Response where
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Rosby.Protocol.Serial
data Result
= Ok
| Fail ByteString
deriving (Eq, Show)
data Response
= Response
{ result :: Result
}
deriving (Eq, Show)
toPrim :: Response -> Primitive
toPrim (Response result) =
case result of
Ok -> Str 2 "Ok"
Fail msg ->
Array 2
[ Str 4 "Fail"
, Str (B.length msg) msg]
serializeResponse :: Response -> ByteString
serializeResponse = serialize . toPrim
| |
98451467f14e6d5239d1bf007ccf4b61b19e7535f67967aa30524d8b41c77d2a | ogri-la/strongbox | release_json_test.clj | (ns strongbox.release-json-test
(:require
[clojure.test :refer [deftest testing is use-fixtures]]
;;[taoensso.timbre :as log :refer [debug info warn error spy]]
[strongbox
[release-json :as release-json]
;;[test-helper :refer [fixture-path slurp-fixture]]
]
;;[clj-http.fake :refer [with-fake-routes-in-isolation]]
))
(deftest release-json-game-tracks
(let [cases [[[{:filename "Foo.zip" :metadata [{:flavor "bcc"}]}]
{"Foo.zip" [:classic-tbc]}]
[[{:filename "Foo.zip" :metadata [{:flavor "bcc"}
{:flavor "mainline"}
{:flavor "vanilla"}]}]
{"Foo.zip" [:classic :classic-tbc :retail]}]]]
(doseq [[given expected] cases]
(is (= expected (release-json/release-json-game-tracks given))))))
| null | https://raw.githubusercontent.com/ogri-la/strongbox/6edf6d2501c059d66e63da3c9d4d0997027a7b11/test/strongbox/release_json_test.clj | clojure | [taoensso.timbre :as log :refer [debug info warn error spy]]
[test-helper :refer [fixture-path slurp-fixture]]
[clj-http.fake :refer [with-fake-routes-in-isolation]] | (ns strongbox.release-json-test
(:require
[clojure.test :refer [deftest testing is use-fixtures]]
[strongbox
[release-json :as release-json]
]
))
(deftest release-json-game-tracks
(let [cases [[[{:filename "Foo.zip" :metadata [{:flavor "bcc"}]}]
{"Foo.zip" [:classic-tbc]}]
[[{:filename "Foo.zip" :metadata [{:flavor "bcc"}
{:flavor "mainline"}
{:flavor "vanilla"}]}]
{"Foo.zip" [:classic :classic-tbc :retail]}]]]
(doseq [[given expected] cases]
(is (= expected (release-json/release-json-game-tracks given))))))
|
53b5125d5a7afb767d80b9ddc5010b54a845d07e9c68893e566b633a2a2a973a | jberryman/unagi-chan | Deadlocks.hs | module Deadlocks (deadlocksMain) where
import Control.Concurrent.MVar
import Control.Concurrent(getNumCapabilities,threadDelay,forkIO)
import Control.Exception
import Control.Monad
import Implementations
import qualified Control.Concurrent.Chan.Unagi.Bounded as UB
deadlocksMain :: IO ()
deadlocksMain = do
let tries = 10000
putStrLn "==================="
putStrLn "Testing Unagi:"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi (with tryReadChan):"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiTryReadImpl tries
putStrLn "OK"
-- No real need to checkDeadlocksWriter for tryReadChan.
putStrLn "==================="
putStrLn "Testing Unagi (with tryReadChan, blocking):"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiTryReadBlockingImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiTryReadBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking:"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiNoBlockingImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiNoBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking.Unboxed:"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiNoBlockingUnboxedImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiNoBlockingUnboxedImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed (with tryReadChan):"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiTryReadImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking.Unboxed (with tryReadChan, blocking):"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiTryReadBlockingImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unboxedUnagiTryReadBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed:"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiImpl tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unboxedUnagiImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Bounded:"
-- ------
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedImpl 50000) tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed reader (tryReadChan), x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedTryReadImpl 50000) tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed reader (tryReadChan, blocking), x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedTryReadBlockingImpl 50000) tries
putStrLn "OK"
-- ------
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
-- fragile bounds must be large enought to never be reached here:
checkDeadlocksWriterBounded tries
putStrLn "OK"
TODO same test for unagiBoundedTryReadBlockingImpl
-- -- Chan002.hs -- --
-- test for deadlocks caused by async exceptions in reader.
checkDeadlocksReader :: Implementation inc outc Int -> Int -> IO ()
checkDeadlocksReader (newChan,writeChan,readChan,_) times = do
-- this might become an argument, indicating whether a killed reader might
result in one missing element ( currently all do )
let mightDropOne = True
procs <- getNumCapabilities
let run _ 0 = putStrLn ""
run retries n = do
when (retries > (times `div` 3)) $
error "This test is taking too long. Please retry, and if still failing send the log to me"
(i,o) <- newChan
if we do n't have at least three cores , then we need to write enough messages in first , before killing reader .
NOTE 4 might mean only two real cores , so be conservative here .
then do wStart <- newEmptyMVar
wid <- forkIO $ (putMVar wStart () >> (forever $ writeChan i (0::Int)))
takeMVar wStart >> threadDelay 1 -- wait until we're writing
return $ Just wid
else do replicateM_ 15000 $ writeChan i (0::Int)
return Nothing
rStart <- newEmptyMVar
rid <- forkIO $ (putMVar rStart () >> (forever $ void $ readChan o))
takeMVar rStart >> threadDelay 1
throwTo rid ThreadKilled
-- did killing reader damage queue for reads or writes?
writeChan i 1 `onException` ( putStrLn "Exception from writeChan 1")
when mightDropOne $
writeChan i 2 `onException` ( putStrLn "Exception from last writeChan 2")
z <- readChan o `onException` ( putStrLn "Exception from last readChan")
-- clean up:
case maybeWid of
Just wid -> throwTo wid ThreadKilled ; _ -> return ()
case z of
0 -> putStr "." >> run retries (n-1)
-- reader probably killed while blocked or before writer even wrote anything
1 -> putStr "+" >> run (retries+1) n
2 | not mightDropOne -> error "Fix tests; 2 when not mightDropOne"
| otherwise -> putStr "*" >> run (retries+1) n
_ -> error "Fix checkDeadlocksReader test; not 0, 1, or 2"
run 0 times
-- -- Chan003.hs -- --
-- test for deadlocks from async exceptions raised in writer
checkDeadlocksWriter :: Implementation inc outc Int -> Int -> IO ()
checkDeadlocksWriter (newChan,writeChan,readChan,_) n = void $
replicateM_ n $ do
(i,o) <- newChan
wStart <- newEmptyMVar
wid <- forkIO (putMVar wStart () >> ( forever $ writeChan i (0::Int)) )
-- wait for writer to start
takeMVar wStart >> threadDelay 1
throwTo wid ThreadKilled
-- did killing the writer damage queue for writes or reads?
writeChan i (1::Int)
z <- readChan o
unless (z == 0) $
error "Writer never got a chance to write!"
-- A bit ugly, but we need this slight variant for Bounded variant:
checkDeadlocksWriterBounded :: Int -> IO ()
checkDeadlocksWriterBounded cnt = go 0 cnt where
go lates n
| lates > (cnt `div` 4) = error "This is taking too long; we probably need a bigger bounds, sorry."
| otherwise =
when (n > 0) $ do
(i,o) <- UB.newChan (2^(14::Int))
wStart <- newEmptyMVar
wid <- forkIO (putMVar wStart () >> ( forever $ UB.writeChan i (0::Int)) )
-- wait for writer to start
takeMVar wStart >> threadDelay 1
throwTo wid ThreadKilled
-- did killing the writer damage queue for writes or reads?
success <- UB.tryWriteChan i (1::Int)
if success
then do
z <- UB.readChan o
if (z /= 0)
-- Writer never got a chance to write, retry:
then go (lates+1) n
-- OK:
else go lates (n-1)
-- throwTo probably didn't catch writeChan while running, retry:
else go (lates+1) n
| null | https://raw.githubusercontent.com/jberryman/unagi-chan/03f62bb6989fcfa3372a93925b7bc0294b51a65d/tests/Deadlocks.hs | haskell | ------
------
------
No real need to checkDeadlocksWriter for tryReadChan.
------
------
------
------
------
------
------
------
------
------
------
------
------
------
------
fragile bounds must be large enought to never be reached here:
-- Chan002.hs -- --
test for deadlocks caused by async exceptions in reader.
this might become an argument, indicating whether a killed reader might
wait until we're writing
did killing reader damage queue for reads or writes?
clean up:
reader probably killed while blocked or before writer even wrote anything
-- Chan003.hs -- --
test for deadlocks from async exceptions raised in writer
wait for writer to start
did killing the writer damage queue for writes or reads?
A bit ugly, but we need this slight variant for Bounded variant:
wait for writer to start
did killing the writer damage queue for writes or reads?
Writer never got a chance to write, retry:
OK:
throwTo probably didn't catch writeChan while running, retry: | module Deadlocks (deadlocksMain) where
import Control.Concurrent.MVar
import Control.Concurrent(getNumCapabilities,threadDelay,forkIO)
import Control.Exception
import Control.Monad
import Implementations
import qualified Control.Concurrent.Chan.Unagi.Bounded as UB
deadlocksMain :: IO ()
deadlocksMain = do
let tries = 10000
putStrLn "==================="
putStrLn "Testing Unagi:"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi (with tryReadChan):"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiTryReadImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi (with tryReadChan, blocking):"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiTryReadBlockingImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiTryReadBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking:"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiNoBlockingImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiNoBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking.Unboxed:"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unagiNoBlockingUnboxedImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unagiNoBlockingUnboxedImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed (with tryReadChan):"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiTryReadImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.NoBlocking.Unboxed (with tryReadChan, blocking):"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiTryReadBlockingImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unboxedUnagiTryReadBlockingImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed:"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
checkDeadlocksReader unboxedUnagiImpl tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriter unboxedUnagiImpl tries
putStrLn "OK"
putStrLn "==================="
putStrLn "Testing Unagi.Bounded:"
putStr $ " Checking for deadlocks from killed reader, x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedImpl 50000) tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed reader (tryReadChan), x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedTryReadImpl 50000) tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed reader (tryReadChan, blocking), x"++show tries++"... "
bounds must be > 10000 here ( note actual bounds rounded up to power of 2 ):
checkDeadlocksReader (unagiBoundedTryReadBlockingImpl 50000) tries
putStrLn "OK"
putStr $ " Checking for deadlocks from killed writer, x"++show tries++"... "
checkDeadlocksWriterBounded tries
putStrLn "OK"
TODO same test for unagiBoundedTryReadBlockingImpl
checkDeadlocksReader :: Implementation inc outc Int -> Int -> IO ()
checkDeadlocksReader (newChan,writeChan,readChan,_) times = do
result in one missing element ( currently all do )
let mightDropOne = True
procs <- getNumCapabilities
let run _ 0 = putStrLn ""
run retries n = do
when (retries > (times `div` 3)) $
error "This test is taking too long. Please retry, and if still failing send the log to me"
(i,o) <- newChan
if we do n't have at least three cores , then we need to write enough messages in first , before killing reader .
NOTE 4 might mean only two real cores , so be conservative here .
then do wStart <- newEmptyMVar
wid <- forkIO $ (putMVar wStart () >> (forever $ writeChan i (0::Int)))
return $ Just wid
else do replicateM_ 15000 $ writeChan i (0::Int)
return Nothing
rStart <- newEmptyMVar
rid <- forkIO $ (putMVar rStart () >> (forever $ void $ readChan o))
takeMVar rStart >> threadDelay 1
throwTo rid ThreadKilled
writeChan i 1 `onException` ( putStrLn "Exception from writeChan 1")
when mightDropOne $
writeChan i 2 `onException` ( putStrLn "Exception from last writeChan 2")
z <- readChan o `onException` ( putStrLn "Exception from last readChan")
case maybeWid of
Just wid -> throwTo wid ThreadKilled ; _ -> return ()
case z of
0 -> putStr "." >> run retries (n-1)
1 -> putStr "+" >> run (retries+1) n
2 | not mightDropOne -> error "Fix tests; 2 when not mightDropOne"
| otherwise -> putStr "*" >> run (retries+1) n
_ -> error "Fix checkDeadlocksReader test; not 0, 1, or 2"
run 0 times
checkDeadlocksWriter :: Implementation inc outc Int -> Int -> IO ()
checkDeadlocksWriter (newChan,writeChan,readChan,_) n = void $
replicateM_ n $ do
(i,o) <- newChan
wStart <- newEmptyMVar
wid <- forkIO (putMVar wStart () >> ( forever $ writeChan i (0::Int)) )
takeMVar wStart >> threadDelay 1
throwTo wid ThreadKilled
writeChan i (1::Int)
z <- readChan o
unless (z == 0) $
error "Writer never got a chance to write!"
checkDeadlocksWriterBounded :: Int -> IO ()
checkDeadlocksWriterBounded cnt = go 0 cnt where
go lates n
| lates > (cnt `div` 4) = error "This is taking too long; we probably need a bigger bounds, sorry."
| otherwise =
when (n > 0) $ do
(i,o) <- UB.newChan (2^(14::Int))
wStart <- newEmptyMVar
wid <- forkIO (putMVar wStart () >> ( forever $ UB.writeChan i (0::Int)) )
takeMVar wStart >> threadDelay 1
throwTo wid ThreadKilled
success <- UB.tryWriteChan i (1::Int)
if success
then do
z <- UB.readChan o
if (z /= 0)
then go (lates+1) n
else go lates (n-1)
else go (lates+1) n
|
28d922942975ffa90cd015514e7ec569546f5ddd309a3c6c22d24b595b6a57e9 | hercules-ci/hercules-ci-agent | Pushed.hs | {-# LANGUAGE DeriveAnyClass #-}
module Hercules.API.Agent.Build.BuildEvent.Pushed where
import Hercules.API.Prelude
data Pushed = Pushed
{ cache :: Text
}
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON)
| null | https://raw.githubusercontent.com/hercules-ci/hercules-ci-agent/216a1d178d57471b05f60bf3e21ce46d3fdc5f94/hercules-ci-api-agent/src/Hercules/API/Agent/Build/BuildEvent/Pushed.hs | haskell | # LANGUAGE DeriveAnyClass # |
module Hercules.API.Agent.Build.BuildEvent.Pushed where
import Hercules.API.Prelude
data Pushed = Pushed
{ cache :: Text
}
deriving (Generic, Show, Eq, NFData, ToJSON, FromJSON)
|
5cbd280073d4cbd974e65ed487f423156da6c8ecd9d93af81ed18f4f5d2183a5 | avik-das/garlic | apply.scm | (display (apply + '(1 2 3))) (apply newline '())
(apply display '(1 " " 2 " " 3)) (apply newline '())
| null | https://raw.githubusercontent.com/avik-das/garlic/5545f5a70f33c2ff9ec449ef66e6acc7881419dc/test/success/apply.scm | scheme | (display (apply + '(1 2 3))) (apply newline '())
(apply display '(1 " " 2 " " 3)) (apply newline '())
| |
f95b243276cd35ee20bd80eced9dc5aabce4795ec3bafc2cdcc87de36a11240a | semaj/mini-tcp-haskell | 3700recv.hs | module Main where
import TCP
import Control.Monad (unless, when, forever, void, replicateM_)
import System.Exit
import System.IO
import Network.Socket
import Control.Exception
import System.Random
import Data.Time.Clock
import Data.List
import Control.Concurrent
import Data.Maybe
import System.Exit
import Data.List.Split
data SState = SEstablished | SClose deriving (Eq)
data Server = Server {
sstate :: SState, -- server state
toPrint :: [Seg], -- what to print on next IO cycle
buffer :: [Seg], -- stored segments (can't print because they're out of order)
lastSeqPrinted :: Int, -- last sequence number printed
sockaddr :: SockAddr
}
-- it's a duplicate if it's smaller than the last thing we printed (already printed)
-- or if we have it in the buffer
isDup :: Server -> Seg -> Bool
isDup server seg = (seqNum seg) < (lastSeqPrinted server) || any ((== (seqNum seg)) . seqNum) (buffer server)
-- used for debug printing.
-- the lastSeq num is either the last received, last to print, or last printed
lastSeqNum :: Server -> Int
lastSeqNum (Server _ [] [] i _) = i
lastSeqNum (Server _ toP [] _ _) = last $ sort $ map seqNum toP
lastSeqNum (Server _ _ buff _ _) = last $ sort $ map seqNum buff
outOfOrder :: Server -> Seg -> String
outOfOrder server seg = if ((seqNum seg) - 1) == lsn then "(in-order)" else "(out-of-order)"
where lsn = lastSeqNum server
pull consective ( by seq num ) out of buffer , into toPrint
whatToPrint :: Server -> Server
whatToPrint s@(Server ss toprint buff lastseq sa) = newS printMe
where printMe = find ((== (lastseq + 1)) . seqNum) buff
newS Nothing = s
-- this is pretty gross, there's a fold here somewhere
newS (Just a) = whatToPrint $ Server ss (toprint ++ [a]) (delete a buff) (lastseq + 1) sa
-- if it's a dup, don't add it
addToBuffer :: Server -> Maybe Seg -> Server
addToBuffer s Nothing = s
addToBuffer s (Just seg) = if isDup s seg
then s
else s { buffer = ((buffer s) ++ [seg]) }
stepServer :: Server -> Maybe Seg -> Server
-- if we receive a fin, let's finish up
stepServer s (Just (Seg Fin _ _ _)) = s { sstate = SClose }
-- else let's add to the buffer and add things to be printed
stepServer s mseg = whatToPrint $ addToBuffer s mseg
add our nacks to the data
getAck :: Seg -> [String] -> String
getAck (Seg _ num _ _) nacks = show $ hashSeg $ Seg Ack num (intercalate nackSplitter nacks) ""
receiveFromClient :: Socket -> Chan (String, SockAddr) -> IO ()
receiveFromClient s segs = do
forever $ do
(msg,_,d) <- recvFrom s 32768
writeChan segs (msg, d)
sendAck :: Socket -> SockAddr -> Maybe Seg -> [String] -> IO ()
sendAck _ _ Nothing _ = return ()
sendAck conn sa (Just seg) nacks = void $ sendTo conn (getAck seg nacks) sa
printRecv :: Maybe Seg -> Server -> IO ()
printRecv Nothing _ = timestamp "[recv corrupt packet]"
printRecv (Just seg@(Seg Data num dat _)) server =
do
let (off,len) = offsetLengthSeg seg
pref = "[recv data] " ++ off ++ " (" ++ len ++ ") " ++ (show num)
if (isDup server seg)
then timestamp $ pref ++ "IGNORED"
else timestamp $ pref ++ "ACCEPTED " ++ (outOfOrder server seg)
do n't print
diff :: Server -> Maybe Seg -> [String]
diff _ Nothing = []
-- in the range from what we've printed to what we've received, what are we missing?
-- (what should we nack?)
diff s (Just seg) = map show $ [((lastSeqPrinted s) + 1)..((seqNum seg) - 1)] \\ (map seqNum (buffer s))
handler :: Server -> Chan (String, SockAddr) -> Socket -> IO ()
handler server fromClient conn =
do
msg <- tryGet fromClient
let (fromC, sockAddr) = maybe (Nothing,(sockaddr server))
(\ (x,y) -> (Just x,y))
msg
mSeg = parseSeg fromC -- returns Nothing is corrupt
-- we update server's state, which may depend on the seg rec'd from client
nextServer = stepServer server mSeg
when we popped , fork print debug info ( parsed seg )
when (isJust fromC) $ void $ forkIO $ void $ printRecv mSeg server
if (sstate nextServer) == SClose
then do -- let's finish up
mapM putStr $ map dat $ toPrint nextServer
let finAck = show $ hashSeg $ Seg Fin (-1) "" ""
send 4 fin acks
replicateM_ 4 $ sendTo conn finAck sockAddr
close conn
timestamp $ "[completed]"
else do -- ack the data packet we received
-- print everything
mapM putStr $ map dat $ toPrint nextServer
let emptiedToPrint = nextServer { toPrint = [], sockaddr = sockAddr }
-- sends ack to the server
forkIO $ sendAck conn sockAddr mSeg $ diff nextServer mSeg
handler emptiedToPrint fromClient conn
initialize :: Socket -> IO ()
initialize conn =
do
receiving <- newChan
-- fork off our socket-reading code
rec <- forkIO $ receiveFromClient conn receiving
let server = Server SEstablished [] [] 0 (SockAddrUnix "unimportantplaceholder")
handler server receiving conn
-- kill our socket-reading code once we're done
killThread rec
connectMe :: String -> IO Socket
connectMe port =
do
(serveraddr:_) <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing (Just port)
Datagram for UDP , Stream for TCP
sock <- socket (addrFamily serveraddr) Datagram defaultProtocol
bindSocket sock (addrAddress serveraddr)
return sock
main :: IO ()
main =
do
hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering
r <- getStdRandom $ randomR (1024, 65535)
let rS = show (r :: Int)
timestamp $ "[bound] " ++ rS
-- the "bracket" pattern (bracket a b c) basically
runs a first , c in between , finally b ( in this case with a socket )
withSocketsDo $ bracket (connectMe rS) sClose initialize
| null | https://raw.githubusercontent.com/semaj/mini-tcp-haskell/55eb08bc536c2ce7e4765a0a5acdd23cf4bdca88/3700recv.hs | haskell | server state
what to print on next IO cycle
stored segments (can't print because they're out of order)
last sequence number printed
it's a duplicate if it's smaller than the last thing we printed (already printed)
or if we have it in the buffer
used for debug printing.
the lastSeq num is either the last received, last to print, or last printed
this is pretty gross, there's a fold here somewhere
if it's a dup, don't add it
if we receive a fin, let's finish up
else let's add to the buffer and add things to be printed
in the range from what we've printed to what we've received, what are we missing?
(what should we nack?)
returns Nothing is corrupt
we update server's state, which may depend on the seg rec'd from client
let's finish up
ack the data packet we received
print everything
sends ack to the server
fork off our socket-reading code
kill our socket-reading code once we're done
the "bracket" pattern (bracket a b c) basically | module Main where
import TCP
import Control.Monad (unless, when, forever, void, replicateM_)
import System.Exit
import System.IO
import Network.Socket
import Control.Exception
import System.Random
import Data.Time.Clock
import Data.List
import Control.Concurrent
import Data.Maybe
import System.Exit
import Data.List.Split
data SState = SEstablished | SClose deriving (Eq)
data Server = Server {
sockaddr :: SockAddr
}
isDup :: Server -> Seg -> Bool
isDup server seg = (seqNum seg) < (lastSeqPrinted server) || any ((== (seqNum seg)) . seqNum) (buffer server)
lastSeqNum :: Server -> Int
lastSeqNum (Server _ [] [] i _) = i
lastSeqNum (Server _ toP [] _ _) = last $ sort $ map seqNum toP
lastSeqNum (Server _ _ buff _ _) = last $ sort $ map seqNum buff
outOfOrder :: Server -> Seg -> String
outOfOrder server seg = if ((seqNum seg) - 1) == lsn then "(in-order)" else "(out-of-order)"
where lsn = lastSeqNum server
pull consective ( by seq num ) out of buffer , into toPrint
whatToPrint :: Server -> Server
whatToPrint s@(Server ss toprint buff lastseq sa) = newS printMe
where printMe = find ((== (lastseq + 1)) . seqNum) buff
newS Nothing = s
newS (Just a) = whatToPrint $ Server ss (toprint ++ [a]) (delete a buff) (lastseq + 1) sa
addToBuffer :: Server -> Maybe Seg -> Server
addToBuffer s Nothing = s
addToBuffer s (Just seg) = if isDup s seg
then s
else s { buffer = ((buffer s) ++ [seg]) }
stepServer :: Server -> Maybe Seg -> Server
stepServer s (Just (Seg Fin _ _ _)) = s { sstate = SClose }
stepServer s mseg = whatToPrint $ addToBuffer s mseg
add our nacks to the data
getAck :: Seg -> [String] -> String
getAck (Seg _ num _ _) nacks = show $ hashSeg $ Seg Ack num (intercalate nackSplitter nacks) ""
receiveFromClient :: Socket -> Chan (String, SockAddr) -> IO ()
receiveFromClient s segs = do
forever $ do
(msg,_,d) <- recvFrom s 32768
writeChan segs (msg, d)
sendAck :: Socket -> SockAddr -> Maybe Seg -> [String] -> IO ()
sendAck _ _ Nothing _ = return ()
sendAck conn sa (Just seg) nacks = void $ sendTo conn (getAck seg nacks) sa
printRecv :: Maybe Seg -> Server -> IO ()
printRecv Nothing _ = timestamp "[recv corrupt packet]"
printRecv (Just seg@(Seg Data num dat _)) server =
do
let (off,len) = offsetLengthSeg seg
pref = "[recv data] " ++ off ++ " (" ++ len ++ ") " ++ (show num)
if (isDup server seg)
then timestamp $ pref ++ "IGNORED"
else timestamp $ pref ++ "ACCEPTED " ++ (outOfOrder server seg)
do n't print
diff :: Server -> Maybe Seg -> [String]
diff _ Nothing = []
diff s (Just seg) = map show $ [((lastSeqPrinted s) + 1)..((seqNum seg) - 1)] \\ (map seqNum (buffer s))
handler :: Server -> Chan (String, SockAddr) -> Socket -> IO ()
handler server fromClient conn =
do
msg <- tryGet fromClient
let (fromC, sockAddr) = maybe (Nothing,(sockaddr server))
(\ (x,y) -> (Just x,y))
msg
nextServer = stepServer server mSeg
when we popped , fork print debug info ( parsed seg )
when (isJust fromC) $ void $ forkIO $ void $ printRecv mSeg server
if (sstate nextServer) == SClose
mapM putStr $ map dat $ toPrint nextServer
let finAck = show $ hashSeg $ Seg Fin (-1) "" ""
send 4 fin acks
replicateM_ 4 $ sendTo conn finAck sockAddr
close conn
timestamp $ "[completed]"
mapM putStr $ map dat $ toPrint nextServer
let emptiedToPrint = nextServer { toPrint = [], sockaddr = sockAddr }
forkIO $ sendAck conn sockAddr mSeg $ diff nextServer mSeg
handler emptiedToPrint fromClient conn
initialize :: Socket -> IO ()
initialize conn =
do
receiving <- newChan
rec <- forkIO $ receiveFromClient conn receiving
let server = Server SEstablished [] [] 0 (SockAddrUnix "unimportantplaceholder")
handler server receiving conn
killThread rec
connectMe :: String -> IO Socket
connectMe port =
do
(serveraddr:_) <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing (Just port)
Datagram for UDP , Stream for TCP
sock <- socket (addrFamily serveraddr) Datagram defaultProtocol
bindSocket sock (addrAddress serveraddr)
return sock
main :: IO ()
main =
do
hSetBuffering stdout NoBuffering
hSetBuffering stderr NoBuffering
r <- getStdRandom $ randomR (1024, 65535)
let rS = show (r :: Int)
timestamp $ "[bound] " ++ rS
runs a first , c in between , finally b ( in this case with a socket )
withSocketsDo $ bracket (connectMe rS) sClose initialize
|
2545ee899433649d15821b07de2d1a386aad7f3f69158108afc3e3f37cf7a7fc | pflanze/chj-schemelib | transaction-cps.scm | Copyright 2010 , 2011 by < >
;;; This file is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
;;; (at your option) any later version.
(require monad/syntax)
;; particular monad for use in transactions:
;; each monad (?ç) takes the commit (state) and a continuation, and
;; passes the new commit and a new continuation to the latter.
monads that return values first pass the value to the continuation
-- ç ehr , b ist monad ? sondern returns einen ok ? . -- ah
aber still true , passen den value zu ihrer eigenen continuation .
(define (transaction-cps:>> a b)
(lambda (commit cont)
(a commit
(lambda (commit)
(b commit
cont)))))
(define (transaction-cps:>>= a b)
(lambda (commit cont)
(a commit
(lambda (commit val)
((b val)
commit
cont)))))
(define (transaction-cps:return val)
(lambda (commit cont)
(cont commit
val)))
;; turn a normal expression into one that is just run as a side-effect
;; of the monad's execution
(define-macro* (transaction-cps:inline! expr)
`(lambda (commit cont)
,expr ;; could be done with thunks instead of a macro, of course..
(cont commit)))
(TEST
;; example, list creation
> (define (m:create val)
(lambda (commit cont)
(cont (cons val commit))))
> (define (m:nth n)
(lambda (commit cont)
(cont commit
(list-ref commit n))))
> (define k0
(m:create "hallo"))
> (k0 '() identity)
("hallo")
> (define k1
(in-monad
transaction-cps
(>> (m:create "hallo")
(m:create "welt"))))
> (k1 '() identity)
("welt" "hallo")
> (define msgs '())
> (define (msg! . args)
(set! msgs (cons (apply string-append args) msgs)))
> (define (k2 whichcase)
(in-monad
transaction-cps
(>> (m:create "hallo")
(>> (m:create "welt")
(case whichcase
((0)
(>>= (m:nth 1)
(lambda (x)
(m:inline! (msg! "got0: " x)))))
((1)
(letm (v (m:nth 0))
(m:inline! (msg! "got1: " v))))
((2)
(m:let ((v (m:nth 0)))
(m:inline! (msg! "got2: " v)))))))))
> ((k2 0) '() identity)
("welt" "hallo")
> ((k2 1) '() identity)
("welt" "hallo")
> ((k2 2) '() identity)
("welt" "hallo")
> msgs
("got2: welt" "got1: welt" "got0: hallo")
> (set! msgs '())
> (define (k3)
(in-monad
transaction-cps
(m:begin (m:create "hallo")
(m:create "welt")
(letm (v (m:nth 0))
(m:inline! (msg! "got I: " v)))
(m:create "andsoon")
(letm (v (m:nth 0))
(m:inline! (msg! "got II: " v))))))
> ((k3) '() identity)
("andsoon" "welt" "hallo")
> msgs
("got II: andsoon" "got I: welt")
> (set! msgs '())
> (define (k4)
(in-monad
transaction-cps
(m:begin (m:create "hallo")
(m:create "welt")
(m:let ((hal (m:begin
(m:create "neue")
(return "Hellou")))
(wel (m:nth 0)))
(m:inline! (msg! "k4: " hal wel))))))
> ((k4) '() identity)
("neue" "welt" "hallo")
> msgs
("k4: Hellouneue")
;; monad rules:
;; (stupid tests, but a start)
> (define (test . args)
(define (run m)
(m '(X) vector))
(apply equal? (map run args)))
;; return a >>= k == k a
> (define a "A")
> (define k (lambda (v)
(in-monad transaction-cps
(return (cons "k got: " v)))))
> (in-monad transaction-cps
(test (>>= (return a) k)
(k a)))
#t
;; m >>= return == m
;; m must return a value, e.g.:
> (define m (m:nth 0))
> (in-monad transaction-cps
(test (>>= m return)
m))
#t
m > > = ( \x - > k x > > = h ) = = ( m > > = k ) > > = h
> (define h (lambda (v)
(in-monad transaction-cps
(return (cons "k got: " v)))))
> (in-monad transaction-cps
(test (>>= m
(lambda (x)
(>>= (k x)
h)))
(>>= (>>= m k)
h)))
#t
)
| null | https://raw.githubusercontent.com/pflanze/chj-schemelib/59ff8476e39f207c2f1d807cfc9670581c8cedd3/monad/transaction-cps.scm | scheme | This file is free software; you can redistribute it and/or modify
(at your option) any later version.
particular monad for use in transactions:
each monad (?ç) takes the commit (state) and a continuation, and
passes the new commit and a new continuation to the latter.
turn a normal expression into one that is just run as a side-effect
of the monad's execution
could be done with thunks instead of a macro, of course..
example, list creation
monad rules:
(stupid tests, but a start)
return a >>= k == k a
m >>= return == m
m must return a value, e.g.: | Copyright 2010 , 2011 by < >
it under the terms of the GNU General Public License ( GPL ) as published
by the Free Software Foundation , either version 2 of the License , or
(require monad/syntax)
monads that return values first pass the value to the continuation
-- ç ehr , b ist monad ? sondern returns einen ok ? . -- ah
aber still true , passen den value zu ihrer eigenen continuation .
(define (transaction-cps:>> a b)
(lambda (commit cont)
(a commit
(lambda (commit)
(b commit
cont)))))
(define (transaction-cps:>>= a b)
(lambda (commit cont)
(a commit
(lambda (commit val)
((b val)
commit
cont)))))
(define (transaction-cps:return val)
(lambda (commit cont)
(cont commit
val)))
(define-macro* (transaction-cps:inline! expr)
`(lambda (commit cont)
(cont commit)))
(TEST
> (define (m:create val)
(lambda (commit cont)
(cont (cons val commit))))
> (define (m:nth n)
(lambda (commit cont)
(cont commit
(list-ref commit n))))
> (define k0
(m:create "hallo"))
> (k0 '() identity)
("hallo")
> (define k1
(in-monad
transaction-cps
(>> (m:create "hallo")
(m:create "welt"))))
> (k1 '() identity)
("welt" "hallo")
> (define msgs '())
> (define (msg! . args)
(set! msgs (cons (apply string-append args) msgs)))
> (define (k2 whichcase)
(in-monad
transaction-cps
(>> (m:create "hallo")
(>> (m:create "welt")
(case whichcase
((0)
(>>= (m:nth 1)
(lambda (x)
(m:inline! (msg! "got0: " x)))))
((1)
(letm (v (m:nth 0))
(m:inline! (msg! "got1: " v))))
((2)
(m:let ((v (m:nth 0)))
(m:inline! (msg! "got2: " v)))))))))
> ((k2 0) '() identity)
("welt" "hallo")
> ((k2 1) '() identity)
("welt" "hallo")
> ((k2 2) '() identity)
("welt" "hallo")
> msgs
("got2: welt" "got1: welt" "got0: hallo")
> (set! msgs '())
> (define (k3)
(in-monad
transaction-cps
(m:begin (m:create "hallo")
(m:create "welt")
(letm (v (m:nth 0))
(m:inline! (msg! "got I: " v)))
(m:create "andsoon")
(letm (v (m:nth 0))
(m:inline! (msg! "got II: " v))))))
> ((k3) '() identity)
("andsoon" "welt" "hallo")
> msgs
("got II: andsoon" "got I: welt")
> (set! msgs '())
> (define (k4)
(in-monad
transaction-cps
(m:begin (m:create "hallo")
(m:create "welt")
(m:let ((hal (m:begin
(m:create "neue")
(return "Hellou")))
(wel (m:nth 0)))
(m:inline! (msg! "k4: " hal wel))))))
> ((k4) '() identity)
("neue" "welt" "hallo")
> msgs
("k4: Hellouneue")
> (define (test . args)
(define (run m)
(m '(X) vector))
(apply equal? (map run args)))
> (define a "A")
> (define k (lambda (v)
(in-monad transaction-cps
(return (cons "k got: " v)))))
> (in-monad transaction-cps
(test (>>= (return a) k)
(k a)))
#t
> (define m (m:nth 0))
> (in-monad transaction-cps
(test (>>= m return)
m))
#t
m > > = ( \x - > k x > > = h ) = = ( m > > = k ) > > = h
> (define h (lambda (v)
(in-monad transaction-cps
(return (cons "k got: " v)))))
> (in-monad transaction-cps
(test (>>= m
(lambda (x)
(>>= (k x)
h)))
(>>= (>>= m k)
h)))
#t
)
|
8b2a617a034ce2fe4e6905479e01846c90ab44d1bbb539c87d6adbfd6c94c3b1 | jaspervdj/fugacious | Views.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Fugacious.Web.Views
( template
, index
, exception
, inbox
, mail
) where
import Control.Applicative ((<|>))
import Control.Monad (forM_)
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Time as Time
import Data.Version (showVersion)
import qualified Fugacious.Database as Database
import Fugacious.ParseMail
import Fugacious.Web.Routes
import qualified Fugacious.Web.Routes as Routes
import qualified Paths_fugacious
import Text.Blaze.Html (Html, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.HTML.SanitizeXSS as SanitizeXSS
template :: T.Text -> Html -> Html
template title body = H.docTypeHtml $ do
H.head $ do
H.title $ H.toHtml title
H.link ! A.rel "stylesheet" ! A.type_ "text/css"
! A.href (Routes.renderAttr GetAssetsStyle)
H.body $ do
H.header $ H.a ! A.href (Routes.renderAttr GetIndex) $ "fugacious"
body
H.footer $ H.toHtml $
"fugacious-v" ++ showVersion Paths_fugacious.version
exception :: Int -> T.Text -> T.Text -> Html
exception code line body = template ("Error " <> T.pack (show code)) $ do
H.h1 $ H.toHtml code <> " " <> H.toHtml line
H.p $ H.toHtml body
index :: T.Text -> Html
index domain = template "Home" $ do
H.p $ do
"Fugacious is an email service that allows you to claim short-lived "
"email addresses and receive (not send) email on those. This is useful "
"to subscribe to spammy services."
H.form ! A.class_ "login" ! A.action (Routes.renderAttr PostUsers)
! A.method "POST" $ do
H.input ! A.type_ "text" ! A.size "10" ! A.id "address" ! A.name "address"
H.code $ "@" <> H.toHtml domain
H.br
H.input ! A.type_ "submit" ! A.value "Claim address"
userHeader
:: Time.UTCTime
-> Database.User
-> H.Html
-> H.Html
userHeader now user controls = H.p $ do
H.div ! A.class_ "controls" $ controls
"Signed in as "
H.code (H.toHtml (Database.uAddress user))
" - "
"your account expires in "
H.em $ H.toHtml (max 0 minutes)
" minutes"
where
minutes :: Int
minutes = round $
toRational (Database.uExpires user `Time.diffUTCTime` now) / 60
inbox :: Time.UTCTime -> Database.User -> [Database.Mail] -> Html
inbox now {..} emails = template (uAddress <> " - fugacious") $ do
userHeader now user $ do
H.form ! A.action (Routes.renderAttr $ PostUsersRenew uId) ! A.method "POST" $
H.input ! A.type_ "submit" ! A.value "Renew"
H.form ! A.action (Routes.renderAttr $ GetInbox uId) ! A.method "GET" $
H.input ! A.type_ "submit" ! A.value "Refresh"
H.form ! A.action (Routes.renderAttr $ PostUsersLogout uId) ! A.method "POST" $
H.input ! A.type_ "submit" ! A.value "Logout"
H.h1 "Inbox"
if null emails
then H.p $ do
"You have no emails. You can receive email at "
H.code (H.toHtml uAddress)
"."
else H.table $ do
H.tr $ do
H.th "From"
H.th "Subject"
forM_ emails $ \msg -> H.tr $ do
H.td $ H.toHtml (Database.mFrom msg)
H.td $ H.a ! A.href (Routes.renderAttr $ GetInboxMail uId (Database.mId msg) False) $
H.toHtml (Database.mSubject msg)
mail :: Time.UTCTime -> Database.User -> T.Text -> ParsedMail -> Html
mail now {..} msgId msg = template (uAddress <> " - fugacious") $ do
userHeader now user $ do
H.form ! A.action (Routes.renderAttr $ GetInbox uId) ! A.method "GET" $
H.input ! A.type_ "submit" ! A.value "Back"
H.h1 $ H.toHtml $ pmSubject msg
H.p $ do
"From "
H.toHtml (pmFrom msg)
H.div ! A.class_ "body" $ renderBody (pmBody msg)
H.p $ H.a ! A.href (Routes.renderAttr $ GetInboxMail uId msgId True) $
"view source"
where
renderBody (PlainTextBody txt) = H.pre $ H.code $ H.toHtml txt
renderBody (HtmlBody txt) = H.preEscapedToHtml $
SanitizeXSS.sanitizeXSS $ txt
renderBody (MultipartBody parts) = case preferredPart parts of
Just b -> renderBody b
Nothing -> "Empty multipart body"
preferredPart parts =
listToMaybe [b | b@(HtmlBody _) <- parts] <|>
listToMaybe [b | b@(PlainTextBody _) <- parts]
| null | https://raw.githubusercontent.com/jaspervdj/fugacious/4e9c2d48174c852616fbfbf28bd9cc90812a1c95/lib/Fugacious/Web/Views.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE RecordWildCards #
module Fugacious.Web.Views
( template
, index
, exception
, inbox
, mail
) where
import Control.Applicative ((<|>))
import Control.Monad (forM_)
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Time as Time
import Data.Version (showVersion)
import qualified Fugacious.Database as Database
import Fugacious.ParseMail
import Fugacious.Web.Routes
import qualified Fugacious.Web.Routes as Routes
import qualified Paths_fugacious
import Text.Blaze.Html (Html, (!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.HTML.SanitizeXSS as SanitizeXSS
template :: T.Text -> Html -> Html
template title body = H.docTypeHtml $ do
H.head $ do
H.title $ H.toHtml title
H.link ! A.rel "stylesheet" ! A.type_ "text/css"
! A.href (Routes.renderAttr GetAssetsStyle)
H.body $ do
H.header $ H.a ! A.href (Routes.renderAttr GetIndex) $ "fugacious"
body
H.footer $ H.toHtml $
"fugacious-v" ++ showVersion Paths_fugacious.version
exception :: Int -> T.Text -> T.Text -> Html
exception code line body = template ("Error " <> T.pack (show code)) $ do
H.h1 $ H.toHtml code <> " " <> H.toHtml line
H.p $ H.toHtml body
index :: T.Text -> Html
index domain = template "Home" $ do
H.p $ do
"Fugacious is an email service that allows you to claim short-lived "
"email addresses and receive (not send) email on those. This is useful "
"to subscribe to spammy services."
H.form ! A.class_ "login" ! A.action (Routes.renderAttr PostUsers)
! A.method "POST" $ do
H.input ! A.type_ "text" ! A.size "10" ! A.id "address" ! A.name "address"
H.code $ "@" <> H.toHtml domain
H.br
H.input ! A.type_ "submit" ! A.value "Claim address"
userHeader
:: Time.UTCTime
-> Database.User
-> H.Html
-> H.Html
userHeader now user controls = H.p $ do
H.div ! A.class_ "controls" $ controls
"Signed in as "
H.code (H.toHtml (Database.uAddress user))
" - "
"your account expires in "
H.em $ H.toHtml (max 0 minutes)
" minutes"
where
minutes :: Int
minutes = round $
toRational (Database.uExpires user `Time.diffUTCTime` now) / 60
inbox :: Time.UTCTime -> Database.User -> [Database.Mail] -> Html
inbox now {..} emails = template (uAddress <> " - fugacious") $ do
userHeader now user $ do
H.form ! A.action (Routes.renderAttr $ PostUsersRenew uId) ! A.method "POST" $
H.input ! A.type_ "submit" ! A.value "Renew"
H.form ! A.action (Routes.renderAttr $ GetInbox uId) ! A.method "GET" $
H.input ! A.type_ "submit" ! A.value "Refresh"
H.form ! A.action (Routes.renderAttr $ PostUsersLogout uId) ! A.method "POST" $
H.input ! A.type_ "submit" ! A.value "Logout"
H.h1 "Inbox"
if null emails
then H.p $ do
"You have no emails. You can receive email at "
H.code (H.toHtml uAddress)
"."
else H.table $ do
H.tr $ do
H.th "From"
H.th "Subject"
forM_ emails $ \msg -> H.tr $ do
H.td $ H.toHtml (Database.mFrom msg)
H.td $ H.a ! A.href (Routes.renderAttr $ GetInboxMail uId (Database.mId msg) False) $
H.toHtml (Database.mSubject msg)
mail :: Time.UTCTime -> Database.User -> T.Text -> ParsedMail -> Html
mail now {..} msgId msg = template (uAddress <> " - fugacious") $ do
userHeader now user $ do
H.form ! A.action (Routes.renderAttr $ GetInbox uId) ! A.method "GET" $
H.input ! A.type_ "submit" ! A.value "Back"
H.h1 $ H.toHtml $ pmSubject msg
H.p $ do
"From "
H.toHtml (pmFrom msg)
H.div ! A.class_ "body" $ renderBody (pmBody msg)
H.p $ H.a ! A.href (Routes.renderAttr $ GetInboxMail uId msgId True) $
"view source"
where
renderBody (PlainTextBody txt) = H.pre $ H.code $ H.toHtml txt
renderBody (HtmlBody txt) = H.preEscapedToHtml $
SanitizeXSS.sanitizeXSS $ txt
renderBody (MultipartBody parts) = case preferredPart parts of
Just b -> renderBody b
Nothing -> "Empty multipart body"
preferredPart parts =
listToMaybe [b | b@(HtmlBody _) <- parts] <|>
listToMaybe [b | b@(PlainTextBody _) <- parts]
|
3527504ee911b906f2b5cc9482e5cdc652560085a9dbb28541bde953c8aff145 | ndmitchell/shake | Rebuild.hs |
module Test.Rebuild(main) where
import Development.Shake
import Test.Type
import Text.Read
import Data.List.Extra
import Control.Monad
import General.GetOpt
data Opt = Timestamp String | Pattern Pat
opts = [Option "" ["timestamp"] (ReqArg (Right . Timestamp) "VALUE") "Value used to detect what has rebuilt when"
,Option "" ["pattern"] (ReqArg (fmap Pattern . readEither) "PATTERN") "Which file rules to use (%>, &?> etc)"]
main = testBuildArgs test opts $ \args -> do
let timestamp = concat [x | Timestamp x <- args]
let p = lastDef PatWildcard [x | Pattern x <- args]
want ["a.txt"]
pat p "a.txt" $ \out -> do
src <- readFile' "b.txt"
writeFile' out $ src ++ timestamp
pat p "b.txt" $ \out -> do
src <- readFile' "c.txt"
writeFile' out $ src ++ timestamp
test build =
forM_ [minBound..maxBound :: Pat] $ \pat -> do
build ["clean"]
let go arg c b a flags = do
writeFileChanged "c.txt" c
build $ ["--timestamp=" ++ arg, "--sleep","--no-reports","--pattern=" ++ show pat] ++ flags
assertContents "b.txt" b
assertContents "a.txt" a
-- check rebuild works
go "1" "x" "x1" "x11" []
go "2" "x" "x1" "x11" []
go "3" "x" "x1" "x13" ["--rebuild=a.*"]
go "4" "x" "x1" "x13" []
go "5" "x" "x5" "x55" ["--rebuild=b.*"]
go "6" "x" "x6" "x66" ["--rebuild"]
go "7" "x" "x6" "x66" []
go "8" "y" "y8" "y88" []
-- check skip works
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip=a.*"]
go "3" "y" "y2" "y23" []
go "4" "z" "y2" "y23" ["--skip=b.*"]
go "5" "z" "y2" "y23" ["--skip=b.*"]
go "6" "z" "z6" "z66" []
go "7" "a" "z6" "z66" ["--skip=c.*"]
go "8" "a" "z6" "z66" ["--skip=b.*"]
go "9" "a" "a9" "z66" ["--skip=a.*"]
go "0" "a" "a9" "a90" []
-- check skip - forever works
-- currently it does not work properly
go " 1 " " x " " x1 " " x11 " [ ]
go " 2 " " y " " y2 " " x11 " [ " --skip - forever = a. * " ]
go " 3 " " y " " y2 " " x11 " [ ]
go " 4 " " z " " z4 " " z44 " [ ]
-- check skip-forever works
-- currently it does not work properly
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip-forever=a.*"]
go "3" "y" "y2" "x11" []
go "4" "z" "z4" "z44" []
-}
| null | https://raw.githubusercontent.com/ndmitchell/shake/99c5a7a4dc1d5a069b13ed5c1bc8e4bc7f13f4a6/src/Test/Rebuild.hs | haskell | check rebuild works
check skip works
check skip - forever works
currently it does not work properly
check skip-forever works
currently it does not work properly |
module Test.Rebuild(main) where
import Development.Shake
import Test.Type
import Text.Read
import Data.List.Extra
import Control.Monad
import General.GetOpt
data Opt = Timestamp String | Pattern Pat
opts = [Option "" ["timestamp"] (ReqArg (Right . Timestamp) "VALUE") "Value used to detect what has rebuilt when"
,Option "" ["pattern"] (ReqArg (fmap Pattern . readEither) "PATTERN") "Which file rules to use (%>, &?> etc)"]
main = testBuildArgs test opts $ \args -> do
let timestamp = concat [x | Timestamp x <- args]
let p = lastDef PatWildcard [x | Pattern x <- args]
want ["a.txt"]
pat p "a.txt" $ \out -> do
src <- readFile' "b.txt"
writeFile' out $ src ++ timestamp
pat p "b.txt" $ \out -> do
src <- readFile' "c.txt"
writeFile' out $ src ++ timestamp
test build =
forM_ [minBound..maxBound :: Pat] $ \pat -> do
build ["clean"]
let go arg c b a flags = do
writeFileChanged "c.txt" c
build $ ["--timestamp=" ++ arg, "--sleep","--no-reports","--pattern=" ++ show pat] ++ flags
assertContents "b.txt" b
assertContents "a.txt" a
go "1" "x" "x1" "x11" []
go "2" "x" "x1" "x11" []
go "3" "x" "x1" "x13" ["--rebuild=a.*"]
go "4" "x" "x1" "x13" []
go "5" "x" "x5" "x55" ["--rebuild=b.*"]
go "6" "x" "x6" "x66" ["--rebuild"]
go "7" "x" "x6" "x66" []
go "8" "y" "y8" "y88" []
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip=a.*"]
go "3" "y" "y2" "y23" []
go "4" "z" "y2" "y23" ["--skip=b.*"]
go "5" "z" "y2" "y23" ["--skip=b.*"]
go "6" "z" "z6" "z66" []
go "7" "a" "z6" "z66" ["--skip=c.*"]
go "8" "a" "z6" "z66" ["--skip=b.*"]
go "9" "a" "a9" "z66" ["--skip=a.*"]
go "0" "a" "a9" "a90" []
go " 1 " " x " " x1 " " x11 " [ ]
go " 2 " " y " " y2 " " x11 " [ " --skip - forever = a. * " ]
go " 3 " " y " " y2 " " x11 " [ ]
go " 4 " " z " " z4 " " z44 " [ ]
go "1" "x" "x1" "x11" []
go "2" "y" "y2" "x11" ["--skip-forever=a.*"]
go "3" "y" "y2" "x11" []
go "4" "z" "z4" "z44" []
-}
|
61f5bbb974cdc7dcf8b37b814971dc86c0e17739d05236c089e483f8a67178ab | protz/mezzo | Driver.mli | (*****************************************************************************)
(* Mezzo, a programming language based on permissions *)
Copyright ( C ) 2011 , 2012 and
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
(* along with this program. If not, see </>. *)
(* *)
(*****************************************************************************)
(** This module sets up a lexer and a parser to create an AST. *)
type run_options = {
html_errors: bool;
backtraces: bool;
}
(** Last directory included has higher precedence. *)
val add_include_dir: string -> unit
(** For the -print-config option. *)
val print_include_dirs: unit -> string
(** [process] doesn't catch exceptions. This is useful for tests that want to
assert that a test program failed in a certain way. *)
val process: string -> TypeCore.env
(** [run] runs the specified function and prints any error that may pop up. *)
val run: run_options -> (unit -> 'a) -> 'a
(** [print_signature] prints out (in order, and in a fancy manner) the types that have been
found in the file. *)
val print_signature: Buffer.t -> TypeCore.env -> unit
(** [interpret] is a driver for the interpreter. It evaluates the
specified file, as well as the files that it depends upon, in
an appropriate order. *)
val interpret: string -> unit
val lex_and_parse_raw: Ulexing.lexbuf ->
string -> (Grammar.token, 'a) MenhirLib.Convert.traditional -> 'a
val check_implementation: Module.name -> SurfaceSyntax.implementation ->
SurfaceSyntax.interface option -> TypeCore.env
| null | https://raw.githubusercontent.com/protz/mezzo/4e9d917558bd96067437116341b7a6ea02ab9c39/parsing/Driver.mli | ocaml | ***************************************************************************
Mezzo, a programming language based on permissions
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
***************************************************************************
* This module sets up a lexer and a parser to create an AST.
* Last directory included has higher precedence.
* For the -print-config option.
* [process] doesn't catch exceptions. This is useful for tests that want to
assert that a test program failed in a certain way.
* [run] runs the specified function and prints any error that may pop up.
* [print_signature] prints out (in order, and in a fancy manner) the types that have been
found in the file.
* [interpret] is a driver for the interpreter. It evaluates the
specified file, as well as the files that it depends upon, in
an appropriate order. | Copyright ( C ) 2011 , 2012 and
it 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
type run_options = {
html_errors: bool;
backtraces: bool;
}
val add_include_dir: string -> unit
val print_include_dirs: unit -> string
val process: string -> TypeCore.env
val run: run_options -> (unit -> 'a) -> 'a
val print_signature: Buffer.t -> TypeCore.env -> unit
val interpret: string -> unit
val lex_and_parse_raw: Ulexing.lexbuf ->
string -> (Grammar.token, 'a) MenhirLib.Convert.traditional -> 'a
val check_implementation: Module.name -> SurfaceSyntax.implementation ->
SurfaceSyntax.interface option -> TypeCore.env
|
f3e97788ee14a3a8f0690bc64c2fbdd2443418a7407cd0f88a47da6d02d734e6 | mirage/alcotest | test_source_code_position.ml |
* Copyright ( c ) 2022 >
*
* Permission to use , copy , modify , and 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 .
* Copyright (c) 2022 Antonin Décimo <>
*
* Permission to use, copy, modify, and 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.
*)
(* A module with functions to test *)
module To_test = struct
let capitalise = Astring.String.Ascii.uppercase
let double_all = List.map (fun a -> a + a)
end
let test_capitalise () =
To_test.capitalise "b" |> Alcotest.(check string) "strings" "A";
()
let test_double_all () =
To_test.double_all [ 1; 1; 2; 3 ]
|> Alcotest.(check (list int)) "int lists 1" [ 1 ];
To_test.double_all [ 1; 1; 2; 3 ]
|> Alcotest.(check (list int)) "int lists 2" [ 2 ]
let suite1 =
[
( "to_test",
[
("capitalise", `Quick, test_capitalise);
("double all", `Slow, test_double_all);
] );
]
let suite2 =
[
( "Ωèone",
[
("Passing test 1", `Quick, fun () -> ());
( "Failing test",
`Quick,
fun () -> Alcotest.fail "This was never going to work..." );
("Passing test 2", `Quick, fun () -> ());
] );
]
Run both suites completely , even if the first contains failures
let () =
try Alcotest.run ~and_exit:false "First suite" suite1
with Alcotest.Test_error ->
Printf.printf "Forging ahead regardless!\n%!";
Alcotest.run ~and_exit:false "Second suite" suite2;
Printf.printf "Finally done."
| null | https://raw.githubusercontent.com/mirage/alcotest/838987da59f4e647d2286fdc18f445d30dc880ed/test/e2e/alcotest/source_code_position/test_source_code_position.ml | ocaml | A module with functions to test |
* Copyright ( c ) 2022 >
*
* Permission to use , copy , modify , and 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 .
* Copyright (c) 2022 Antonin Décimo <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
module To_test = struct
let capitalise = Astring.String.Ascii.uppercase
let double_all = List.map (fun a -> a + a)
end
let test_capitalise () =
To_test.capitalise "b" |> Alcotest.(check string) "strings" "A";
()
let test_double_all () =
To_test.double_all [ 1; 1; 2; 3 ]
|> Alcotest.(check (list int)) "int lists 1" [ 1 ];
To_test.double_all [ 1; 1; 2; 3 ]
|> Alcotest.(check (list int)) "int lists 2" [ 2 ]
let suite1 =
[
( "to_test",
[
("capitalise", `Quick, test_capitalise);
("double all", `Slow, test_double_all);
] );
]
let suite2 =
[
( "Ωèone",
[
("Passing test 1", `Quick, fun () -> ());
( "Failing test",
`Quick,
fun () -> Alcotest.fail "This was never going to work..." );
("Passing test 2", `Quick, fun () -> ());
] );
]
Run both suites completely , even if the first contains failures
let () =
try Alcotest.run ~and_exit:false "First suite" suite1
with Alcotest.Test_error ->
Printf.printf "Forging ahead regardless!\n%!";
Alcotest.run ~and_exit:false "Second suite" suite2;
Printf.printf "Finally done."
|
1c07adf0b7a5a90866d43c85ec5f745bad68c1a2c666241b4aa525f93f78e377 | AbstractMachinesLab/caramel | pid.mli | (** Process id's as returned by the Unix family of functions *)
type t
val to_dyn : t -> Dyn.t
val hash : t -> int
val equal : t -> t -> bool
val to_int : t -> int
(** Unsafe cast of integers to pids. Will be removed once we improve the API
further *)
val of_int : int -> t
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/vendor/stdune/pid.mli | ocaml | * Process id's as returned by the Unix family of functions
* Unsafe cast of integers to pids. Will be removed once we improve the API
further | type t
val to_dyn : t -> Dyn.t
val hash : t -> int
val equal : t -> t -> bool
val to_int : t -> int
val of_int : int -> t
|
33f19ebbad92b85c674f5cff3b53afec2f2bbe27edf293242caadb78afc10381 | roelvandijk/numerals | TestData.hs | |
[ @ISO639 - 1@ ] -
[ @ISO639 - 2B@ ] -
[ @ISO639 - 3@ ] nqm
[ @Native name@ ] -
[ @English name@ ]
[@ISO639-1@] -
[@ISO639-2B@] -
[@ISO639-3@] nqm
[@Native name@] -
[@English name@] Ndom
-}
module Text.Numeral.Language.NQM.TestData (cardinals) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
--------------------------------------------------------------------------------
-- Test data
--------------------------------------------------------------------------------
cardinals :: (Num i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "sas")
, (2, "thef")
, (3, "ithin")
, (4, "thonith")
, (5, "meregh")
, (6, "mer")
, (7, "mer abo sas")
, (8, "mer abo thef")
, (9, "mer abo ithin")
, (10, "mer abo thonith")
, (11, "mer abo meregh")
, (12, "mer an thef")
, (13, "mer an thef abo sas")
, (14, "mer an thef abo thef")
, (15, "mer an thef abo ithin")
, (16, "mer an thef abo thonith")
, (17, "mer an thef abo meregh")
, (18, "tondor")
, (19, "tondor abo sas")
, (20, "tondor abo thef")
, (21, "tondor abo ithin")
, (22, "tondor abo thonith")
, (23, "tondor abo meregh")
, (24, "tondor abo mer")
, (25, "tondor abo mer abo sas")
, (26, "tondor abo mer abo thef")
, (27, "tondor abo mer abo ithin")
, (28, "tondor abo mer abo thonith")
, (29, "tondor abo mer abo meregh")
, (30, "tondor abo mer an thef")
, (31, "tondor abo mer an thef abo sas")
, (32, "tondor abo mer an thef abo thef")
, (33, "tondor abo mer an thef abo ithin")
, (34, "tondor abo mer an thef abo thonith")
, (35, "tondor abo mer an thef abo meregh")
, (36, "nif")
, (37, "nif abo sas")
, (38, "nif abo thef")
, (39, "nif abo ithin")
, (40, "nif abo thonith")
, (41, "nif abo meregh")
, (42, "nif abo mer")
, (43, "nif abo mer abo sas")
, (44, "nif abo mer abo thef")
, (45, "nif abo mer abo ithin")
, (46, "nif abo mer abo thonith")
, (47, "nif abo mer abo meregh")
, (48, "nif abo mer an thef")
, (49, "nif abo mer an thef abo sas")
, (50, "nif abo mer an thef abo thef")
, (51, "nif abo mer an thef abo ithin")
, (52, "nif abo mer an thef abo thonith")
, (53, "nif abo mer an thef abo meregh")
, (54, "nif abo tondor")
, (55, "nif abo tondor abo sas")
, (56, "nif abo tondor abo thef")
, (57, "nif abo tondor abo ithin")
, (58, "nif abo tondor abo thonith")
, (59, "nif abo tondor abo meregh")
, (60, "nif abo tondor abo mer")
, (61, "nif abo tondor abo mer abo sas")
, (62, "nif abo tondor abo mer abo thef")
, (63, "nif abo tondor abo mer abo ithin")
, (64, "nif abo tondor abo mer abo thonith")
, (65, "nif abo tondor abo mer abo meregh")
, (66, "nif abo tondor abo mer an thef")
, (67, "nif abo tondor abo mer an thef abo sas")
, (68, "nif abo tondor abo mer an thef abo thef")
, (69, "nif abo tondor abo mer an thef abo ithin")
, (70, "nif abo tondor abo mer an thef abo thonith")
, (71, "nif abo tondor abo mer an thef abo meregh")
, (72, "nif thef")
, (73, "nif thef abo sas")
, (74, "nif thef abo thef")
, (75, "nif thef abo ithin")
, (76, "nif thef abo thonith")
, (77, "nif thef abo meregh")
, (78, "nif thef abo mer")
, (79, "nif thef abo mer abo sas")
, (80, "nif thef abo mer abo thef")
, (81, "nif thef abo mer abo ithin")
, (82, "nif thef abo mer abo thonith")
, (83, "nif thef abo mer abo meregh")
, (84, "nif thef abo mer an thef")
, (85, "nif thef abo mer an thef abo sas")
, (86, "nif thef abo mer an thef abo thef")
, (87, "nif thef abo mer an thef abo ithin")
, (88, "nif thef abo mer an thef abo thonith")
, (89, "nif thef abo mer an thef abo meregh")
, (90, "nif thef abo tondor")
, (91, "nif thef abo tondor abo sas")
, (92, "nif thef abo tondor abo thef")
, (93, "nif thef abo tondor abo ithin")
, (94, "nif thef abo tondor abo thonith")
, (95, "nif thef abo tondor abo meregh")
, (96, "nif thef abo tondor abo mer")
, (97, "nif thef abo tondor abo mer abo sas")
, (98, "nif thef abo tondor abo mer abo thef")
, (99, "nif thef abo tondor abo mer abo ithin")
, (100, "nif thef abo tondor abo mer abo thonith")
]
)
]
| null | https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src-test/Text/Numeral/Language/NQM/TestData.hs | haskell | ------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Test data
------------------------------------------------------------------------------ | |
[ @ISO639 - 1@ ] -
[ @ISO639 - 2B@ ] -
[ @ISO639 - 3@ ] nqm
[ @Native name@ ] -
[ @English name@ ]
[@ISO639-1@] -
[@ISO639-2B@] -
[@ISO639-3@] nqm
[@Native name@] -
[@English name@] Ndom
-}
module Text.Numeral.Language.NQM.TestData (cardinals) where
import "numerals" Text.Numeral.Grammar ( defaultInflection )
import "this" Text.Numeral.Test ( TestData )
cardinals :: (Num i) => TestData i
cardinals =
[ ( "default"
, defaultInflection
, [ (1, "sas")
, (2, "thef")
, (3, "ithin")
, (4, "thonith")
, (5, "meregh")
, (6, "mer")
, (7, "mer abo sas")
, (8, "mer abo thef")
, (9, "mer abo ithin")
, (10, "mer abo thonith")
, (11, "mer abo meregh")
, (12, "mer an thef")
, (13, "mer an thef abo sas")
, (14, "mer an thef abo thef")
, (15, "mer an thef abo ithin")
, (16, "mer an thef abo thonith")
, (17, "mer an thef abo meregh")
, (18, "tondor")
, (19, "tondor abo sas")
, (20, "tondor abo thef")
, (21, "tondor abo ithin")
, (22, "tondor abo thonith")
, (23, "tondor abo meregh")
, (24, "tondor abo mer")
, (25, "tondor abo mer abo sas")
, (26, "tondor abo mer abo thef")
, (27, "tondor abo mer abo ithin")
, (28, "tondor abo mer abo thonith")
, (29, "tondor abo mer abo meregh")
, (30, "tondor abo mer an thef")
, (31, "tondor abo mer an thef abo sas")
, (32, "tondor abo mer an thef abo thef")
, (33, "tondor abo mer an thef abo ithin")
, (34, "tondor abo mer an thef abo thonith")
, (35, "tondor abo mer an thef abo meregh")
, (36, "nif")
, (37, "nif abo sas")
, (38, "nif abo thef")
, (39, "nif abo ithin")
, (40, "nif abo thonith")
, (41, "nif abo meregh")
, (42, "nif abo mer")
, (43, "nif abo mer abo sas")
, (44, "nif abo mer abo thef")
, (45, "nif abo mer abo ithin")
, (46, "nif abo mer abo thonith")
, (47, "nif abo mer abo meregh")
, (48, "nif abo mer an thef")
, (49, "nif abo mer an thef abo sas")
, (50, "nif abo mer an thef abo thef")
, (51, "nif abo mer an thef abo ithin")
, (52, "nif abo mer an thef abo thonith")
, (53, "nif abo mer an thef abo meregh")
, (54, "nif abo tondor")
, (55, "nif abo tondor abo sas")
, (56, "nif abo tondor abo thef")
, (57, "nif abo tondor abo ithin")
, (58, "nif abo tondor abo thonith")
, (59, "nif abo tondor abo meregh")
, (60, "nif abo tondor abo mer")
, (61, "nif abo tondor abo mer abo sas")
, (62, "nif abo tondor abo mer abo thef")
, (63, "nif abo tondor abo mer abo ithin")
, (64, "nif abo tondor abo mer abo thonith")
, (65, "nif abo tondor abo mer abo meregh")
, (66, "nif abo tondor abo mer an thef")
, (67, "nif abo tondor abo mer an thef abo sas")
, (68, "nif abo tondor abo mer an thef abo thef")
, (69, "nif abo tondor abo mer an thef abo ithin")
, (70, "nif abo tondor abo mer an thef abo thonith")
, (71, "nif abo tondor abo mer an thef abo meregh")
, (72, "nif thef")
, (73, "nif thef abo sas")
, (74, "nif thef abo thef")
, (75, "nif thef abo ithin")
, (76, "nif thef abo thonith")
, (77, "nif thef abo meregh")
, (78, "nif thef abo mer")
, (79, "nif thef abo mer abo sas")
, (80, "nif thef abo mer abo thef")
, (81, "nif thef abo mer abo ithin")
, (82, "nif thef abo mer abo thonith")
, (83, "nif thef abo mer abo meregh")
, (84, "nif thef abo mer an thef")
, (85, "nif thef abo mer an thef abo sas")
, (86, "nif thef abo mer an thef abo thef")
, (87, "nif thef abo mer an thef abo ithin")
, (88, "nif thef abo mer an thef abo thonith")
, (89, "nif thef abo mer an thef abo meregh")
, (90, "nif thef abo tondor")
, (91, "nif thef abo tondor abo sas")
, (92, "nif thef abo tondor abo thef")
, (93, "nif thef abo tondor abo ithin")
, (94, "nif thef abo tondor abo thonith")
, (95, "nif thef abo tondor abo meregh")
, (96, "nif thef abo tondor abo mer")
, (97, "nif thef abo tondor abo mer abo sas")
, (98, "nif thef abo tondor abo mer abo thef")
, (99, "nif thef abo tondor abo mer abo ithin")
, (100, "nif thef abo tondor abo mer abo thonith")
]
)
]
|
4ee2d730abb1bf8d739e5eea8ac8cf958a23a2ec34d6a3a78e4bff08eed4f579 | privet-kitty/cl-competitive | read-digit.lisp | (defpackage :cp/read-digit
(:use :cl)
(:export #:read-digit))
(in-package :cp/read-digit)
(declaim (ftype (function * (values (integer 0 9) &optional)) read-digit))
(defun read-digit (&optional (in *standard-input*))
"Reads a non-negative one-digit integer."
(macrolet ((%read-byte ()
`(the (unsigned-byte 8)
#+swank (char-code (read-char in nil #\Nul))
#-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
(loop (let ((byte (%read-byte)))
(cond ((<= 48 byte 57)
(return (- byte 48)))
((zerop byte) ; #\Nul
(error "Read EOF or #\Nul.")))))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/read-digit.lisp | lisp | #\Nul | (defpackage :cp/read-digit
(:use :cl)
(:export #:read-digit))
(in-package :cp/read-digit)
(declaim (ftype (function * (values (integer 0 9) &optional)) read-digit))
(defun read-digit (&optional (in *standard-input*))
"Reads a non-negative one-digit integer."
(macrolet ((%read-byte ()
`(the (unsigned-byte 8)
#+swank (char-code (read-char in nil #\Nul))
#-swank (sb-impl::ansi-stream-read-byte in nil #.(char-code #\Nul) nil))))
(loop (let ((byte (%read-byte)))
(cond ((<= 48 byte 57)
(return (- byte 48)))
(error "Read EOF or #\Nul.")))))))
|
dc2b5e33971dc838f7c115946f5f975c208004fcd4b3919a8a963bacd8312899 | cpeikert/Lol | PosBin.hs | |
Module : Crypto . Lol . PosBin
Description : Type - level positive naturals in and binary .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Positive naturals in and binary representations ,
singletonized and promoted to the type level . This module relies
on Template Haskell , so parts of the documentation may be difficult
to read . See source - level comments for further details .
Module : Crypto.Lol.PosBin
Description : Type-level positive naturals in Peano and binary.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Positive naturals in Peano and binary representations,
singletonized and promoted to the type level. This module relies
on Template Haskell, so parts of the documentation may be difficult
to read. See source-level comments for further details.
-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE TemplateHaskell #
module Crypto.Lol.PosBin
( module Crypto.Lol.PosBinDefs
* Convenient synonyms for ' Pos ' and ' ' types
, module Crypto.Lol.PosBin
) where
import Crypto.Lol.PosBinDefs
$(mapM posDec [1..64])
$(mapM binDec [1..128])
| null | https://raw.githubusercontent.com/cpeikert/Lol/4416ac4f03b0bff08cb1115c72a45eed1fa48ec3/lol/Crypto/Lol/PosBin.hs | haskell | # LANGUAGE DataKinds # | |
Module : Crypto . Lol . PosBin
Description : Type - level positive naturals in and binary .
Copyright : ( c ) , 2011 - 2017
, 2011 - 2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Positive naturals in and binary representations ,
singletonized and promoted to the type level . This module relies
on Template Haskell , so parts of the documentation may be difficult
to read . See source - level comments for further details .
Module : Crypto.Lol.PosBin
Description : Type-level positive naturals in Peano and binary.
Copyright : (c) Eric Crockett, 2011-2017
Chris Peikert, 2011-2017
License : GPL-3
Maintainer :
Stability : experimental
Portability : POSIX
Positive naturals in Peano and binary representations,
singletonized and promoted to the type level. This module relies
on Template Haskell, so parts of the documentation may be difficult
to read. See source-level comments for further details.
-}
# LANGUAGE TemplateHaskell #
module Crypto.Lol.PosBin
( module Crypto.Lol.PosBinDefs
* Convenient synonyms for ' Pos ' and ' ' types
, module Crypto.Lol.PosBin
) where
import Crypto.Lol.PosBinDefs
$(mapM posDec [1..64])
$(mapM binDec [1..128])
|
1b93250677c66f502f8ecd2272819b422de8ed9b983409d9f2398b8dcd6e404d | scrintal/heroicons-reagent | document_arrow_up.cljs | (ns com.scrintal.heroicons.outline.document-arrow-up)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m6.75 12l-3-3m0 0l-3 3m3-3v6m-1.5-15H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/outline/document_arrow_up.cljs | clojure | (ns com.scrintal.heroicons.outline.document-arrow-up)
(defn render []
[:svg {:xmlns ""
:fill "none"
:viewBox "0 0 24 24"
:strokeWidth "1.5"
:stroke "currentColor"
:aria-hidden "true"}
[:path {:strokeLinecap "round"
:strokeLinejoin "round"
:d "M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m6.75 12l-3-3m0 0l-3 3m3-3v6m-1.5-15H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"}]]) | |
55a3fdab4598f268fb8049b3fbaad6891759c91e668fc0acf6a3ba0ffcf22431 | ds-wizard/engine-backend | Number.hs | module Shared.Util.Number where
import System.Random
generateInt :: Int -> IO Int
generateInt max = do
number <- randomIO
return $ number `mod` max
generateIntInRange :: Int -> Int -> IO Int
generateIntInRange min max = randomRIO (min, max)
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/8f2fadd4a0dae84eb1f5f09230c4c5b58ac3e18d/engine-shared/src/Shared/Util/Number.hs | haskell | module Shared.Util.Number where
import System.Random
generateInt :: Int -> IO Int
generateInt max = do
number <- randomIO
return $ number `mod` max
generateIntInRange :: Int -> Int -> IO Int
generateIntInRange min max = randomRIO (min, max)
| |
9a4788a6083f62258042eaca79eee161b69670ff90d69c1e51f396992bc4bf7b | brendanhay/gogol | Product.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . OSLogin . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
module Gogol.OSLogin.Internal.Product
( -- * Empty
Empty (..),
newEmpty,
* ImportSshPublicKeyResponse
ImportSshPublicKeyResponse (..),
newImportSshPublicKeyResponse,
-- * LoginProfile
LoginProfile (..),
newLoginProfile,
-- * LoginProfile_SshPublicKeys
LoginProfile_SshPublicKeys (..),
newLoginProfile_SshPublicKeys,
-- * PosixAccount
PosixAccount (..),
newPosixAccount,
* SshPublicKey
SshPublicKey (..),
newSshPublicKey,
)
where
import Gogol.OSLogin.Internal.Sum
import qualified Gogol.Prelude as Core
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
--
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
| A response message for importing an SSH public key .
--
-- /See:/ 'newImportSshPublicKeyResponse' smart constructor.
data ImportSshPublicKeyResponse = ImportSshPublicKeyResponse
{ -- | Detailed information about import results.
details :: (Core.Maybe Core.Text),
-- | The login profile information for the user.
loginProfile :: (Core.Maybe LoginProfile)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ImportSshPublicKeyResponse ' with the minimum fields required to make a request .
newImportSshPublicKeyResponse ::
ImportSshPublicKeyResponse
newImportSshPublicKeyResponse =
ImportSshPublicKeyResponse
{ details = Core.Nothing,
loginProfile = Core.Nothing
}
instance Core.FromJSON ImportSshPublicKeyResponse where
parseJSON =
Core.withObject
"ImportSshPublicKeyResponse"
( \o ->
ImportSshPublicKeyResponse
Core.<$> (o Core..:? "details")
Core.<*> (o Core..:? "loginProfile")
)
instance Core.ToJSON ImportSshPublicKeyResponse where
toJSON ImportSshPublicKeyResponse {..} =
Core.object
( Core.catMaybes
[ ("details" Core..=) Core.<$> details,
("loginProfile" Core..=) Core.<$> loginProfile
]
)
| The user profile information used for logging in to a virtual machine on Google Compute Engine .
--
-- /See:/ 'newLoginProfile' smart constructor.
data LoginProfile = LoginProfile
{ -- | Required. A unique user ID.
name :: (Core.Maybe Core.Text),
-- | The list of POSIX accounts associated with the user.
posixAccounts :: (Core.Maybe [PosixAccount]),
| A map from SSH public key fingerprint to the associated key object .
sshPublicKeys :: (Core.Maybe LoginProfile_SshPublicKeys)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' LoginProfile ' with the minimum fields required to make a request .
newLoginProfile ::
LoginProfile
newLoginProfile =
LoginProfile
{ name = Core.Nothing,
posixAccounts = Core.Nothing,
sshPublicKeys = Core.Nothing
}
instance Core.FromJSON LoginProfile where
parseJSON =
Core.withObject
"LoginProfile"
( \o ->
LoginProfile
Core.<$> (o Core..:? "name")
Core.<*> (o Core..:? "posixAccounts")
Core.<*> (o Core..:? "sshPublicKeys")
)
instance Core.ToJSON LoginProfile where
toJSON LoginProfile {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("posixAccounts" Core..=) Core.<$> posixAccounts,
("sshPublicKeys" Core..=) Core.<$> sshPublicKeys
]
)
| A map from SSH public key fingerprint to the associated key object .
--
-- /See:/ 'newLoginProfile_SshPublicKeys' smart constructor.
newtype LoginProfile_SshPublicKeys = LoginProfile_SshPublicKeys
{ -- |
additional :: (Core.HashMap Core.Text SshPublicKey)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'LoginProfile_SshPublicKeys' with the minimum fields required to make a request.
newLoginProfile_SshPublicKeys ::
-- | See 'additional'.
Core.HashMap Core.Text SshPublicKey ->
LoginProfile_SshPublicKeys
newLoginProfile_SshPublicKeys additional =
LoginProfile_SshPublicKeys {additional = additional}
instance Core.FromJSON LoginProfile_SshPublicKeys where
parseJSON =
Core.withObject
"LoginProfile_SshPublicKeys"
( \o ->
LoginProfile_SshPublicKeys
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON LoginProfile_SshPublicKeys where
toJSON LoginProfile_SshPublicKeys {..} =
Core.toJSON additional
| The POSIX account information associated with a Google account .
--
-- /See:/ 'newPosixAccount' smart constructor.
data PosixAccount = PosixAccount
{ -- | Output only. A POSIX account identifier.
accountId :: (Core.Maybe Core.Text),
-- | The GECOS (user information) entry for this account.
gecos :: (Core.Maybe Core.Text),
-- | The default group ID.
gid :: (Core.Maybe Core.Int64),
-- | The path to the home directory for this account.
homeDirectory :: (Core.Maybe Core.Text),
-- | Output only. The canonical resource name.
name :: (Core.Maybe Core.Text),
-- | The operating system type where this account applies.
operatingSystemType :: (Core.Maybe PosixAccount_OperatingSystemType),
| Only one POSIX account can be marked as primary .
primary :: (Core.Maybe Core.Bool),
-- | The path to the logic shell for this account.
shell :: (Core.Maybe Core.Text),
| System identifier for which account the username or uid applies to . By default , the empty value is used .
systemId :: (Core.Maybe Core.Text),
-- | The user ID.
uid :: (Core.Maybe Core.Int64),
-- | The username of the POSIX account.
username :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' PosixAccount ' with the minimum fields required to make a request .
newPosixAccount ::
PosixAccount
newPosixAccount =
PosixAccount
{ accountId = Core.Nothing,
gecos = Core.Nothing,
gid = Core.Nothing,
homeDirectory = Core.Nothing,
name = Core.Nothing,
operatingSystemType = Core.Nothing,
primary = Core.Nothing,
shell = Core.Nothing,
systemId = Core.Nothing,
uid = Core.Nothing,
username = Core.Nothing
}
instance Core.FromJSON PosixAccount where
parseJSON =
Core.withObject
"PosixAccount"
( \o ->
PosixAccount
Core.<$> (o Core..:? "accountId")
Core.<*> (o Core..:? "gecos")
Core.<*> (o Core..:? "gid" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "homeDirectory")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "operatingSystemType")
Core.<*> (o Core..:? "primary")
Core.<*> (o Core..:? "shell")
Core.<*> (o Core..:? "systemId")
Core.<*> (o Core..:? "uid" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "username")
)
instance Core.ToJSON PosixAccount where
toJSON PosixAccount {..} =
Core.object
( Core.catMaybes
[ ("accountId" Core..=) Core.<$> accountId,
("gecos" Core..=) Core.<$> gecos,
("gid" Core..=) Core.. Core.AsText Core.<$> gid,
("homeDirectory" Core..=) Core.<$> homeDirectory,
("name" Core..=) Core.<$> name,
("operatingSystemType" Core..=)
Core.<$> operatingSystemType,
("primary" Core..=) Core.<$> primary,
("shell" Core..=) Core.<$> shell,
("systemId" Core..=) Core.<$> systemId,
("uid" Core..=) Core.. Core.AsText Core.<$> uid,
("username" Core..=) Core.<$> username
]
)
| The SSH public key information associated with a Google account .
--
-- /See:/ 'newSshPublicKey' smart constructor.
data SshPublicKey = SshPublicKey
{ -- | An expiration time in microseconds since epoch.
expirationTimeUsec :: (Core.Maybe Core.Int64),
| Output only . The SHA-256 fingerprint of the SSH public key .
fingerprint :: (Core.Maybe Core.Text),
| Public key text in SSH format , defined by RFC4253 section 6.6 .
key :: (Core.Maybe Core.Text),
-- | Output only. The canonical resource name.
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'SshPublicKey' with the minimum fields required to make a request.
newSshPublicKey ::
SshPublicKey
newSshPublicKey =
SshPublicKey
{ expirationTimeUsec = Core.Nothing,
fingerprint = Core.Nothing,
key = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON SshPublicKey where
parseJSON =
Core.withObject
"SshPublicKey"
( \o ->
SshPublicKey
Core.<$> ( o Core..:? "expirationTimeUsec"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "fingerprint")
Core.<*> (o Core..:? "key")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON SshPublicKey where
toJSON SshPublicKey {..} =
Core.object
( Core.catMaybes
[ ("expirationTimeUsec" Core..=) Core.. Core.AsText
Core.<$> expirationTimeUsec,
("fingerprint" Core..=) Core.<$> fingerprint,
("key" Core..=) Core.<$> key,
("name" Core..=) Core.<$> name
]
)
| null | https://raw.githubusercontent.com/brendanhay/gogol/8cbceeaaba36a3c08712b2e272606161500fbe91/lib/services/gogol-oslogin/gen/Gogol/OSLogin/Internal/Product.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
* Empty
* LoginProfile
* LoginProfile_SshPublicKeys
* PosixAccount
| Creates a value of 'Empty' with the minimum fields required to make a request.
/See:/ 'newImportSshPublicKeyResponse' smart constructor.
| Detailed information about import results.
| The login profile information for the user.
/See:/ 'newLoginProfile' smart constructor.
| Required. A unique user ID.
| The list of POSIX accounts associated with the user.
/See:/ 'newLoginProfile_SshPublicKeys' smart constructor.
|
| Creates a value of 'LoginProfile_SshPublicKeys' with the minimum fields required to make a request.
| See 'additional'.
/See:/ 'newPosixAccount' smart constructor.
| Output only. A POSIX account identifier.
| The GECOS (user information) entry for this account.
| The default group ID.
| The path to the home directory for this account.
| Output only. The canonical resource name.
| The operating system type where this account applies.
| The path to the logic shell for this account.
| The user ID.
| The username of the POSIX account.
/See:/ 'newSshPublicKey' smart constructor.
| An expiration time in microseconds since epoch.
| Output only. The canonical resource name.
| Creates a value of 'SshPublicKey' with the minimum fields required to make a request. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . OSLogin . Internal . Product
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.OSLogin.Internal.Product
Empty (..),
newEmpty,
* ImportSshPublicKeyResponse
ImportSshPublicKeyResponse (..),
newImportSshPublicKeyResponse,
LoginProfile (..),
newLoginProfile,
LoginProfile_SshPublicKeys (..),
newLoginProfile_SshPublicKeys,
PosixAccount (..),
newPosixAccount,
* SshPublicKey
SshPublicKey (..),
newSshPublicKey,
)
where
import Gogol.OSLogin.Internal.Sum
import qualified Gogol.Prelude as Core
| A generic empty message that you can re - use to avoid defining duplicated empty messages in your APIs . A typical example is to use it as the request or the response type of an API method . For instance : service Foo { rpc Bar(google.protobuf . Empty ) returns ( google.protobuf . Empty ) ; } The JSON representation for @Empty@ is empty JSON object @{}@.
/See:/ ' ' smart constructor .
data Empty = Empty
deriving (Core.Eq, Core.Show, Core.Generic)
newEmpty ::
Empty
newEmpty = Empty
instance Core.FromJSON Empty where
parseJSON =
Core.withObject "Empty" (\o -> Core.pure Empty)
instance Core.ToJSON Empty where
toJSON = Core.const Core.emptyObject
| A response message for importing an SSH public key .
data ImportSshPublicKeyResponse = ImportSshPublicKeyResponse
details :: (Core.Maybe Core.Text),
loginProfile :: (Core.Maybe LoginProfile)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' ImportSshPublicKeyResponse ' with the minimum fields required to make a request .
newImportSshPublicKeyResponse ::
ImportSshPublicKeyResponse
newImportSshPublicKeyResponse =
ImportSshPublicKeyResponse
{ details = Core.Nothing,
loginProfile = Core.Nothing
}
instance Core.FromJSON ImportSshPublicKeyResponse where
parseJSON =
Core.withObject
"ImportSshPublicKeyResponse"
( \o ->
ImportSshPublicKeyResponse
Core.<$> (o Core..:? "details")
Core.<*> (o Core..:? "loginProfile")
)
instance Core.ToJSON ImportSshPublicKeyResponse where
toJSON ImportSshPublicKeyResponse {..} =
Core.object
( Core.catMaybes
[ ("details" Core..=) Core.<$> details,
("loginProfile" Core..=) Core.<$> loginProfile
]
)
| The user profile information used for logging in to a virtual machine on Google Compute Engine .
data LoginProfile = LoginProfile
name :: (Core.Maybe Core.Text),
posixAccounts :: (Core.Maybe [PosixAccount]),
| A map from SSH public key fingerprint to the associated key object .
sshPublicKeys :: (Core.Maybe LoginProfile_SshPublicKeys)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' LoginProfile ' with the minimum fields required to make a request .
newLoginProfile ::
LoginProfile
newLoginProfile =
LoginProfile
{ name = Core.Nothing,
posixAccounts = Core.Nothing,
sshPublicKeys = Core.Nothing
}
instance Core.FromJSON LoginProfile where
parseJSON =
Core.withObject
"LoginProfile"
( \o ->
LoginProfile
Core.<$> (o Core..:? "name")
Core.<*> (o Core..:? "posixAccounts")
Core.<*> (o Core..:? "sshPublicKeys")
)
instance Core.ToJSON LoginProfile where
toJSON LoginProfile {..} =
Core.object
( Core.catMaybes
[ ("name" Core..=) Core.<$> name,
("posixAccounts" Core..=) Core.<$> posixAccounts,
("sshPublicKeys" Core..=) Core.<$> sshPublicKeys
]
)
| A map from SSH public key fingerprint to the associated key object .
newtype LoginProfile_SshPublicKeys = LoginProfile_SshPublicKeys
additional :: (Core.HashMap Core.Text SshPublicKey)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLoginProfile_SshPublicKeys ::
Core.HashMap Core.Text SshPublicKey ->
LoginProfile_SshPublicKeys
newLoginProfile_SshPublicKeys additional =
LoginProfile_SshPublicKeys {additional = additional}
instance Core.FromJSON LoginProfile_SshPublicKeys where
parseJSON =
Core.withObject
"LoginProfile_SshPublicKeys"
( \o ->
LoginProfile_SshPublicKeys
Core.<$> (Core.parseJSONObject o)
)
instance Core.ToJSON LoginProfile_SshPublicKeys where
toJSON LoginProfile_SshPublicKeys {..} =
Core.toJSON additional
| The POSIX account information associated with a Google account .
data PosixAccount = PosixAccount
accountId :: (Core.Maybe Core.Text),
gecos :: (Core.Maybe Core.Text),
gid :: (Core.Maybe Core.Int64),
homeDirectory :: (Core.Maybe Core.Text),
name :: (Core.Maybe Core.Text),
operatingSystemType :: (Core.Maybe PosixAccount_OperatingSystemType),
| Only one POSIX account can be marked as primary .
primary :: (Core.Maybe Core.Bool),
shell :: (Core.Maybe Core.Text),
| System identifier for which account the username or uid applies to . By default , the empty value is used .
systemId :: (Core.Maybe Core.Text),
uid :: (Core.Maybe Core.Int64),
username :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
| Creates a value of ' PosixAccount ' with the minimum fields required to make a request .
newPosixAccount ::
PosixAccount
newPosixAccount =
PosixAccount
{ accountId = Core.Nothing,
gecos = Core.Nothing,
gid = Core.Nothing,
homeDirectory = Core.Nothing,
name = Core.Nothing,
operatingSystemType = Core.Nothing,
primary = Core.Nothing,
shell = Core.Nothing,
systemId = Core.Nothing,
uid = Core.Nothing,
username = Core.Nothing
}
instance Core.FromJSON PosixAccount where
parseJSON =
Core.withObject
"PosixAccount"
( \o ->
PosixAccount
Core.<$> (o Core..:? "accountId")
Core.<*> (o Core..:? "gecos")
Core.<*> (o Core..:? "gid" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "homeDirectory")
Core.<*> (o Core..:? "name")
Core.<*> (o Core..:? "operatingSystemType")
Core.<*> (o Core..:? "primary")
Core.<*> (o Core..:? "shell")
Core.<*> (o Core..:? "systemId")
Core.<*> (o Core..:? "uid" Core.<&> Core.fmap Core.fromAsText)
Core.<*> (o Core..:? "username")
)
instance Core.ToJSON PosixAccount where
toJSON PosixAccount {..} =
Core.object
( Core.catMaybes
[ ("accountId" Core..=) Core.<$> accountId,
("gecos" Core..=) Core.<$> gecos,
("gid" Core..=) Core.. Core.AsText Core.<$> gid,
("homeDirectory" Core..=) Core.<$> homeDirectory,
("name" Core..=) Core.<$> name,
("operatingSystemType" Core..=)
Core.<$> operatingSystemType,
("primary" Core..=) Core.<$> primary,
("shell" Core..=) Core.<$> shell,
("systemId" Core..=) Core.<$> systemId,
("uid" Core..=) Core.. Core.AsText Core.<$> uid,
("username" Core..=) Core.<$> username
]
)
| The SSH public key information associated with a Google account .
data SshPublicKey = SshPublicKey
expirationTimeUsec :: (Core.Maybe Core.Int64),
| Output only . The SHA-256 fingerprint of the SSH public key .
fingerprint :: (Core.Maybe Core.Text),
| Public key text in SSH format , defined by RFC4253 section 6.6 .
key :: (Core.Maybe Core.Text),
name :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newSshPublicKey ::
SshPublicKey
newSshPublicKey =
SshPublicKey
{ expirationTimeUsec = Core.Nothing,
fingerprint = Core.Nothing,
key = Core.Nothing,
name = Core.Nothing
}
instance Core.FromJSON SshPublicKey where
parseJSON =
Core.withObject
"SshPublicKey"
( \o ->
SshPublicKey
Core.<$> ( o Core..:? "expirationTimeUsec"
Core.<&> Core.fmap Core.fromAsText
)
Core.<*> (o Core..:? "fingerprint")
Core.<*> (o Core..:? "key")
Core.<*> (o Core..:? "name")
)
instance Core.ToJSON SshPublicKey where
toJSON SshPublicKey {..} =
Core.object
( Core.catMaybes
[ ("expirationTimeUsec" Core..=) Core.. Core.AsText
Core.<$> expirationTimeUsec,
("fingerprint" Core..=) Core.<$> fingerprint,
("key" Core..=) Core.<$> key,
("name" Core..=) Core.<$> name
]
)
|
b273b1da72d29c5a74823f200dfef5859d1f7de33c2071131a1df67dd2716647 | 2600hz/kazoo | props_tests.erl | %%%-----------------------------------------------------------------------------
( C ) 2010 - 2020 , 2600Hz
@doc Mostly a drop - in replacement and extension of the proplists module ,
%%% but using the lists module to implement
%%%
@author
@author
%%%
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(props_tests).
-ifdef(PROPER).
-include_lib("proper/include/proper.hrl").
-include_lib("kazoo_stdlib/include/kz_types.hrl").
-endif.
-include_lib("eunit/include/eunit.hrl").
filter_test_() ->
Fun = fun({_, V}) -> V < 5 end,
[?_assertEqual([], props:filter(Fun, []))
,?_assertEqual([], props:filter(Fun, [{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'z', 1}], props:filter(Fun, [{'a', 10}, {'b', 8}, {'c', 6}, {'z', 1}]))
].
filter_empty_test_() ->
[?_assertEqual([], props:filter_empty([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_empty([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([], props:filter_empty([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual(['a'], props:filter_empty(['a']))
,?_assertEqual(['a'], props:filter_empty(['a', {'b', 0}]))
,?_assertEqual([], props:filter_empty([{<<"a">>, 'undefined'}]))
,?_assertEqual([{<<"a">>, 'false'}], props:filter_empty([{<<"a">>, 'false'}]))
,?_assertEqual([{<<"a">>, 'true'}], props:filter_empty([{<<"a">>, 'true'}]))
].
filter_empty_strings_test_() ->
[?_assertEqual([], props:filter_empty_strings([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_empty_strings([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'a', 0}, {'b', []}, {'z', 'undefined'}], props:filter_empty_strings([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual(['a'], props:filter_empty_strings(['a']))
,?_assertEqual(['a', {'b', 0}], props:filter_empty_strings(['a', {'b', 0}]))
,?_assertEqual([{<<"a">>, 'undefined'}], props:filter_empty_strings([{<<"a">>, 'undefined'}]))
,?_assertEqual([{<<"a">>, 'false'}], props:filter_empty_strings([{<<"a">>, 'false'}]))
,?_assertEqual([{<<"a">>, 'true'}], props:filter_empty_strings([{<<"a">>, 'true'}]))
].
filter_undefined_test_() ->
[?_assertEqual(['a'], props:filter_undefined(['a']))
,?_assertEqual([], props:filter_undefined([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_undefined([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'a', 0}, {'b', []}, {'c', <<>>}], props:filter_undefined([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual([{<<"pouet">>, 'null'}], props:filter_undefined([{<<"pouet">>, 'null'}]))
].
unique_test_() ->
L = [{'a', 'b'}, {'a', 'b'}, {'a', 'c'}, {'b','c'}, {'b','d'}],
[?_assertEqual([{'a', 'b'}, {'b', 'c'}], props:unique(L))
,?_assertEqual([], props:unique([]))
,?_assertEqual([{module_name, <<"my_module">>}]
,props:unique([{module_name, <<"my_module">>}
,{module_name, <<"blaaa">>}
,{module_name, false}
])
)
].
delete_test_() ->
L = [{'a', 1}, {'b', 2}, 'c', {'d', 3}],
[?_assertEqual(L, props:delete('foo', L))
,?_assertEqual([{'a', 1}, {'b', 2}, {'d', 3}], props:delete('c', L))
,?_assertEqual([{'a', 1}, 'c', {'d', 3}], props:delete('b', L))
].
insert_value_test_() ->
P = [{'a', 1}, {'b', 2}],
P1 = props:insert_value('a', 2, P),
P2 = props:insert_value({'b', '3'}, P),
P3 = props:insert_value('c', 3, P),
P4 = props:insert_value('d', P),
[?_assertEqual(1, props:get_value('a', P1))
,?_assertEqual(2, props:get_value('b', P2))
,?_assertEqual(3, props:get_value('c', P3))
,?_assertEqual('true', props:get_value('d', P4))
].
insert_values_test_() ->
P = [{'a', 1}, {'b', 2}],
KVs = [{'a', 2}, {'b', 3}, {'c', 3}, 'd'],
P1 = props:insert_values(KVs, P),
[?_assertEqual(1, props:get_value('a', P1))
,?_assertEqual(2, props:get_value('b', P1))
,?_assertEqual(3, props:get_value('c', P1))
,?_assertEqual('true', props:get_value('d', P1))
].
take_value_test_() ->
P = [{'a', 1}, {'b', 2}],
[?_assertEqual({1, [{'b', 2}]}, props:take_value('a', P))
,?_assertEqual({2, [{'a', 1}]}, props:take_value('b', P))
,?_assertEqual({'undefined', [{'a', 1}, {'b', 2}]}, props:take_value('c', P))
,?_assertEqual({4, [{'a', 1}, {'b', 2}]}, props:take_value('d', P, 4))
].
is_defined_test_() ->
Tests = [{[], 'foo', 'false'}
,{['foo'], 'foo', 'true'}
,{['foo'], 'bar', 'false'}
,{[{'foo', 'bar'}], 'foo', 'true'}
,{[{'foo', 'bar'}], 'bar', 'false'}
],
[?_assertEqual(Expected, props:is_defined(Key, Props))
|| {Props, Key, Expected} <- Tests
].
bools_test_() ->
Props1 = [{key, undefined}],
Props2 = [{key, <<"undefined">>}],
Props3 = [{key, <<"false">>}],
Props4 = [{key, false}],
Props5 = [{key, <<"true">>}],
Props6 = [{key, true}],
[?_assertEqual(undefined, props:is_true(key, []))
,?_assertEqual(undefined, props:is_true(key, Props1))
,?_assertEqual(false, props:is_true(key, Props2))
,?_assertEqual(false, props:is_true(key, Props3))
,?_assertEqual(false, props:is_true(key, Props4))
,?_assertEqual(true, props:is_true(key, Props5))
,?_assertEqual(true, props:is_true(key, Props6))
,?_assertEqual(undefined, props:is_false(key, []))
,?_assertEqual(undefined, props:is_false(key, Props1))
,?_assertEqual(false, props:is_false(key, Props2))
,?_assertEqual(true, props:is_false(key, Props3))
,?_assertEqual(true, props:is_false(key, Props4))
,?_assertEqual(false, props:is_false(key, Props5))
,?_assertEqual(false, props:is_false(key, Props6))
].
-ifdef(PROPER).
run_proper_test_() ->
{"Runs props PropEr tests"
,[{'timeout'
,10000
,{atom_to_list(F)
,fun() ->
?assert(proper:quickcheck(?MODULE:F(), [{'to_file', 'user'}, 500]))
end
}
}
|| {F, 0} <- ?MODULE:module_info('exports'),
F > 'prop_',
F < 'prop`'
]
}.
prop_set_value() ->
?FORALL({KV, Before, After}
,{test_property(), test_proplist(), test_proplist()}
,?WHENFAIL(?debugFmt("failed: props:is_defined(~p, ~p ++ props:set_value(~p, ~p)).~n", [KV, Before, KV, After])
,props:is_defined(KV, Before ++ props:set_value(KV, After))
)
).
prop_set_values() ->
?FORALL({KVs, Before, After}
,{unique_proplist(), test_proplist(), test_proplist()}
,?WHENFAIL(?debugFmt("Props = ~p ++ props:set_values(~p, ~p)~n", [Before, KVs, After])
,begin
Props = Before ++ props:set_values(KVs, After),
lists:all(fun(KV) -> props:is_defined(KV, Props) end
,KVs
)
end
)
).
prop_get_value() ->
?FORALL({Props, KV}
,test_proplist_and_kv()
,begin
K = case is_tuple(KV) of 'true' -> element(1, KV); 'false' -> KV end,
V = case is_tuple(KV) of 'true' -> element(2, KV); 'false' -> 'true' end,
?WHENFAIL(?debugFmt("~p = props:get_value(~p, ~p).~n"
,[V, K, Props]
)
,V =:= props:get_value(K, Props)
)
end
).
prop_is_defined() ->
?FORALL({Props, Existing, NonExisting}
,test_proplist_and_keys()
,?WHENFAIL(?debugFmt("exists props:is_defined(~p, ~p)~nnot props:is_defined(~p, ~p)~n"
,[Existing, Props, NonExisting, Props]
)
,props:is_defined(Existing, Props)
andalso 'false' =:= props:is_defined(NonExisting, Props)
)
).
test_proplist() ->
list(test_property()).
test_property() ->
oneof([atom()
,{test_key(), test_value()}
]).
%% TODO: generate recursive proplists and key paths to test get/set on nested proplists
test_value() -> any().
test_key() ->
oneof([atom(), binary()]).
test_proplist_and_kv() ->
?LET(Props
,?SUCHTHAT(UniqueProps
,unique_proplist()
,is_list(UniqueProps)
)
,{Props, elements(Props)}
).
unique_proplist() ->
?LET(GenProps, non_empty(test_proplist()), props:unique(GenProps)).
test_proplist_and_keys() ->
?LET(Props
,?SUCHTHAT(UniqueProps
,?LET(GenProps, non_empty(test_proplist()), props:unique(GenProps))
,is_list(UniqueProps)
)
,{Props, element_of(Props), not_oneof(Props)}
).
element_of(Props) ->
element_of(Props, rand:uniform()).
element_of([K], _) -> as_key(K);
element_of([K|_], Rand) when Rand < 0.5 -> as_key(K);
element_of([_|Rest], _) -> element_of(Rest, rand:uniform()).
as_key(A) when is_atom(A) -> A;
as_key({K, _}) -> K.
not_oneof(Props) ->
?LET(K
,test_key()
,(not lists:member(K, Props))
andalso ('false' =:= lists:keyfind(K, 1, Props))
).
-endif.
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_stdlib/test/props_tests.erl | erlang | -----------------------------------------------------------------------------
but using the lists module to implement
@end
-----------------------------------------------------------------------------
TODO: generate recursive proplists and key paths to test get/set on nested proplists | ( C ) 2010 - 2020 , 2600Hz
@doc Mostly a drop - in replacement and extension of the proplists module ,
@author
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(props_tests).
-ifdef(PROPER).
-include_lib("proper/include/proper.hrl").
-include_lib("kazoo_stdlib/include/kz_types.hrl").
-endif.
-include_lib("eunit/include/eunit.hrl").
filter_test_() ->
Fun = fun({_, V}) -> V < 5 end,
[?_assertEqual([], props:filter(Fun, []))
,?_assertEqual([], props:filter(Fun, [{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'z', 1}], props:filter(Fun, [{'a', 10}, {'b', 8}, {'c', 6}, {'z', 1}]))
].
filter_empty_test_() ->
[?_assertEqual([], props:filter_empty([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_empty([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([], props:filter_empty([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual(['a'], props:filter_empty(['a']))
,?_assertEqual(['a'], props:filter_empty(['a', {'b', 0}]))
,?_assertEqual([], props:filter_empty([{<<"a">>, 'undefined'}]))
,?_assertEqual([{<<"a">>, 'false'}], props:filter_empty([{<<"a">>, 'false'}]))
,?_assertEqual([{<<"a">>, 'true'}], props:filter_empty([{<<"a">>, 'true'}]))
].
filter_empty_strings_test_() ->
[?_assertEqual([], props:filter_empty_strings([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_empty_strings([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'a', 0}, {'b', []}, {'z', 'undefined'}], props:filter_empty_strings([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual(['a'], props:filter_empty_strings(['a']))
,?_assertEqual(['a', {'b', 0}], props:filter_empty_strings(['a', {'b', 0}]))
,?_assertEqual([{<<"a">>, 'undefined'}], props:filter_empty_strings([{<<"a">>, 'undefined'}]))
,?_assertEqual([{<<"a">>, 'false'}], props:filter_empty_strings([{<<"a">>, 'false'}]))
,?_assertEqual([{<<"a">>, 'true'}], props:filter_empty_strings([{<<"a">>, 'true'}]))
].
filter_undefined_test_() ->
[?_assertEqual(['a'], props:filter_undefined(['a']))
,?_assertEqual([], props:filter_undefined([]))
,?_assertEqual([{'a', 10}, {'b', 8}, {'c', 6}], props:filter_undefined([{'a', 10}, {'b', 8}, {'c', 6}]))
,?_assertEqual([{'a', 0}, {'b', []}, {'c', <<>>}], props:filter_undefined([{'a', 0}, {'b', []}, {'c', <<>>}, {'z', 'undefined'}]))
,?_assertEqual([{<<"pouet">>, 'null'}], props:filter_undefined([{<<"pouet">>, 'null'}]))
].
unique_test_() ->
L = [{'a', 'b'}, {'a', 'b'}, {'a', 'c'}, {'b','c'}, {'b','d'}],
[?_assertEqual([{'a', 'b'}, {'b', 'c'}], props:unique(L))
,?_assertEqual([], props:unique([]))
,?_assertEqual([{module_name, <<"my_module">>}]
,props:unique([{module_name, <<"my_module">>}
,{module_name, <<"blaaa">>}
,{module_name, false}
])
)
].
delete_test_() ->
L = [{'a', 1}, {'b', 2}, 'c', {'d', 3}],
[?_assertEqual(L, props:delete('foo', L))
,?_assertEqual([{'a', 1}, {'b', 2}, {'d', 3}], props:delete('c', L))
,?_assertEqual([{'a', 1}, 'c', {'d', 3}], props:delete('b', L))
].
insert_value_test_() ->
P = [{'a', 1}, {'b', 2}],
P1 = props:insert_value('a', 2, P),
P2 = props:insert_value({'b', '3'}, P),
P3 = props:insert_value('c', 3, P),
P4 = props:insert_value('d', P),
[?_assertEqual(1, props:get_value('a', P1))
,?_assertEqual(2, props:get_value('b', P2))
,?_assertEqual(3, props:get_value('c', P3))
,?_assertEqual('true', props:get_value('d', P4))
].
insert_values_test_() ->
P = [{'a', 1}, {'b', 2}],
KVs = [{'a', 2}, {'b', 3}, {'c', 3}, 'd'],
P1 = props:insert_values(KVs, P),
[?_assertEqual(1, props:get_value('a', P1))
,?_assertEqual(2, props:get_value('b', P1))
,?_assertEqual(3, props:get_value('c', P1))
,?_assertEqual('true', props:get_value('d', P1))
].
take_value_test_() ->
P = [{'a', 1}, {'b', 2}],
[?_assertEqual({1, [{'b', 2}]}, props:take_value('a', P))
,?_assertEqual({2, [{'a', 1}]}, props:take_value('b', P))
,?_assertEqual({'undefined', [{'a', 1}, {'b', 2}]}, props:take_value('c', P))
,?_assertEqual({4, [{'a', 1}, {'b', 2}]}, props:take_value('d', P, 4))
].
is_defined_test_() ->
Tests = [{[], 'foo', 'false'}
,{['foo'], 'foo', 'true'}
,{['foo'], 'bar', 'false'}
,{[{'foo', 'bar'}], 'foo', 'true'}
,{[{'foo', 'bar'}], 'bar', 'false'}
],
[?_assertEqual(Expected, props:is_defined(Key, Props))
|| {Props, Key, Expected} <- Tests
].
bools_test_() ->
Props1 = [{key, undefined}],
Props2 = [{key, <<"undefined">>}],
Props3 = [{key, <<"false">>}],
Props4 = [{key, false}],
Props5 = [{key, <<"true">>}],
Props6 = [{key, true}],
[?_assertEqual(undefined, props:is_true(key, []))
,?_assertEqual(undefined, props:is_true(key, Props1))
,?_assertEqual(false, props:is_true(key, Props2))
,?_assertEqual(false, props:is_true(key, Props3))
,?_assertEqual(false, props:is_true(key, Props4))
,?_assertEqual(true, props:is_true(key, Props5))
,?_assertEqual(true, props:is_true(key, Props6))
,?_assertEqual(undefined, props:is_false(key, []))
,?_assertEqual(undefined, props:is_false(key, Props1))
,?_assertEqual(false, props:is_false(key, Props2))
,?_assertEqual(true, props:is_false(key, Props3))
,?_assertEqual(true, props:is_false(key, Props4))
,?_assertEqual(false, props:is_false(key, Props5))
,?_assertEqual(false, props:is_false(key, Props6))
].
-ifdef(PROPER).
run_proper_test_() ->
{"Runs props PropEr tests"
,[{'timeout'
,10000
,{atom_to_list(F)
,fun() ->
?assert(proper:quickcheck(?MODULE:F(), [{'to_file', 'user'}, 500]))
end
}
}
|| {F, 0} <- ?MODULE:module_info('exports'),
F > 'prop_',
F < 'prop`'
]
}.
prop_set_value() ->
?FORALL({KV, Before, After}
,{test_property(), test_proplist(), test_proplist()}
,?WHENFAIL(?debugFmt("failed: props:is_defined(~p, ~p ++ props:set_value(~p, ~p)).~n", [KV, Before, KV, After])
,props:is_defined(KV, Before ++ props:set_value(KV, After))
)
).
prop_set_values() ->
?FORALL({KVs, Before, After}
,{unique_proplist(), test_proplist(), test_proplist()}
,?WHENFAIL(?debugFmt("Props = ~p ++ props:set_values(~p, ~p)~n", [Before, KVs, After])
,begin
Props = Before ++ props:set_values(KVs, After),
lists:all(fun(KV) -> props:is_defined(KV, Props) end
,KVs
)
end
)
).
prop_get_value() ->
?FORALL({Props, KV}
,test_proplist_and_kv()
,begin
K = case is_tuple(KV) of 'true' -> element(1, KV); 'false' -> KV end,
V = case is_tuple(KV) of 'true' -> element(2, KV); 'false' -> 'true' end,
?WHENFAIL(?debugFmt("~p = props:get_value(~p, ~p).~n"
,[V, K, Props]
)
,V =:= props:get_value(K, Props)
)
end
).
prop_is_defined() ->
?FORALL({Props, Existing, NonExisting}
,test_proplist_and_keys()
,?WHENFAIL(?debugFmt("exists props:is_defined(~p, ~p)~nnot props:is_defined(~p, ~p)~n"
,[Existing, Props, NonExisting, Props]
)
,props:is_defined(Existing, Props)
andalso 'false' =:= props:is_defined(NonExisting, Props)
)
).
test_proplist() ->
list(test_property()).
test_property() ->
oneof([atom()
,{test_key(), test_value()}
]).
test_value() -> any().
test_key() ->
oneof([atom(), binary()]).
test_proplist_and_kv() ->
?LET(Props
,?SUCHTHAT(UniqueProps
,unique_proplist()
,is_list(UniqueProps)
)
,{Props, elements(Props)}
).
unique_proplist() ->
?LET(GenProps, non_empty(test_proplist()), props:unique(GenProps)).
test_proplist_and_keys() ->
?LET(Props
,?SUCHTHAT(UniqueProps
,?LET(GenProps, non_empty(test_proplist()), props:unique(GenProps))
,is_list(UniqueProps)
)
,{Props, element_of(Props), not_oneof(Props)}
).
element_of(Props) ->
element_of(Props, rand:uniform()).
element_of([K], _) -> as_key(K);
element_of([K|_], Rand) when Rand < 0.5 -> as_key(K);
element_of([_|Rest], _) -> element_of(Rest, rand:uniform()).
as_key(A) when is_atom(A) -> A;
as_key({K, _}) -> K.
not_oneof(Props) ->
?LET(K
,test_key()
,(not lists:member(K, Props))
andalso ('false' =:= lists:keyfind(K, 1, Props))
).
-endif.
|
4b494dc522e5b97b98f783df6c882e45b4cab2057b41b0d78a604cc1a05183b5 | mzp/coq-ruby | sos.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
type vname = string;;
type term =
| Zero
| Const of Num.num
| Var of vname
| Inv of term
| Opp of term
| Add of (term * term)
| Sub of (term * term)
| Mul of (term * term)
| Div of (term * term)
| Pow of (term * int)
type positivstellensatz =
Axiom_eq of int
| Axiom_le of int
| Axiom_lt of int
| Rational_eq of Num.num
| Rational_le of Num.num
| Rational_lt of Num.num
| Square of term
| Monoid of int list
| Eqmul of term * positivstellensatz
| Sum of positivstellensatz * positivstellensatz
| Product of positivstellensatz * positivstellensatz
type poly
val poly_isconst : poly -> bool
val poly_neg : poly -> poly
val poly_mul : poly -> poly -> poly
val poly_pow : poly -> int -> poly
val poly_const : Num.num -> poly
val poly_of_term : term -> poly
val term_of_poly : poly -> term
val term_of_sos : positivstellensatz * (Num.num * poly) list ->
positivstellensatz
val string_of_poly : poly -> string
exception TooDeep
val deepen_until : int -> (int -> 'a) -> int -> 'a
val real_positivnullstellensatz_general : bool -> int -> poly list ->
(poly * positivstellensatz) list ->
poly -> poly list * (positivstellensatz * (Num.num * poly) list) list
val sumofsquares : poly -> Num.num * ( Num.num * poly) list
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/contrib/micromega/sos.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
type vname = string;;
type term =
| Zero
| Const of Num.num
| Var of vname
| Inv of term
| Opp of term
| Add of (term * term)
| Sub of (term * term)
| Mul of (term * term)
| Div of (term * term)
| Pow of (term * int)
type positivstellensatz =
Axiom_eq of int
| Axiom_le of int
| Axiom_lt of int
| Rational_eq of Num.num
| Rational_le of Num.num
| Rational_lt of Num.num
| Square of term
| Monoid of int list
| Eqmul of term * positivstellensatz
| Sum of positivstellensatz * positivstellensatz
| Product of positivstellensatz * positivstellensatz
type poly
val poly_isconst : poly -> bool
val poly_neg : poly -> poly
val poly_mul : poly -> poly -> poly
val poly_pow : poly -> int -> poly
val poly_const : Num.num -> poly
val poly_of_term : term -> poly
val term_of_poly : poly -> term
val term_of_sos : positivstellensatz * (Num.num * poly) list ->
positivstellensatz
val string_of_poly : poly -> string
exception TooDeep
val deepen_until : int -> (int -> 'a) -> int -> 'a
val real_positivnullstellensatz_general : bool -> int -> poly list ->
(poly * positivstellensatz) list ->
poly -> poly list * (positivstellensatz * (Num.num * poly) list) list
val sumofsquares : poly -> Num.num * ( Num.num * poly) list
|
91a3b8e624034e728a4fb5eb7bd0663550e3c263ba87ee69526839423ac6e7df | MLstate/opalang | pass_SimplifyMagic.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 </>.
*)
(* depends *)
module Format = BaseFormat
module List = BaseList
(* shorthands *)
module Q = QmlAst
(* -- *)
type info = { strict : bool ; specialize : (Q.ty * Q.expr) list }
type env = info IdentMap.t
let (@) info1 info2 =
let strict = info1.strict || info2.strict in
let specialize = info1.specialize @ info2.specialize in
{
strict ;
specialize ;
}
let fold_expr f acc env =
IdentMap.fold (fun _ info acc ->
List.fold_left (fun acc (_,e) -> f acc e) acc info.specialize
) env acc
let fold_map_expr f acc env =
IdentMap.fold_map (
fun _ info acc ->
let acc, specialize =
List.fold_left_map (
fun acc (ty,e) ->
let acc, e = f acc e in
acc, (ty, e)
) acc info.specialize
in acc, {
info with
specialize
}
) env acc
let map_type f env =
IdentMap.map
(fun info ->
let specialize =
List.map
(fun (ty,e) ->
(f ty, e))
info.specialize
in
{
info with
specialize ;
}
) env
module S =
struct
type t = Q.annotmap * env
let pass = "pass_SimplifyMagic"
let pp f _ = Format.pp_print_string f "<dummy>"
end
module R =
struct
include ObjectFiles.Make(S)
let load annotmap (env:env) : S.t =
fold_with_name
(fun package (annotmap,(env:env)) (annotmap_old,old_env) ->
let annotmap_old = QmlRefresh.refresh_annotmap package annotmap_old in
let annotmap, old_env = fold_map_expr (QmlRefresh.refresh_expr package ~annotmap_old) annotmap old_env in
let old_env = map_type (QmlRefresh.refresh_typevars_from_ty package) old_env in
let env = IdentMap.merge (@) env old_env in
annotmap, env
) (annotmap,env)
let save annotmap env =
let small_annotmap = QmlRefresh.restrict_annotmap_fold_expr fold_expr annotmap env in
save (small_annotmap,env)
end
let is_monomorphic ty =
not (
QmlAstWalk.Type.exists
(function
FIXME : actually , we should check for rowvars and colvars also
| _ -> false) ty
)
let build_env env gamma annotmap code =
let _, code as result =
QmlAstWalk.CodeExpr.fold_map_name_expr
(fun (env,annotmap) (ident,expr) ->
match expr with
| Q.Directive (_, `specialize variant, inner_expr :: l, _) ->
(* we refuse polymorphic types for now
* or else we might create troubles with ei *)
let general_type = QmlAnnotMap.find_ty (Q.QAnnot.expr inner_expr) annotmap in
let l =
let specialize = List.map (fun e ->
let ty = QmlAnnotMap.find_ty (Q.QAnnot.expr e) annotmap in
if not (is_monomorphic ty) then
OManager.serror "%a@\n This expression shouldn't contain type variables@."
FilePos.pp_pos (Q.Pos.expr e)
else (
(* should check that ty is an instance of general_type
* but since ty is monomorphic, checking the unifiability is equivalent *)
if not (QmlMoreTypes.unifiable ~gamma general_type ty) then
OManager.serror "%a@\n This expression's type should be an instance of the generic expression's type.@."
FilePos.pp_pos (Q.Pos.expr e)
);
ty, e) l in
let strict = variant = `strict in
{
strict ;
specialize ;
}
in
let env = IdentMap.update_default ident ((@) l) l env in
let tsc = QmlAnnotMap.find_tsc_opt (Q.QAnnot.expr expr) annotmap in
let annotmap = QmlAnnotMap.add_tsc_opt (Q.QAnnot.expr inner_expr) tsc annotmap in
(env,annotmap), (ident, inner_expr)
| _ ->
(env,annotmap), (ident, expr))
(env,annotmap) code in
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (label, `specialize _, _, _) ->
OManager.serror "%a@\n Illegal @@specialize: it can only be the topmost directive on a toplevel binding.@."
FilePos.pp_pos (Annot.pos label)
| _ -> ()
)
) code;
result
let rewrite_expr env gamma annotmap code =
let rec aux tra annotmap e =
match e with
| Q.Ident (label, i) ->
let annot = Annot.annot label in
(try
let info = IdentMap.find i env in
let choices = info.specialize in
let ty = QmlAnnotMap.find_ty annot annotmap in
try let _, expr = List.find (fun (ty',_) -> QmlMoreTypes.equal_ty ~gamma ty ty') choices in
let annotmap, expr = QmlAstCons.TypedExpr.copy annotmap expr in
aux tra annotmap expr
with Not_found ->
let fail () =
QmlPrint.pp#reset_typevars;
let context = QmlError.Context.label label in
QmlError.error context (
"Failed specialization on %s with type %a@\n"^^
"@[<2>@{<bright>Hint@}:@\n"^^
"Add a type annotation for a specialization in one of the following types:@\n"^^
"%a"^^
"@]"
)
(Ident.original_name i) QmlPrint.pp#ty ty
(Format.pp_list "@\n" (Format.pp_fst QmlPrint.pp#ty)) choices
in
if info.strict
then
fail ()
else (
#<If:SIMPLIFYMAGIC_FAILURES>
fail ()
#<End> ;
) ;
tra annotmap e
with Not_found -> tra annotmap e)
| _ -> tra annotmap e in
QmlAstWalk.Expr.traverse_foldmap aux annotmap code
let empty_env = IdentMap.empty
let process_code ?(specialized_env=empty_env) gamma annotmap code =
let (env,annotmap), code = build_env specialized_env gamma annotmap code in
R.save annotmap env;
#<If:SIMPLIFYMAGIC_DISABLE>
annotmap, code
#<Else>
let annotmap, env2 = R.load annotmap empty_env in
the old env has priority over the current one
* so that does n't override intToString
* in the package date
* so that Date.to_string doesn't override intToString
* in the package date *)
QmlAstWalk.CodeExpr.fold_map (rewrite_expr env gamma) annotmap code
#<End>
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/qmlpasses/pass_SimplifyMagic.ml | ocaml | depends
shorthands
--
we refuse polymorphic types for now
* or else we might create troubles with ei
should check that ty is an instance of general_type
* but since ty is monomorphic, checking the unifiability is equivalent |
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 </>.
*)
module Format = BaseFormat
module List = BaseList
module Q = QmlAst
type info = { strict : bool ; specialize : (Q.ty * Q.expr) list }
type env = info IdentMap.t
let (@) info1 info2 =
let strict = info1.strict || info2.strict in
let specialize = info1.specialize @ info2.specialize in
{
strict ;
specialize ;
}
let fold_expr f acc env =
IdentMap.fold (fun _ info acc ->
List.fold_left (fun acc (_,e) -> f acc e) acc info.specialize
) env acc
let fold_map_expr f acc env =
IdentMap.fold_map (
fun _ info acc ->
let acc, specialize =
List.fold_left_map (
fun acc (ty,e) ->
let acc, e = f acc e in
acc, (ty, e)
) acc info.specialize
in acc, {
info with
specialize
}
) env acc
let map_type f env =
IdentMap.map
(fun info ->
let specialize =
List.map
(fun (ty,e) ->
(f ty, e))
info.specialize
in
{
info with
specialize ;
}
) env
module S =
struct
type t = Q.annotmap * env
let pass = "pass_SimplifyMagic"
let pp f _ = Format.pp_print_string f "<dummy>"
end
module R =
struct
include ObjectFiles.Make(S)
let load annotmap (env:env) : S.t =
fold_with_name
(fun package (annotmap,(env:env)) (annotmap_old,old_env) ->
let annotmap_old = QmlRefresh.refresh_annotmap package annotmap_old in
let annotmap, old_env = fold_map_expr (QmlRefresh.refresh_expr package ~annotmap_old) annotmap old_env in
let old_env = map_type (QmlRefresh.refresh_typevars_from_ty package) old_env in
let env = IdentMap.merge (@) env old_env in
annotmap, env
) (annotmap,env)
let save annotmap env =
let small_annotmap = QmlRefresh.restrict_annotmap_fold_expr fold_expr annotmap env in
save (small_annotmap,env)
end
let is_monomorphic ty =
not (
QmlAstWalk.Type.exists
(function
FIXME : actually , we should check for rowvars and colvars also
| _ -> false) ty
)
let build_env env gamma annotmap code =
let _, code as result =
QmlAstWalk.CodeExpr.fold_map_name_expr
(fun (env,annotmap) (ident,expr) ->
match expr with
| Q.Directive (_, `specialize variant, inner_expr :: l, _) ->
let general_type = QmlAnnotMap.find_ty (Q.QAnnot.expr inner_expr) annotmap in
let l =
let specialize = List.map (fun e ->
let ty = QmlAnnotMap.find_ty (Q.QAnnot.expr e) annotmap in
if not (is_monomorphic ty) then
OManager.serror "%a@\n This expression shouldn't contain type variables@."
FilePos.pp_pos (Q.Pos.expr e)
else (
if not (QmlMoreTypes.unifiable ~gamma general_type ty) then
OManager.serror "%a@\n This expression's type should be an instance of the generic expression's type.@."
FilePos.pp_pos (Q.Pos.expr e)
);
ty, e) l in
let strict = variant = `strict in
{
strict ;
specialize ;
}
in
let env = IdentMap.update_default ident ((@) l) l env in
let tsc = QmlAnnotMap.find_tsc_opt (Q.QAnnot.expr expr) annotmap in
let annotmap = QmlAnnotMap.add_tsc_opt (Q.QAnnot.expr inner_expr) tsc annotmap in
(env,annotmap), (ident, inner_expr)
| _ ->
(env,annotmap), (ident, expr))
(env,annotmap) code in
QmlAstWalk.CodeExpr.iter
(QmlAstWalk.Expr.iter
(function
| Q.Directive (label, `specialize _, _, _) ->
OManager.serror "%a@\n Illegal @@specialize: it can only be the topmost directive on a toplevel binding.@."
FilePos.pp_pos (Annot.pos label)
| _ -> ()
)
) code;
result
let rewrite_expr env gamma annotmap code =
let rec aux tra annotmap e =
match e with
| Q.Ident (label, i) ->
let annot = Annot.annot label in
(try
let info = IdentMap.find i env in
let choices = info.specialize in
let ty = QmlAnnotMap.find_ty annot annotmap in
try let _, expr = List.find (fun (ty',_) -> QmlMoreTypes.equal_ty ~gamma ty ty') choices in
let annotmap, expr = QmlAstCons.TypedExpr.copy annotmap expr in
aux tra annotmap expr
with Not_found ->
let fail () =
QmlPrint.pp#reset_typevars;
let context = QmlError.Context.label label in
QmlError.error context (
"Failed specialization on %s with type %a@\n"^^
"@[<2>@{<bright>Hint@}:@\n"^^
"Add a type annotation for a specialization in one of the following types:@\n"^^
"%a"^^
"@]"
)
(Ident.original_name i) QmlPrint.pp#ty ty
(Format.pp_list "@\n" (Format.pp_fst QmlPrint.pp#ty)) choices
in
if info.strict
then
fail ()
else (
#<If:SIMPLIFYMAGIC_FAILURES>
fail ()
#<End> ;
) ;
tra annotmap e
with Not_found -> tra annotmap e)
| _ -> tra annotmap e in
QmlAstWalk.Expr.traverse_foldmap aux annotmap code
let empty_env = IdentMap.empty
let process_code ?(specialized_env=empty_env) gamma annotmap code =
let (env,annotmap), code = build_env specialized_env gamma annotmap code in
R.save annotmap env;
#<If:SIMPLIFYMAGIC_DISABLE>
annotmap, code
#<Else>
let annotmap, env2 = R.load annotmap empty_env in
the old env has priority over the current one
* so that does n't override intToString
* in the package date
* so that Date.to_string doesn't override intToString
* in the package date *)
QmlAstWalk.CodeExpr.fold_map (rewrite_expr env gamma) annotmap code
#<End>
|
63650411dfff7cf55fbc41e4799e34ebba56b048abe76e26092361812fd417ef | linoscope/okasaki-book-ocaml | assoc_list.mli | open Okasaki_book
module Make (Key : Ordered_intf.S) : Finite_map_intf.S with type key = Key.t
| null | https://raw.githubusercontent.com/linoscope/okasaki-book-ocaml/04b299fb978c75a0c4da5991dc187fef2e91d9cb/test/ch10/assoc_list.mli | ocaml | open Okasaki_book
module Make (Key : Ordered_intf.S) : Finite_map_intf.S with type key = Key.t
| |
c57bdf078acc660c2c9c1cff512e549d7fb0001cf7ecdfa1b24bbbd6b82dd0a2 | puppetlabs/jruby-utils | slj4j_logger_test.clj | (ns puppetlabs.jruby-utils.slj4j-logger-test
(:require [clojure.test :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils])
(:import (org.jruby.util.log LoggerFactory)))
(deftest slf4j-logger-test
(let [actual-logger-name "my-test-logger"
exception-message "exceptionally bad news"
expected-logger-name (str "jruby." actual-logger-name)
logger (LoggerFactory/getLogger actual-logger-name)
actual-log-event (fn [event]
(assoc event :exception
(when-let [exception (:exception event)]
(.getMessage exception))))
expected-log-event (fn [message level exception]
{:message message
:level level
:exception exception
:logger expected-logger-name})]
(testing "name stored in logger"
(is (= expected-logger-name (.getName logger))))
(testing "warn with a string and objects"
(logutils/with-test-logging
(.warn logger "a {} {} warning" (into-array Object ["strongly" "worded"]))
(is (logged? "a strongly worded warning" :warn))))
(testing "warn with an exception"
(logutils/with-test-logging
(.warn logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :warn exception-message)
(actual-log-event %))))))
(testing "warn with a string and an exception"
(logutils/with-test-logging
(.warn logger "a warning" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "a warning" :warn exception-message)
(actual-log-event %))))))
(testing "error with a string and objects"
(logutils/with-test-logging
(.error logger "a {} {} error" (into-array Object ["strongly" "worded"]))
(is (logged? "a strongly worded error" :error))))
(testing "error with an exception"
(logutils/with-test-logging
(.error logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :error exception-message)
(actual-log-event %))))))
(testing "error with a string and an exception"
(logutils/with-test-logging
(.error logger "an error" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "an error" :error exception-message)
(actual-log-event %))))))
(testing "info with a string and objects"
(logutils/with-test-logging
(.info logger
"some {} {} info"
(into-array Object ["strongly" "worded"]))
(is (logged? "some strongly worded info" :info))))
(testing "info with an exception"
(logutils/with-test-logging
(.info logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :info exception-message)
(actual-log-event %))))))
(testing "info with a string and an exception"
(logutils/with-test-logging
(.info logger "some info" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "some info" :info exception-message)
(actual-log-event %))))))
(testing "debug with a string and objects"
(logutils/with-test-logging
(.debug logger
"some {} {} debug"
(into-array Object ["strongly" "worded"]))
(is (logged? "some strongly worded debug" :debug))))
(testing "info with an exception"
(logutils/with-test-logging
(.debug logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :debug exception-message)
(actual-log-event %))))))
(testing "debug with a string and an exception"
(logutils/with-test-logging
(.debug logger "some debug" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "some debug" :debug exception-message)
(actual-log-event %))))))))
| null | https://raw.githubusercontent.com/puppetlabs/jruby-utils/7b53c3c6a0c61635362402313bcec809abf5a856/test/unit/puppetlabs/jruby_utils/slj4j_logger_test.clj | clojure | (ns puppetlabs.jruby-utils.slj4j-logger-test
(:require [clojure.test :refer :all]
[puppetlabs.trapperkeeper.testutils.logging :as logutils])
(:import (org.jruby.util.log LoggerFactory)))
(deftest slf4j-logger-test
(let [actual-logger-name "my-test-logger"
exception-message "exceptionally bad news"
expected-logger-name (str "jruby." actual-logger-name)
logger (LoggerFactory/getLogger actual-logger-name)
actual-log-event (fn [event]
(assoc event :exception
(when-let [exception (:exception event)]
(.getMessage exception))))
expected-log-event (fn [message level exception]
{:message message
:level level
:exception exception
:logger expected-logger-name})]
(testing "name stored in logger"
(is (= expected-logger-name (.getName logger))))
(testing "warn with a string and objects"
(logutils/with-test-logging
(.warn logger "a {} {} warning" (into-array Object ["strongly" "worded"]))
(is (logged? "a strongly worded warning" :warn))))
(testing "warn with an exception"
(logutils/with-test-logging
(.warn logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :warn exception-message)
(actual-log-event %))))))
(testing "warn with a string and an exception"
(logutils/with-test-logging
(.warn logger "a warning" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "a warning" :warn exception-message)
(actual-log-event %))))))
(testing "error with a string and objects"
(logutils/with-test-logging
(.error logger "a {} {} error" (into-array Object ["strongly" "worded"]))
(is (logged? "a strongly worded error" :error))))
(testing "error with an exception"
(logutils/with-test-logging
(.error logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :error exception-message)
(actual-log-event %))))))
(testing "error with a string and an exception"
(logutils/with-test-logging
(.error logger "an error" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "an error" :error exception-message)
(actual-log-event %))))))
(testing "info with a string and objects"
(logutils/with-test-logging
(.info logger
"some {} {} info"
(into-array Object ["strongly" "worded"]))
(is (logged? "some strongly worded info" :info))))
(testing "info with an exception"
(logutils/with-test-logging
(.info logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :info exception-message)
(actual-log-event %))))))
(testing "info with a string and an exception"
(logutils/with-test-logging
(.info logger "some info" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "some info" :info exception-message)
(actual-log-event %))))))
(testing "debug with a string and objects"
(logutils/with-test-logging
(.debug logger
"some {} {} debug"
(into-array Object ["strongly" "worded"]))
(is (logged? "some strongly worded debug" :debug))))
(testing "info with an exception"
(logutils/with-test-logging
(.debug logger (Exception. exception-message))
(is (logged?
#(= (expected-log-event "" :debug exception-message)
(actual-log-event %))))))
(testing "debug with a string and an exception"
(logutils/with-test-logging
(.debug logger "some debug" (Exception. exception-message))
(is (logged?
#(= (expected-log-event "some debug" :debug exception-message)
(actual-log-event %))))))))
| |
aea410cc9358f53eea325ca819b6d5ba5017fa229e897007ae0b5f305c59cca4 | VisionsGlobalEmpowerment/webchange | layout_markup.cljc | (ns webchange.question.common.layout-markup
(:require
[webchange.question.common.params :as params]
[webchange.question.utils :as utils]))
(defn- get-layout-params
[]
(let [{template-width :width template-height :height} params/template-size
content-margin-horizontal 256
content-margin-vertical 64
content-width (->> (* content-margin-horizontal 2) (- template-width))
content-height (->> (* content-margin-vertical 2) (- template-height))]
{:image-width 256
:image-height 256
:image-width-big 512
:image-height-big 512
:text-height 80
:check-button-size 128
:elements-gap 56
:elements-gap-big 128
:footer-margin 64
:mark-options-list-height 200
:content-width content-width
:content-height content-height
:content-margin-horizontal content-margin-horizontal
:content-margin-vertical content-margin-vertical}))
(defn- get-options-layout--image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.2
item-max-width 384
item-max-height 536
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (->> (- container-height item-height)
(* 0.5))]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-options-layout--arrange-image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.2
item-max-width 384
item-max-height 268
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (- container-height item-height)]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-placeholders-layout--arrange-image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.4
item-max-width 384
item-max-height 268
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y 0]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-options-layout--text
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-margin-ratio 0.2
item-max-width 10000
item-max-height 10000
item-margin-horizontal-min 40
item-margin-vertical-min 40
columns-number (quot options-number 2)
rows-number (-> (/ options-number columns-number) Math/ceil utils/round)
item-width-calculated (->> (+ columns-number
(* columns-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (->> (+ rows-number
(* rows-number item-margin-ratio)
(- item-margin-ratio))
(/ container-height)
(min item-max-height))
item-margin-horizontal (max (* item-width-calculated item-margin-ratio)
item-margin-horizontal-min)
item-margin-vertical (max (* item-height-calculated item-margin-ratio)
item-margin-vertical-min)
item-margin (min item-margin-horizontal item-margin-vertical)
item-width (-> (->> (dec columns-number)
(* item-margin)
(- container-width))
(/ columns-number)
utils/round)
item-height (-> (->> (dec rows-number)
(* item-margin)
(- container-height))
(/ rows-number)
utils/round)]
(->> (range options-number)
(map (fn [idx]
(let [column (quot idx rows-number)
row (mod idx rows-number)]
[(inc idx)
{:x (->> (+ item-width item-margin) (* column))
:y (->> (+ item-height item-margin) (* row))
:width item-width
:height item-height}])))
(into {}))))
(defn- get-options-layout--mark
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1
item-margin-ratio 0.2
item-max-width 1000
item-max-height 1000
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (->> (- container-height item-height)
(* 0.5))]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-question-layout
([form-data layout-params]
(get-question-layout form-data layout-params {}))
([form-data
{:keys [content-margin-horizontal content-margin-vertical image-height text-height check-button-size elements-gap footer-margin]}
{:keys [header-height with-header? with-footer?]
:or {with-header? true
with-footer? true}}]
(let [has-header? (and with-header?
(or (utils/task-has-image? form-data)
(utils/task-has-text? form-data)))
has-footer? with-footer?
content-x content-margin-horizontal
content-y content-margin-vertical
content-width (->> (* content-margin-horizontal 2) (- params/template-width))
content-height (->> (* content-margin-vertical 2) (- params/template-height))
add-header (fn [layout]
(let [header (cond
(utils/task-has-image? form-data) {:x content-x
:y content-y
:width content-width
:height (if (some? header-height)
header-height
image-height)}
(utils/task-has-text? form-data) {:x content-x
:y content-y
:width content-width
:height (if (some? header-height)
header-height
text-height)})
shift (+ (:height header) elements-gap)]
(-> layout
(assoc :header header)
(update-in [:body :y] + shift)
(update-in [:body :height] - shift))))
add-footer (fn [layout]
(let [footer {:x content-x
:y (- (+ content-y content-height) check-button-size)
:width content-width
:height check-button-size}
shift (+ (:height footer) footer-margin)]
(-> layout
(assoc :footer footer)
(update-in [:body :height] - shift))))]
(cond-> {:body {:x content-x
:y content-y
:width content-width
:height content-height}}
has-header? (add-header)
has-footer? (add-footer)))))
(defn- add-check-button
[data layout {:keys [check-button-size]}]
(assoc data :check-button {:x (-> (- (get-in layout [:footer :width])
check-button-size)
(/ 2)
(+ (get-in layout [:footer :x]))
(utils/round))
:y (get-in layout [:footer :y])
:width check-button-size
:height check-button-size}))
(defn- get-task-layout--text
[form-data layout-params]
(let [layout (get-question-layout form-data layout-params)]
(-> {:text (:header layout)
:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- get-task-layout--image
[{:keys [options-number question-type] :as form-data} {:keys [elements-gap-big image-width image-width-big text-height] :as layout-params}]
(if (and (= question-type "multiple-choice-text")
(some #{options-number} [2 3]))
(let [layout (get-question-layout form-data layout-params {:header-height text-height})]
(-> {:image (-> (:body layout)
(update :x + (- (:width (:body layout)) image-width-big))
(assoc :width image-width-big))
:options-container (-> (:body layout)
(update :width - image-width-big elements-gap-big))}
(add-check-button layout layout-params)))
(let [layout (get-question-layout form-data layout-params)]
(-> {:image (-> (:header layout)
(update :x + (/ (- (get-in layout [:header :width]) image-width) 2))
(assoc :width image-width))
:options-container (:body layout)}
(add-check-button layout layout-params)))))
(defn- get-task-layout--voice-over
[form-data layout-params]
(let [layout (get-question-layout form-data layout-params)]
(-> {:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- get-task-layout--text-image
[form-data {:keys [elements-gap image-width] :as layout-params}]
(let [layout (get-question-layout form-data layout-params)]
(-> {:image {:x (get-in layout [:header :x])
:y (get-in layout [:header :y])
:width image-width
:height (get-in layout [:header :height])}
:text {:x (+ (get-in layout [:header :x])
image-width
elements-gap)
:y (get-in layout [:header :y])
:width (- (get-in layout [:header :width])
image-width
elements-gap)
:height (get-in layout [:header :height])}
:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- centralize
[w1 w2]
(-> (- w1 w2) (/ 2) (utils/round)))
(defn- shift-to-center
[x w1 w2]
(-> (centralize w1 w2)
(+ x)))
(defn- get-task-layout--thumbs-up-n-down--text
[form-data {:keys [elements-gap mark-options-list-height text-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
total-height (+ text-height elements-gap mark-options-list-height)
padding-top (/ (- (:height body) total-height) 2)]
(-> {:text {:x (:x body)
:y (+ (:y body) padding-top)
:width (:width body)
:height text-height}
:options-container {:x (:x body)
:y (+ (:y body) padding-top text-height elements-gap)
:width (:width body)
:height mark-options-list-height}}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--image
[form-data {:keys [elements-gap-big image-height-big image-width-big mark-options-list-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
right-side-left (+ image-width-big elements-gap-big)]
(-> {:image (-> body
(update :y shift-to-center (:height body) image-height-big)
(assoc :width image-width-big)
(assoc :height image-height-big))
:options-container (-> body
(update :x + right-side-left)
(update :y shift-to-center (:height body) mark-options-list-height)
(update :width - right-side-left)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--text-image
[form-data {:keys [elements-gap-big image-height-big image-width-big mark-options-list-height text-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
right-side-height (+ text-height elements-gap-big mark-options-list-height)
right-side-left (+ image-width-big elements-gap-big)
right-side-top (centralize (:height body) right-side-height)]
(-> {:text (-> body
(update :x + right-side-left)
(update :y + right-side-top)
(update :width - right-side-left)
(assoc :height text-height))
:image (-> body
(update :y shift-to-center (:height body) image-height-big)
(assoc :width image-width-big)
(assoc :height image-height-big))
:options-container (-> body
(update :x + right-side-left)
(update :y + right-side-top text-height elements-gap-big)
(update :width - right-side-left)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--voice-over
[form-data {:keys [mark-options-list-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})]
(-> {:options-container (-> body
(update :y shift-to-center (:height body) mark-options-list-height)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn get-layout-coordinates
[{:keys [task-type question-type] :as form-data}]
"Get question main elements position and size.
- :options-number - a number of available answer options,
- :task-type - one of the next values: 'text', 'image', 'text-image' or 'voice-over',
- :question-type - one of the next values: 'multiple-choice-image', 'multiple-choice-text' or 'thumbs-up-n-down';
Returns map of dimensions for question element if it presents or nil if absent:
- :image - 'dimensions' of task image,
- :text - 'dimensions' of task text,
- :options-container - 'dimensions' all options block,
- :options-items:
- 1 - 'dimensions' of the first option,
- 2 - 'dimensions' of the second option,
..etc,
- :check-button - 'dimensions' of check button for multiple correct answers;
Where 'dimensions' is a map:
- :x - number,
- :y - number,
- :width - number,
- :height - number."
(let [layout-params (get-layout-params)]
(case question-type
"multiple-choice-image" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
nil)
"multiple-choice-text" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
nil)
"arrange-images" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--arrange-image options-container form-data)
:placeholder-items (get-placeholders-layout--arrange-image options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--arrange-image options-container form-data)
:placeholder-items (get-placeholders-layout--arrange-image options-container form-data)}))
nil)
"thumbs-up-n-down" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
nil)
nil)))
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/fe9738f5c1d32036e7cd8a3744ee3774bc8a5748/src/cljc/webchange/question/common/layout_markup.cljc | clojure | (ns webchange.question.common.layout-markup
(:require
[webchange.question.common.params :as params]
[webchange.question.utils :as utils]))
(defn- get-layout-params
[]
(let [{template-width :width template-height :height} params/template-size
content-margin-horizontal 256
content-margin-vertical 64
content-width (->> (* content-margin-horizontal 2) (- template-width))
content-height (->> (* content-margin-vertical 2) (- template-height))]
{:image-width 256
:image-height 256
:image-width-big 512
:image-height-big 512
:text-height 80
:check-button-size 128
:elements-gap 56
:elements-gap-big 128
:footer-margin 64
:mark-options-list-height 200
:content-width content-width
:content-height content-height
:content-margin-horizontal content-margin-horizontal
:content-margin-vertical content-margin-vertical}))
(defn- get-options-layout--image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.2
item-max-width 384
item-max-height 536
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (->> (- container-height item-height)
(* 0.5))]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-options-layout--arrange-image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.2
item-max-width 384
item-max-height 268
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (- container-height item-height)]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-placeholders-layout--arrange-image
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1.3958
item-margin-ratio 0.4
item-max-width 384
item-max-height 268
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y 0]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-options-layout--text
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-margin-ratio 0.2
item-max-width 10000
item-max-height 10000
item-margin-horizontal-min 40
item-margin-vertical-min 40
columns-number (quot options-number 2)
rows-number (-> (/ options-number columns-number) Math/ceil utils/round)
item-width-calculated (->> (+ columns-number
(* columns-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (->> (+ rows-number
(* rows-number item-margin-ratio)
(- item-margin-ratio))
(/ container-height)
(min item-max-height))
item-margin-horizontal (max (* item-width-calculated item-margin-ratio)
item-margin-horizontal-min)
item-margin-vertical (max (* item-height-calculated item-margin-ratio)
item-margin-vertical-min)
item-margin (min item-margin-horizontal item-margin-vertical)
item-width (-> (->> (dec columns-number)
(* item-margin)
(- container-width))
(/ columns-number)
utils/round)
item-height (-> (->> (dec rows-number)
(* item-margin)
(- container-height))
(/ rows-number)
utils/round)]
(->> (range options-number)
(map (fn [idx]
(let [column (quot idx rows-number)
row (mod idx rows-number)]
[(inc idx)
{:x (->> (+ item-width item-margin) (* column))
:y (->> (+ item-height item-margin) (* row))
:width item-width
:height item-height}])))
(into {}))))
(defn- get-options-layout--mark
[{container-width :width container-height :height} {:keys [options-number]}]
(let [item-sides-ratio 1
item-margin-ratio 0.2
item-max-width 1000
item-max-height 1000
item-width-calculated (->> (+ options-number
(* options-number item-margin-ratio)
(- item-margin-ratio))
(/ container-width)
(min item-max-width))
item-height-calculated (* item-width-calculated item-sides-ratio)
item-height-fixed (min item-height-calculated item-max-height container-height)
[item-width item-height] (if (< item-height-fixed item-height-calculated)
[(/ item-height-fixed item-sides-ratio) item-height-fixed]
[item-width-calculated item-height-calculated])
item-margin (* item-width item-margin-ratio)
list-margin-x (->> (+ (* item-width options-number)
(* item-margin (dec options-number)))
(- container-width)
(* 0.5))
list-margin-y (->> (- container-height item-height)
(* 0.5))]
(->> (range options-number)
(map (fn [idx]
[(inc idx)
{:x (->> (+ item-width item-margin) (* idx) (+ list-margin-x))
:y list-margin-y
:width item-width
:height item-height}]))
(into {}))))
(defn- get-question-layout
([form-data layout-params]
(get-question-layout form-data layout-params {}))
([form-data
{:keys [content-margin-horizontal content-margin-vertical image-height text-height check-button-size elements-gap footer-margin]}
{:keys [header-height with-header? with-footer?]
:or {with-header? true
with-footer? true}}]
(let [has-header? (and with-header?
(or (utils/task-has-image? form-data)
(utils/task-has-text? form-data)))
has-footer? with-footer?
content-x content-margin-horizontal
content-y content-margin-vertical
content-width (->> (* content-margin-horizontal 2) (- params/template-width))
content-height (->> (* content-margin-vertical 2) (- params/template-height))
add-header (fn [layout]
(let [header (cond
(utils/task-has-image? form-data) {:x content-x
:y content-y
:width content-width
:height (if (some? header-height)
header-height
image-height)}
(utils/task-has-text? form-data) {:x content-x
:y content-y
:width content-width
:height (if (some? header-height)
header-height
text-height)})
shift (+ (:height header) elements-gap)]
(-> layout
(assoc :header header)
(update-in [:body :y] + shift)
(update-in [:body :height] - shift))))
add-footer (fn [layout]
(let [footer {:x content-x
:y (- (+ content-y content-height) check-button-size)
:width content-width
:height check-button-size}
shift (+ (:height footer) footer-margin)]
(-> layout
(assoc :footer footer)
(update-in [:body :height] - shift))))]
(cond-> {:body {:x content-x
:y content-y
:width content-width
:height content-height}}
has-header? (add-header)
has-footer? (add-footer)))))
(defn- add-check-button
[data layout {:keys [check-button-size]}]
(assoc data :check-button {:x (-> (- (get-in layout [:footer :width])
check-button-size)
(/ 2)
(+ (get-in layout [:footer :x]))
(utils/round))
:y (get-in layout [:footer :y])
:width check-button-size
:height check-button-size}))
(defn- get-task-layout--text
[form-data layout-params]
(let [layout (get-question-layout form-data layout-params)]
(-> {:text (:header layout)
:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- get-task-layout--image
[{:keys [options-number question-type] :as form-data} {:keys [elements-gap-big image-width image-width-big text-height] :as layout-params}]
(if (and (= question-type "multiple-choice-text")
(some #{options-number} [2 3]))
(let [layout (get-question-layout form-data layout-params {:header-height text-height})]
(-> {:image (-> (:body layout)
(update :x + (- (:width (:body layout)) image-width-big))
(assoc :width image-width-big))
:options-container (-> (:body layout)
(update :width - image-width-big elements-gap-big))}
(add-check-button layout layout-params)))
(let [layout (get-question-layout form-data layout-params)]
(-> {:image (-> (:header layout)
(update :x + (/ (- (get-in layout [:header :width]) image-width) 2))
(assoc :width image-width))
:options-container (:body layout)}
(add-check-button layout layout-params)))))
(defn- get-task-layout--voice-over
[form-data layout-params]
(let [layout (get-question-layout form-data layout-params)]
(-> {:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- get-task-layout--text-image
[form-data {:keys [elements-gap image-width] :as layout-params}]
(let [layout (get-question-layout form-data layout-params)]
(-> {:image {:x (get-in layout [:header :x])
:y (get-in layout [:header :y])
:width image-width
:height (get-in layout [:header :height])}
:text {:x (+ (get-in layout [:header :x])
image-width
elements-gap)
:y (get-in layout [:header :y])
:width (- (get-in layout [:header :width])
image-width
elements-gap)
:height (get-in layout [:header :height])}
:options-container (:body layout)}
(add-check-button layout layout-params))))
(defn- centralize
[w1 w2]
(-> (- w1 w2) (/ 2) (utils/round)))
(defn- shift-to-center
[x w1 w2]
(-> (centralize w1 w2)
(+ x)))
(defn- get-task-layout--thumbs-up-n-down--text
[form-data {:keys [elements-gap mark-options-list-height text-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
total-height (+ text-height elements-gap mark-options-list-height)
padding-top (/ (- (:height body) total-height) 2)]
(-> {:text {:x (:x body)
:y (+ (:y body) padding-top)
:width (:width body)
:height text-height}
:options-container {:x (:x body)
:y (+ (:y body) padding-top text-height elements-gap)
:width (:width body)
:height mark-options-list-height}}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--image
[form-data {:keys [elements-gap-big image-height-big image-width-big mark-options-list-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
right-side-left (+ image-width-big elements-gap-big)]
(-> {:image (-> body
(update :y shift-to-center (:height body) image-height-big)
(assoc :width image-width-big)
(assoc :height image-height-big))
:options-container (-> body
(update :x + right-side-left)
(update :y shift-to-center (:height body) mark-options-list-height)
(update :width - right-side-left)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--text-image
[form-data {:keys [elements-gap-big image-height-big image-width-big mark-options-list-height text-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})
right-side-height (+ text-height elements-gap-big mark-options-list-height)
right-side-left (+ image-width-big elements-gap-big)
right-side-top (centralize (:height body) right-side-height)]
(-> {:text (-> body
(update :x + right-side-left)
(update :y + right-side-top)
(update :width - right-side-left)
(assoc :height text-height))
:image (-> body
(update :y shift-to-center (:height body) image-height-big)
(assoc :width image-width-big)
(assoc :height image-height-big))
:options-container (-> body
(update :x + right-side-left)
(update :y + right-side-top text-height elements-gap-big)
(update :width - right-side-left)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn- get-task-layout--thumbs-up-n-down--voice-over
[form-data {:keys [mark-options-list-height] :as layout-params}]
(let [{:keys [body] :as layout} (get-question-layout form-data layout-params {:with-header? false})]
(-> {:options-container (-> body
(update :y shift-to-center (:height body) mark-options-list-height)
(assoc :height mark-options-list-height))}
(add-check-button layout layout-params))))
(defn get-layout-coordinates
[{:keys [task-type question-type] :as form-data}]
"Get question main elements position and size.
- :options-number - a number of available answer options,
- :task-type - one of the next values: 'text', 'image', 'text-image' or 'voice-over',
Returns map of dimensions for question element if it presents or nil if absent:
- :image - 'dimensions' of task image,
- :text - 'dimensions' of task text,
- :options-container - 'dimensions' all options block,
- :options-items:
- 1 - 'dimensions' of the first option,
- 2 - 'dimensions' of the second option,
..etc,
Where 'dimensions' is a map:
- :x - number,
- :y - number,
- :width - number,
- :height - number."
(let [layout-params (get-layout-params)]
(case question-type
"multiple-choice-image" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--image options-container form-data)}))
nil)
"multiple-choice-text" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--text options-container form-data)}))
nil)
"arrange-images" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--arrange-image options-container form-data)
:placeholder-items (get-placeholders-layout--arrange-image options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--arrange-image options-container form-data)
:placeholder-items (get-placeholders-layout--arrange-image options-container form-data)}))
nil)
"thumbs-up-n-down" (case task-type
"text" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--text form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"image" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"text-image" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--text-image form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
"voice-over" (let [{:keys [options-container] :as layout} (get-task-layout--thumbs-up-n-down--voice-over form-data layout-params)]
(merge layout
{:options-items (get-options-layout--mark options-container form-data)}))
nil)
nil)))
| |
1747185f39d3176ee00aa4a8f51ebcc0d97640b34dda62c42ea710ce8405f6fd | default-kramer/plisqin | fragment.rkt | #lang racket
(provide fragment% fragment? >>
fragment-as-name fragment-nullability fragment-fallback)
(require "../token.rkt"
racket/struct)
(define fragment%
(class* token% (printable<%>)
(inherit-field type as-name nullability fallback)
(init-field kind
id
content
reducer)
(super-new)
(define/override (change #:cast [:type type]
#:as [:as-name as-name]
#:null [:nullability nullability]
#:fallback [:fallback fallback])
(new fragment%
[kind kind]
[id id]
[content content]
[reducer reducer]
[type (or :type type)]
[as-name (or :as-name as-name)]
[nullability (or :nullability nullability)]
[fallback (or :fallback fallback)]))
; sql-token<%>
(define/override (token-kind) kind)
(define/override (token-content) content)
(define/override (sql-token-reduce) (reducer content))
; equal<%>
(define/override (equal-content)
(list kind id content type as-name))
; printable<%>
(define/public (custom-print port mode)
(fragment-printer this port mode))
(define/public (custom-write port)
(fragment-printer this port #t))
(define/public (custom-display port)
(fragment-printer this port #f))))
(define fragment? (is-a?/c fragment%))
(define fragment-id (class-field-accessor fragment% id))
(define fragment-content (class-field-accessor fragment% content))
(define fragment-as-name (class-field-accessor fragment% as-name))
(define fragment-nullability (class-field-accessor fragment% nullability))
(define fragment-fallback (class-field-accessor fragment% fallback))
(define fragment-printer
(make-constructor-style-printer fragment-id fragment-content))
| null | https://raw.githubusercontent.com/default-kramer/plisqin/26421c7c42656c873c4e0a4fc7f48c0a3ed7770f/plisqin-lib/private2/sql/fragment.rkt | racket | sql-token<%>
equal<%>
printable<%> | #lang racket
(provide fragment% fragment? >>
fragment-as-name fragment-nullability fragment-fallback)
(require "../token.rkt"
racket/struct)
(define fragment%
(class* token% (printable<%>)
(inherit-field type as-name nullability fallback)
(init-field kind
id
content
reducer)
(super-new)
(define/override (change #:cast [:type type]
#:as [:as-name as-name]
#:null [:nullability nullability]
#:fallback [:fallback fallback])
(new fragment%
[kind kind]
[id id]
[content content]
[reducer reducer]
[type (or :type type)]
[as-name (or :as-name as-name)]
[nullability (or :nullability nullability)]
[fallback (or :fallback fallback)]))
(define/override (token-kind) kind)
(define/override (token-content) content)
(define/override (sql-token-reduce) (reducer content))
(define/override (equal-content)
(list kind id content type as-name))
(define/public (custom-print port mode)
(fragment-printer this port mode))
(define/public (custom-write port)
(fragment-printer this port #t))
(define/public (custom-display port)
(fragment-printer this port #f))))
(define fragment? (is-a?/c fragment%))
(define fragment-id (class-field-accessor fragment% id))
(define fragment-content (class-field-accessor fragment% content))
(define fragment-as-name (class-field-accessor fragment% as-name))
(define fragment-nullability (class-field-accessor fragment% nullability))
(define fragment-fallback (class-field-accessor fragment% fallback))
(define fragment-printer
(make-constructor-style-printer fragment-id fragment-content))
|
948c191de7c4af6792a644a822c6b8048b1228f111269802f306e99bc0113826 | dnlkrgr/hsreduce | Contexts.hs | module Contexts where
arst :: (Eq a, Show a) => a -> a
arst = undefined
| null | https://raw.githubusercontent.com/dnlkrgr/hsreduce/8f66fdee036f8639053067572b55d9a64359d22c/test-cases/regressions/Contexts.hs | haskell | module Contexts where
arst :: (Eq a, Show a) => a -> a
arst = undefined
| |
57c75ac3dc4dd42eb9d809b6743caa9e56035ed77fc81229174b2ada0eab27e9 | jserot/lascar | fsm_expr.mli | (**********************************************************************)
(* *)
LASCAr
(* *)
Copyright ( c ) 2017 - present , . All rights reserved .
(* *)
(* This source code is licensed under the license found in the *)
(* LICENSE file in the root directory of this source tree. *)
(* *)
(**********************************************************************)
* { 2 Simple expressions for FSMs }
module type T = sig
type ident = string [@@deriving show]
(** The type of identifiers occuring in expressions *)
type value [@@deriving show]
(** The type of expression values *)
(** The type of expressions *)
type t =
EConst of value (** Constants *)
| EVar of ident (** Input, output or local variable *)
| EBinop of string * t * t (** Binary operation *)
| EUnop of char * t (** Unary operation *)
[@@deriving show {with_path=false}]
type env = (ident * value option) list
exception Unknown of ident
exception Unknown_op of string
exception Unbound of ident
exception Illegal_expr
val test_ops: (string * (value -> value -> bool)) list (** name, fun *)
val to_string: t -> string
val of_string: string -> t
val lookup: env -> ident -> value
val eval: env -> t -> value
val lexer: string -> Genlex.token Stream.t
val parse: Genlex.token Stream.t -> t
val keywords: string list
val mk_unaries: string -> string
end
(** Functor building an implementation of the Fsm_expr structure given an implementation of values *)
module Make (V: Fsm_value.T) : T with type value = V.t
* Functor for converting a FSM expression , with a given implementation of values
into another one with a different implementations
into another one with a different implementations *)
module Trans (E1: T) (E2: T) :
sig
val map: (E1.value -> E2.value) -> E1.t -> E2.t
end
(** Some predefined instances *)
module Int : T with type value = int
module Bool : T with type value = bool
| null | https://raw.githubusercontent.com/jserot/lascar/79bd11cd0d47545bccfc3a3571f37af065915c83/src/lib/fsm_expr.mli | ocaml | ********************************************************************
This source code is licensed under the license found in the
LICENSE file in the root directory of this source tree.
********************************************************************
* The type of identifiers occuring in expressions
* The type of expression values
* The type of expressions
* Constants
* Input, output or local variable
* Binary operation
* Unary operation
* name, fun
* Functor building an implementation of the Fsm_expr structure given an implementation of values
* Some predefined instances | LASCAr
Copyright ( c ) 2017 - present , . All rights reserved .
* { 2 Simple expressions for FSMs }
module type T = sig
type ident = string [@@deriving show]
type value [@@deriving show]
type t =
[@@deriving show {with_path=false}]
type env = (ident * value option) list
exception Unknown of ident
exception Unknown_op of string
exception Unbound of ident
exception Illegal_expr
val to_string: t -> string
val of_string: string -> t
val lookup: env -> ident -> value
val eval: env -> t -> value
val lexer: string -> Genlex.token Stream.t
val parse: Genlex.token Stream.t -> t
val keywords: string list
val mk_unaries: string -> string
end
module Make (V: Fsm_value.T) : T with type value = V.t
* Functor for converting a FSM expression , with a given implementation of values
into another one with a different implementations
into another one with a different implementations *)
module Trans (E1: T) (E2: T) :
sig
val map: (E1.value -> E2.value) -> E1.t -> E2.t
end
module Int : T with type value = int
module Bool : T with type value = bool
|
1de6c70ebf8a00e4c078d11f7e1b6f777d23edcc229172a4792b3c3804459f3f | google/proto-lens | Default.hs | -- | A compatibility layer for older code to create default protocol buffer messages.
--
In older versions of @proto - lens@ , messages could be constructed with
@Data . Default . Class.def@. However , for @proto - lens > = 0.4@ , that is
-- no longer the case and @Data.ProtoLens.defMessage@ should be used instead.
--
-- This module provides a compatibility layer that may be used to upgrade
-- older code without substantial code changes.
module Data.ProtoLens.Default
( def
, Message
) where
import Data.ProtoLens.Message (Message(defMessage))
-- | A message with all fields set to their default values.
--
For new code , prefer ` defMessage ` .
def :: Message a => a
def = defMessage
| null | https://raw.githubusercontent.com/google/proto-lens/081815877430afc1db669ca5e4edde1558b5fd9d/proto-lens/src/Data/ProtoLens/Default.hs | haskell | | A compatibility layer for older code to create default protocol buffer messages.
no longer the case and @Data.ProtoLens.defMessage@ should be used instead.
This module provides a compatibility layer that may be used to upgrade
older code without substantial code changes.
| A message with all fields set to their default values.
| In older versions of @proto - lens@ , messages could be constructed with
@Data . Default . Class.def@. However , for @proto - lens > = 0.4@ , that is
module Data.ProtoLens.Default
( def
, Message
) where
import Data.ProtoLens.Message (Message(defMessage))
For new code , prefer ` defMessage ` .
def :: Message a => a
def = defMessage
|
e43c7a7dba7019c0791c3768baad05af40d86a73f626fe9f3aa54febb2b87b40 | part-cw/lambdanative | srfi-13-local.scm |
;;(include "../libs/gambit/myenv.sch")
;;(include "../libs/gambit/common.sch")
; Top-level cond-expand expanded automatically
(define (string-xcopy! target tstart s sfrom sto)
(do ((i sfrom (inc i)) (j tstart (inc j)))
((>= i sto))
(string-set! target j (string-ref s i))))
; procedure string-concatenate-reverse STRINGS FINAL END
(define (string-concatenate-reverse strs final end)
(if (null? strs) (substring final 0 end)
(let*
((total-len
(let loop ((len end) (lst strs))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((len end) (j total-len) (str final) (lst strs))
(string-xcopy! result (- j len) str 0 len)
(if (null? lst) result
(loop (string-length (car lst)) (- j len)
(car lst) (cdr lst)))))))
; string-concatenate/shared STRING-LIST -> STRING
(define (string-concatenate/shared strs)
(cond
Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(let*
((total-len
(let loop ((len (string-length (car strs))) (lst (cdr strs)))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((j 0) (str (car strs)) (lst (cdr strs)))
(string-xcopy! result j str 0 (string-length str))
(if (null? lst) result
(loop (+ j (string-length str))
(car lst) (cdr lst))))))))
; string-concatenate-reverse/shared STRING-LIST [FINAL-STRING END] -> STRING
; We do not use the optional arguments of this procedure. Therefore,
; we do not implement them. See SRFI-13 for the complete
; implementation.
(define (string-concatenate-reverse/shared strs)
(cond
Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(string-concatenate-reverse (cdr strs)
(car strs) (string-length (car strs))))))
Return the index of the last occurence of a - char in str , or # f
This is a subset of the corresponding SRFI-13 function .
; The latter is more generic.
(define (string-index-right str a-char)
(let loop ((pos (dec (string-length str))))
(cond
((negative? pos) #f) ; whole string has been searched, in vain
((char=? a-char (string-ref str pos)) pos)
(else (loop (dec pos))))))
| null | https://raw.githubusercontent.com/part-cw/lambdanative/74ec19dddf2f2ff787ee70ad677bc13b9dfafc29/modules/ssax/srfi-13-local.scm | scheme | (include "../libs/gambit/myenv.sch")
(include "../libs/gambit/common.sch")
Top-level cond-expand expanded automatically
procedure string-concatenate-reverse STRINGS FINAL END
string-concatenate/shared STRING-LIST -> STRING
string-concatenate-reverse/shared STRING-LIST [FINAL-STRING END] -> STRING
We do not use the optional arguments of this procedure. Therefore,
we do not implement them. See SRFI-13 for the complete
implementation.
The latter is more generic.
whole string has been searched, in vain |
(define (string-xcopy! target tstart s sfrom sto)
(do ((i sfrom (inc i)) (j tstart (inc j)))
((>= i sto))
(string-set! target j (string-ref s i))))
(define (string-concatenate-reverse strs final end)
(if (null? strs) (substring final 0 end)
(let*
((total-len
(let loop ((len end) (lst strs))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((len end) (j total-len) (str final) (lst strs))
(string-xcopy! result (- j len) str 0 len)
(if (null? lst) result
(loop (string-length (car lst)) (- j len)
(car lst) (cdr lst)))))))
(define (string-concatenate/shared strs)
(cond
Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(let*
((total-len
(let loop ((len (string-length (car strs))) (lst (cdr strs)))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((j 0) (str (car strs)) (lst (cdr strs)))
(string-xcopy! result j str 0 (string-length str))
(if (null? lst) result
(loop (+ j (string-length str))
(car lst) (cdr lst))))))))
(define (string-concatenate-reverse/shared strs)
(cond
Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(string-concatenate-reverse (cdr strs)
(car strs) (string-length (car strs))))))
Return the index of the last occurence of a - char in str , or # f
This is a subset of the corresponding SRFI-13 function .
(define (string-index-right str a-char)
(let loop ((pos (dec (string-length str))))
(cond
((char=? a-char (string-ref str pos)) pos)
(else (loop (dec pos))))))
|
f5fb4deb13a8477c7ba683dfaf25a90314b6947ca6cf2035073de7ae3c150d04 | xmonad/xmonad-contrib | CopyWindow.hs | # LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
-----------------------------------------------------------------------------
-- |
Module : XMonad . Actions . CopyWindow
-- Description : Duplicate a window on multiple workspaces.
Copyright : ( c ) < > , < > , < >
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : ???
-- Stability : unstable
-- Portability : unportable
--
-- Provides bindings to duplicate a window on multiple workspaces,
-- providing dwm-like tagging functionality.
--
-----------------------------------------------------------------------------
module XMonad.Actions.CopyWindow (
-- * Usage
-- $usage
copy, copyToAll, copyWindow, runOrCopy
, killAllOtherCopies, kill1, taggedWindows, copiesOfOn
-- * Highlight workspaces containing copies in logHook
$ logHook
, wsContainingCopies, copiesPP
) where
import XMonad
import XMonad.Prelude
import Control.Arrow ((&&&))
import qualified Data.List as L
import XMonad.Actions.WindowGo
import XMonad.Hooks.StatusBar.PP (PP(..), WS(..), isHidden)
import qualified XMonad.StackSet as W
-- $usage
--
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file:
--
> import XMonad . Actions . CopyWindow
--
-- Then add something like this to your keybindings:
--
> -- mod-[1 .. 9 ] @@ Switch to workspace N
> -- mod - shift-[1 .. 9 ] @@ Move client to workspace N
> -- mod - control - shift-[1 .. 9 ] @@ Copy client to workspace N
> [ ( ( m .| . ) , windows $ f i )
> | ( i , k ) < - zip ( workspaces x ) [ xK_1 .. ]
-- > , (f, m) <- [(W.view, 0), (W.shift, shiftMask), (copy, shiftMask .|. controlMask)]]
--
-- To use the above key bindings you need also to import
" XMonad . StackSet " :
--
> import qualified XMonad . StackSet as W
--
-- You may also wish to redefine the binding to kill a window so it only
-- removes it from the current workspace, if it's present elsewhere:
--
> , ( ( modm .| . shiftMask , xK_c ) , kill1 ) -- @@ Close the focused window
--
Instead of copying a window from one workspace to another maybe you do n't
-- want to have to remember where you placed it. For that consider:
--
> , ( ( modm , xK_b ) , runOrCopy " firefox " ( className = ? " Firefox " ) ) -- @@ run or copy firefox
--
-- Another possibility which this extension provides is 'making window
-- always visible' (i.e. always on current workspace), similar to corresponding
-- metacity functionality. This behaviour is emulated through copying given
-- window to all the workspaces and then removing it when it's unneeded on
-- all workspaces any more.
--
-- Here is the example of keybindings which provide these actions:
--
> , ( ( modm , xK_v ) , windows copyToAll ) -- @@ Make focused window always visible
> , ( ( modm .| . shiftMask , xK_v ) , killAllOtherCopies ) -- @@ Toggle window state back
--
-- For detailed instructions on editing your key bindings, see
-- <#customizing-xmonad the tutorial>.
$ logHook
--
-- To distinguish workspaces containing copies of the focused window, use 'copiesPP'.
-- 'copiesPP' takes a pretty printer and makes it aware of copies of the focused window.
It can be applied when creating a ' XMonad . Hooks . StatusBar . StatusBarConfig ' .
--
-- A sample config looks like this:
--
> mySB = statusBarProp " xmobar " ( copiesPP ( pad . xmobarColor " red " " black " ) xmobarPP )
> main = xmonad $ withEasySB mySB
-- | Take a pretty printer and make it aware of copies by using the provided function
-- to show hidden workspaces that contain copies of the focused window.
copiesPP :: (WorkspaceId -> String) -> PP -> X PP
copiesPP wtoS pp = do
copies <- wsContainingCopies
let check WS{..} = W.tag wsWS `elem` copies
let printer = (asks (isHidden <&&> check) >>= guard) $> wtoS
return pp{ ppPrinters = printer <|> ppPrinters pp }
-- | Copy the focused window to a workspace.
copy :: (Eq s, Eq i, Eq a) => i -> W.StackSet i l a s sd -> W.StackSet i l a s sd
copy n s | Just w <- W.peek s = copyWindow w n s
| otherwise = s
-- | Copy the focused window to all workspaces.
copyToAll :: (Eq s, Eq i, Eq a) => W.StackSet i l a s sd -> W.StackSet i l a s sd
copyToAll s = foldr (copy . W.tag) s (W.workspaces s)
-- | Copy an arbitrary window to a workspace.
copyWindow :: (Eq a, Eq i, Eq s) => a -> i -> W.StackSet i l a s sd -> W.StackSet i l a s sd
copyWindow w n = copy'
where copy' s = if n `W.tagMember` s
then W.view (W.currentTag s) $ insertUp' w $ W.view n s
else s
insertUp' a = W.modify (Just $ W.Stack a [] [])
(\(W.Stack t l r) -> if a `elem` t:l++r
then Just $ W.Stack t l r
else Just $ W.Stack a (L.delete a l) (L.delete a (t:r)))
-- | runOrCopy will run the provided shell command unless it can
-- find a specified window in which case it will copy the window to
-- the current workspace. Similar to (i.e., stolen from) "XMonad.Actions.WindowGo".
runOrCopy :: String -> Query Bool -> X ()
runOrCopy = copyMaybe . spawn
| Copy a window if it exists , run the first argument otherwise .
copyMaybe :: X () -> Query Bool -> X ()
copyMaybe f qry = ifWindow qry copyWin f
where copyWin = ask >>= \w -> doF (\ws -> copyWindow w (W.currentTag ws) ws)
-- | Remove the focused window from this workspace. If it's present in no
-- other workspace, then kill it instead. If we do kill it, we'll get a
delete notify back from X.
--
There are two ways to delete a window . Either just kill it , or if it
-- supports the delete protocol, send a delete event (e.g. firefox).
kill1 :: X ()
kill1 = do ss <- gets windowset
whenJust (W.peek ss) $ \w -> if W.member w $ delete'' w ss
then windows $ delete'' w
else kill
where delete'' w = W.modify Nothing (W.filter (/= w))
-- | Kill all other copies of focused window (if they're present).
-- 'All other' means here 'copies which are not on the current workspace'.
killAllOtherCopies :: X ()
killAllOtherCopies = do ss <- gets windowset
whenJust (W.peek ss) $ \w -> windows $
W.view (W.currentTag ss) .
delFromAllButCurrent w
where
delFromAllButCurrent w ss = foldr (delWinFromWorkspace w . W.tag)
ss
(W.hidden ss ++ map W.workspace (W.visible ss))
delWinFromWorkspace w wid = viewing wid $ W.modify Nothing (W.filter (/= w))
viewing wis f ss = W.view (W.currentTag ss) $ f $ W.view wis ss
-- | A list of hidden workspaces containing a copy of the focused window.
wsContainingCopies :: X [WorkspaceId]
wsContainingCopies = do
ws <- gets windowset
return $ copiesOfOn (W.peek ws) (taggedWindows $ W.hidden ws)
-- | Get a list of tuples (tag, [Window]) for each workspace.
taggedWindows :: [W.Workspace i l a] -> [(i, [a])]
taggedWindows = map $ W.tag &&& W.integrate' . W.stack
-- | Get tags with copies of the focused window (if present.)
copiesOfOn :: (Eq a) => Maybe a -> [(i, [a])] -> [i]
copiesOfOn foc tw = maybe [] hasCopyOf foc
where hasCopyOf f = map fst $ filter ((f `elem` ) . snd) tw
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/571d017b8259340971db1736eedc992a54e9022c/XMonad/Actions/CopyWindow.hs | haskell | ---------------------------------------------------------------------------
|
Description : Duplicate a window on multiple workspaces.
License : BSD3-style (see LICENSE)
Maintainer : ???
Stability : unstable
Portability : unportable
Provides bindings to duplicate a window on multiple workspaces,
providing dwm-like tagging functionality.
---------------------------------------------------------------------------
* Usage
$usage
* Highlight workspaces containing copies in logHook
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@ file:
Then add something like this to your keybindings:
mod-[1 .. 9 ] @@ Switch to workspace N
mod - shift-[1 .. 9 ] @@ Move client to workspace N
mod - control - shift-[1 .. 9 ] @@ Copy client to workspace N
> , (f, m) <- [(W.view, 0), (W.shift, shiftMask), (copy, shiftMask .|. controlMask)]]
To use the above key bindings you need also to import
You may also wish to redefine the binding to kill a window so it only
removes it from the current workspace, if it's present elsewhere:
@@ Close the focused window
want to have to remember where you placed it. For that consider:
@@ run or copy firefox
Another possibility which this extension provides is 'making window
always visible' (i.e. always on current workspace), similar to corresponding
metacity functionality. This behaviour is emulated through copying given
window to all the workspaces and then removing it when it's unneeded on
all workspaces any more.
Here is the example of keybindings which provide these actions:
@@ Make focused window always visible
@@ Toggle window state back
For detailed instructions on editing your key bindings, see
<#customizing-xmonad the tutorial>.
To distinguish workspaces containing copies of the focused window, use 'copiesPP'.
'copiesPP' takes a pretty printer and makes it aware of copies of the focused window.
A sample config looks like this:
| Take a pretty printer and make it aware of copies by using the provided function
to show hidden workspaces that contain copies of the focused window.
| Copy the focused window to a workspace.
| Copy the focused window to all workspaces.
| Copy an arbitrary window to a workspace.
| runOrCopy will run the provided shell command unless it can
find a specified window in which case it will copy the window to
the current workspace. Similar to (i.e., stolen from) "XMonad.Actions.WindowGo".
| Remove the focused window from this workspace. If it's present in no
other workspace, then kill it instead. If we do kill it, we'll get a
supports the delete protocol, send a delete event (e.g. firefox).
| Kill all other copies of focused window (if they're present).
'All other' means here 'copies which are not on the current workspace'.
| A list of hidden workspaces containing a copy of the focused window.
| Get a list of tuples (tag, [Window]) for each workspace.
| Get tags with copies of the focused window (if present.) | # LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
Module : XMonad . Actions . CopyWindow
Copyright : ( c ) < > , < > , < >
module XMonad.Actions.CopyWindow (
copy, copyToAll, copyWindow, runOrCopy
, killAllOtherCopies, kill1, taggedWindows, copiesOfOn
$ logHook
, wsContainingCopies, copiesPP
) where
import XMonad
import XMonad.Prelude
import Control.Arrow ((&&&))
import qualified Data.List as L
import XMonad.Actions.WindowGo
import XMonad.Hooks.StatusBar.PP (PP(..), WS(..), isHidden)
import qualified XMonad.StackSet as W
> import XMonad . Actions . CopyWindow
> [ ( ( m .| . ) , windows $ f i )
> | ( i , k ) < - zip ( workspaces x ) [ xK_1 .. ]
" XMonad . StackSet " :
> import qualified XMonad . StackSet as W
Instead of copying a window from one workspace to another maybe you do n't
$ logHook
It can be applied when creating a ' XMonad . Hooks . StatusBar . StatusBarConfig ' .
> mySB = statusBarProp " xmobar " ( copiesPP ( pad . xmobarColor " red " " black " ) xmobarPP )
> main = xmonad $ withEasySB mySB
copiesPP :: (WorkspaceId -> String) -> PP -> X PP
copiesPP wtoS pp = do
copies <- wsContainingCopies
let check WS{..} = W.tag wsWS `elem` copies
let printer = (asks (isHidden <&&> check) >>= guard) $> wtoS
return pp{ ppPrinters = printer <|> ppPrinters pp }
copy :: (Eq s, Eq i, Eq a) => i -> W.StackSet i l a s sd -> W.StackSet i l a s sd
copy n s | Just w <- W.peek s = copyWindow w n s
| otherwise = s
copyToAll :: (Eq s, Eq i, Eq a) => W.StackSet i l a s sd -> W.StackSet i l a s sd
copyToAll s = foldr (copy . W.tag) s (W.workspaces s)
copyWindow :: (Eq a, Eq i, Eq s) => a -> i -> W.StackSet i l a s sd -> W.StackSet i l a s sd
copyWindow w n = copy'
where copy' s = if n `W.tagMember` s
then W.view (W.currentTag s) $ insertUp' w $ W.view n s
else s
insertUp' a = W.modify (Just $ W.Stack a [] [])
(\(W.Stack t l r) -> if a `elem` t:l++r
then Just $ W.Stack t l r
else Just $ W.Stack a (L.delete a l) (L.delete a (t:r)))
runOrCopy :: String -> Query Bool -> X ()
runOrCopy = copyMaybe . spawn
| Copy a window if it exists , run the first argument otherwise .
copyMaybe :: X () -> Query Bool -> X ()
copyMaybe f qry = ifWindow qry copyWin f
where copyWin = ask >>= \w -> doF (\ws -> copyWindow w (W.currentTag ws) ws)
delete notify back from X.
There are two ways to delete a window . Either just kill it , or if it
kill1 :: X ()
kill1 = do ss <- gets windowset
whenJust (W.peek ss) $ \w -> if W.member w $ delete'' w ss
then windows $ delete'' w
else kill
where delete'' w = W.modify Nothing (W.filter (/= w))
killAllOtherCopies :: X ()
killAllOtherCopies = do ss <- gets windowset
whenJust (W.peek ss) $ \w -> windows $
W.view (W.currentTag ss) .
delFromAllButCurrent w
where
delFromAllButCurrent w ss = foldr (delWinFromWorkspace w . W.tag)
ss
(W.hidden ss ++ map W.workspace (W.visible ss))
delWinFromWorkspace w wid = viewing wid $ W.modify Nothing (W.filter (/= w))
viewing wis f ss = W.view (W.currentTag ss) $ f $ W.view wis ss
wsContainingCopies :: X [WorkspaceId]
wsContainingCopies = do
ws <- gets windowset
return $ copiesOfOn (W.peek ws) (taggedWindows $ W.hidden ws)
taggedWindows :: [W.Workspace i l a] -> [(i, [a])]
taggedWindows = map $ W.tag &&& W.integrate' . W.stack
copiesOfOn :: (Eq a) => Maybe a -> [(i, [a])] -> [i]
copiesOfOn foc tw = maybe [] hasCopyOf foc
where hasCopyOf f = map fst $ filter ((f `elem` ) . snd) tw
|
08fcce79867dc28817295ce8927d1a721c02b13eb5fb30238bc782259b61625c | umutisik/mathvas | Snippet.hs | module Handler.Snippet where
import Import
import Model.Activity
import Model.Snippet
import Widget.Editor
import Widget.RunResult
import Text.Julius (rawJS)
import Database.Persist.Sql (fromSqlKey)
import Text.Blaze (text)
getSnippetR :: StoredSnippetId -> Handler Html
getSnippetR sId = do
userId <- requireAuthId
let isExistingSnippet = True
let snippetId = show (fromSqlKey $ sId)
let numberOfLines = 30
mSnippet <- runDB $ get sId
case mSnippet of
Nothing -> error "There was a problem retrieving this snippet"
Just strsnippet -> let snippet = fromStoredSnippet strsnippet
activity = snippetActivity snippet
activityName = activityId activity
in if (storedSnippetSnippetOwner strsnippet == userId) then
defaultLayout $ do
aDomId <- newIdent
addScript $ StaticR lib_ace_ace_js
setTitle $ text ("Mathvas - " ++ (snippetTitle snippet))
$(widgetFile "homepage")
$(widgetFile "compose")
else error "There was a problem with your permission access to this code."
deleteSnippetR :: StoredSnippetId -> Handler Value
deleteSnippetR sId = do
mUserId <- requireAuthId
runDB $ do delete sId
return $ object []
| null | https://raw.githubusercontent.com/umutisik/mathvas/9f764cd4d54370262c70c7ec3eadae076a1eb489/Handler/Snippet.hs | haskell | module Handler.Snippet where
import Import
import Model.Activity
import Model.Snippet
import Widget.Editor
import Widget.RunResult
import Text.Julius (rawJS)
import Database.Persist.Sql (fromSqlKey)
import Text.Blaze (text)
getSnippetR :: StoredSnippetId -> Handler Html
getSnippetR sId = do
userId <- requireAuthId
let isExistingSnippet = True
let snippetId = show (fromSqlKey $ sId)
let numberOfLines = 30
mSnippet <- runDB $ get sId
case mSnippet of
Nothing -> error "There was a problem retrieving this snippet"
Just strsnippet -> let snippet = fromStoredSnippet strsnippet
activity = snippetActivity snippet
activityName = activityId activity
in if (storedSnippetSnippetOwner strsnippet == userId) then
defaultLayout $ do
aDomId <- newIdent
addScript $ StaticR lib_ace_ace_js
setTitle $ text ("Mathvas - " ++ (snippetTitle snippet))
$(widgetFile "homepage")
$(widgetFile "compose")
else error "There was a problem with your permission access to this code."
deleteSnippetR :: StoredSnippetId -> Handler Value
deleteSnippetR sId = do
mUserId <- requireAuthId
runDB $ do delete sId
return $ object []
| |
c18726b87cb5af8fe139c3e7fbc842acd795dbb57ccbfec79b5bf8ac371a1abb | hcarty/msgpackaf | bench.ml | open Benchmark
module Msgpack = Msgpackaf.Easy
let () =
(* cases.mpac is a test data set from the C msgpack library repo *)
let cases_raw =
let file = "test/cases_compact.mpac" in
let ic = open_in_bin file in
let length = in_channel_length ic in
let content = really_input_string ic length in
close_in ic;
Bigstringaf.of_string ~off:0 ~len:(String.length content) content
in
let cases_parsed = Msgpack.msgs_of_bigstring_exn cases_raw in
(* Bigger messages *)
let make_blob len =
let open Bigarray in
let bs = Array1.create char c_layout len in
Array1.fill bs '\x00';
bs
in
let bigger_parsed =
let open Msgpack in
map'
[
(string "name", string "Bigger");
(string "tag", int64 Int64.max_int);
( string "embedded",
map'
[
( string "numbers",
array' (Array.init 1_000 (fun i -> int64 (Int64.of_int i))) );
(string "string", string (String.make 0x1000 'x'));
(string "blob", bin (make_blob 65_536));
] );
]
in
let bigger_raw = Msgpack.to_bigstring bigger_parsed in
(* Really big message *)
let really_big_parsed =
let open Msgpack in
map'
[
(string "name", string "Really big!");
(string "blob", bin (make_blob (10 * 1_024 * 1_024)));
]
in
let really_big_raw = Msgpack.to_bigstring really_big_parsed in
ignore
@@ throughput1 3 ~name:"Msgpack.msgs_of_bigstring" Msgpack.msgs_of_bigstring
cases_raw;
ignore
@@ throughput1 3 ~name:"Msgpack.msgs_to_bigstring" Msgpack.msgs_to_bigstring
cases_parsed;
ignore
@@ throughput1 3 ~name:"Msgpack.of_bigstring (bigger message)"
Msgpack.of_bigstring bigger_raw;
ignore
@@ throughput1 3 ~name:"Msgpack.to_bigstring (bigger message)"
Msgpack.to_bigstring bigger_parsed;
Gc.compact ();
ignore
@@ throughput1 1 ~name:"Msgpack.of_bigstring (really big message)"
Msgpack.of_bigstring really_big_raw;
Gc.compact ();
ignore
@@ throughput1 1 ~name:"Msgpack.to_bigstring (really big message)"
Msgpack.to_bigstring really_big_parsed;
print_newline ()
| null | https://raw.githubusercontent.com/hcarty/msgpackaf/7cc48b72d75a2ba74c1ff0672a5c64f094883b0d/benchmark/bench.ml | ocaml | cases.mpac is a test data set from the C msgpack library repo
Bigger messages
Really big message | open Benchmark
module Msgpack = Msgpackaf.Easy
let () =
let cases_raw =
let file = "test/cases_compact.mpac" in
let ic = open_in_bin file in
let length = in_channel_length ic in
let content = really_input_string ic length in
close_in ic;
Bigstringaf.of_string ~off:0 ~len:(String.length content) content
in
let cases_parsed = Msgpack.msgs_of_bigstring_exn cases_raw in
let make_blob len =
let open Bigarray in
let bs = Array1.create char c_layout len in
Array1.fill bs '\x00';
bs
in
let bigger_parsed =
let open Msgpack in
map'
[
(string "name", string "Bigger");
(string "tag", int64 Int64.max_int);
( string "embedded",
map'
[
( string "numbers",
array' (Array.init 1_000 (fun i -> int64 (Int64.of_int i))) );
(string "string", string (String.make 0x1000 'x'));
(string "blob", bin (make_blob 65_536));
] );
]
in
let bigger_raw = Msgpack.to_bigstring bigger_parsed in
let really_big_parsed =
let open Msgpack in
map'
[
(string "name", string "Really big!");
(string "blob", bin (make_blob (10 * 1_024 * 1_024)));
]
in
let really_big_raw = Msgpack.to_bigstring really_big_parsed in
ignore
@@ throughput1 3 ~name:"Msgpack.msgs_of_bigstring" Msgpack.msgs_of_bigstring
cases_raw;
ignore
@@ throughput1 3 ~name:"Msgpack.msgs_to_bigstring" Msgpack.msgs_to_bigstring
cases_parsed;
ignore
@@ throughput1 3 ~name:"Msgpack.of_bigstring (bigger message)"
Msgpack.of_bigstring bigger_raw;
ignore
@@ throughput1 3 ~name:"Msgpack.to_bigstring (bigger message)"
Msgpack.to_bigstring bigger_parsed;
Gc.compact ();
ignore
@@ throughput1 1 ~name:"Msgpack.of_bigstring (really big message)"
Msgpack.of_bigstring really_big_raw;
Gc.compact ();
ignore
@@ throughput1 1 ~name:"Msgpack.to_bigstring (really big message)"
Msgpack.to_bigstring really_big_parsed;
print_newline ()
|
6110b1145dc7cf0e74c9a2e6e69c427222471f2f6dfd02b83b98034b9e6f2054 | RiugaBachi/necrophagy | Necrophagy.hs | |
Copyright : ( c ) 2020 Riuga
SPDX - License - Identifier : BSD-3 - Clause
Maintainer : Riuga < >
A concise , type - level , statically - checked EDSL
for programming guitar tablature .
Copyright: (c) 2020 Riuga
SPDX-License-Identifier: BSD-3-Clause
Maintainer: Riuga <>
A concise, type-level, statically-checked Haskell EDSL
for programming guitar tablature.
-}
# OPTIONS_GHC -Wno - missing - signatures #
module Necrophagy (
-- * Tabs
Tablature(..),
TabMeta(..),
TrackList(..),
Program(..),
TimeStrictness(..),
-- * Tracks
Track(..),
-- * Compositions
Composition(..),
type (/),
-- ** Playback
play, at, fret,
-- ** Export
exportMidi,
-- * Measures
Measure(..),
(#),
empty,
-- * Poly-kinded sequences
type (>),
-- * Durations
NoteDurations,
T, T', P, P', Q,
-- * Tuning
Note(..),
Tuning,
-- ** Common Tunings
EStandard(..),
DStandard(..),
DropAb(..),
-- * Notes
On,
-- ** Combinators
type (-),
type (+),
type (*),
-- ** Dynamics
H, M, X,
-- ** Synonyms
Arp, Rep,
-- ** Modifiers
Direction(..),
GraceDynamic(..),
PM, LR, Vb, Lg, Gh, Sl, Gr, Bd,
NH, AH, SH, TH,
Sk,
type (^),
type (//), type (///), type (////),
type (\\), type (\\\), type (\\\\),
-- *** Bend curves
type (-@-),
BenC, BenRelC, BenRelBenC, PreRelC,
-- *** Custom
ParseGraph,
-- * Debugging
-- ** Note values
NoteDenomination,
-- ** Parsing helpers
RString,
FStrings,
WellFormedGraph,
InStringRange,
NonOverlappingChord,
LyricsFitOutline,
GraphFitsOutline,
OutlineTotalsSignature,
-- ** Fractions
Gcd, Simplified,
-- * Re-exports
Nat,
(>>), ($), (.),
undefined,
mempty,
fromString,
fromInteger,
InstrumentName(..)
) where
import Prelude ( ($), const
, Fractional, Double
, String
, Maybe(..), Bool(..), Ordering(..)
, undefined, mempty
, fromIntegral, fromInteger
, otherwise
, realToFrac, fromRational
, IO, putStrLn, pure
)
import qualified Prelude
import Control.Concurrent
import Control.Arrow
import Control.Category ((.), id)
import Control.Monad hiding ((>>))
import Data.Void
import Data.Singletons hiding (Apply)
import Data.Monoid
import Data.Type.Equality
import Data.Type.Bool
import qualified Data.Text as T
import Data.String
import Data.Kind
import Euterpea hiding (PitchClass(..), Text, Marker, Tempo, play)
import qualified Euterpea as E
import GHC.TypeLits ( Nat, KnownNat, natVal
, Symbol, KnownSymbol, symbolVal
, Log2, Mod
, CmpNat
, TypeError, ErrorMessage(..)
)
import qualified GHC.TypeLits as Nat
-- * Tablature
-- | Greatest common denominator
type family Gcd (n :: Nat) (d :: Nat) where
Gcd n 0 = n
Gcd n d = Gcd d (n `Mod` d)
type family Simplified f where
Simplified (n / d) =
(n `Div` Gcd n d) / (d `Div` Gcd n d)
data Tablature = Tablature TabMeta TrackList
data TabMeta
= TabMeta { tabAuthor :: T.Text
, tabArtist :: T.Text
, tabName :: T.Text
, tabDifficulty :: T.Text
, tabComments :: T.Text
}
data TrackList = forall v c. TrackList [Track v c]
data Program p
= Tuned InstrumentName p
data TimeStrictness
= Strict
| Flexible
type family TrackTag (o :: TimeStrictness) c :: Type where
TrackTag 'Strict c = c
TrackTag 'Flexible _ = Void
data Track (r :: TimeStrictness) c where
Track :: forall r p u m m' s s' t t' c. u ~ Tuning p
=> { trackName :: T.Text
, trackProgram :: Program p
, trackBody :: Composition m m' s s' t t' u c
} -> Track r (TrackTag r (Simplified c))
-- * Graphing
-- ** Graph unit
-- | Graph unit; (fret/dynamic) `On` (string)
data On (n :: k) (s :: l)
-- ** Dynamics
-- | Mute (Empty)
data M
-- | Dead
data X
-- | Hold
data H
-- * Combinators
-- | Sequential note combinator
data (-) (a :: k) (b :: l)
infixr 3 -
-- | Parallel arbitrary note combinator
data (+) (a :: k) (b :: l)
infixr 3 +
-- | Parallel ascending combinator (reduces in terms of (+))
data (*) (a :: k) (b :: l)
infixr 3 *
-- ** Synonyms
-- | Fret the note only if it is 'Just
type family (+?) a (b :: Maybe Type) where
a +? ('Just b) = a + b
a +? _ = a
infixr 3 +?
-- | Calculate notes needed to be held from previous sequences
-- in an arpeggio
type family Holds (held :: [Nat]) :: Maybe Type where
Holds '[] = 'Nothing
Holds (h ': hs) = ('Just (H `On` h +? Holds hs))
-- | Maybe to List
type family M2L (x :: Maybe k) :: [k] where
M2L ('Just x) = '[x]
M2L _ = '[]
-- | Root string (of a modifier stack)
type family RString (x :: k) :: Maybe Nat where
RString ((x :: k) `On` s) = 'Just s
RString ((m :: k -> Type) x) = RString x
RString _ = 'Nothing
-- | Fretted strings
type family FStrings xs where
FStrings (x + xs) = M2L (RString x) ::: FStrings xs
FStrings x = M2L (RString x)
type family Arpeggiate (held :: [Nat]) a where
--Arpeggiate hs _ (x - xs) =
-- Arpeggiate hs '[] x - Arpeggiate (FStrings x ::: hs) '[] xs
Arpeggiate held (x `On` s - xs) =
(x `On` s +? Holds held) - Arpeggiate (s ': held) xs
Arpeggiate held (x `On` s) =
x `On` s +? Holds held
Arpeggiate _ _ = TypeError
('Text "Arpeggios must use chords with explicit `On` notation.")
-- | Arpeggios
type Arp a = Arpeggiate '[] a
type family ExpandSeq (n :: Nat) a where
ExpandSeq 1 xs = xs
ExpandSeq n xs = xs - ExpandSeq (n `Sub` 1) xs
-- | Repeat
type Rep (n :: Nat) a
= ExpandSeq n a
-- ** Modifiers
-- | Let ring
data LR (a :: k)
-- | Slide
data Sl (a :: k)
-- | Ghost note
data Gh (a :: k)
data GraceDynamic
= On
| Pre
-- | Grace (dynamic) (modifier) (duration) (group)
data NoteDenomination n
=> Gr (d :: GraceDynamic) m (n :: Nat) (a :: k)
-- | Bend curve vertex / (steps) -@- (time)
Resolution for steps is ( 1/4 ) ( quarter step )
Resolution for time is ( 1/12 ) ( relative to note duration )
data (-@-) f p
type BenC f =
'[ (0/4) -@- (0 / 12)
, f -@- (6 / 12)
]
type BenRelC f =
'[ (0/4) -@- (0 / 12)
, f -@- (3 / 12)
, f -@- (6 / 12)
, (0/4) -@- (9 / 12)
]
type BenRelBenC f =
'[ (0/4) -@- (0 / 12)
, f -@- (2 / 12)
, f -@- (4 / 12)
, (0/4) -@- (6 / 12)
, (0/4) -@- (8 / 12)
, f -@- (10 / 12)
]
type PreRelC f =
'[ f -@- (0 / 12)
, f -@- (4 / 12)
, (0/4) -@- (8 / 12)
]
-- | Bend (curve) (group)
data Bd (c :: [Type]) (a :: k)
-- | Vibrato
data Vb (a :: k)
-- | Palm mutes
data PM (a :: k)
-- | Legato (current to next note)
data Lg (a :: k)
-- | Hammer on / Pull offs, in terms of legato
type (^) (a :: k) (b :: l) = Lg a - b
infixr 6 ^
data Direction = Up | Dw
| String skip by @n@ in the direction @d@ before playing @a@
data Sk (d :: Direction) (n :: Nat) (a :: k)
-- | String skip +1
type (//) a b = a - Sk 'Up 1 b
-- | String skip +2
type (///) a b = a - Sk 'Up 2 b
-- | String skip +3
type (////) a b = a - Sk 'Up 3 b
-- | String skip -1
type (\\) a b = a - Sk 'Dw 1 b
-- | String skip -2
type (\\\) a b = a - Sk 'Dw 2 b
-- | String skip -3
type (\\\\) a b = a - Sk 'Dw 3 b
infixr 1 //
infixr 1 ///
infixr 1 ////
infixr 1 \\
infixr 1 \\\
infixr 1 \\\\
-- ** Harmonics
data NH (a :: k)
data AH (a :: k)
data SH (a :: k)
data TH (a :: k)
-- * Notes
data Note (n :: Nat)
= Ab | A | Bb | B | C | Db | D | Eb | E | F | Gb | G
-- * Poly-kinded sequences
-- | Poly-kinded sequences
data (>) (a :: k) (b :: l)
infixr 1 >
-- * Guitar tunings
type family Tuning p = u | u -> p
data EStandard (n :: Nat) = EStandard
type instance Tuning (EStandard 6)
= 'E @2
> 'A @2
> 'D @3
> 'G @3
> 'B @3
> 'E @4
data DStandard (n :: Nat) = DStandard
type instance Tuning (DStandard 6)
= 'D @2
> 'G @2
> 'C @3
> 'F @3
> 'A @3
> 'D @4
data DropAb (n :: Nat) = DropAb
type instance Tuning (DropAb 6)
= 'Ab @1
> 'Eb @2
> 'Ab @2
> 'Eb @3
> 'Ab @3
> 'Bb @3
-- * Utilities
type Add a b = a Nat.+ b
type Sub a b = a Nat.- b
type Mul a b = a Nat.* b
type Pow a b = a Nat.^ b
type Div a b = Nat.Div a b
type (>=) (a :: Nat) (b :: Nat)
= CmpNat a b == 'GT || CmpNat a b == 'EQ
type family Length (a :: [Type]) :: Nat where
Length '[] = 0
Length (x ': xs) = 1 `Add` Length xs
type family Elem (x :: k) (xs :: [k]) where
Elem x (x ': xs) = 'True
Elem x (_ ': xs) = Elem x xs
Elem x '[] = 'False
type family KLength (a :: k) :: Nat where
KLength ((x :: k) > (xs :: l)) = 1 `Add` KLength xs
KLength (xs :: k) = 1
type family Replicate (n :: Nat) (a :: k) :: [k] where
Replicate 0 _ = '[]
Replicate n x = x ': Replicate (n `Sub` 1) x
-- | Replication
type Repl a b = Replicate a b
type family (:::) (xs :: [k]) (ys :: [k]) :: [k] where
'[] ::: ys = ys
(x ': xs) ::: ys = x ': (xs ::: ys)
type family Ensure (b :: Bool) (s :: Symbol) :: Constraint where
Ensure 'True _ = ()
Ensure 'False s = TypeError ('Text s)
-- | Type-level (<|>) specialized for 'Maybe'.
type family
(<|>) (a :: Maybe k)
(b :: Maybe k) :: Maybe k where
(<|>) 'Nothing 'Nothing = 'Nothing
(<|>) 'Nothing x = x
(<|>) x 'Nothing = x
(<|>) x _ = x
-- | Type-level 'Just unwrap for 'Maybe'
type family Unwrap (a :: Maybe k) :: k where
Unwrap ('Just x) = x
Unwrap _ = TypeError ('Text "Unwrapped 'Nothing")
-- * Composition
-- | Time signatures (quarters/min) | Fractionals
data (/) (n :: Nat) (d :: Nat)
-- | Fraction addition
type family (^+^) f f' where
(b / v) ^+^ (b' / v') =
((b `Mul` v') `Add` (b' `Mul` v)) / (v `Mul` v')
-- | Fraction summation
type family FractionalSum (xs :: [Type]) where
FractionalSum '[] = (0 / 1)
FractionalSum (x ': xs) = x ^+^ FractionalSum xs
-- | Composition
-- @m@ - section marker
-- @s@ - time signature
-- @t@ - tempo
@u@ - tuning
-- @c@ - cumulative time
data Composition (m :: Symbol) (m' :: Symbol)
s s'
(t :: Nat) (t' :: Nat) u c where
Marker
:: forall (m' :: Symbol) m s t u. KnownSymbol m'
=> Composition m m' s s t t u (0 / 1)
Tempo
:: forall (t' :: Nat) t m s u. KnownNat t'
=> Composition m m s s t t' u (0 / 1)
Sig
:: forall s' s (n :: Nat) (d :: Nat) m (t :: Nat) u.
( Fraction s' n d
, NoteDenomination d
)
=> Composition m m s s' t t u (0 / 1)
Bar
:: forall m (n :: Nat) (d :: Nat) (t :: Nat) s u g o l.
( Fraction s n d
, OutlineTotalsSignature s o
, WellFormedGraph (KLength u) g
, GraphFitsOutline o g
, LyricsFitOutline o l
, Musicalize u o g
)
=> Measure o g l
-> Composition m m s s t t u ((n `Mul` t) / (d `Mul` 4))
Compose
:: forall u m m' s s' t t' c c' j r g. ()
=> Composition m m' s s' t t' u c
-> Composition m' g s' r t' j u c'
-> Composition m g s r t j u (c ^+^ c')
-- * Durations
type NoteDenomination (n :: Nat) = (2 `Pow` Log2 n) ~ n
-- | Triplets
data T (v :: Nat)
-- | Triplets (standalone)
data T' (v :: Nat)
-- | Quadruplets
data Q (v :: Nat)
-- | Pointed (single dotted) notes
data P v
-- | Extra-pointed (double dotted) notes
data P' v
type family ExpandDotted (dots :: Nat) (n :: Nat) (d :: Nat) where
ExpandDotted 0 n d = (n / d)
ExpandDotted dots n d =
(n / ((2 `Pow` dots) `Mul` d)) ^+^ ExpandDotted (dots `Sub` 1) n d
type family NoteDurations (v :: k) = (a :: [Type])
type instance NoteDurations (u > v)
= NoteDurations u ::: NoteDurations v
type instance NoteDurations (v :: Nat)
= '[1 / v]
type instance NoteDurations (T (v :: Nat))
= Repl 3 (2 / (3 `Mul` v))
type instance NoteDurations (T' (v :: Nat))
= '[2 / (3 `Mul` v)]
type instance NoteDurations (Q (v :: Nat))
= Repl 4 (1 / v)
type instance NoteDurations (P (v :: Nat))
= '[ExpandDotted 1 1 v]
type instance NoteDurations (P (T' v))
= '[ExpandDotted 1 2 (3 `Mul` v)]
type instance NoteDurations (P' (v :: Nat))
= '[ExpandDotted 2 1 v]
type instance NoteDurations (P' (T' v))
= '[ExpandDotted 2 2 (3 `Mul` v)]
-- | Measure
--
@o@ - parsed durations
-- @g@ - parsed graph
-- @g@ - parsed lyrics
data Measure o g (l :: Maybe [Symbol]) where
-- | Outline (note values)
O
:: forall v g. ()
=> Measure (NoteDurations v) g 'Nothing
-- | Run, @r@ - root (starting) string, @g@ - run graph
R
:: forall r g (o :: [Type]). ()
=> Measure o (ParseGraph r g) 'Nothing
-- | Lyrics, @l@ - lyric sequence
L
:: forall l o g. ()
=> Measure o g ('Just (ParseLyrics l))
-- | Combinator
Splice
:: forall o g l l' h. (h ~ (l <|> l'))
=> Measure o g l
-> Measure o g l'
-> Measure o g h
(#) = Splice
-- | An empty measure
empty :: Measure '[(1/1)] '[M `On` 1] 'Nothing
empty = O @1 # R @1 @M
type family Apply (f :: k -> l) (xs :: [k]) :: [l] where
Apply f '[] = '[]
Apply f (x ': xs) = f x ': Apply f xs
type family ApplyBend (c :: [Type]) (xs :: [k]) :: [l] where
ApplyBend c '[] = '[]
ApplyBend c (x ': xs) = Bd c x ': ApplyBend c xs
type family ApplyGrace (d :: GraceDynamic) m (n :: Nat) (a :: [k]) where
ApplyGrace d m n '[] = '[]
ApplyGrace d m n (x ': xs) = Gr d m n x ': ApplyGrace d m n xs
type family Expand (n :: Nat) (xs :: [k]) :: [k] where
Expand 0 _ = '[]
Expand n xs = xs ::: Expand (n `Sub` 1) xs
type OutlineTotalsSignature s o
= Ensure (Simplified (FractionalSum o) == Simplified s)
"Note value outline does not total time signature."
| Produces a proof if parsed graph @g@ is well - formed .
type family WellFormedGraph (t :: Nat) (g :: k) :: Constraint where
WellFormedGraph _ '[] = ()
-- Sequential test
WellFormedGraph t (x ': xs) =
( WellFormedGraph t x
, WellFormedGraph t xs
)
Parallel test
WellFormedGraph t (x + xs) =
( WellFormedGraph t x
, WellFormedGraph t xs
, NonOverlappingChord (Unwrap (RString x)) (FStrings xs)
)
-- Modifier stack
WellFormedGraph t x = InStringRange t (Unwrap (RString x))
type NonOverlappingChord (x :: Nat) (xs :: [Nat])
= Ensure (Not (x `Elem` xs))
"There can only be one fretted note per string in a chord."
type InStringRange (t :: Nat) (r :: Nat)
= Ensure (t >= r)
"String range out-of-bounds in graph."
type GraphFitsOutline d g'
= Ensure (Length g' == Length d)
"Number of notes in a run must match number of \
\declared note values."
type family LyricsFitOutline d l where
LyricsFitOutline d ('Just l) =
Ensure (Length d >= KLength l)
"Number of lyric syllables must match note outline."
LyricsFitOutline _ _ = ()
type family ParseLyrics (l :: k) :: [Symbol] where
ParseLyrics ((l :: Symbol) > ls) = l ': ParseLyrics ls
ParseLyrics (l :: Symbol) = '[l]
-- | Flatten note modifiers down to a linear list of notes with
-- stacks of modifiers.
--
-- @r@ - current string
-- @g@ - graph
type family ParseGraph (r :: Nat) (g :: k) :: [Type]
-- ** Unit instances
-- | Mute (empty) note
type instance ParseGraph r M
= '[M `On` r]
-- | Dead note
type instance ParseGraph r X
= '[X `On` r]
-- | Held note
type instance ParseGraph r H
= '[H `On` r]
-- | Pluck (single note)
type instance ParseGraph r (n :: Nat)
= '[n `On` r]
-- | Pluck (single note) (explicit string)
type instance ParseGraph r (n `On` s)
= '[n `On` s]
-- ** Combinator instances
-- | Sequence notes
type instance ParseGraph r (xs - ys)
= ParseGraph r xs ::: ParseGraph r ys
-- | Skip up (amount) (group)
type instance ParseGraph r (Sk 'Up n xs)
= ParseGraph (r `Add` n) xs
-- | Skip down (amount) (group)
type instance ParseGraph r (Sk 'Dw n xs)
= ParseGraph (r `Sub` n) xs
-- * Chord instances
type family Head (xs :: [k]) where
Head (x ': _) = x
Head _ = TypeError ('Text "Matching on Head failed.")
type instance ParseGraph r (x * xs)
= '[Head (ParseGraph r x) + Head (ParseGraph (r `Add` 1) xs)]
type instance ParseGraph r ((x `On` s) + xs)
= '[(x `On` s) + Head (ParseGraph r xs)]
-- ** Stock modifier instances
-- | Slide
type instance ParseGraph r (Sl xs)
= Apply Sl (ParseGraph r xs)
-- | Legato (group)
type instance ParseGraph r (Lg xs)
= Apply Lg (ParseGraph r xs)
-- | Ghost note
type instance ParseGraph r (Gh xs)
= Apply Gh (ParseGraph r xs)
-- | Palm mute (group)
type instance ParseGraph r (PM xs)
= Apply PM (ParseGraph r xs)
-- | Vibrato (group)
type instance ParseGraph r (Vb xs)
= Apply Vb (ParseGraph r xs)
-- | Let ring (group)
type instance ParseGraph r (LR xs)
= Apply LR (ParseGraph r xs)
-- | Natural harmonic
type instance ParseGraph r (NH xs)
= Apply NH (ParseGraph r xs)
-- | Artificial harmonic
type instance ParseGraph r (AH xs)
= Apply AH (ParseGraph r xs)
-- | Semi-harmonic
type instance ParseGraph r (SH xs)
= Apply SH (ParseGraph r xs)
-- | Tap harmonic
type instance ParseGraph r (TH xs)
= Apply TH (ParseGraph r xs)
-- | Bend
type instance ParseGraph r (Bd c xs)
= ApplyBend c (ParseGraph r xs)
-- | Grace
type instance ParseGraph r (Gr d m n xs)
= ApplyGrace d m n (ParseGraph r xs)
(>>) = Compose
infixr 1 >>
-- * Music conversion
div :: Fractional a => a -> a -> a
div = (Prelude./)
duration :: forall f n d. Fraction f n d => Proxy f -> Dur
duration _ = realToFrac (natVal (Proxy @n)) `div` realToFrac (natVal (Proxy @d))
type family NoteIndex (n :: Nat) (xs :: k) :: SomeNote where
NoteIndex 1 ((x :: Note _) > _) = 'SomeNote x
NoteIndex 1 (x :: Note _) = 'SomeNote x
NoteIndex n (_ > xs) = NoteIndex (n `Sub` 1) xs
data SomeNote = forall (o :: Nat). SomeNote (Note o)
type family HalfStepsFrom (f :: Nat) (n :: SomeNote) :: SomeNote where
0 `HalfStepsFrom` n = n
n `HalfStepsFrom` ('SomeNote ('Ab :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('A @o)
n `HalfStepsFrom` ('SomeNote ('A :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Bb @o)
n `HalfStepsFrom` ('SomeNote ('Bb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('B @o)
n `HalfStepsFrom` ('SomeNote ('B :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('C @(o `Add` 1))
n `HalfStepsFrom` ('SomeNote ('C :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Db @o)
n `HalfStepsFrom` ('SomeNote ('Db :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('D @o)
n `HalfStepsFrom` ('SomeNote ('D :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Eb @o)
n `HalfStepsFrom` ('SomeNote ('Eb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('E @o)
n `HalfStepsFrom` ('SomeNote ('E :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('F @o)
n `HalfStepsFrom` ('SomeNote ('F :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Gb @o)
n `HalfStepsFrom` ('SomeNote ('Gb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('G @o)
n `HalfStepsFrom` ('SomeNote ('G :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Ab @o)
type LookupNote u (f :: Nat) (s :: Nat)
= f `HalfStepsFrom` NoteIndex s u
class ToPitch (n :: SomeNote) where
toPitch :: Proxy n -> Pitch
instance KnownNat o => ToPitch ('SomeNote ('Ab :: Note o)) where
toPitch _ = (E.Af, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('A :: Note o)) where
toPitch _ = (E.A, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Bb :: Note o)) where
toPitch _ = (E.Bf, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('B :: Note o)) where
toPitch _ = (E.B, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('C :: Note o)) where
toPitch _ = (E.C, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Db :: Note o)) where
toPitch _ = (E.Df, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('D :: Note o)) where
toPitch _ = (E.D, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Eb :: Note o)) where
toPitch _ = (E.Ef, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('E :: Note o)) where
toPitch _ = (E.E, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('F :: Note o)) where
toPitch _ = (E.F, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Gb :: Note o)) where
toPitch _ = (E.Gf, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('G :: Note o)) where
toPitch _ = (E.G, fromIntegral $ natVal (Proxy @o))
type family FractionList n d (ts :: [Type]) :: Constraint where
FractionList n d '[] = ()
FractionList n d (x ': _) = x ~ (n / d)
type Fraction t n d
= ( t ~ (n / d)
, KnownNat n
, KnownNat d
)
exportMidi :: String -> Composition m m' s s' t t' u c -> IO ()
exportMidi file = writeMidi file . Modify (E.Instrument OverdrivenGuitar) . line . composeSlices
play :: Composition m m' s s' t t' u c -> IO ()
play = playDev 2 . Modify (E.Instrument OverdrivenGuitar) . line . composeSlices
at :: String -> Composition m m' s s' t t' u c -> IO ()
at marker (x `Compose` xs)
| sameMarker marker x = playDev 2 $ Modify (E.Tempo 1.75) $ line $ composeSlices xs
| otherwise = at marker xs
at marker m@Marker = when (sameMarker marker m) $ putStrLn "Empty section."
at _ _ = putStrLn "Marker not found."
fret
:: forall position tuningId tuning note fret string.
( position ~ fret `On` string
, tuning ~ Tuning tuningId
, note ~ LookupNote tuning fret string
, ToPitch note
)
=> IO ()
fret = void . forkIO . playDev 2 . Modify (E.Instrument OverdrivenGuitar) . line . pure $ musicalize (Proxy @tuning) (Proxy @'[(1/2)]) (Proxy @'[(fret `On` string)])
sameMarker
:: forall m m' s s' t t' u c. ()
=> String
-> Composition m m' s s' t t' u c
-> Bool
sameMarker marker Marker = marker Prelude.== symbolVal (Proxy @m')
sameMarker _ _ = False
composeSlices :: forall m m' s s' t t' u c. Composition m m' s s' t t' u c -> [Music Pitch]
composeSlices (x `Compose` xs) = go x xs
where
go :: forall q w e j l. ()
=> Composition m q s w t e u j
-> Composition q m' w s' e t' u l
-> [Music Pitch]
go Tempo rs = pure . Modify (E.Tempo . (`div` 120) . fromIntegral . natVal $ Proxy @e) $ line (composeSlices rs)
go l rs = composeSlices l <> composeSlices rs
composeSlices (Bar (_ :: Measure o g l)) = [musicalize (Proxy @u) (Proxy @o) (Proxy @g)]
composeSlices _ = [Prim (Rest 0)]
class Musicalize u (ts :: [Type]) (vs :: [Type]) where
musicalize :: Proxy u -> Proxy ts -> Proxy vs -> Music Pitch
instance Musicalize u '[] '[] where
musicalize _ _ _ = Prim (Rest 0)
instance ( GraphUnit u t v
, Musicalize u ts vs
, Fraction t n d
) => Musicalize u (t ': ts) (v ': vs) where
musicalize _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @v)
:+: musicalize (Proxy @u) (Proxy @ts) (Proxy @vs)
-- | Parsing of graph units, i.e. @f `On` s@ elements.
class GraphUnit u t f where
graphUnit :: Proxy u -> Proxy t -> Proxy f -> Music Pitch
instance ( ToPitch l
, l ~ LookupNote u f s
, Fraction t n d
) => GraphUnit u t ((f :: Nat) `On` (s :: Nat)) where
graphUnit _ _ _ = note (duration (Proxy @t)) . toPitch $ Proxy @l
instance {-# OVERLAPPING #-} Fraction t n d => GraphUnit u t (H `On` s) where
graphUnit _ _ _ = rest . duration $ Proxy @(0/1)
instance {-# OVERLAPPING #-} Fraction t n d => GraphUnit u t (M `On` s) where
graphUnit _ _ _ = rest . duration $ Proxy @t
instance {-# OVERLAPPING #-} Fraction t n d => GraphUnit u t (X `On` s) where
graphUnit _ _ _ = rest . duration $ Proxy @t
instance {-# OVERLAPPABLE #-} GraphUnit u t s => GraphUnit u t ((m :: k -> Type) s) where
graphUnit _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @s)
instance {-# OVERLAPS #-} (GraphUnit u t x, GraphUnit u t xs) => GraphUnit u t (x + xs) where
graphUnit _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @x)
:=: graphUnit (Proxy @u) (Proxy @t) (Proxy @xs)
| null | https://raw.githubusercontent.com/RiugaBachi/necrophagy/b68bf9bc5445db9196665ad92f6f0b2869aaf90c/src/Necrophagy.hs | haskell | * Tabs
* Tracks
* Compositions
** Playback
** Export
* Measures
* Poly-kinded sequences
* Durations
* Tuning
** Common Tunings
* Notes
** Combinators
** Dynamics
** Synonyms
** Modifiers
*** Bend curves
*** Custom
* Debugging
** Note values
** Parsing helpers
** Fractions
* Re-exports
* Tablature
| Greatest common denominator
* Graphing
** Graph unit
| Graph unit; (fret/dynamic) `On` (string)
** Dynamics
| Mute (Empty)
| Dead
| Hold
* Combinators
| Sequential note combinator
| Parallel arbitrary note combinator
| Parallel ascending combinator (reduces in terms of (+))
** Synonyms
| Fret the note only if it is 'Just
| Calculate notes needed to be held from previous sequences
in an arpeggio
| Maybe to List
| Root string (of a modifier stack)
| Fretted strings
Arpeggiate hs _ (x - xs) =
Arpeggiate hs '[] x - Arpeggiate (FStrings x ::: hs) '[] xs
| Arpeggios
| Repeat
** Modifiers
| Let ring
| Slide
| Ghost note
| Grace (dynamic) (modifier) (duration) (group)
| Bend curve vertex / (steps) -@- (time)
| Bend (curve) (group)
| Vibrato
| Palm mutes
| Legato (current to next note)
| Hammer on / Pull offs, in terms of legato
| String skip +1
| String skip +2
| String skip +3
| String skip -1
| String skip -2
| String skip -3
** Harmonics
* Notes
* Poly-kinded sequences
| Poly-kinded sequences
* Guitar tunings
* Utilities
| Replication
| Type-level (<|>) specialized for 'Maybe'.
| Type-level 'Just unwrap for 'Maybe'
* Composition
| Time signatures (quarters/min) | Fractionals
| Fraction addition
| Fraction summation
| Composition
@m@ - section marker
@s@ - time signature
@t@ - tempo
@c@ - cumulative time
* Durations
| Triplets
| Triplets (standalone)
| Quadruplets
| Pointed (single dotted) notes
| Extra-pointed (double dotted) notes
| Measure
@g@ - parsed graph
@g@ - parsed lyrics
| Outline (note values)
| Run, @r@ - root (starting) string, @g@ - run graph
| Lyrics, @l@ - lyric sequence
| Combinator
| An empty measure
Sequential test
Modifier stack
| Flatten note modifiers down to a linear list of notes with
stacks of modifiers.
@r@ - current string
@g@ - graph
** Unit instances
| Mute (empty) note
| Dead note
| Held note
| Pluck (single note)
| Pluck (single note) (explicit string)
** Combinator instances
| Sequence notes
| Skip up (amount) (group)
| Skip down (amount) (group)
* Chord instances
** Stock modifier instances
| Slide
| Legato (group)
| Ghost note
| Palm mute (group)
| Vibrato (group)
| Let ring (group)
| Natural harmonic
| Artificial harmonic
| Semi-harmonic
| Tap harmonic
| Bend
| Grace
* Music conversion
| Parsing of graph units, i.e. @f `On` s@ elements.
# OVERLAPPING #
# OVERLAPPING #
# OVERLAPPING #
# OVERLAPPABLE #
# OVERLAPS # | |
Copyright : ( c ) 2020 Riuga
SPDX - License - Identifier : BSD-3 - Clause
Maintainer : Riuga < >
A concise , type - level , statically - checked EDSL
for programming guitar tablature .
Copyright: (c) 2020 Riuga
SPDX-License-Identifier: BSD-3-Clause
Maintainer: Riuga <>
A concise, type-level, statically-checked Haskell EDSL
for programming guitar tablature.
-}
# OPTIONS_GHC -Wno - missing - signatures #
module Necrophagy (
Tablature(..),
TabMeta(..),
TrackList(..),
Program(..),
TimeStrictness(..),
Track(..),
Composition(..),
type (/),
play, at, fret,
exportMidi,
Measure(..),
(#),
empty,
type (>),
NoteDurations,
T, T', P, P', Q,
Note(..),
Tuning,
EStandard(..),
DStandard(..),
DropAb(..),
On,
type (-),
type (+),
type (*),
H, M, X,
Arp, Rep,
Direction(..),
GraceDynamic(..),
PM, LR, Vb, Lg, Gh, Sl, Gr, Bd,
NH, AH, SH, TH,
Sk,
type (^),
type (//), type (///), type (////),
type (\\), type (\\\), type (\\\\),
type (-@-),
BenC, BenRelC, BenRelBenC, PreRelC,
ParseGraph,
NoteDenomination,
RString,
FStrings,
WellFormedGraph,
InStringRange,
NonOverlappingChord,
LyricsFitOutline,
GraphFitsOutline,
OutlineTotalsSignature,
Gcd, Simplified,
Nat,
(>>), ($), (.),
undefined,
mempty,
fromString,
fromInteger,
InstrumentName(..)
) where
import Prelude ( ($), const
, Fractional, Double
, String
, Maybe(..), Bool(..), Ordering(..)
, undefined, mempty
, fromIntegral, fromInteger
, otherwise
, realToFrac, fromRational
, IO, putStrLn, pure
)
import qualified Prelude
import Control.Concurrent
import Control.Arrow
import Control.Category ((.), id)
import Control.Monad hiding ((>>))
import Data.Void
import Data.Singletons hiding (Apply)
import Data.Monoid
import Data.Type.Equality
import Data.Type.Bool
import qualified Data.Text as T
import Data.String
import Data.Kind
import Euterpea hiding (PitchClass(..), Text, Marker, Tempo, play)
import qualified Euterpea as E
import GHC.TypeLits ( Nat, KnownNat, natVal
, Symbol, KnownSymbol, symbolVal
, Log2, Mod
, CmpNat
, TypeError, ErrorMessage(..)
)
import qualified GHC.TypeLits as Nat
type family Gcd (n :: Nat) (d :: Nat) where
Gcd n 0 = n
Gcd n d = Gcd d (n `Mod` d)
type family Simplified f where
Simplified (n / d) =
(n `Div` Gcd n d) / (d `Div` Gcd n d)
data Tablature = Tablature TabMeta TrackList
data TabMeta
= TabMeta { tabAuthor :: T.Text
, tabArtist :: T.Text
, tabName :: T.Text
, tabDifficulty :: T.Text
, tabComments :: T.Text
}
data TrackList = forall v c. TrackList [Track v c]
data Program p
= Tuned InstrumentName p
data TimeStrictness
= Strict
| Flexible
type family TrackTag (o :: TimeStrictness) c :: Type where
TrackTag 'Strict c = c
TrackTag 'Flexible _ = Void
data Track (r :: TimeStrictness) c where
Track :: forall r p u m m' s s' t t' c. u ~ Tuning p
=> { trackName :: T.Text
, trackProgram :: Program p
, trackBody :: Composition m m' s s' t t' u c
} -> Track r (TrackTag r (Simplified c))
data On (n :: k) (s :: l)
data M
data X
data H
data (-) (a :: k) (b :: l)
infixr 3 -
data (+) (a :: k) (b :: l)
infixr 3 +
data (*) (a :: k) (b :: l)
infixr 3 *
type family (+?) a (b :: Maybe Type) where
a +? ('Just b) = a + b
a +? _ = a
infixr 3 +?
type family Holds (held :: [Nat]) :: Maybe Type where
Holds '[] = 'Nothing
Holds (h ': hs) = ('Just (H `On` h +? Holds hs))
type family M2L (x :: Maybe k) :: [k] where
M2L ('Just x) = '[x]
M2L _ = '[]
type family RString (x :: k) :: Maybe Nat where
RString ((x :: k) `On` s) = 'Just s
RString ((m :: k -> Type) x) = RString x
RString _ = 'Nothing
type family FStrings xs where
FStrings (x + xs) = M2L (RString x) ::: FStrings xs
FStrings x = M2L (RString x)
type family Arpeggiate (held :: [Nat]) a where
Arpeggiate held (x `On` s - xs) =
(x `On` s +? Holds held) - Arpeggiate (s ': held) xs
Arpeggiate held (x `On` s) =
x `On` s +? Holds held
Arpeggiate _ _ = TypeError
('Text "Arpeggios must use chords with explicit `On` notation.")
type Arp a = Arpeggiate '[] a
type family ExpandSeq (n :: Nat) a where
ExpandSeq 1 xs = xs
ExpandSeq n xs = xs - ExpandSeq (n `Sub` 1) xs
type Rep (n :: Nat) a
= ExpandSeq n a
data LR (a :: k)
data Sl (a :: k)
data Gh (a :: k)
data GraceDynamic
= On
| Pre
data NoteDenomination n
=> Gr (d :: GraceDynamic) m (n :: Nat) (a :: k)
Resolution for steps is ( 1/4 ) ( quarter step )
Resolution for time is ( 1/12 ) ( relative to note duration )
data (-@-) f p
type BenC f =
'[ (0/4) -@- (0 / 12)
, f -@- (6 / 12)
]
type BenRelC f =
'[ (0/4) -@- (0 / 12)
, f -@- (3 / 12)
, f -@- (6 / 12)
, (0/4) -@- (9 / 12)
]
type BenRelBenC f =
'[ (0/4) -@- (0 / 12)
, f -@- (2 / 12)
, f -@- (4 / 12)
, (0/4) -@- (6 / 12)
, (0/4) -@- (8 / 12)
, f -@- (10 / 12)
]
type PreRelC f =
'[ f -@- (0 / 12)
, f -@- (4 / 12)
, (0/4) -@- (8 / 12)
]
data Bd (c :: [Type]) (a :: k)
data Vb (a :: k)
data PM (a :: k)
data Lg (a :: k)
type (^) (a :: k) (b :: l) = Lg a - b
infixr 6 ^
data Direction = Up | Dw
| String skip by @n@ in the direction @d@ before playing @a@
data Sk (d :: Direction) (n :: Nat) (a :: k)
type (//) a b = a - Sk 'Up 1 b
type (///) a b = a - Sk 'Up 2 b
type (////) a b = a - Sk 'Up 3 b
type (\\) a b = a - Sk 'Dw 1 b
type (\\\) a b = a - Sk 'Dw 2 b
type (\\\\) a b = a - Sk 'Dw 3 b
infixr 1 //
infixr 1 ///
infixr 1 ////
infixr 1 \\
infixr 1 \\\
infixr 1 \\\\
data NH (a :: k)
data AH (a :: k)
data SH (a :: k)
data TH (a :: k)
data Note (n :: Nat)
= Ab | A | Bb | B | C | Db | D | Eb | E | F | Gb | G
data (>) (a :: k) (b :: l)
infixr 1 >
type family Tuning p = u | u -> p
data EStandard (n :: Nat) = EStandard
type instance Tuning (EStandard 6)
= 'E @2
> 'A @2
> 'D @3
> 'G @3
> 'B @3
> 'E @4
data DStandard (n :: Nat) = DStandard
type instance Tuning (DStandard 6)
= 'D @2
> 'G @2
> 'C @3
> 'F @3
> 'A @3
> 'D @4
data DropAb (n :: Nat) = DropAb
type instance Tuning (DropAb 6)
= 'Ab @1
> 'Eb @2
> 'Ab @2
> 'Eb @3
> 'Ab @3
> 'Bb @3
type Add a b = a Nat.+ b
type Sub a b = a Nat.- b
type Mul a b = a Nat.* b
type Pow a b = a Nat.^ b
type Div a b = Nat.Div a b
type (>=) (a :: Nat) (b :: Nat)
= CmpNat a b == 'GT || CmpNat a b == 'EQ
type family Length (a :: [Type]) :: Nat where
Length '[] = 0
Length (x ': xs) = 1 `Add` Length xs
type family Elem (x :: k) (xs :: [k]) where
Elem x (x ': xs) = 'True
Elem x (_ ': xs) = Elem x xs
Elem x '[] = 'False
type family KLength (a :: k) :: Nat where
KLength ((x :: k) > (xs :: l)) = 1 `Add` KLength xs
KLength (xs :: k) = 1
type family Replicate (n :: Nat) (a :: k) :: [k] where
Replicate 0 _ = '[]
Replicate n x = x ': Replicate (n `Sub` 1) x
type Repl a b = Replicate a b
type family (:::) (xs :: [k]) (ys :: [k]) :: [k] where
'[] ::: ys = ys
(x ': xs) ::: ys = x ': (xs ::: ys)
type family Ensure (b :: Bool) (s :: Symbol) :: Constraint where
Ensure 'True _ = ()
Ensure 'False s = TypeError ('Text s)
type family
(<|>) (a :: Maybe k)
(b :: Maybe k) :: Maybe k where
(<|>) 'Nothing 'Nothing = 'Nothing
(<|>) 'Nothing x = x
(<|>) x 'Nothing = x
(<|>) x _ = x
type family Unwrap (a :: Maybe k) :: k where
Unwrap ('Just x) = x
Unwrap _ = TypeError ('Text "Unwrapped 'Nothing")
data (/) (n :: Nat) (d :: Nat)
type family (^+^) f f' where
(b / v) ^+^ (b' / v') =
((b `Mul` v') `Add` (b' `Mul` v)) / (v `Mul` v')
type family FractionalSum (xs :: [Type]) where
FractionalSum '[] = (0 / 1)
FractionalSum (x ': xs) = x ^+^ FractionalSum xs
@u@ - tuning
data Composition (m :: Symbol) (m' :: Symbol)
s s'
(t :: Nat) (t' :: Nat) u c where
Marker
:: forall (m' :: Symbol) m s t u. KnownSymbol m'
=> Composition m m' s s t t u (0 / 1)
Tempo
:: forall (t' :: Nat) t m s u. KnownNat t'
=> Composition m m s s t t' u (0 / 1)
Sig
:: forall s' s (n :: Nat) (d :: Nat) m (t :: Nat) u.
( Fraction s' n d
, NoteDenomination d
)
=> Composition m m s s' t t u (0 / 1)
Bar
:: forall m (n :: Nat) (d :: Nat) (t :: Nat) s u g o l.
( Fraction s n d
, OutlineTotalsSignature s o
, WellFormedGraph (KLength u) g
, GraphFitsOutline o g
, LyricsFitOutline o l
, Musicalize u o g
)
=> Measure o g l
-> Composition m m s s t t u ((n `Mul` t) / (d `Mul` 4))
Compose
:: forall u m m' s s' t t' c c' j r g. ()
=> Composition m m' s s' t t' u c
-> Composition m' g s' r t' j u c'
-> Composition m g s r t j u (c ^+^ c')
type NoteDenomination (n :: Nat) = (2 `Pow` Log2 n) ~ n
data T (v :: Nat)
data T' (v :: Nat)
data Q (v :: Nat)
data P v
data P' v
type family ExpandDotted (dots :: Nat) (n :: Nat) (d :: Nat) where
ExpandDotted 0 n d = (n / d)
ExpandDotted dots n d =
(n / ((2 `Pow` dots) `Mul` d)) ^+^ ExpandDotted (dots `Sub` 1) n d
type family NoteDurations (v :: k) = (a :: [Type])
type instance NoteDurations (u > v)
= NoteDurations u ::: NoteDurations v
type instance NoteDurations (v :: Nat)
= '[1 / v]
type instance NoteDurations (T (v :: Nat))
= Repl 3 (2 / (3 `Mul` v))
type instance NoteDurations (T' (v :: Nat))
= '[2 / (3 `Mul` v)]
type instance NoteDurations (Q (v :: Nat))
= Repl 4 (1 / v)
type instance NoteDurations (P (v :: Nat))
= '[ExpandDotted 1 1 v]
type instance NoteDurations (P (T' v))
= '[ExpandDotted 1 2 (3 `Mul` v)]
type instance NoteDurations (P' (v :: Nat))
= '[ExpandDotted 2 1 v]
type instance NoteDurations (P' (T' v))
= '[ExpandDotted 2 2 (3 `Mul` v)]
@o@ - parsed durations
data Measure o g (l :: Maybe [Symbol]) where
O
:: forall v g. ()
=> Measure (NoteDurations v) g 'Nothing
R
:: forall r g (o :: [Type]). ()
=> Measure o (ParseGraph r g) 'Nothing
L
:: forall l o g. ()
=> Measure o g ('Just (ParseLyrics l))
Splice
:: forall o g l l' h. (h ~ (l <|> l'))
=> Measure o g l
-> Measure o g l'
-> Measure o g h
(#) = Splice
empty :: Measure '[(1/1)] '[M `On` 1] 'Nothing
empty = O @1 # R @1 @M
type family Apply (f :: k -> l) (xs :: [k]) :: [l] where
Apply f '[] = '[]
Apply f (x ': xs) = f x ': Apply f xs
type family ApplyBend (c :: [Type]) (xs :: [k]) :: [l] where
ApplyBend c '[] = '[]
ApplyBend c (x ': xs) = Bd c x ': ApplyBend c xs
type family ApplyGrace (d :: GraceDynamic) m (n :: Nat) (a :: [k]) where
ApplyGrace d m n '[] = '[]
ApplyGrace d m n (x ': xs) = Gr d m n x ': ApplyGrace d m n xs
type family Expand (n :: Nat) (xs :: [k]) :: [k] where
Expand 0 _ = '[]
Expand n xs = xs ::: Expand (n `Sub` 1) xs
type OutlineTotalsSignature s o
= Ensure (Simplified (FractionalSum o) == Simplified s)
"Note value outline does not total time signature."
| Produces a proof if parsed graph @g@ is well - formed .
type family WellFormedGraph (t :: Nat) (g :: k) :: Constraint where
WellFormedGraph _ '[] = ()
WellFormedGraph t (x ': xs) =
( WellFormedGraph t x
, WellFormedGraph t xs
)
Parallel test
WellFormedGraph t (x + xs) =
( WellFormedGraph t x
, WellFormedGraph t xs
, NonOverlappingChord (Unwrap (RString x)) (FStrings xs)
)
WellFormedGraph t x = InStringRange t (Unwrap (RString x))
type NonOverlappingChord (x :: Nat) (xs :: [Nat])
= Ensure (Not (x `Elem` xs))
"There can only be one fretted note per string in a chord."
type InStringRange (t :: Nat) (r :: Nat)
= Ensure (t >= r)
"String range out-of-bounds in graph."
type GraphFitsOutline d g'
= Ensure (Length g' == Length d)
"Number of notes in a run must match number of \
\declared note values."
type family LyricsFitOutline d l where
LyricsFitOutline d ('Just l) =
Ensure (Length d >= KLength l)
"Number of lyric syllables must match note outline."
LyricsFitOutline _ _ = ()
type family ParseLyrics (l :: k) :: [Symbol] where
ParseLyrics ((l :: Symbol) > ls) = l ': ParseLyrics ls
ParseLyrics (l :: Symbol) = '[l]
type family ParseGraph (r :: Nat) (g :: k) :: [Type]
type instance ParseGraph r M
= '[M `On` r]
type instance ParseGraph r X
= '[X `On` r]
type instance ParseGraph r H
= '[H `On` r]
type instance ParseGraph r (n :: Nat)
= '[n `On` r]
type instance ParseGraph r (n `On` s)
= '[n `On` s]
type instance ParseGraph r (xs - ys)
= ParseGraph r xs ::: ParseGraph r ys
type instance ParseGraph r (Sk 'Up n xs)
= ParseGraph (r `Add` n) xs
type instance ParseGraph r (Sk 'Dw n xs)
= ParseGraph (r `Sub` n) xs
type family Head (xs :: [k]) where
Head (x ': _) = x
Head _ = TypeError ('Text "Matching on Head failed.")
type instance ParseGraph r (x * xs)
= '[Head (ParseGraph r x) + Head (ParseGraph (r `Add` 1) xs)]
type instance ParseGraph r ((x `On` s) + xs)
= '[(x `On` s) + Head (ParseGraph r xs)]
type instance ParseGraph r (Sl xs)
= Apply Sl (ParseGraph r xs)
type instance ParseGraph r (Lg xs)
= Apply Lg (ParseGraph r xs)
type instance ParseGraph r (Gh xs)
= Apply Gh (ParseGraph r xs)
type instance ParseGraph r (PM xs)
= Apply PM (ParseGraph r xs)
type instance ParseGraph r (Vb xs)
= Apply Vb (ParseGraph r xs)
type instance ParseGraph r (LR xs)
= Apply LR (ParseGraph r xs)
type instance ParseGraph r (NH xs)
= Apply NH (ParseGraph r xs)
type instance ParseGraph r (AH xs)
= Apply AH (ParseGraph r xs)
type instance ParseGraph r (SH xs)
= Apply SH (ParseGraph r xs)
type instance ParseGraph r (TH xs)
= Apply TH (ParseGraph r xs)
type instance ParseGraph r (Bd c xs)
= ApplyBend c (ParseGraph r xs)
type instance ParseGraph r (Gr d m n xs)
= ApplyGrace d m n (ParseGraph r xs)
(>>) = Compose
infixr 1 >>
div :: Fractional a => a -> a -> a
div = (Prelude./)
duration :: forall f n d. Fraction f n d => Proxy f -> Dur
duration _ = realToFrac (natVal (Proxy @n)) `div` realToFrac (natVal (Proxy @d))
type family NoteIndex (n :: Nat) (xs :: k) :: SomeNote where
NoteIndex 1 ((x :: Note _) > _) = 'SomeNote x
NoteIndex 1 (x :: Note _) = 'SomeNote x
NoteIndex n (_ > xs) = NoteIndex (n `Sub` 1) xs
data SomeNote = forall (o :: Nat). SomeNote (Note o)
type family HalfStepsFrom (f :: Nat) (n :: SomeNote) :: SomeNote where
0 `HalfStepsFrom` n = n
n `HalfStepsFrom` ('SomeNote ('Ab :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('A @o)
n `HalfStepsFrom` ('SomeNote ('A :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Bb @o)
n `HalfStepsFrom` ('SomeNote ('Bb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('B @o)
n `HalfStepsFrom` ('SomeNote ('B :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('C @(o `Add` 1))
n `HalfStepsFrom` ('SomeNote ('C :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Db @o)
n `HalfStepsFrom` ('SomeNote ('Db :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('D @o)
n `HalfStepsFrom` ('SomeNote ('D :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Eb @o)
n `HalfStepsFrom` ('SomeNote ('Eb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('E @o)
n `HalfStepsFrom` ('SomeNote ('E :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('F @o)
n `HalfStepsFrom` ('SomeNote ('F :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Gb @o)
n `HalfStepsFrom` ('SomeNote ('Gb :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('G @o)
n `HalfStepsFrom` ('SomeNote ('G :: Note o)) = (n `Sub` 1) `HalfStepsFrom` 'SomeNote ('Ab @o)
type LookupNote u (f :: Nat) (s :: Nat)
= f `HalfStepsFrom` NoteIndex s u
class ToPitch (n :: SomeNote) where
toPitch :: Proxy n -> Pitch
instance KnownNat o => ToPitch ('SomeNote ('Ab :: Note o)) where
toPitch _ = (E.Af, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('A :: Note o)) where
toPitch _ = (E.A, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Bb :: Note o)) where
toPitch _ = (E.Bf, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('B :: Note o)) where
toPitch _ = (E.B, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('C :: Note o)) where
toPitch _ = (E.C, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Db :: Note o)) where
toPitch _ = (E.Df, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('D :: Note o)) where
toPitch _ = (E.D, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Eb :: Note o)) where
toPitch _ = (E.Ef, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('E :: Note o)) where
toPitch _ = (E.E, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('F :: Note o)) where
toPitch _ = (E.F, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('Gb :: Note o)) where
toPitch _ = (E.Gf, fromIntegral $ natVal (Proxy @o))
instance KnownNat o => ToPitch ('SomeNote ('G :: Note o)) where
toPitch _ = (E.G, fromIntegral $ natVal (Proxy @o))
type family FractionList n d (ts :: [Type]) :: Constraint where
FractionList n d '[] = ()
FractionList n d (x ': _) = x ~ (n / d)
type Fraction t n d
= ( t ~ (n / d)
, KnownNat n
, KnownNat d
)
exportMidi :: String -> Composition m m' s s' t t' u c -> IO ()
exportMidi file = writeMidi file . Modify (E.Instrument OverdrivenGuitar) . line . composeSlices
play :: Composition m m' s s' t t' u c -> IO ()
play = playDev 2 . Modify (E.Instrument OverdrivenGuitar) . line . composeSlices
at :: String -> Composition m m' s s' t t' u c -> IO ()
at marker (x `Compose` xs)
| sameMarker marker x = playDev 2 $ Modify (E.Tempo 1.75) $ line $ composeSlices xs
| otherwise = at marker xs
at marker m@Marker = when (sameMarker marker m) $ putStrLn "Empty section."
at _ _ = putStrLn "Marker not found."
fret
:: forall position tuningId tuning note fret string.
( position ~ fret `On` string
, tuning ~ Tuning tuningId
, note ~ LookupNote tuning fret string
, ToPitch note
)
=> IO ()
fret = void . forkIO . playDev 2 . Modify (E.Instrument OverdrivenGuitar) . line . pure $ musicalize (Proxy @tuning) (Proxy @'[(1/2)]) (Proxy @'[(fret `On` string)])
sameMarker
:: forall m m' s s' t t' u c. ()
=> String
-> Composition m m' s s' t t' u c
-> Bool
sameMarker marker Marker = marker Prelude.== symbolVal (Proxy @m')
sameMarker _ _ = False
composeSlices :: forall m m' s s' t t' u c. Composition m m' s s' t t' u c -> [Music Pitch]
composeSlices (x `Compose` xs) = go x xs
where
go :: forall q w e j l. ()
=> Composition m q s w t e u j
-> Composition q m' w s' e t' u l
-> [Music Pitch]
go Tempo rs = pure . Modify (E.Tempo . (`div` 120) . fromIntegral . natVal $ Proxy @e) $ line (composeSlices rs)
go l rs = composeSlices l <> composeSlices rs
composeSlices (Bar (_ :: Measure o g l)) = [musicalize (Proxy @u) (Proxy @o) (Proxy @g)]
composeSlices _ = [Prim (Rest 0)]
class Musicalize u (ts :: [Type]) (vs :: [Type]) where
musicalize :: Proxy u -> Proxy ts -> Proxy vs -> Music Pitch
instance Musicalize u '[] '[] where
musicalize _ _ _ = Prim (Rest 0)
instance ( GraphUnit u t v
, Musicalize u ts vs
, Fraction t n d
) => Musicalize u (t ': ts) (v ': vs) where
musicalize _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @v)
:+: musicalize (Proxy @u) (Proxy @ts) (Proxy @vs)
class GraphUnit u t f where
graphUnit :: Proxy u -> Proxy t -> Proxy f -> Music Pitch
instance ( ToPitch l
, l ~ LookupNote u f s
, Fraction t n d
) => GraphUnit u t ((f :: Nat) `On` (s :: Nat)) where
graphUnit _ _ _ = note (duration (Proxy @t)) . toPitch $ Proxy @l
graphUnit _ _ _ = rest . duration $ Proxy @(0/1)
graphUnit _ _ _ = rest . duration $ Proxy @t
graphUnit _ _ _ = rest . duration $ Proxy @t
graphUnit _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @s)
graphUnit _ _ _ = graphUnit (Proxy @u) (Proxy @t) (Proxy @x)
:=: graphUnit (Proxy @u) (Proxy @t) (Proxy @xs)
|
0ed5f860774431ce9862e4f5eb434407f3358924682dbe8076760bb3dabb2766 | mstksg/backprop-learn | Regression.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ApplicativeDo #-}
# LANGUAGE
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE KindSignatures #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
module Backprop.Learn.Model.Regression (
-- * Linear Regression
linReg, logReg
, LRp(..), lrAlpha, lrBeta, runLRp
-- * Reshape
, reshapeLRpInput, reshapeLRpOutput
, expandLRpInput, expandLRpOutput
, premuteLRpInput, permuteLRpOutput
* ARIMA
, arima, autoregressive, movingAverage, arma
, ARIMAp(..), ARIMAs(..)
, arimaPhi, arimaTheta, arimaConstant, arimaYPred, arimaYHist, arimaEHist
) where
import Backprop.Learn.Initialize
import Backprop.Learn.Model.Combinator
import Backprop.Learn.Model.Function
import Backprop.Learn.Model.Types
import Backprop.Learn.Regularize
import Control.DeepSeq
import Control.Monad.Primitive
import Data.Finite
import Data.Kind
import Data.List
import Data.Maybe
import Data.Proxy
import Data.Type.Equality
import Data.Typeable
import GHC.Generics (Generic)
import GHC.TypeLits.Compare
import GHC.TypeNats
import Lens.Micro.TH
import Numeric.Backprop
import Numeric.LinearAlgebra.Static.Backprop
import Numeric.LinearAlgebra.Static.Vector
import Numeric.OneLiner
import Numeric.Opto.Ref
import Numeric.Opto.Update hiding ((<.>))
import Statistics.Distribution
import Unsafe.Coerce
import qualified Data.Binary as Bi
import qualified Data.Vector.Generic.Sized as SVG
import qualified Data.Vector.Sized as SV
import qualified Data.Vector.Storable.Sized as SVS
import qualified Numeric.LinearAlgebra as HU
import qualified Numeric.LinearAlgebra.Static as H
import qualified System.Random.MWC as MWC
-- | Linear Regression parameter
data LRp (i :: Nat) (o :: Nat) = LRp
{ _lrAlpha :: !(R o)
, _lrBeta :: !(L o i)
}
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Bi.Binary, Initialize, Backprop)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Num (LRp i o)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Fractional (LRp i o)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Floating (LRp i o)
makeLenses ''LRp
instance (PrimMonad m, KnownNat i, KnownNat o) => Mutable m (LRp i o) where
type Ref m (LRp i o) = GRef m (LRp i o)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (PrimMonad m, KnownNat i, KnownNat o) => LinearInPlace m Double (LRp i o)
instance (KnownNat i, KnownNat o) => Regularize (LRp i o) where
rnorm_1 = rnorm_1 . _lrBeta
rnorm_2 = rnorm_2 . _lrBeta
lasso r LRp{..} = LRp { _lrAlpha = 0
, _lrBeta = lasso r _lrBeta
}
ridge r LRp{..} = LRp { _lrAlpha = 0
, _lrBeta = ridge r _lrBeta
}
instance (KnownNat i, KnownNat o, PrimMonad m) => Learnable m (LRp i o)
runLRp
:: (KnownNat i, KnownNat o, Reifies s W)
=> BVar s (LRp i o)
-> BVar s (R i)
-> BVar s (R o)
runLRp lrp x = (lrp ^^. lrBeta) #> x + (lrp ^^. lrAlpha)
-- | Reshape an 'LRp' to take more or less inputs. If more, new parameters
-- are initialized randomly according to the given distribution.
reshapeLRpInput
:: (ContGen d, PrimMonad m, KnownNat i, KnownNat i', KnownNat o)
=> d
-> MWC.Gen (PrimState m)
-> LRp i o
-> m (LRp i' o)
reshapeLRpInput d g (LRp α β) =
LRp α <$> reshapeLCols d g β
-- | Reshape an 'LRp' to return more or less outputs If more, new
-- parameters are initialized randomly according to the given distribution.
reshapeLRpOutput
:: (ContGen d, PrimMonad m, KnownNat i, KnownNat o, KnownNat o')
=> d
-> MWC.Gen (PrimState m)
-> LRp i o
-> m (LRp i o')
reshapeLRpOutput d g (LRp α β) =
LRp <$> reshapeR d g α
<*> reshapeLRows d g β
linReg
:: (KnownNat i, KnownNat o)
=> Model ('Just (LRp i o)) 'Nothing (R i) (R o)
linReg = modelStatelessD (\(PJust p) -> runLRp p)
logReg
:: (KnownNat i, KnownNat o)
=> Model ('Just (LRp i o)) 'Nothing (R i) (R o)
logReg = funcD logistic <~ linReg
-- | Adjust an 'LRp' to take extra inputs, initialized randomly.
--
-- Initial contributions to each output is randomized.
expandLRpInput
:: (PrimMonad m, ContGen d, KnownNat i, KnownNat j, KnownNat o)
=> LRp i o
-> d
-> MWC.Gen (PrimState m)
-> m (LRp (i + j) o)
expandLRpInput LRp{..} d g = LRp _lrAlpha . (_lrBeta H.|||) <$> initialize d g
-- | Adjust an 'LRp' to return extra ouputs, initialized randomly
expandLRpOutput
:: (PrimMonad m, ContGen d, KnownNat i, KnownNat o, KnownNat p)
=> LRp i o
-> d
-> MWC.Gen (PrimState m)
-> m (LRp i (o + p))
expandLRpOutput LRp{..} d g = do
newAlpha <- initialize d g
newBeta <- initialize d g
pure (LRp (_lrAlpha H.# newAlpha) (_lrBeta H.=== newBeta))
-- | Premute (or remove) inputs
--
-- Removed inputs will simply have their contributions removed from each
-- output.
premuteLRpInput
:: (KnownNat i, KnownNat o)
=> SV.Vector i' (Finite i)
-> LRp i o
-> LRp i' o
premuteLRpInput is p = p { _lrBeta = colsL . fmap (β `SV.index`) $ is }
where
β = lCols (_lrBeta p)
-- | Premute (or remove) outputs
permuteLRpOutput
:: (KnownNat i, KnownNat o)
=> SV.Vector o' (Finite o)
-> LRp i o
-> LRp i o'
permuteLRpOutput is LRp{..} =
LRp { _lrAlpha = vecR . SVG.convert . fmap (α `SVS.index`) $ is
, _lrBeta = rowsL . fmap (β `SV.index`) $ is
}
where
α = rVec _lrAlpha
β = lRows _lrBeta
| ' ARIMA ' parmaeters
data ARIMAp :: Nat -> Nat -> Type where
ARIMAp :: { _arimaPhi :: !(R p)
, _arimaTheta :: !(R q)
, _arimaConstant :: !Double
}
-> ARIMAp p q
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)
deriving via (GNum (ARIMAp p q)) instance Num (ARIMAp p q)
deriving via (GNum (ARIMAp p q)) instance Fractional (ARIMAp p q)
deriving via (GNum (ARIMAp p q)) instance Floating (ARIMAp p q)
makeLenses ''ARIMAp
| ' ARIMA ' state
data ARIMAs :: Nat -> Nat -> Nat -> Type where
ARIMAs :: { _arimaYPred :: !Double
, _arimaYHist :: !(R (p + d))
, _arimaEHist :: !(R q)
}
-> ARIMAs p d q
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)
deriving via (NoRegularize (ARIMAs p d q)) instance Regularize (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Num (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Fractional (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Floating (ARIMAs p d q)
makeLenses ''ARIMAs
arima
:: forall p d q. (KnownNat p, KnownNat d, KnownNat q)
=> Model ('Just (ARIMAp p q)) ('Just (ARIMAs p d q)) Double Double
arima = modelD $ \(PJust p) x (PJust s) ->
let d :: L p (p + d)
d = difference
e = x - (s ^^. arimaYPred)
y = (p ^^. arimaConstant)
+ (p ^^. arimaPhi ) <.> (constVar d #> (s ^^. arimaYHist))
+ (p ^^. arimaTheta) <.> (s ^^. arimaEHist)
yHist' = case Proxy @1 %<=? Proxy @(p + d) of
LE Refl -> single y # constVar dropLast #> (s ^^. arimaYHist)
NLE _ _ -> 0
eHist' = case Proxy @1 %<=? Proxy @q of
LE Refl -> single e # constVar dropLast #> (s ^^. arimaEHist)
NLE _ _ -> 0
s' = isoVar3 ARIMAs (\(ARIMAs pr yh eh) -> (pr,yh,eh))
y
yHist'
eHist'
in (y, PJust s')
autoregressive
:: KnownNat p
=> Model ('Just (ARIMAp p 0)) ('Just (ARIMAs p 0 0)) Double Double
autoregressive = arima
movingAverage
:: KnownNat q
=> Model ('Just (ARIMAp 0 q)) ('Just (ARIMAs 0 0 q)) Double Double
movingAverage = arima
arma
:: (KnownNat p, KnownNat q)
=> Model ('Just (ARIMAp p q)) ('Just (ARIMAs p 0 q)) Double Double
arma = arima
monosquare :: forall n. (n <=? (n ^ 2)) :~: 'True
monosquare = unsafeCoerce Refl
dropLast :: forall n. (KnownNat n, 1 <= n) => L (n - 1) n
dropLast = case monosquare @n of
Refl -> vecL . SVS.generate $ \ij ->
let i :: Finite n
j :: Finite (n - 1)
(i, j) = separateProduct ij
in if fromIntegral @_ @Int i == fromIntegral j
then 1
else 0
single :: Reifies s W => BVar s Double -> BVar s (R 1)
single = konst
difference'
:: Int -- ^ initial
-> Int -- ^ target
-> HU.Matrix Double -- ^ target x initial
difference' n m = foldl' go (HU.ident m) [m + 1 .. n]
where
go x k = x HU.<> d k
d k = HU.build (k-1, k) $ \i j ->
case round @_ @Int (j - i) of
0 -> 1
1 -> -1
_ -> 0
difference :: forall n m. (KnownNat n, KnownNat m) => L n (n + m)
difference = fromJust . H.create $ difference' (n + m) n
where
n = fromIntegral $ natVal (Proxy @n)
m = fromIntegral $ natVal (Proxy @m)
instance (PrimMonad m, KnownNat p, KnownNat q) => Mutable m (ARIMAp p q) where
type Ref m (ARIMAp p q) = GRef m (ARIMAp p q)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (PrimMonad m, KnownNat p, KnownNat d, KnownNat q) => Mutable m (ARIMAs p d q) where
type Ref m (ARIMAs p d q) = GRef m (ARIMAs p d q)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (KnownNat p, KnownNat q, PrimMonad m) => LinearInPlace m Double (ARIMAp p q)
instance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => LinearInPlace m Double (ARIMAs p d q)
instance (KnownNat p, KnownNat q) => Regularize (ARIMAp p q) where
rnorm_1 ARIMAp{..} = rnorm_1 _arimaPhi + rnorm_1 _arimaTheta
rnorm_2 ARIMAp{..} = rnorm_2 _arimaPhi + rnorm_2 _arimaTheta
lasso r ARIMAp{..} = ARIMAp { _arimaPhi = lasso r _arimaPhi
, _arimaTheta = lasso r _arimaTheta
, _arimaConstant = 0
}
ridge r ARIMAp{..} = ARIMAp { _arimaPhi = ridge r _arimaPhi
, _arimaTheta = ridge r _arimaTheta
, _arimaConstant = 0
}
instance (KnownNat p, KnownNat q, PrimMonad m) => Learnable m (ARIMAp p q)
instance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => Learnable m (ARIMAs p d q)
| null | https://raw.githubusercontent.com/mstksg/backprop-learn/59aea530a0fad45de6d18b9a723914d1d66dc222/src/Backprop/Learn/Model/Regression.hs | haskell | # LANGUAGE ApplicativeDo #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE GADTs #
# LANGUAGE InstanceSigs #
# LANGUAGE KindSignatures #
# LANGUAGE PatternSynonyms #
# LANGUAGE RankNTypes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeInType #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #
* Linear Regression
* Reshape
| Linear Regression parameter
| Reshape an 'LRp' to take more or less inputs. If more, new parameters
are initialized randomly according to the given distribution.
| Reshape an 'LRp' to return more or less outputs If more, new
parameters are initialized randomly according to the given distribution.
| Adjust an 'LRp' to take extra inputs, initialized randomly.
Initial contributions to each output is randomized.
| Adjust an 'LRp' to return extra ouputs, initialized randomly
| Premute (or remove) inputs
Removed inputs will simply have their contributions removed from each
output.
| Premute (or remove) outputs
^ initial
^ target
^ target x initial | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
module Backprop.Learn.Model.Regression (
linReg, logReg
, LRp(..), lrAlpha, lrBeta, runLRp
, reshapeLRpInput, reshapeLRpOutput
, expandLRpInput, expandLRpOutput
, premuteLRpInput, permuteLRpOutput
* ARIMA
, arima, autoregressive, movingAverage, arma
, ARIMAp(..), ARIMAs(..)
, arimaPhi, arimaTheta, arimaConstant, arimaYPred, arimaYHist, arimaEHist
) where
import Backprop.Learn.Initialize
import Backprop.Learn.Model.Combinator
import Backprop.Learn.Model.Function
import Backprop.Learn.Model.Types
import Backprop.Learn.Regularize
import Control.DeepSeq
import Control.Monad.Primitive
import Data.Finite
import Data.Kind
import Data.List
import Data.Maybe
import Data.Proxy
import Data.Type.Equality
import Data.Typeable
import GHC.Generics (Generic)
import GHC.TypeLits.Compare
import GHC.TypeNats
import Lens.Micro.TH
import Numeric.Backprop
import Numeric.LinearAlgebra.Static.Backprop
import Numeric.LinearAlgebra.Static.Vector
import Numeric.OneLiner
import Numeric.Opto.Ref
import Numeric.Opto.Update hiding ((<.>))
import Statistics.Distribution
import Unsafe.Coerce
import qualified Data.Binary as Bi
import qualified Data.Vector.Generic.Sized as SVG
import qualified Data.Vector.Sized as SV
import qualified Data.Vector.Storable.Sized as SVS
import qualified Numeric.LinearAlgebra as HU
import qualified Numeric.LinearAlgebra.Static as H
import qualified System.Random.MWC as MWC
data LRp (i :: Nat) (o :: Nat) = LRp
{ _lrAlpha :: !(R o)
, _lrBeta :: !(L o i)
}
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Bi.Binary, Initialize, Backprop)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Num (LRp i o)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Fractional (LRp i o)
deriving via (GNum (LRp i o)) instance (KnownNat i, KnownNat o) => Floating (LRp i o)
makeLenses ''LRp
instance (PrimMonad m, KnownNat i, KnownNat o) => Mutable m (LRp i o) where
type Ref m (LRp i o) = GRef m (LRp i o)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (PrimMonad m, KnownNat i, KnownNat o) => LinearInPlace m Double (LRp i o)
instance (KnownNat i, KnownNat o) => Regularize (LRp i o) where
rnorm_1 = rnorm_1 . _lrBeta
rnorm_2 = rnorm_2 . _lrBeta
lasso r LRp{..} = LRp { _lrAlpha = 0
, _lrBeta = lasso r _lrBeta
}
ridge r LRp{..} = LRp { _lrAlpha = 0
, _lrBeta = ridge r _lrBeta
}
instance (KnownNat i, KnownNat o, PrimMonad m) => Learnable m (LRp i o)
runLRp
:: (KnownNat i, KnownNat o, Reifies s W)
=> BVar s (LRp i o)
-> BVar s (R i)
-> BVar s (R o)
runLRp lrp x = (lrp ^^. lrBeta) #> x + (lrp ^^. lrAlpha)
reshapeLRpInput
:: (ContGen d, PrimMonad m, KnownNat i, KnownNat i', KnownNat o)
=> d
-> MWC.Gen (PrimState m)
-> LRp i o
-> m (LRp i' o)
reshapeLRpInput d g (LRp α β) =
LRp α <$> reshapeLCols d g β
reshapeLRpOutput
:: (ContGen d, PrimMonad m, KnownNat i, KnownNat o, KnownNat o')
=> d
-> MWC.Gen (PrimState m)
-> LRp i o
-> m (LRp i o')
reshapeLRpOutput d g (LRp α β) =
LRp <$> reshapeR d g α
<*> reshapeLRows d g β
linReg
:: (KnownNat i, KnownNat o)
=> Model ('Just (LRp i o)) 'Nothing (R i) (R o)
linReg = modelStatelessD (\(PJust p) -> runLRp p)
logReg
:: (KnownNat i, KnownNat o)
=> Model ('Just (LRp i o)) 'Nothing (R i) (R o)
logReg = funcD logistic <~ linReg
expandLRpInput
:: (PrimMonad m, ContGen d, KnownNat i, KnownNat j, KnownNat o)
=> LRp i o
-> d
-> MWC.Gen (PrimState m)
-> m (LRp (i + j) o)
expandLRpInput LRp{..} d g = LRp _lrAlpha . (_lrBeta H.|||) <$> initialize d g
expandLRpOutput
:: (PrimMonad m, ContGen d, KnownNat i, KnownNat o, KnownNat p)
=> LRp i o
-> d
-> MWC.Gen (PrimState m)
-> m (LRp i (o + p))
expandLRpOutput LRp{..} d g = do
newAlpha <- initialize d g
newBeta <- initialize d g
pure (LRp (_lrAlpha H.# newAlpha) (_lrBeta H.=== newBeta))
premuteLRpInput
:: (KnownNat i, KnownNat o)
=> SV.Vector i' (Finite i)
-> LRp i o
-> LRp i' o
premuteLRpInput is p = p { _lrBeta = colsL . fmap (β `SV.index`) $ is }
where
β = lCols (_lrBeta p)
permuteLRpOutput
:: (KnownNat i, KnownNat o)
=> SV.Vector o' (Finite o)
-> LRp i o
-> LRp i o'
permuteLRpOutput is LRp{..} =
LRp { _lrAlpha = vecR . SVG.convert . fmap (α `SVS.index`) $ is
, _lrBeta = rowsL . fmap (β `SV.index`) $ is
}
where
α = rVec _lrAlpha
β = lRows _lrBeta
| ' ARIMA ' parmaeters
data ARIMAp :: Nat -> Nat -> Type where
ARIMAp :: { _arimaPhi :: !(R p)
, _arimaTheta :: !(R q)
, _arimaConstant :: !Double
}
-> ARIMAp p q
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)
deriving via (GNum (ARIMAp p q)) instance Num (ARIMAp p q)
deriving via (GNum (ARIMAp p q)) instance Fractional (ARIMAp p q)
deriving via (GNum (ARIMAp p q)) instance Floating (ARIMAp p q)
makeLenses ''ARIMAp
| ' ARIMA ' state
data ARIMAs :: Nat -> Nat -> Nat -> Type where
ARIMAs :: { _arimaYPred :: !Double
, _arimaYHist :: !(R (p + d))
, _arimaEHist :: !(R q)
}
-> ARIMAs p d q
deriving stock (Generic, Typeable, Show)
deriving anyclass (NFData, Linear Double, Metric Double, Initialize, Backprop, Bi.Binary)
deriving via (NoRegularize (ARIMAs p d q)) instance Regularize (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Num (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Fractional (ARIMAs p d q)
deriving via (GNum (ARIMAs p d q)) instance Floating (ARIMAs p d q)
makeLenses ''ARIMAs
arima
:: forall p d q. (KnownNat p, KnownNat d, KnownNat q)
=> Model ('Just (ARIMAp p q)) ('Just (ARIMAs p d q)) Double Double
arima = modelD $ \(PJust p) x (PJust s) ->
let d :: L p (p + d)
d = difference
e = x - (s ^^. arimaYPred)
y = (p ^^. arimaConstant)
+ (p ^^. arimaPhi ) <.> (constVar d #> (s ^^. arimaYHist))
+ (p ^^. arimaTheta) <.> (s ^^. arimaEHist)
yHist' = case Proxy @1 %<=? Proxy @(p + d) of
LE Refl -> single y # constVar dropLast #> (s ^^. arimaYHist)
NLE _ _ -> 0
eHist' = case Proxy @1 %<=? Proxy @q of
LE Refl -> single e # constVar dropLast #> (s ^^. arimaEHist)
NLE _ _ -> 0
s' = isoVar3 ARIMAs (\(ARIMAs pr yh eh) -> (pr,yh,eh))
y
yHist'
eHist'
in (y, PJust s')
autoregressive
:: KnownNat p
=> Model ('Just (ARIMAp p 0)) ('Just (ARIMAs p 0 0)) Double Double
autoregressive = arima
movingAverage
:: KnownNat q
=> Model ('Just (ARIMAp 0 q)) ('Just (ARIMAs 0 0 q)) Double Double
movingAverage = arima
arma
:: (KnownNat p, KnownNat q)
=> Model ('Just (ARIMAp p q)) ('Just (ARIMAs p 0 q)) Double Double
arma = arima
monosquare :: forall n. (n <=? (n ^ 2)) :~: 'True
monosquare = unsafeCoerce Refl
dropLast :: forall n. (KnownNat n, 1 <= n) => L (n - 1) n
dropLast = case monosquare @n of
Refl -> vecL . SVS.generate $ \ij ->
let i :: Finite n
j :: Finite (n - 1)
(i, j) = separateProduct ij
in if fromIntegral @_ @Int i == fromIntegral j
then 1
else 0
single :: Reifies s W => BVar s Double -> BVar s (R 1)
single = konst
difference'
difference' n m = foldl' go (HU.ident m) [m + 1 .. n]
where
go x k = x HU.<> d k
d k = HU.build (k-1, k) $ \i j ->
case round @_ @Int (j - i) of
0 -> 1
1 -> -1
_ -> 0
difference :: forall n m. (KnownNat n, KnownNat m) => L n (n + m)
difference = fromJust . H.create $ difference' (n + m) n
where
n = fromIntegral $ natVal (Proxy @n)
m = fromIntegral $ natVal (Proxy @m)
instance (PrimMonad m, KnownNat p, KnownNat q) => Mutable m (ARIMAp p q) where
type Ref m (ARIMAp p q) = GRef m (ARIMAp p q)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (PrimMonad m, KnownNat p, KnownNat d, KnownNat q) => Mutable m (ARIMAs p d q) where
type Ref m (ARIMAs p d q) = GRef m (ARIMAs p d q)
thawRef = gThawRef
freezeRef = gFreezeRef
copyRef = gCopyRef
instance (KnownNat p, KnownNat q, PrimMonad m) => LinearInPlace m Double (ARIMAp p q)
instance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => LinearInPlace m Double (ARIMAs p d q)
instance (KnownNat p, KnownNat q) => Regularize (ARIMAp p q) where
rnorm_1 ARIMAp{..} = rnorm_1 _arimaPhi + rnorm_1 _arimaTheta
rnorm_2 ARIMAp{..} = rnorm_2 _arimaPhi + rnorm_2 _arimaTheta
lasso r ARIMAp{..} = ARIMAp { _arimaPhi = lasso r _arimaPhi
, _arimaTheta = lasso r _arimaTheta
, _arimaConstant = 0
}
ridge r ARIMAp{..} = ARIMAp { _arimaPhi = ridge r _arimaPhi
, _arimaTheta = ridge r _arimaTheta
, _arimaConstant = 0
}
instance (KnownNat p, KnownNat q, PrimMonad m) => Learnable m (ARIMAp p q)
instance (KnownNat p, KnownNat d, KnownNat q, PrimMonad m) => Learnable m (ARIMAs p d q)
|
a305e9cae47b3b77e5be1fa80096f1fb6f4ab9e26189dfb3c0e6a394c0cd0ba8 | facebook/flow | parser_tests.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
let tests =
"parser_utils"
>::: [Flow_ast_mapper_test.tests; Jsdoc_test.tests; Loc_test.tests; Offset_utils_test.tests]
let () = run_test_tt_main tests
| null | https://raw.githubusercontent.com/facebook/flow/f7d50bb772462888b27b5dbf9acf7d079eb1ff5f/src/parser/__tests__/parser_tests.ml | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
let tests =
"parser_utils"
>::: [Flow_ast_mapper_test.tests; Jsdoc_test.tests; Loc_test.tests; Offset_utils_test.tests]
let () = run_test_tt_main tests
| |
74d8f4b3dba24d571f6510f612610e1171a77e2625f2aad7b4da9b682a0997aa | LCBH/UKano | parsing_helper.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2020 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2020 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type extent
val dummy_ext : extent
val merge_ext : extent -> extent -> extent
val extent : Lexing.lexbuf -> extent
val parse_extent : unit -> extent
val set_start : Lexing.lexbuf -> extent -> unit
val input_error : string -> extent -> 'a
val input_warning : string -> extent -> unit
val user_error : string -> 'a
val internal_error : string -> 'a
val add_point_if_necessary : string -> string
val get_mess_from : bool -> string -> string -> extent -> string
val display_input_error : string -> extent -> 'a
exception InputError of string * extent
val interactive_mode : bool ref
val get_warning_list : unit -> (string * extent) list
(*String parsing*)
val clear_buffer : unit -> unit
val get_string : unit -> string * extent
val set_start_pos : Lexing.lexbuf -> unit
val set_end_pos : Lexing.lexbuf -> unit
val add_char : char -> unit
val char_backslash : char -> char
| null | https://raw.githubusercontent.com/LCBH/UKano/13c046ddaca48b45d3652c3ea08e21599e051527/proverif2.01/src/parsing_helper.mli | ocaml | String parsing | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* , , and *
* *
* Copyright ( C ) INRIA , CNRS 2000 - 2020 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Cryptographic protocol verifier *
* *
* Bruno Blanchet, Vincent Cheval, and Marc Sylvestre *
* *
* Copyright (C) INRIA, CNRS 2000-2020 *
* *
*************************************************************)
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details ( in file LICENSE ) .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details (in file LICENSE).
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type extent
val dummy_ext : extent
val merge_ext : extent -> extent -> extent
val extent : Lexing.lexbuf -> extent
val parse_extent : unit -> extent
val set_start : Lexing.lexbuf -> extent -> unit
val input_error : string -> extent -> 'a
val input_warning : string -> extent -> unit
val user_error : string -> 'a
val internal_error : string -> 'a
val add_point_if_necessary : string -> string
val get_mess_from : bool -> string -> string -> extent -> string
val display_input_error : string -> extent -> 'a
exception InputError of string * extent
val interactive_mode : bool ref
val get_warning_list : unit -> (string * extent) list
val clear_buffer : unit -> unit
val get_string : unit -> string * extent
val set_start_pos : Lexing.lexbuf -> unit
val set_end_pos : Lexing.lexbuf -> unit
val add_char : char -> unit
val char_backslash : char -> char
|
af06caf706f1bd0902708d2ae12aca9166f3b492a1c4a51464f72db36da3ed4e | ghcjs/jsaddle-dom | XPathExpression.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.XPathExpression
(evaluate, evaluate_, XPathExpression(..), gTypeXPathExpression)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/XPathExpression.evaluate Mozilla XPathExpression.evaluate documentation >
evaluate ::
(MonadDOM m, IsNode contextNode) =>
XPathExpression ->
Maybe contextNode ->
Maybe Word -> Maybe XPathResult -> m XPathResult
evaluate self contextNode type' inResult
= liftDOM
((self ^. jsf "evaluate"
[toJSVal contextNode, toJSVal type', toJSVal inResult])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/XPathExpression.evaluate Mozilla XPathExpression.evaluate documentation >
evaluate_ ::
(MonadDOM m, IsNode contextNode) =>
XPathExpression ->
Maybe contextNode -> Maybe Word -> Maybe XPathResult -> m ()
evaluate_ self contextNode type' inResult
= liftDOM
(void
(self ^. jsf "evaluate"
[toJSVal contextNode, toJSVal type', toJSVal inResult]))
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/XPathExpression.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.XPathExpression
(evaluate, evaluate_, XPathExpression(..), gTypeXPathExpression)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
| < -US/docs/Web/API/XPathExpression.evaluate Mozilla XPathExpression.evaluate documentation >
evaluate ::
(MonadDOM m, IsNode contextNode) =>
XPathExpression ->
Maybe contextNode ->
Maybe Word -> Maybe XPathResult -> m XPathResult
evaluate self contextNode type' inResult
= liftDOM
((self ^. jsf "evaluate"
[toJSVal contextNode, toJSVal type', toJSVal inResult])
>>= fromJSValUnchecked)
| < -US/docs/Web/API/XPathExpression.evaluate Mozilla XPathExpression.evaluate documentation >
evaluate_ ::
(MonadDOM m, IsNode contextNode) =>
XPathExpression ->
Maybe contextNode -> Maybe Word -> Maybe XPathResult -> m ()
evaluate_ self contextNode type' inResult
= liftDOM
(void
(self ^. jsf "evaluate"
[toJSVal contextNode, toJSVal type', toJSVal inResult]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.