_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 |
|---|---|---|---|---|---|---|---|---|
a792ddf05b4d4dfa090a9ca27b68637da31c78f62758b6803ade2cb84b0883e6 | well-typed/optics | At.hs | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - orphans #
-- |
-- Module: Optics.At
Description : Optics for ' Data . Map . Map ' and ' Data . Set . Set'-like containers .
--
-- This module provides optics for 'Data.Map.Map' and 'Data.Set.Set'-like
-- containers, including an 'AffineTraversal' to traverse a key in a map or an
-- element of a sequence:
--
-- >>> preview (ix 1) ['a','b','c']
-- Just 'b'
--
-- a 'Lens' to get, set or delete a key in a map:
--
> > > set ( at 0 ) ( Just ' b ' ) ( Map.fromList [ ( 0 , ' a ' ) ] )
-- fromList [(0,'b')]
--
-- and a 'Lens' to insert or remove an element of a set:
--
> > > IntSet.fromList [ 1,2,3,4 ] & contains 3 .~ False
-- fromList [1,2,4]
--
-- This module includes the core definitions from "Optics.At.Core" along with
-- extra (orphan) instances.
--
module Optics.At
(
-- * Type families
Index
, IxValue
-- * Ixed
, Ixed(..)
, ixAt
-- * At
, At(..)
, at'
, sans
-- * Contains
, Contains(..)
) where
import qualified Data.ByteString as StrictB
import qualified Data.ByteString.Lazy as LazyB
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.HashSet (HashSet)
import qualified Data.HashSet as HashSet
import Data.Hashable (Hashable)
import Data.Int (Int64)
import qualified Data.Text as StrictT
import qualified Data.Text.Lazy as LazyT
import qualified Data.Vector as Vector hiding (indexed)
import qualified Data.Vector.Primitive as Prim
import qualified Data.Vector.Storable as Storable
import qualified Data.Vector.Unboxed as Unboxed hiding (indexed)
import Data.Word (Word8)
import Optics.Core
type instance Index (HashSet a) = a
type instance Index (HashMap k a) = k
type instance Index (Vector.Vector a) = Int
type instance Index (Prim.Vector a) = Int
type instance Index (Storable.Vector a) = Int
type instance Index (Unboxed.Vector a) = Int
type instance Index StrictT.Text = Int
type instance Index LazyT.Text = Int64
type instance Index StrictB.ByteString = Int
type instance Index LazyB.ByteString = Int64
-- Contains
instance (Eq a, Hashable a) => Contains (HashSet a) where
contains k = lensVL $ \f s -> f (HashSet.member k s) <&> \b ->
if b then HashSet.insert k s else HashSet.delete k s
# INLINE contains #
Ixed
type instance IxValue (HashMap k a) = a
-- Default implementation uses HashMap.alterF
instance (Eq k, Hashable k) => Ixed (HashMap k a)
type instance IxValue (HashSet k) = ()
instance (Eq k, Hashable k) => Ixed (HashSet k) where
ix k = atraversalVL $ \point f m ->
if HashSet.member k m
then f () <&> \() -> HashSet.insert k m
else point m
# INLINE ix #
type instance IxValue (Vector.Vector a) = a
instance Ixed (Vector.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Vector.length v
then f (v Vector.! i) <&> \a -> v Vector.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Prim.Vector a) = a
instance Prim.Prim a => Ixed (Prim.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Prim.length v
then f (v Prim.! i) <&> \a -> v Prim.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Storable.Vector a) = a
instance Storable.Storable a => Ixed (Storable.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Storable.length v
then f (v Storable.! i) <&> \a -> v Storable.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Unboxed.Vector a) = a
instance Unboxed.Unbox a => Ixed (Unboxed.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Unboxed.length v
then f (v Unboxed.! i) <&> \a -> v Unboxed.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue StrictT.Text = Char
instance Ixed StrictT.Text where
ix e = atraversalVL $ \point f s ->
case StrictT.splitAt e s of
(l, mr) -> case StrictT.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> StrictT.concat [l, StrictT.singleton d, xs]
# INLINE ix #
type instance IxValue LazyT.Text = Char
instance Ixed LazyT.Text where
ix e = atraversalVL $ \point f s ->
case LazyT.splitAt e s of
(l, mr) -> case LazyT.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> LazyT.append l (LazyT.cons d xs)
# INLINE ix #
type instance IxValue StrictB.ByteString = Word8
instance Ixed StrictB.ByteString where
ix e = atraversalVL $ \point f s ->
case StrictB.splitAt e s of
(l, mr) -> case StrictB.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> StrictB.concat [l, StrictB.singleton d, xs]
# INLINE ix #
type instance IxValue LazyB.ByteString = Word8
instance Ixed LazyB.ByteString where
-- TODO: we could be lazier, returning each chunk as it is passed
ix e = atraversalVL $ \point f s ->
case LazyB.splitAt e s of
(l, mr) -> case LazyB.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> LazyB.append l (LazyB.cons d xs)
# INLINE ix #
-- At
instance (Eq k, Hashable k) => At (HashMap k a) where
#if MIN_VERSION_unordered_containers(0,2,10)
at k = lensVL $ \f -> HashMap.alterF f k
#else
at k = lensVL $ \f m ->
let mv = HashMap.lookup k m
in f mv <&> \r -> case r of
Nothing -> maybe m (const (HashMap.delete k m)) mv
Just v' -> HashMap.insert k v' m
#endif
# INLINE at #
instance (Eq k, Hashable k) => At (HashSet k) where
at k = lensVL $ \f m ->
let mv = if HashSet.member k m
then Just ()
else Nothing
in f mv <&> \r -> case r of
Nothing -> maybe m (const (HashSet.delete k m)) mv
Just () -> HashSet.insert k m
# INLINE at #
-- $setup
> > > import qualified Data . IntSet as
-- >>> import qualified Data.Map as Map
| null | https://raw.githubusercontent.com/well-typed/optics/7cc3f9c334cdf69feaf10f58b11d3dbe2f98812c/optics-extra/src/Optics/At.hs | haskell | |
Module: Optics.At
This module provides optics for 'Data.Map.Map' and 'Data.Set.Set'-like
containers, including an 'AffineTraversal' to traverse a key in a map or an
element of a sequence:
>>> preview (ix 1) ['a','b','c']
Just 'b'
a 'Lens' to get, set or delete a key in a map:
fromList [(0,'b')]
and a 'Lens' to insert or remove an element of a set:
fromList [1,2,4]
This module includes the core definitions from "Optics.At.Core" along with
extra (orphan) instances.
* Type families
* Ixed
* At
* Contains
Contains
Default implementation uses HashMap.alterF
TODO: we could be lazier, returning each chunk as it is passed
At
$setup
>>> import qualified Data.Map as Map | # LANGUAGE CPP #
# OPTIONS_GHC -fno - warn - orphans #
Description : Optics for ' Data . Map . Map ' and ' Data . Set . Set'-like containers .
> > > set ( at 0 ) ( Just ' b ' ) ( Map.fromList [ ( 0 , ' a ' ) ] )
> > > IntSet.fromList [ 1,2,3,4 ] & contains 3 .~ False
module Optics.At
(
Index
, IxValue
, Ixed(..)
, ixAt
, At(..)
, at'
, sans
, Contains(..)
) where
import qualified Data.ByteString as StrictB
import qualified Data.ByteString.Lazy as LazyB
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap
import Data.HashSet (HashSet)
import qualified Data.HashSet as HashSet
import Data.Hashable (Hashable)
import Data.Int (Int64)
import qualified Data.Text as StrictT
import qualified Data.Text.Lazy as LazyT
import qualified Data.Vector as Vector hiding (indexed)
import qualified Data.Vector.Primitive as Prim
import qualified Data.Vector.Storable as Storable
import qualified Data.Vector.Unboxed as Unboxed hiding (indexed)
import Data.Word (Word8)
import Optics.Core
type instance Index (HashSet a) = a
type instance Index (HashMap k a) = k
type instance Index (Vector.Vector a) = Int
type instance Index (Prim.Vector a) = Int
type instance Index (Storable.Vector a) = Int
type instance Index (Unboxed.Vector a) = Int
type instance Index StrictT.Text = Int
type instance Index LazyT.Text = Int64
type instance Index StrictB.ByteString = Int
type instance Index LazyB.ByteString = Int64
instance (Eq a, Hashable a) => Contains (HashSet a) where
contains k = lensVL $ \f s -> f (HashSet.member k s) <&> \b ->
if b then HashSet.insert k s else HashSet.delete k s
# INLINE contains #
Ixed
type instance IxValue (HashMap k a) = a
instance (Eq k, Hashable k) => Ixed (HashMap k a)
type instance IxValue (HashSet k) = ()
instance (Eq k, Hashable k) => Ixed (HashSet k) where
ix k = atraversalVL $ \point f m ->
if HashSet.member k m
then f () <&> \() -> HashSet.insert k m
else point m
# INLINE ix #
type instance IxValue (Vector.Vector a) = a
instance Ixed (Vector.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Vector.length v
then f (v Vector.! i) <&> \a -> v Vector.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Prim.Vector a) = a
instance Prim.Prim a => Ixed (Prim.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Prim.length v
then f (v Prim.! i) <&> \a -> v Prim.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Storable.Vector a) = a
instance Storable.Storable a => Ixed (Storable.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Storable.length v
then f (v Storable.! i) <&> \a -> v Storable.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue (Unboxed.Vector a) = a
instance Unboxed.Unbox a => Ixed (Unboxed.Vector a) where
ix i = atraversalVL $ \point f v ->
if 0 <= i && i < Unboxed.length v
then f (v Unboxed.! i) <&> \a -> v Unboxed.// [(i, a)]
else point v
# INLINE ix #
type instance IxValue StrictT.Text = Char
instance Ixed StrictT.Text where
ix e = atraversalVL $ \point f s ->
case StrictT.splitAt e s of
(l, mr) -> case StrictT.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> StrictT.concat [l, StrictT.singleton d, xs]
# INLINE ix #
type instance IxValue LazyT.Text = Char
instance Ixed LazyT.Text where
ix e = atraversalVL $ \point f s ->
case LazyT.splitAt e s of
(l, mr) -> case LazyT.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> LazyT.append l (LazyT.cons d xs)
# INLINE ix #
type instance IxValue StrictB.ByteString = Word8
instance Ixed StrictB.ByteString where
ix e = atraversalVL $ \point f s ->
case StrictB.splitAt e s of
(l, mr) -> case StrictB.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> StrictB.concat [l, StrictB.singleton d, xs]
# INLINE ix #
type instance IxValue LazyB.ByteString = Word8
instance Ixed LazyB.ByteString where
ix e = atraversalVL $ \point f s ->
case LazyB.splitAt e s of
(l, mr) -> case LazyB.uncons mr of
Nothing -> point s
Just (c, xs) -> f c <&> \d -> LazyB.append l (LazyB.cons d xs)
# INLINE ix #
instance (Eq k, Hashable k) => At (HashMap k a) where
#if MIN_VERSION_unordered_containers(0,2,10)
at k = lensVL $ \f -> HashMap.alterF f k
#else
at k = lensVL $ \f m ->
let mv = HashMap.lookup k m
in f mv <&> \r -> case r of
Nothing -> maybe m (const (HashMap.delete k m)) mv
Just v' -> HashMap.insert k v' m
#endif
# INLINE at #
instance (Eq k, Hashable k) => At (HashSet k) where
at k = lensVL $ \f m ->
let mv = if HashSet.member k m
then Just ()
else Nothing
in f mv <&> \r -> case r of
Nothing -> maybe m (const (HashSet.delete k m)) mv
Just () -> HashSet.insert k m
# INLINE at #
> > > import qualified Data . IntSet as
|
07577d653c230c88337dfb1d51af36b493e10499219b5908bc32b5ebdb8907fd | ReactiveX/RxClojure | future_test.clj | (ns rx.lang.clojure.future-test
(:require [rx.lang.clojure.core :as rx]
[rx.lang.clojure.blocking :as b]
[rx.lang.clojure.future :as f])
(:require [clojure.test :refer [deftest testing is]]))
(deftest test-future-generator
(is (not= [(.getId (Thread/currentThread))]
(b/into []
(f/future-generator* future-call
#(rx/on-next % (.getId (Thread/currentThread))))))))
(deftest test-future
(is (= [15] (b/into [] (f/future* future-call + 1 2 3 4 5)))))
(deftest test-future-exception
(is (= "Caught: boo"
(->> (f/future* future-call #(throw (java.io.FileNotFoundException. "boo")))
(rx/catch java.io.FileNotFoundException e
(rx/return (str "Caught: " (.getMessage e))))
(b/single)))))
(deftest test-future-cancel
(let [exited? (atom nil)
o (f/future* future-call
(fn [] (Thread/sleep 1000)
(reset! exited? true)
"WAT"))
result (->> o
(rx/take 0)
(b/into []))]
(Thread/sleep 2000)
(is (= [nil []]
[@exited? result]))))
(deftest test-future-generator-cancel
(let [exited? (atom nil)
o (f/future-generator* future-call
(fn [o]
(rx/on-next o "FIRST")
(Thread/sleep 1000)
(reset! exited? true)))
result (->> o
(rx/take 1)
(b/into []))]
(Thread/sleep 2000)
(is (= [nil ["FIRST"]]
[@exited? result]))))
(deftest test-future-generator-exception
(let [e (java.io.FileNotFoundException. "snake")]
(is (= [1 2 e]
(->> (f/future-generator*
future-call
(fn [o]
(rx/on-next o 1)
(rx/on-next o 2)
(throw e)))
(rx/catch java.io.FileNotFoundException e
(rx/return e))
(b/into []))))))
| null | https://raw.githubusercontent.com/ReactiveX/RxClojure/8f8e454f447ae24549bcf5f001c9d2458af21cac/src/test/clojure/rx/lang/clojure/future_test.clj | clojure | (ns rx.lang.clojure.future-test
(:require [rx.lang.clojure.core :as rx]
[rx.lang.clojure.blocking :as b]
[rx.lang.clojure.future :as f])
(:require [clojure.test :refer [deftest testing is]]))
(deftest test-future-generator
(is (not= [(.getId (Thread/currentThread))]
(b/into []
(f/future-generator* future-call
#(rx/on-next % (.getId (Thread/currentThread))))))))
(deftest test-future
(is (= [15] (b/into [] (f/future* future-call + 1 2 3 4 5)))))
(deftest test-future-exception
(is (= "Caught: boo"
(->> (f/future* future-call #(throw (java.io.FileNotFoundException. "boo")))
(rx/catch java.io.FileNotFoundException e
(rx/return (str "Caught: " (.getMessage e))))
(b/single)))))
(deftest test-future-cancel
(let [exited? (atom nil)
o (f/future* future-call
(fn [] (Thread/sleep 1000)
(reset! exited? true)
"WAT"))
result (->> o
(rx/take 0)
(b/into []))]
(Thread/sleep 2000)
(is (= [nil []]
[@exited? result]))))
(deftest test-future-generator-cancel
(let [exited? (atom nil)
o (f/future-generator* future-call
(fn [o]
(rx/on-next o "FIRST")
(Thread/sleep 1000)
(reset! exited? true)))
result (->> o
(rx/take 1)
(b/into []))]
(Thread/sleep 2000)
(is (= [nil ["FIRST"]]
[@exited? result]))))
(deftest test-future-generator-exception
(let [e (java.io.FileNotFoundException. "snake")]
(is (= [1 2 e]
(->> (f/future-generator*
future-call
(fn [o]
(rx/on-next o 1)
(rx/on-next o 2)
(throw e)))
(rx/catch java.io.FileNotFoundException e
(rx/return e))
(b/into []))))))
| |
4a1e5c7fa855fb1cdab97a4e94ba65d538b1d4add2902c8b108a5f3f6c57ac94 | herd/herdtools7 | testInfo.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2016 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
Extract information from test , at the moment name hash
module T = struct
type t =
{ tname : string ;
fname : string ;
hash : string ; }
let cmp_pair cmp1 cmp2 t1 t2 = match cmp1 t1 t2 with
| 0 -> cmp2 t1 t2
| r -> r
let compare t1 t2 =
cmp_pair
(fun t1 t2 -> String.compare t1.tname t2.tname)
(cmp_pair
(fun t1 t2 -> String.compare t1.hash t2.hash)
(fun t1 t2 -> String.compare t1.fname t2.fname))
t1 t2
end
module Make(A:ArchBase.S)(Pte:PteVal.S) = struct
let zyva name parsed =
let tname = name.Name.name in
let fname = name.Name.file in
let hash = MiscParser.get_hash parsed in
let hash =
match hash with
| None -> assert false
| Some h -> h in
{ T.tname = tname ; fname=fname; hash = hash; }
end
module Z = ToolParse.Top(T)(Make)
| null | https://raw.githubusercontent.com/herd/herdtools7/6a5b3085a9d2357f98f4d560d7dd12add34edabe/tools/testInfo.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
************************************************************************** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2016 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
Extract information from test , at the moment name hash
module T = struct
type t =
{ tname : string ;
fname : string ;
hash : string ; }
let cmp_pair cmp1 cmp2 t1 t2 = match cmp1 t1 t2 with
| 0 -> cmp2 t1 t2
| r -> r
let compare t1 t2 =
cmp_pair
(fun t1 t2 -> String.compare t1.tname t2.tname)
(cmp_pair
(fun t1 t2 -> String.compare t1.hash t2.hash)
(fun t1 t2 -> String.compare t1.fname t2.fname))
t1 t2
end
module Make(A:ArchBase.S)(Pte:PteVal.S) = struct
let zyva name parsed =
let tname = name.Name.name in
let fname = name.Name.file in
let hash = MiscParser.get_hash parsed in
let hash =
match hash with
| None -> assert false
| Some h -> h in
{ T.tname = tname ; fname=fname; hash = hash; }
end
module Z = ToolParse.Top(T)(Make)
|
0463fa674b7b3f528cda12b2edd338d01a11c2dac0fd2a13f028764e66fca2e2 | squirrel-prover/squirrel-prover | location.mli | --------------------------------------------------------------------
* Copyright ( c ) - 2012 - -2016 - IMDEA Software Institute
* Copyright ( c ) - 2012 - -2018 - Inria
* Copyright ( c ) - 2012 - -2018 - Ecole Polytechnique
*
* Distributed under the terms of the CeCILL - C - V1 license
* --------------------------------------------------------------------
* Copyright (c) - 2012--2016 - IMDEA Software Institute
* Copyright (c) - 2012--2018 - Inria
* Copyright (c) - 2012--2018 - Ecole Polytechnique
*
* Distributed under the terms of the CeCILL-C-V1 license
* -------------------------------------------------------------------- *)
(* -------------------------------------------------------------------- *)
open Lexing
(* -------------------------------------------------------------------- *)
type t = {
loc_fname : string;
loc_start : int * int;
loc_end : int * int;
loc_bchar : int;
loc_echar : int;
}
(* -------------------------------------------------------------------- *)
val _dummy : t
val make : position -> position -> t
val of_lexbuf : lexbuf -> t
val tostring : t -> string
val tostring_raw : ?with_fname:bool -> t -> string
val merge : t -> t -> t
val mergeall : t list -> t
val isdummy : t -> bool
(* -------------------------------------------------------------------- *)
type 'a located = {
pl_loc : t;
pl_desc : 'a;
}
val loc : 'a located -> t
val unloc : 'a located -> 'a
val unlocs : ('a located) list -> 'a list
val mk_loc : t -> 'a -> 'a located
val lmap : ('a -> 'b) -> 'a located -> 'b located
(* -------------------------------------------------------------------- *)
exception LocError of t * exn
val locate_error : t -> exn -> 'a
val set_loc : t -> ('a -> 'b) -> 'a -> 'b
val set_oloc : t option -> ('a -> 'b) -> 'a -> 'b
| null | https://raw.githubusercontent.com/squirrel-prover/squirrel-prover/cd0dd445d0e5d739f059730d9f54b7d2c21dc694/src/location.mli | ocaml | --------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | --------------------------------------------------------------------
* Copyright ( c ) - 2012 - -2016 - IMDEA Software Institute
* Copyright ( c ) - 2012 - -2018 - Inria
* Copyright ( c ) - 2012 - -2018 - Ecole Polytechnique
*
* Distributed under the terms of the CeCILL - C - V1 license
* --------------------------------------------------------------------
* Copyright (c) - 2012--2016 - IMDEA Software Institute
* Copyright (c) - 2012--2018 - Inria
* Copyright (c) - 2012--2018 - Ecole Polytechnique
*
* Distributed under the terms of the CeCILL-C-V1 license
* -------------------------------------------------------------------- *)
open Lexing
type t = {
loc_fname : string;
loc_start : int * int;
loc_end : int * int;
loc_bchar : int;
loc_echar : int;
}
val _dummy : t
val make : position -> position -> t
val of_lexbuf : lexbuf -> t
val tostring : t -> string
val tostring_raw : ?with_fname:bool -> t -> string
val merge : t -> t -> t
val mergeall : t list -> t
val isdummy : t -> bool
type 'a located = {
pl_loc : t;
pl_desc : 'a;
}
val loc : 'a located -> t
val unloc : 'a located -> 'a
val unlocs : ('a located) list -> 'a list
val mk_loc : t -> 'a -> 'a located
val lmap : ('a -> 'b) -> 'a located -> 'b located
exception LocError of t * exn
val locate_error : t -> exn -> 'a
val set_loc : t -> ('a -> 'b) -> 'a -> 'b
val set_oloc : t option -> ('a -> 'b) -> 'a -> 'b
|
178e3f219470c7838e99f38e01bd946b68af4f5452390e92433cd2e847cf42c4 | haskell/cabal | cabal.test.hs | import Test.Cabal.Prelude
main = cabalTest . void $ do
isWin <- isWindows
ghc94 <- isGhcVersion "== 9.4.*"
expectBrokenIf (isWin && ghc94) 8451 $ do
cabal' "v2-build" ["script.hs"]
cabal' "v2-clean" ["script.hs"]
env <- getTestEnv
cacheDir <- getScriptCacheDirectory (testCurrentDir env </> "script.hs")
shouldDirectoryNotExist cacheDir
shouldDirectoryNotExist (testDistDir env)
| null | https://raw.githubusercontent.com/haskell/cabal/410f871df899e5af0847089354e0031fe051551d/cabal-testsuite/PackageTests/NewBuild/CmdClean/Script/cabal.test.hs | haskell | import Test.Cabal.Prelude
main = cabalTest . void $ do
isWin <- isWindows
ghc94 <- isGhcVersion "== 9.4.*"
expectBrokenIf (isWin && ghc94) 8451 $ do
cabal' "v2-build" ["script.hs"]
cabal' "v2-clean" ["script.hs"]
env <- getTestEnv
cacheDir <- getScriptCacheDirectory (testCurrentDir env </> "script.hs")
shouldDirectoryNotExist cacheDir
shouldDirectoryNotExist (testDistDir env)
| |
b1a623080fd79832427b7ec8d8a54593d551b006543eb2493a87535ca8326bd1 | backtracking/ocamlgraph | coloring.ml | (**************************************************************************)
(* *)
: a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
(* *)
(* This software is free software; you can redistribute it and/or *)
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
(* described in file LICENSE. *)
(* *)
(* This software 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. *)
(* *)
(**************************************************************************)
module type GM = sig
val is_directed : bool
type t
val nb_vertex : t -> int
module V : Sig.COMPARABLE
val out_degree : t -> V.t -> int
val iter_vertex : (V.t -> unit) -> t -> unit
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
val fold_succ : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
module Mark : sig
val get : V.t -> int
val set : V.t -> int -> unit
end
end
exception NoColoring
(** Graph coloring with marking.
Only applies to imperative graphs with marks. *)
module Mark(G : GM) = struct
module Bfs = Traverse.Bfs(G)
let coloring g k =
if G.is_directed then invalid_arg "coloring: directed graph";
first step : we eliminate vertices with less than [ k ] successors
let stack = Stack.create () in
let nb_to_color = ref (G.nb_vertex g) in
let count = ref 1 in
while !count > 0 do
count := 0;
let erase v = incr count; G.Mark.set v (k+1); Stack.push v stack in
G.iter_vertex
(fun v -> if G.Mark.get v = 0 && G.out_degree g v < k then erase v)
g;
" eliminating % d nodes@. " ! count ;
nb_to_color := !nb_to_color - !count
done;
second step : we k - color the remaining of the graph
(* [try_color v i] tries to assign color [i] to vertex [v] *)
let try_color v i =
G.Mark.set v i;
G.iter_succ (fun w -> if G.Mark.get w = i then raise NoColoring) g v
in
let uncolor v = G.Mark.set v 0 in
if !nb_to_color > 0 then begin
let rec iterate iter =
let v = Bfs.get iter in
let m = G.Mark.get v in
if m > 0 then
iterate (Bfs.step iter)
else begin
for i = 1 to k do
try try_color v i; iterate (Bfs.step iter)
with NoColoring -> ()
done;
uncolor v;
raise NoColoring
end
in
try iterate (Bfs.start g) with Exit -> ()
end;
third step : we color the eliminated vertices , in reverse order
Stack.iter
(fun v ->
try
for i = 1 to k do
try try_color v i; raise Exit with NoColoring -> ()
done;
raise NoColoring (* it may still fail on a self edge v->v *)
with Exit -> ())
stack
let two_color g =
if G.is_directed then invalid_arg "coloring: directed graph";
first , set all colors to 0
let erase v = G.Mark.set v 0 in
G.iter_vertex erase g;
(* then, use dfs to color the nodes *)
let rec dfs c v = match G.Mark.get v with
| 1 | 2 as cv -> if cv <> c then raise NoColoring (* check for cycles *)
| _ -> G.Mark.set v c; G.iter_succ (dfs (1-c)) g v in
let start v = match G.Mark.get v with 1 | 2 -> () | _ -> dfs 1 v in
G.iter_vertex start g
end
(** Graph coloring for graphs without marks: we use an external hash table *)
module type G = sig
val is_directed : bool
type t
val nb_vertex : t -> int
module V : Sig.COMPARABLE
val out_degree : t -> V.t -> int
val iter_vertex : (V.t -> unit) -> t -> unit
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
val fold_succ : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
end
module Make(G: G) = struct
module H = Hashtbl.Make(G.V)
let add_marks () =
let h = H.create 97 in
h, (module struct
include G
module Mark = struct
let get v = try H.find h v with Not_found -> 0
let set v n = H.replace h v n end end :
GM with type t = G.t and type V.t = G.V.t)
let coloring g k =
let h, (module GM) = add_marks () in
let module M = Mark(GM) in
M.coloring g k;
h
let two_color g =
let h, (module GM) = add_marks () in
let module M = Mark(GM) in
M.two_color g;
h
end
| null | https://raw.githubusercontent.com/backtracking/ocamlgraph/1c028af097339ca8bc379436f7bd9477fa3a49cd/src/coloring.ml | ocaml | ************************************************************************
This software is free software; you can redistribute it and/or
described in file LICENSE.
This software 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.
************************************************************************
* Graph coloring with marking.
Only applies to imperative graphs with marks.
[try_color v i] tries to assign color [i] to vertex [v]
it may still fail on a self edge v->v
then, use dfs to color the nodes
check for cycles
* Graph coloring for graphs without marks: we use an external hash table | : a generic graph library for OCaml
Copyright ( C ) 2004 - 2010
, and
modify it under the terms of the GNU Library General Public
License version 2.1 , with the special exception on linking
module type GM = sig
val is_directed : bool
type t
val nb_vertex : t -> int
module V : Sig.COMPARABLE
val out_degree : t -> V.t -> int
val iter_vertex : (V.t -> unit) -> t -> unit
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
val fold_succ : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
module Mark : sig
val get : V.t -> int
val set : V.t -> int -> unit
end
end
exception NoColoring
module Mark(G : GM) = struct
module Bfs = Traverse.Bfs(G)
let coloring g k =
if G.is_directed then invalid_arg "coloring: directed graph";
first step : we eliminate vertices with less than [ k ] successors
let stack = Stack.create () in
let nb_to_color = ref (G.nb_vertex g) in
let count = ref 1 in
while !count > 0 do
count := 0;
let erase v = incr count; G.Mark.set v (k+1); Stack.push v stack in
G.iter_vertex
(fun v -> if G.Mark.get v = 0 && G.out_degree g v < k then erase v)
g;
" eliminating % d nodes@. " ! count ;
nb_to_color := !nb_to_color - !count
done;
second step : we k - color the remaining of the graph
let try_color v i =
G.Mark.set v i;
G.iter_succ (fun w -> if G.Mark.get w = i then raise NoColoring) g v
in
let uncolor v = G.Mark.set v 0 in
if !nb_to_color > 0 then begin
let rec iterate iter =
let v = Bfs.get iter in
let m = G.Mark.get v in
if m > 0 then
iterate (Bfs.step iter)
else begin
for i = 1 to k do
try try_color v i; iterate (Bfs.step iter)
with NoColoring -> ()
done;
uncolor v;
raise NoColoring
end
in
try iterate (Bfs.start g) with Exit -> ()
end;
third step : we color the eliminated vertices , in reverse order
Stack.iter
(fun v ->
try
for i = 1 to k do
try try_color v i; raise Exit with NoColoring -> ()
done;
with Exit -> ())
stack
let two_color g =
if G.is_directed then invalid_arg "coloring: directed graph";
first , set all colors to 0
let erase v = G.Mark.set v 0 in
G.iter_vertex erase g;
let rec dfs c v = match G.Mark.get v with
| _ -> G.Mark.set v c; G.iter_succ (dfs (1-c)) g v in
let start v = match G.Mark.get v with 1 | 2 -> () | _ -> dfs 1 v in
G.iter_vertex start g
end
module type G = sig
val is_directed : bool
type t
val nb_vertex : t -> int
module V : Sig.COMPARABLE
val out_degree : t -> V.t -> int
val iter_vertex : (V.t -> unit) -> t -> unit
val fold_vertex : (V.t -> 'a -> 'a) -> t -> 'a -> 'a
val iter_succ : (V.t -> unit) -> t -> V.t -> unit
val fold_succ : (V.t -> 'a -> 'a) -> t -> V.t -> 'a -> 'a
end
module Make(G: G) = struct
module H = Hashtbl.Make(G.V)
let add_marks () =
let h = H.create 97 in
h, (module struct
include G
module Mark = struct
let get v = try H.find h v with Not_found -> 0
let set v n = H.replace h v n end end :
GM with type t = G.t and type V.t = G.V.t)
let coloring g k =
let h, (module GM) = add_marks () in
let module M = Mark(GM) in
M.coloring g k;
h
let two_color g =
let h, (module GM) = add_marks () in
let module M = Mark(GM) in
M.two_color g;
h
end
|
ca46e2d93dcb46723940d44b3ec6d777758f7c3c561b27aba66f0e753a9d05fe | plewto/Cadejo | pbank.clj | (println "--> cadejo.midi.pbank")
(ns cadejo.midi.pbank
(:require [cadejo.midi.program])
(:require [cadejo.config :as config])
(:require [cadejo.midi.program])
(:require [cadejo.util.col :as ucol])
(:require [cadejo.util.user-message :as umsg])
(:require [cadejo.util.string])
(:require [overtone.core :as ot])
(:import java.io.FileNotFoundException))
(def program-count 128)
(defn- assert-midi-program-number [pnum]
(or (and (integer? pnum)(>= pnum 0)(< pnum program-count) pnum)))
(defprotocol PBank
(data-format
[this]
"Returns keyword indicating program data format")
(parent!
[this performance]
"Sets parent performance of this")
(parent
[this]
"Returns parent performance of this or nil")
(editor!
[this ed]
"Sets GUI bank editor for this")
(editor
[this]
"Returns GUI editor or nil")
(pp-hook!
[this pp]
"Sets pretty-printer hook function
pp should have the lambda form (pp slot pname data remarks)
and return a String.")
(pp-hook
[this]
"Returns the pp-hook function or nil")
(bank-name!
[this name]
"Sets name for this")
(bank-name
[this]
"Returns name of this")
(bank-remarks!
[this text]
"Sets remarks text for this")
(bank-remarks
[this]
"returns remarks text of this")
(init!
[this]
"Initialize this bank
Bank name, remarks, current-program and programs list are set to
initial values. Synths and editors are not updated.
Returns this.")
(current-slot
[this]
"Returns the current program slot or nil
The slot is an integer MIDI program number.")
(current-program!
[this prog]
[this name remarks data]
"Sets current-program
synths and instument-editor are updated.")
(current-program
[this]
"Returns the current-program, a instance of
cadejo.midi.program/Program or nil")
(current-data
[this]
"Returns current-prgoram data or empty-map {}")
(set-param!
[this param value]
"Sets parameter value for current-program
Active synths are updated to match the new program data,
GUI editor is -not- updated and the current-program is marked
as 'not saved'
Returns the new program data or nil")
(modified!
[this flag]
"Set data modification flag")
(modified?
[this]
"Return data modification flag")
(progressive-count!
[this n]
"Sets progressive-prorgam count
If n nil turn progressive-programs off")
(progressive-count
[this]
"Returns progressive-program count
Returns nil of progressive-programsn turned off")
(programs
[this]
"Returns a sorted map of all programs. The map keys are integer MIDI
program numbers, the map values are instance of
cadejo.midi.program/Program")
(recall
[this slot]
[this]
"Mark the indicated slot as 'current'. If slot is not specified
use the current slot number.
All active synths are updated to match the new current data
The current program is marked as 'saved'
The editor is -NOT- updated.
Return current-data or nil")
(recall-progressive
[this slot]
"Mark indicated slot as 'current'.
All active voices are updated
The current program is marked as 'saved'
The editor is -NOT- updated
Rreturn list of program data")
(program-change ; synths updated, editor updated
[this ev]
"Process MIDI program change event.
If the bank contains a program for the indicated program-number,
make it the current-program.
All synths and the GUI editor are updated to match the new
current-program.
Returns current-data")
(store! ; editor is not updated
[this slot program]
[this slot]
[this]
"Stores program into bank slot.
slot - int MIDI program number, if not specified use current slot number
program - instance of cadejo.midi.program/Program, if not specified
use current program.
The current slot and program are updated and modified flag cleared.
Returns program")
(read-bank!
[this filename]
"Update bank's content from file")
(write-bank
[this filename]
"Save bank data to file")
(clone
[this]
"Returns duplicate copy of this")
(copy-state!
[this other]
"Copies state of other into this.
Returns this or nil.")
(dump
[this verbose depth]
[this]))
(defn pbank
([dformat]
(pbank (keyword dformat)
(format "New %s bank" (name (keyword dformat)))
""))
([dformat bnk-name bnk-remarks]
(let [parent* (atom nil)
programs* (atom (sorted-map))
pp-hook* (atom (fn [&args] ""))
editor* (atom nil)
name* (atom (str bnk-name))
remarks* (atom (str bnk-remarks))
current-slot* (atom nil)
current-program* (atom nil)
progressive* (atom nil)
modified* (atom false)
synths (fn []
(if @parent*
(concat (.synths @parent*)
(.voices @parent*))
[]))
pb (reify PBank
(data-format [this](keyword dformat))
(parent! [this performance]
(reset! parent* performance))
(parent [this] @parent*)
(editor! [this ed]
(reset! editor* ed))
(editor [this] @editor*)
(pp-hook! [this hfn]
(reset! pp-hook* hfn))
(pp-hook [this] @pp-hook*)
(bank-name! [this text]
(reset! name* (str text)))
(bank-name [this] @name*)
(bank-remarks! [this text]
(reset! remarks* (str text)))
(bank-remarks [this]
@remarks*)
(init! [this]
(.bank-name! this (format "New %s Bank" (name (.data-format this))))
(.bank-remarks! this "")
(reset! current-slot* nil)
(reset! current-program* nil)
(.modified! this false)
(reset! programs* (sorted-map))
this)
(current-slot [this] @current-slot*)
(current-program [this] @current-program*)
(current-program! [this prog]
(reset! current-program* prog)
(modified! this false)
(apply ot/ctl (synths)(ucol/map->alist (.data prog)))
(if @editor* (.sync-ui! @editor*))
prog)
(current-program! [this name remarks data]
(let [prog (cadejo.midi.program/program name remarks data)]
(.current-program! this prog)))
(current-data [this]
(let [p (.current-program this)]
(if p
(.data p)
{})))
(set-param! [this param value]
(let [prog (.current-program this)]
(if prog
(do
(.set-param! prog param value)
(apply ot/ctl (synths)(ucol/map->alist (.data prog)))
(.modified! this true)
(.data prog))
nil)))
(modified! [this flag]
(reset! modified* flag))
(modified? [this] @modified*)
(progressive-count! [this n]
(if n
(reset! progressive* (max (min n 10) 0))
(reset! progressive* nil)))
(progressive-count [this]
@progressive*)
(programs [this] @programs*)
(recall [this slot]
(if (assert-midi-program-number slot)
(let [p (get @programs* slot)]
(if p
(let [data (.data p)]
(apply ot/ctl (synths)(ucol/map->alist data))
(reset! current-slot* slot)
(reset! current-program* (.clone p))
(.modified! this false)
(if (and (config/enable-pp) @pp-hook*)
(let [pname (.program-name p)
premarks (.program-remarks p)]
(println (@pp-hook* slot pname data premarks))))
data)
(do ;; p false
nil)))
(do ;; invalid slot
nil)))
(recall [this]
(let [s @current-slot*]
(if s
(.recall this s)
nil)))
(recall-progressive [this slot]
(let [slot (or slot 0)
acc* (atom [])]
(dotimes [n (or (.progressive-count this) 1)]
(let [p (get @programs* (+ slot n))]
(if p
(swap! acc* (fn [q](conj q (ucol/map->alist (.data p))))))))
(if (and @parent* (pos? (count @acc*)))
(let [vcc (.voices @parent*)
syn (.synths @parent*)
mod (count @acc*)
counter* (atom 0)]
(apply ot/ctl syn (first @acc*))
(doseq [v vcc]
(let [i (rem @counter* mod)]
(apply ot/ctl v (nth @acc* i))
(swap! counter* inc)))))
acc*))
(program-change [this event]
(let [slot (:data1 event)
pc (.progressive-count this)]
(if (and pc (pos? pc))
(do
(.modified! this false)
(.recall-progressive this slot)
@current-program*)
(let [rcflag (.recall this slot)
ed @editor*]
(.modified! this false)
(if ed (.sync-ui! ed))
@current-program*))))
(store! [this slot program]
(if (assert-midi-program-number slot)
(do
(swap! programs* (fn [n](assoc n slot program)))
(reset! current-slot* slot)
(reset! current-program* program)
(.modified! this false)
program)
nil))
(store! [this slot]
(if @current-program*
(.store! this slot @current-program*)))
(store! [this]
(.store! this @current-slot*))
(read-bank! [this filename]
(try
(let [rec (read-string (slurp filename))
ftype (:file-type rec)
dform (:data-format rec)]
(if (not (and (= ftype :cadejo-bank)
(= dform (.data-format this))))
(do
(umsg/warning "Wrong file type"
(format "Can not read \"%s\"" filename)
(format "as cadejo %s bank" (.data-format this)))
nil)
(let [progs (:programs rec)]
(.init! this)
(.bank-name! this (:name rec))
(.bank-remarks! this (:remarks rec))
(doseq [[slot pmap] (seq progs)]
(let [prog (cadejo.midi.program/program)]
(.from-map! prog pmap)
(.store! this slot prog)))
(.program-change this {:data1 (first (keys @programs*))})
filename)))
(catch java.io.FileNotFoundException ex
(umsg/warning "FileNotFoundException"
(format "PBank.read-bank! bank-format = %s" (.data-format this))
(format "filename \"%s\"" filename))
nil)))
(write-bank [this filename]
(try
(let [progs (let [acc* (atom {})]
(doseq [[k p] @programs*]
(swap! acc* (fn [q](assoc q k (.to-map p)))))
@acc*)
rec {:file-type :cadejo-bank
:data-format (.data-format this)
:name (.bank-name this)
:remarks (.bank-remarks this)
:programs progs}]
(spit filename (pr-str rec))
filename)
(catch java.io.FileNotFoundException ex
(umsg/warning "FileNotFoundException"
(format "PBank.write-bank! bank-format = %s" (.data-format this))
(format "filename \"%s\"" filename))
nil)))
(clone [this]
(let [other (pbank (.data-format this)
(.bank-name this)
(.bank-remarks this))]
(doseq [[slot prog](seq @programs*)]
(.store! other slot (.clone prog)))
(.pp-hook! other (.pp-hook this))
other))
(copy-state! [this other]
(if (= (.data-format this)(.data-format other))
(let [src-programs (.programs other)]
(.init! this)
(.bank-name! this (.bank-name other))
(.bank-remarks! this (.bank-remarks other))
(dotimes [slot program-count]
(let [p (get src-programs slot)]
(if p
(.store! this slot (.clone p)))))
this)
(do
(umsg/warning (format "Can not copy %s bank to %s bank"
(.data-format other)
(.data-format this)))
nil)))
(dump [this verbose depth]
(let [pad (cadejo.util.string/tab depth)
pad2 (str pad pad)]
(printf "%sPBank %s name '%s'" pad (.data-format this)(.bank-name this))
(if verbose
(do
(printf "%sRemarks %s\n" pad2 (.bank-remarks this))
(printf "%sparent %s\n" pad2 (.parent this))
(printf "%spp-hook %s\n" pad2 (.pp-hook this))
(printf "%seditor %s\n" pad2 (.editor this))
(printf "%scurrent-slot %s\n" pad2 @current-slot*)
(printf "%smodified %s\n" pad2 (.modified? this))
(doseq [k (keys @programs*)]
(let [p (get @programs* k)]
(printf "%s[%3s] '%s'\n" pad2 k (.program-name p))))))
(println)))
(dump [this]
(.dump this true 1)))]
pb)))
| null | https://raw.githubusercontent.com/plewto/Cadejo/2a98610ce1f5fe01dce5f28d986a38c86677fd67/src/cadejo/midi/pbank.clj | clojure | synths updated, editor updated
editor is not updated
p false
invalid slot | (println "--> cadejo.midi.pbank")
(ns cadejo.midi.pbank
(:require [cadejo.midi.program])
(:require [cadejo.config :as config])
(:require [cadejo.midi.program])
(:require [cadejo.util.col :as ucol])
(:require [cadejo.util.user-message :as umsg])
(:require [cadejo.util.string])
(:require [overtone.core :as ot])
(:import java.io.FileNotFoundException))
(def program-count 128)
(defn- assert-midi-program-number [pnum]
(or (and (integer? pnum)(>= pnum 0)(< pnum program-count) pnum)))
(defprotocol PBank
(data-format
[this]
"Returns keyword indicating program data format")
(parent!
[this performance]
"Sets parent performance of this")
(parent
[this]
"Returns parent performance of this or nil")
(editor!
[this ed]
"Sets GUI bank editor for this")
(editor
[this]
"Returns GUI editor or nil")
(pp-hook!
[this pp]
"Sets pretty-printer hook function
pp should have the lambda form (pp slot pname data remarks)
and return a String.")
(pp-hook
[this]
"Returns the pp-hook function or nil")
(bank-name!
[this name]
"Sets name for this")
(bank-name
[this]
"Returns name of this")
(bank-remarks!
[this text]
"Sets remarks text for this")
(bank-remarks
[this]
"returns remarks text of this")
(init!
[this]
"Initialize this bank
Bank name, remarks, current-program and programs list are set to
initial values. Synths and editors are not updated.
Returns this.")
(current-slot
[this]
"Returns the current program slot or nil
The slot is an integer MIDI program number.")
(current-program!
[this prog]
[this name remarks data]
"Sets current-program
synths and instument-editor are updated.")
(current-program
[this]
"Returns the current-program, a instance of
cadejo.midi.program/Program or nil")
(current-data
[this]
"Returns current-prgoram data or empty-map {}")
(set-param!
[this param value]
"Sets parameter value for current-program
Active synths are updated to match the new program data,
GUI editor is -not- updated and the current-program is marked
as 'not saved'
Returns the new program data or nil")
(modified!
[this flag]
"Set data modification flag")
(modified?
[this]
"Return data modification flag")
(progressive-count!
[this n]
"Sets progressive-prorgam count
If n nil turn progressive-programs off")
(progressive-count
[this]
"Returns progressive-program count
Returns nil of progressive-programsn turned off")
(programs
[this]
"Returns a sorted map of all programs. The map keys are integer MIDI
program numbers, the map values are instance of
cadejo.midi.program/Program")
(recall
[this slot]
[this]
"Mark the indicated slot as 'current'. If slot is not specified
use the current slot number.
All active synths are updated to match the new current data
The current program is marked as 'saved'
The editor is -NOT- updated.
Return current-data or nil")
(recall-progressive
[this slot]
"Mark indicated slot as 'current'.
All active voices are updated
The current program is marked as 'saved'
The editor is -NOT- updated
Rreturn list of program data")
[this ev]
"Process MIDI program change event.
If the bank contains a program for the indicated program-number,
make it the current-program.
All synths and the GUI editor are updated to match the new
current-program.
Returns current-data")
[this slot program]
[this slot]
[this]
"Stores program into bank slot.
slot - int MIDI program number, if not specified use current slot number
program - instance of cadejo.midi.program/Program, if not specified
use current program.
The current slot and program are updated and modified flag cleared.
Returns program")
(read-bank!
[this filename]
"Update bank's content from file")
(write-bank
[this filename]
"Save bank data to file")
(clone
[this]
"Returns duplicate copy of this")
(copy-state!
[this other]
"Copies state of other into this.
Returns this or nil.")
(dump
[this verbose depth]
[this]))
(defn pbank
([dformat]
(pbank (keyword dformat)
(format "New %s bank" (name (keyword dformat)))
""))
([dformat bnk-name bnk-remarks]
(let [parent* (atom nil)
programs* (atom (sorted-map))
pp-hook* (atom (fn [&args] ""))
editor* (atom nil)
name* (atom (str bnk-name))
remarks* (atom (str bnk-remarks))
current-slot* (atom nil)
current-program* (atom nil)
progressive* (atom nil)
modified* (atom false)
synths (fn []
(if @parent*
(concat (.synths @parent*)
(.voices @parent*))
[]))
pb (reify PBank
(data-format [this](keyword dformat))
(parent! [this performance]
(reset! parent* performance))
(parent [this] @parent*)
(editor! [this ed]
(reset! editor* ed))
(editor [this] @editor*)
(pp-hook! [this hfn]
(reset! pp-hook* hfn))
(pp-hook [this] @pp-hook*)
(bank-name! [this text]
(reset! name* (str text)))
(bank-name [this] @name*)
(bank-remarks! [this text]
(reset! remarks* (str text)))
(bank-remarks [this]
@remarks*)
(init! [this]
(.bank-name! this (format "New %s Bank" (name (.data-format this))))
(.bank-remarks! this "")
(reset! current-slot* nil)
(reset! current-program* nil)
(.modified! this false)
(reset! programs* (sorted-map))
this)
(current-slot [this] @current-slot*)
(current-program [this] @current-program*)
(current-program! [this prog]
(reset! current-program* prog)
(modified! this false)
(apply ot/ctl (synths)(ucol/map->alist (.data prog)))
(if @editor* (.sync-ui! @editor*))
prog)
(current-program! [this name remarks data]
(let [prog (cadejo.midi.program/program name remarks data)]
(.current-program! this prog)))
(current-data [this]
(let [p (.current-program this)]
(if p
(.data p)
{})))
(set-param! [this param value]
(let [prog (.current-program this)]
(if prog
(do
(.set-param! prog param value)
(apply ot/ctl (synths)(ucol/map->alist (.data prog)))
(.modified! this true)
(.data prog))
nil)))
(modified! [this flag]
(reset! modified* flag))
(modified? [this] @modified*)
(progressive-count! [this n]
(if n
(reset! progressive* (max (min n 10) 0))
(reset! progressive* nil)))
(progressive-count [this]
@progressive*)
(programs [this] @programs*)
(recall [this slot]
(if (assert-midi-program-number slot)
(let [p (get @programs* slot)]
(if p
(let [data (.data p)]
(apply ot/ctl (synths)(ucol/map->alist data))
(reset! current-slot* slot)
(reset! current-program* (.clone p))
(.modified! this false)
(if (and (config/enable-pp) @pp-hook*)
(let [pname (.program-name p)
premarks (.program-remarks p)]
(println (@pp-hook* slot pname data premarks))))
data)
nil)))
nil)))
(recall [this]
(let [s @current-slot*]
(if s
(.recall this s)
nil)))
(recall-progressive [this slot]
(let [slot (or slot 0)
acc* (atom [])]
(dotimes [n (or (.progressive-count this) 1)]
(let [p (get @programs* (+ slot n))]
(if p
(swap! acc* (fn [q](conj q (ucol/map->alist (.data p))))))))
(if (and @parent* (pos? (count @acc*)))
(let [vcc (.voices @parent*)
syn (.synths @parent*)
mod (count @acc*)
counter* (atom 0)]
(apply ot/ctl syn (first @acc*))
(doseq [v vcc]
(let [i (rem @counter* mod)]
(apply ot/ctl v (nth @acc* i))
(swap! counter* inc)))))
acc*))
(program-change [this event]
(let [slot (:data1 event)
pc (.progressive-count this)]
(if (and pc (pos? pc))
(do
(.modified! this false)
(.recall-progressive this slot)
@current-program*)
(let [rcflag (.recall this slot)
ed @editor*]
(.modified! this false)
(if ed (.sync-ui! ed))
@current-program*))))
(store! [this slot program]
(if (assert-midi-program-number slot)
(do
(swap! programs* (fn [n](assoc n slot program)))
(reset! current-slot* slot)
(reset! current-program* program)
(.modified! this false)
program)
nil))
(store! [this slot]
(if @current-program*
(.store! this slot @current-program*)))
(store! [this]
(.store! this @current-slot*))
(read-bank! [this filename]
(try
(let [rec (read-string (slurp filename))
ftype (:file-type rec)
dform (:data-format rec)]
(if (not (and (= ftype :cadejo-bank)
(= dform (.data-format this))))
(do
(umsg/warning "Wrong file type"
(format "Can not read \"%s\"" filename)
(format "as cadejo %s bank" (.data-format this)))
nil)
(let [progs (:programs rec)]
(.init! this)
(.bank-name! this (:name rec))
(.bank-remarks! this (:remarks rec))
(doseq [[slot pmap] (seq progs)]
(let [prog (cadejo.midi.program/program)]
(.from-map! prog pmap)
(.store! this slot prog)))
(.program-change this {:data1 (first (keys @programs*))})
filename)))
(catch java.io.FileNotFoundException ex
(umsg/warning "FileNotFoundException"
(format "PBank.read-bank! bank-format = %s" (.data-format this))
(format "filename \"%s\"" filename))
nil)))
(write-bank [this filename]
(try
(let [progs (let [acc* (atom {})]
(doseq [[k p] @programs*]
(swap! acc* (fn [q](assoc q k (.to-map p)))))
@acc*)
rec {:file-type :cadejo-bank
:data-format (.data-format this)
:name (.bank-name this)
:remarks (.bank-remarks this)
:programs progs}]
(spit filename (pr-str rec))
filename)
(catch java.io.FileNotFoundException ex
(umsg/warning "FileNotFoundException"
(format "PBank.write-bank! bank-format = %s" (.data-format this))
(format "filename \"%s\"" filename))
nil)))
(clone [this]
(let [other (pbank (.data-format this)
(.bank-name this)
(.bank-remarks this))]
(doseq [[slot prog](seq @programs*)]
(.store! other slot (.clone prog)))
(.pp-hook! other (.pp-hook this))
other))
(copy-state! [this other]
(if (= (.data-format this)(.data-format other))
(let [src-programs (.programs other)]
(.init! this)
(.bank-name! this (.bank-name other))
(.bank-remarks! this (.bank-remarks other))
(dotimes [slot program-count]
(let [p (get src-programs slot)]
(if p
(.store! this slot (.clone p)))))
this)
(do
(umsg/warning (format "Can not copy %s bank to %s bank"
(.data-format other)
(.data-format this)))
nil)))
(dump [this verbose depth]
(let [pad (cadejo.util.string/tab depth)
pad2 (str pad pad)]
(printf "%sPBank %s name '%s'" pad (.data-format this)(.bank-name this))
(if verbose
(do
(printf "%sRemarks %s\n" pad2 (.bank-remarks this))
(printf "%sparent %s\n" pad2 (.parent this))
(printf "%spp-hook %s\n" pad2 (.pp-hook this))
(printf "%seditor %s\n" pad2 (.editor this))
(printf "%scurrent-slot %s\n" pad2 @current-slot*)
(printf "%smodified %s\n" pad2 (.modified? this))
(doseq [k (keys @programs*)]
(let [p (get @programs* k)]
(printf "%s[%3s] '%s'\n" pad2 k (.program-name p))))))
(println)))
(dump [this]
(.dump this true 1)))]
pb)))
|
8bf287a3719463c098cec5fe960b003da7671dc1b465708bcbf3e02381c442f7 | w3ntao/sicp-solution | 3-3.rkt | #lang racket
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"insufficient funds"))
(define (deposit amount)
(set! balance
(+ balance amount))
balance)
(define (dispatch psw cmd)
(if (eq? psw password)
(cond ((eq? cmd 'withdraw) withdraw)
((eq? cmd 'deposit) deposit)
(else
(error "error try" cmd)))
(lambda (x)
"incorrect password")))
dispatch)
(define acc (make-account 100 'pass))
((acc 'pass 'withdraw) 40)
((acc 'passss 'deposit) 50) | null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-3/3-3.rkt | racket | #lang racket
(define (make-account balance password)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance
(- balance amount))
balance)
"insufficient funds"))
(define (deposit amount)
(set! balance
(+ balance amount))
balance)
(define (dispatch psw cmd)
(if (eq? psw password)
(cond ((eq? cmd 'withdraw) withdraw)
((eq? cmd 'deposit) deposit)
(else
(error "error try" cmd)))
(lambda (x)
"incorrect password")))
dispatch)
(define acc (make-account 100 'pass))
((acc 'pass 'withdraw) 40)
((acc 'passss 'deposit) 50) | |
3e0404bfeece99e9ef00b3beeb8879c9fdd3f2d3f232ca711b2de3a1eddb0980 | janestreet/virtual_dom | grouped_help_text.ml | open Core
open Import
module Group_name = String
module View_spec = struct
type t =
{ core_spec : Help_text.View_spec.t
; group_name : Group_name.t -> Vdom.Node.t
}
let plain = { core_spec = Help_text.View_spec.plain; group_name = Vdom.Node.text }
let with_classes ~group_name_class ~key_class ~plain_text_class =
let text_div class_ text =
let open Vdom in
Node.div ~attr:(Attr.class_ class_) [ Node.text text ]
in
{ core_spec = Help_text.View_spec.with_classes ~key_class ~plain_text_class
; group_name = text_div group_name_class
}
;;
end
module Command = Help_text.Command
type t =
{ groups : Help_text.t Group_name.Map.t
; group_order : Group_name.t list
}
[@@deriving sexp, compare]
let empty = { groups = Group_name.Map.empty; group_order = [] }
let is_empty t = Map.is_empty t.groups
let of_group_list_exn group_list =
{ groups = Group_name.Map.of_alist_exn group_list
; group_order = List.map group_list ~f:fst
}
;;
let add_group_exn t group_name commands =
{ groups = Map.add_exn t.groups ~key:group_name ~data:commands
; group_order = t.group_order @ [ group_name ]
}
;;
let of_command_list ?(custom_group_order = []) command_list =
let groups =
List.map custom_group_order ~f:(fun group_name -> group_name, [])
|> Group_name.Map.of_alist_exn
in
let rev_group_order = List.rev custom_group_order in
let groups, rev_group_order =
List.fold
command_list
~init:(groups, rev_group_order)
~f:(fun (groups, rev_group_order) (group_name, command) ->
let rev_group_order =
if Map.mem groups group_name
then rev_group_order
else group_name :: rev_group_order
in
let groups =
Map.update groups group_name ~f:(fun commands ->
let commands = Option.value commands ~default:[] in
command :: commands)
in
groups, rev_group_order)
in
{ groups =
Map.filter_map groups ~f:(function
| [] -> None
| commands -> Some (Help_text.of_command_list (List.rev commands)))
; group_order = List.rev rev_group_order
}
;;
let add_command t group_name command =
let group_order =
if Map.mem t.groups group_name then t.group_order else t.group_order @ [ group_name ]
in
let groups =
Map.update t.groups group_name ~f:(fun help_text ->
let help_text = Option.value help_text ~default:Help_text.empty in
Help_text.add_command help_text command)
in
{ groups; group_order }
;;
let groups t =
List.filter_map t.group_order ~f:(fun group_name ->
let open Option.Let_syntax in
let%map group = Map.find t.groups group_name in
group_name, group)
;;
let commands t =
List.concat_map (groups t) ~f:(fun (group_name, help_text) ->
List.map (Help_text.commands help_text) ~f:(fun command -> group_name, command))
;;
let view t (view_spec : View_spec.t) =
let open Vdom in
let rows =
List.concat_map (groups t) ~f:(fun (group_name, help_text) ->
let group_name_row =
Node.tr
[ Node.td
~attr:
(Attr.many_without_merge
[ Attr.create "colspan" "2"
; Css_gen.text_align `Center |> Attr.style
])
[ view_spec.group_name group_name ]
]
in
group_name_row :: Help_text.view_rows help_text view_spec.core_spec)
in
Vdom.Node.table rows
;;
| null | https://raw.githubusercontent.com/janestreet/virtual_dom/53466b0f06875cafd30ee2d22536e494e7237b3a/keyboard/src/grouped_help_text.ml | ocaml | open Core
open Import
module Group_name = String
module View_spec = struct
type t =
{ core_spec : Help_text.View_spec.t
; group_name : Group_name.t -> Vdom.Node.t
}
let plain = { core_spec = Help_text.View_spec.plain; group_name = Vdom.Node.text }
let with_classes ~group_name_class ~key_class ~plain_text_class =
let text_div class_ text =
let open Vdom in
Node.div ~attr:(Attr.class_ class_) [ Node.text text ]
in
{ core_spec = Help_text.View_spec.with_classes ~key_class ~plain_text_class
; group_name = text_div group_name_class
}
;;
end
module Command = Help_text.Command
type t =
{ groups : Help_text.t Group_name.Map.t
; group_order : Group_name.t list
}
[@@deriving sexp, compare]
let empty = { groups = Group_name.Map.empty; group_order = [] }
let is_empty t = Map.is_empty t.groups
let of_group_list_exn group_list =
{ groups = Group_name.Map.of_alist_exn group_list
; group_order = List.map group_list ~f:fst
}
;;
let add_group_exn t group_name commands =
{ groups = Map.add_exn t.groups ~key:group_name ~data:commands
; group_order = t.group_order @ [ group_name ]
}
;;
let of_command_list ?(custom_group_order = []) command_list =
let groups =
List.map custom_group_order ~f:(fun group_name -> group_name, [])
|> Group_name.Map.of_alist_exn
in
let rev_group_order = List.rev custom_group_order in
let groups, rev_group_order =
List.fold
command_list
~init:(groups, rev_group_order)
~f:(fun (groups, rev_group_order) (group_name, command) ->
let rev_group_order =
if Map.mem groups group_name
then rev_group_order
else group_name :: rev_group_order
in
let groups =
Map.update groups group_name ~f:(fun commands ->
let commands = Option.value commands ~default:[] in
command :: commands)
in
groups, rev_group_order)
in
{ groups =
Map.filter_map groups ~f:(function
| [] -> None
| commands -> Some (Help_text.of_command_list (List.rev commands)))
; group_order = List.rev rev_group_order
}
;;
let add_command t group_name command =
let group_order =
if Map.mem t.groups group_name then t.group_order else t.group_order @ [ group_name ]
in
let groups =
Map.update t.groups group_name ~f:(fun help_text ->
let help_text = Option.value help_text ~default:Help_text.empty in
Help_text.add_command help_text command)
in
{ groups; group_order }
;;
let groups t =
List.filter_map t.group_order ~f:(fun group_name ->
let open Option.Let_syntax in
let%map group = Map.find t.groups group_name in
group_name, group)
;;
let commands t =
List.concat_map (groups t) ~f:(fun (group_name, help_text) ->
List.map (Help_text.commands help_text) ~f:(fun command -> group_name, command))
;;
let view t (view_spec : View_spec.t) =
let open Vdom in
let rows =
List.concat_map (groups t) ~f:(fun (group_name, help_text) ->
let group_name_row =
Node.tr
[ Node.td
~attr:
(Attr.many_without_merge
[ Attr.create "colspan" "2"
; Css_gen.text_align `Center |> Attr.style
])
[ view_spec.group_name group_name ]
]
in
group_name_row :: Help_text.view_rows help_text view_spec.core_spec)
in
Vdom.Node.table rows
;;
| |
a9841478c70c656579903791ecedf1b147d1244e2f9d4a9685608845fdaf07a8 | odj/Ouch | InChI.hs | -----------------------------------------------------------------------------
-------------------------------------------------------------------------------
InChi - a module to define input from InChI file format
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
-------------------------------------------------------------------------------
-----------------------------------------------------------------------------
-------------------------------------------------------------------------------
InChi - a module to define input from InChI file format
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
-------------------------------------------------------------------------------
------------------------------------------------------------------------------} | null | https://raw.githubusercontent.com/odj/Ouch/ed20599214cf77b0cb81cc7cefb4cd9c35bc7cf7/Ouch/Input/InChI.hs | haskell | ---------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
---------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
----------------------------------------------------------------------------} | InChi - a module to define input from InChI file format
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
InChi - a module to define input from InChI file format
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
|
3efdecde6ac966dfcd2e510133782507fc47031665c80899ebaad5f34ed42fe7 | icicle-lang/zebra-ambiata | Generic.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DoAndIfThenElse #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
module Zebra.X.Vector.Generic (
group
, segmentedGroup
, segmentedGroupOn
, module Generic
) where
import X.Data.Vector.Stream (Stream(..), Step(..))
import qualified X.Data.Vector.Stream as Stream
import X.Data.Vector.Generic as Generic
import P hiding (concatMap, length, sum)
-- | Run-length encode a segmented vector.
segmentedGroup ::
Eq a
=> Vector v a
=> Vector v Int
=> Vector v (Int, a)
=> Vector v (Int, (Int, a))
=> Vector v (Int, Int)
=> v Int
-> v a
-> (v Int, v (Int, a))
segmentedGroup = segmentedGroupOn id
# INLINE segmentedGroup #
-- | Run-length encode a segmented vector.
segmentedGroupOn ::
Eq b
=> Vector v a
=> Vector v Int
=> Vector v (Int, a)
=> Vector v (Int, (Int, a))
=> Vector v (Int, Int)
=> (a -> b)
-> v Int
-> v a
-> (v Int, v (Int, a))
segmentedGroupOn f ns xs =
let
indices =
concatMap (uncurry $ flip replicate) (indexed ns)
rotate (n, (s, x)) =
(s, (n, x))
in
first (rezero ns . map fst . group) .
unzip .
map rotate $
groupOn (second f) (zip indices xs)
# INLINE segmentedGroupOn #
-- | Run-length encode a vector.
group :: (Eq a, Vector v a, Vector v (Int, a)) => v a -> v (Int, a)
group =
groupOn id
{-# INLINE group #-}
-- | Run-length encode a vector.
groupOn :: (Eq b, Vector v a, Vector v (Int, a)) => (a -> b) -> v a -> v (Int, a)
groupOn f =
Stream.vectorOfStream . groupStreamOn f . Stream.streamOfVector
# INLINE groupOn #
data Run a =
None
| Run !Int !a
groupStreamOn :: (Monad m, Eq b) => (a -> b) -> Stream m a -> Stream m (Int, a)
groupStreamOn f (Stream step sinit) =
let
loop = \case
Nothing ->
pure Done
Just (s0, run) ->
step s0 >>= \case
Done ->
case run of
None ->
pure $ Done
Run n y ->
pure $ Yield (n, y) Nothing
Skip s ->
pure . Skip $
Just (s, run)
Yield x s ->
case run of
None ->
pure . Skip $
Just (s, Run 1 x)
Run n y ->
if f x == f y then
pure . Skip $
Just (s, Run (n + 1) x)
else
pure . Yield (n, y) $
Just (s, Run 1 x)
{-# INLINE [0] loop #-}
in
Stream loop (Just (sinit, None))
# INLINE [ 1 ] groupStreamOn #
| Re - insert zeros that have been lost from a segement descriptor :
--
rezero [ 1,2,0,3 ] [ 4,5,6 ] = = [ 4,5,0,6 ]
--
rezero :: Vector v Int => v Int -> v Int -> v Int
rezero xs ys =
Stream.vectorOfStream $ rezeroStream
(Stream.streamOfVector xs)
(Stream.streamOfVector ys)
# INLINE rezero #
rezeroStream :: Monad m => Stream m Int -> Stream m Int -> Stream m Int
rezeroStream (Stream o_step o_sinit) (Stream n_step n_sinit) =
let
loop (o_s0, n_s0) =
o_step o_s0 >>= \case
Done ->
pure Done
Skip o_s ->
pure $ Skip (o_s, n_s0)
Yield 0 o_s ->
pure $ Yield 0 (o_s, n_s0)
Yield _ o_s ->
n_step n_s0 >>= \case
Done ->
pure Done
Skip n_s ->
pure $ Skip (o_s, n_s)
Yield x n_s ->
pure $ Yield x (o_s, n_s)
{-# INLINE [0] loop #-}
in
Stream loop (o_sinit, n_sinit)
# INLINE [ 1 ] rezeroStream #
| null | https://raw.githubusercontent.com/icicle-lang/zebra-ambiata/394ee5f98b4805df2c76abb52cdaad9fd7825f81/zebra-core/src/Zebra/X/Vector/Generic.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DoAndIfThenElse #
| Run-length encode a segmented vector.
| Run-length encode a segmented vector.
| Run-length encode a vector.
# INLINE group #
| Run-length encode a vector.
# INLINE [0] loop #
# INLINE [0] loop # | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE NoImplicitPrelude #
module Zebra.X.Vector.Generic (
group
, segmentedGroup
, segmentedGroupOn
, module Generic
) where
import X.Data.Vector.Stream (Stream(..), Step(..))
import qualified X.Data.Vector.Stream as Stream
import X.Data.Vector.Generic as Generic
import P hiding (concatMap, length, sum)
segmentedGroup ::
Eq a
=> Vector v a
=> Vector v Int
=> Vector v (Int, a)
=> Vector v (Int, (Int, a))
=> Vector v (Int, Int)
=> v Int
-> v a
-> (v Int, v (Int, a))
segmentedGroup = segmentedGroupOn id
# INLINE segmentedGroup #
segmentedGroupOn ::
Eq b
=> Vector v a
=> Vector v Int
=> Vector v (Int, a)
=> Vector v (Int, (Int, a))
=> Vector v (Int, Int)
=> (a -> b)
-> v Int
-> v a
-> (v Int, v (Int, a))
segmentedGroupOn f ns xs =
let
indices =
concatMap (uncurry $ flip replicate) (indexed ns)
rotate (n, (s, x)) =
(s, (n, x))
in
first (rezero ns . map fst . group) .
unzip .
map rotate $
groupOn (second f) (zip indices xs)
# INLINE segmentedGroupOn #
group :: (Eq a, Vector v a, Vector v (Int, a)) => v a -> v (Int, a)
group =
groupOn id
groupOn :: (Eq b, Vector v a, Vector v (Int, a)) => (a -> b) -> v a -> v (Int, a)
groupOn f =
Stream.vectorOfStream . groupStreamOn f . Stream.streamOfVector
# INLINE groupOn #
data Run a =
None
| Run !Int !a
groupStreamOn :: (Monad m, Eq b) => (a -> b) -> Stream m a -> Stream m (Int, a)
groupStreamOn f (Stream step sinit) =
let
loop = \case
Nothing ->
pure Done
Just (s0, run) ->
step s0 >>= \case
Done ->
case run of
None ->
pure $ Done
Run n y ->
pure $ Yield (n, y) Nothing
Skip s ->
pure . Skip $
Just (s, run)
Yield x s ->
case run of
None ->
pure . Skip $
Just (s, Run 1 x)
Run n y ->
if f x == f y then
pure . Skip $
Just (s, Run (n + 1) x)
else
pure . Yield (n, y) $
Just (s, Run 1 x)
in
Stream loop (Just (sinit, None))
# INLINE [ 1 ] groupStreamOn #
| Re - insert zeros that have been lost from a segement descriptor :
rezero [ 1,2,0,3 ] [ 4,5,6 ] = = [ 4,5,0,6 ]
rezero :: Vector v Int => v Int -> v Int -> v Int
rezero xs ys =
Stream.vectorOfStream $ rezeroStream
(Stream.streamOfVector xs)
(Stream.streamOfVector ys)
# INLINE rezero #
rezeroStream :: Monad m => Stream m Int -> Stream m Int -> Stream m Int
rezeroStream (Stream o_step o_sinit) (Stream n_step n_sinit) =
let
loop (o_s0, n_s0) =
o_step o_s0 >>= \case
Done ->
pure Done
Skip o_s ->
pure $ Skip (o_s, n_s0)
Yield 0 o_s ->
pure $ Yield 0 (o_s, n_s0)
Yield _ o_s ->
n_step n_s0 >>= \case
Done ->
pure Done
Skip n_s ->
pure $ Skip (o_s, n_s)
Yield x n_s ->
pure $ Yield x (o_s, n_s)
in
Stream loop (o_sinit, n_sinit)
# INLINE [ 1 ] rezeroStream #
|
1e0351b619977609238715e436b7e5e795fbb55ff8d2f6ed2b61cdf57aaa5809 | ice1000/learn | alan-partridge-iii-london.hs | module Codewars.AlanPartridge.London where
alan :: [String] -> String
alan ls = if all (`elem` ls) cities then "Smell my cheese you mother!"
else "No, seriously, run. You will miss it."
where cities = ["Rejection", "Disappointment", "Backstabbing Central", "Shattered Dreams Parkway"]
--
| null | https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/alan-partridge-iii-london.hs | haskell | module Codewars.AlanPartridge.London where
alan :: [String] -> String
alan ls = if all (`elem` ls) cities then "Smell my cheese you mother!"
else "No, seriously, run. You will miss it."
where cities = ["Rejection", "Disappointment", "Backstabbing Central", "Shattered Dreams Parkway"]
| |
033d6506e2940ec2f14b5b744ab2367a973550cbbe1596f806d1fd7113285240 | rabbitmq/erlando | test_cut.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License
%% at /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and
%% limitations under the License.
%%
The Original Code is Erlando .
%%
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
%%
-module(test_cut).
-compile({parse_transform, cut}).
-compile({parse_transform, do}).
-compile(export_all).
-record(r, { f1 = false,
f2 = wibble,
f3 = juice }).
test_cut() ->
F0 = foo(a, b, _, 5+6, _),
F1 = F0(_, e),
ok = F1(c),
F2 = _(1,2),
3 = F2(fun erlang:'+'/2),
-1 = F2(fun erlang:'-'/2),
F3 = _:foo(a, b, c, _, e),
ok = F3(?MODULE, 11),
F4 = _:_(_), %% this isn't getting silly at all...
true = 3 == F4(math, sqrt, 9).
foo(a, b, c, 11, e) -> ok.
test_cut_nested() ->
F = f1(1, f2(1 + _), _),
%% should be:
F = \X - > f1(1 , f2(\Y - > 1 + Y ) , X )
ok = F(3).
f1(N, M, L) when N + M =:= L -> ok.
f2(Nf) -> Nf(1).
test_cut_op() ->
F = 1 + _,
3 = F(2).
test_cut_unary_op() ->
F = -_,
0 = 1 + F(1).
test_cut_tuple() ->
{foo, _} = {foo, F} = {foo, {bar, _}},
{bar, qux} = F(qux).
test_cut_record() ->
true = #r{} =/= #r{f3 = _},
orange = ((#r{f3 = _})(orange))#r.f3,
{r, foo, bar, baz} = (#r{f1 = _, f3 = _, f2 = _})(foo, baz, bar),
R = #r{},
F = R#r{f3 = _, f2 = _},
wobble = (F(orange, wobble))#r.f2,
Getter = _#r.f2,
wibble = Getter(R),
Setter = _#r{f2 = gerbil},
gerbil = Getter(Setter(R)),
Setter2 = _#r{f2 = _},
hamster = Getter(Setter2(R, hamster)).
test_cut_record_nested() ->
F = #r{f1 = #r{f1 = _, f3 = _}, f2 = _},
R = F(apple),
F1 = R#r.f1,
#r{f1 = orange, f3 = banana} = F1(orange, banana).
test_cut_map() ->
true = #{} =/= #{f3 => _},
orange = maps:get(f3, (#{f3 => _})(orange)),
#{f1 := foo, f2 := bar, f3 := baz}
= (#{f1 => _, f3 => _, f2 => _})(foo, baz, bar),
M = #{f1 => false, f2 => wibble, f3 => juice},
F = M#{f3 => _, f2 => _},
wobble = maps:get(f2, F(orange, wobble)),
Getter = maps:get(f2, _),
wibble = Getter(M),
Setter = _#{f2 := gerbil},
gerbil = Getter(Setter(M)),
Setter2 = _#{f2 := _},
hamster = Getter(Setter2(M, hamster)).
test_cut_map_nested() ->
F = #{f1 => #{f1 => _, f3 => _}, f2 => _},
M = F(apple),
F1 = maps:get(f1, M),
#{f1 := orange, f3 := banana} = F1(orange, banana).
test_cut_binary() ->
<<"AbA", _/binary>> = (<<65, _, 65>>)($b),
F = <<_:_>>,
G = F(15, _),
<<>> = G(0),
<<1:1/unsigned, 1:1/unsigned, 1:1/unsigned, 1:1/unsigned>> = G(4).
test_cut_list() ->
F = [_|_],
[a,b] = F(a,[b]),
G = [_, _ | [33]],
[a,b,33] = G(a,b),
H = [1, _, _, [_], 5 | [6, [_] | [_]]],
%% This is the same as:
[ 1 , _ , _ , [ _ ] , 5 , 6 , [ _ ] , _ ]
%% And thus becomes
\A , B , C - > [ 1 , A , B , \D - > [ D ] , 5 , 6 , \E - > [ E ] , C ]
[1, 2, 3, H1, 5, 6, H2, 8] = H(2, 3, 8),
[4] = H1(4),
[7] = H2(7),
I = [_, [_]],
[a, I1] = I(a),
[b] = I1(b).
test_cut_case() ->
F = case _ of
N when is_integer(N) andalso 0 =:= (N rem 2) ->
even;
N when is_integer(N) ->
odd;
_ ->
not_a_number
end,
even = F(1234),
odd = F(6789),
not_a_number = F(my_atom).
test_cut_comprehensions() ->
F = << <<(1 + (X*2))>> || _ <- _, X <- _ >>, %% Note, this'll only be a /2 !
<<"AAA">> = F([a,b,c], [32]),
F1 = [ {X, Y, Z} || X <- _, Y <- _, Z <- _,
math:pow(X,2) + math:pow(Y,2) == math:pow(Z,2) ],
[{3,4,5}, {4,3,5}, {6,8,10}, {8,6,10}] =
lists:usort(F1(lists:seq(1,10), lists:seq(1,10), lists:seq(1,10))).
test_cut_named_fun() ->
Add = _ + _,
Fib = fun Self (0) -> 1;
Self (1) -> 1;
Self (N) -> (Add(_, _))(N, Self(N-1))
end,
true = (Fib(_))(10) =:= 55.
test() ->
test:test([{?MODULE, [test_cut,
test_cut_nested,
test_cut_op,
test_cut_unary_op,
test_cut_tuple,
test_cut_map,
test_cut_map_nested,
test_cut_record,
test_cut_record_nested,
test_cut_binary,
test_cut_list,
test_cut_case,
test_cut_comprehensions,
test_cut_named_fun]}],
[report, {name, ?MODULE}]).
| null | https://raw.githubusercontent.com/rabbitmq/erlando/1c1ef25a9bc228671b32b4a6ee30c7525314b1fd/test/src/test_cut.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at /
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
this isn't getting silly at all...
should be:
This is the same as:
And thus becomes
Note, this'll only be a /2 ! | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is Erlando .
The Initial Developer of the Original Code is VMware , Inc.
Copyright ( c ) 2011 - 2013 VMware , Inc. All rights reserved .
-module(test_cut).
-compile({parse_transform, cut}).
-compile({parse_transform, do}).
-compile(export_all).
-record(r, { f1 = false,
f2 = wibble,
f3 = juice }).
test_cut() ->
F0 = foo(a, b, _, 5+6, _),
F1 = F0(_, e),
ok = F1(c),
F2 = _(1,2),
3 = F2(fun erlang:'+'/2),
-1 = F2(fun erlang:'-'/2),
F3 = _:foo(a, b, c, _, e),
ok = F3(?MODULE, 11),
true = 3 == F4(math, sqrt, 9).
foo(a, b, c, 11, e) -> ok.
test_cut_nested() ->
F = f1(1, f2(1 + _), _),
F = \X - > f1(1 , f2(\Y - > 1 + Y ) , X )
ok = F(3).
f1(N, M, L) when N + M =:= L -> ok.
f2(Nf) -> Nf(1).
test_cut_op() ->
F = 1 + _,
3 = F(2).
test_cut_unary_op() ->
F = -_,
0 = 1 + F(1).
test_cut_tuple() ->
{foo, _} = {foo, F} = {foo, {bar, _}},
{bar, qux} = F(qux).
test_cut_record() ->
true = #r{} =/= #r{f3 = _},
orange = ((#r{f3 = _})(orange))#r.f3,
{r, foo, bar, baz} = (#r{f1 = _, f3 = _, f2 = _})(foo, baz, bar),
R = #r{},
F = R#r{f3 = _, f2 = _},
wobble = (F(orange, wobble))#r.f2,
Getter = _#r.f2,
wibble = Getter(R),
Setter = _#r{f2 = gerbil},
gerbil = Getter(Setter(R)),
Setter2 = _#r{f2 = _},
hamster = Getter(Setter2(R, hamster)).
test_cut_record_nested() ->
F = #r{f1 = #r{f1 = _, f3 = _}, f2 = _},
R = F(apple),
F1 = R#r.f1,
#r{f1 = orange, f3 = banana} = F1(orange, banana).
test_cut_map() ->
true = #{} =/= #{f3 => _},
orange = maps:get(f3, (#{f3 => _})(orange)),
#{f1 := foo, f2 := bar, f3 := baz}
= (#{f1 => _, f3 => _, f2 => _})(foo, baz, bar),
M = #{f1 => false, f2 => wibble, f3 => juice},
F = M#{f3 => _, f2 => _},
wobble = maps:get(f2, F(orange, wobble)),
Getter = maps:get(f2, _),
wibble = Getter(M),
Setter = _#{f2 := gerbil},
gerbil = Getter(Setter(M)),
Setter2 = _#{f2 := _},
hamster = Getter(Setter2(M, hamster)).
test_cut_map_nested() ->
F = #{f1 => #{f1 => _, f3 => _}, f2 => _},
M = F(apple),
F1 = maps:get(f1, M),
#{f1 := orange, f3 := banana} = F1(orange, banana).
test_cut_binary() ->
<<"AbA", _/binary>> = (<<65, _, 65>>)($b),
F = <<_:_>>,
G = F(15, _),
<<>> = G(0),
<<1:1/unsigned, 1:1/unsigned, 1:1/unsigned, 1:1/unsigned>> = G(4).
test_cut_list() ->
F = [_|_],
[a,b] = F(a,[b]),
G = [_, _ | [33]],
[a,b,33] = G(a,b),
H = [1, _, _, [_], 5 | [6, [_] | [_]]],
[ 1 , _ , _ , [ _ ] , 5 , 6 , [ _ ] , _ ]
\A , B , C - > [ 1 , A , B , \D - > [ D ] , 5 , 6 , \E - > [ E ] , C ]
[1, 2, 3, H1, 5, 6, H2, 8] = H(2, 3, 8),
[4] = H1(4),
[7] = H2(7),
I = [_, [_]],
[a, I1] = I(a),
[b] = I1(b).
test_cut_case() ->
F = case _ of
N when is_integer(N) andalso 0 =:= (N rem 2) ->
even;
N when is_integer(N) ->
odd;
_ ->
not_a_number
end,
even = F(1234),
odd = F(6789),
not_a_number = F(my_atom).
test_cut_comprehensions() ->
<<"AAA">> = F([a,b,c], [32]),
F1 = [ {X, Y, Z} || X <- _, Y <- _, Z <- _,
math:pow(X,2) + math:pow(Y,2) == math:pow(Z,2) ],
[{3,4,5}, {4,3,5}, {6,8,10}, {8,6,10}] =
lists:usort(F1(lists:seq(1,10), lists:seq(1,10), lists:seq(1,10))).
test_cut_named_fun() ->
Add = _ + _,
Fib = fun Self (0) -> 1;
Self (1) -> 1;
Self (N) -> (Add(_, _))(N, Self(N-1))
end,
true = (Fib(_))(10) =:= 55.
test() ->
test:test([{?MODULE, [test_cut,
test_cut_nested,
test_cut_op,
test_cut_unary_op,
test_cut_tuple,
test_cut_map,
test_cut_map_nested,
test_cut_record,
test_cut_record_nested,
test_cut_binary,
test_cut_list,
test_cut_case,
test_cut_comprehensions,
test_cut_named_fun]}],
[report, {name, ?MODULE}]).
|
01e18e934bec1a75d94fd85330ef5a058377d813b4c73a8bb566a00f91432626 | philopon/haddocset | Plist.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Documentation.Haddocset.Plist
( Plist(..)
, showPlist
) where
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
data Plist = Plist
{ cfBundleIdentifier :: Text
, cfBundleName :: Text
, docSetPlatformFamily :: Text
} deriving Show
showPlist :: Plist -> Text
showPlist Plist{..} = T.unlines
[ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"-1.0.dtd\">"
, "<plist version=\"1.0\">"
, "<dict>"
, "<key>CFBundleIdentifier</key>"
, "<string>" <> cfBundleIdentifier <> "</string>"
, "<key>CFBundleName</key>"
, "<string>" <> cfBundleName <> "</string>"
, "<key>DocSetPlatformFamily</key>"
, "<string>" <> docSetPlatformFamily <> "</string>"
, "<key>isDashDocset</key>"
, "<true/>"
, "<key>dashIndexFilePath</key>"
, "<string>index.html</string>"
, "<key>DashDocSetFamily</key>"
, "<string>dashtoc</string>"
, "</dict>"
, "</plist>"
]
| null | https://raw.githubusercontent.com/philopon/haddocset/0e89ffea4f0c375a1eed2493e2a08c3d3953f8b1/Documentation/Haddocset/Plist.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE RecordWildCards #
module Documentation.Haddocset.Plist
( Plist(..)
, showPlist
) where
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
data Plist = Plist
{ cfBundleIdentifier :: Text
, cfBundleName :: Text
, docSetPlatformFamily :: Text
} deriving Show
showPlist :: Plist -> Text
showPlist Plist{..} = T.unlines
[ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"-1.0.dtd\">"
, "<plist version=\"1.0\">"
, "<dict>"
, "<key>CFBundleIdentifier</key>"
, "<string>" <> cfBundleIdentifier <> "</string>"
, "<key>CFBundleName</key>"
, "<string>" <> cfBundleName <> "</string>"
, "<key>DocSetPlatformFamily</key>"
, "<string>" <> docSetPlatformFamily <> "</string>"
, "<key>isDashDocset</key>"
, "<true/>"
, "<key>dashIndexFilePath</key>"
, "<string>index.html</string>"
, "<key>DashDocSetFamily</key>"
, "<string>dashtoc</string>"
, "</dict>"
, "</plist>"
]
|
64776d8549cfffdb250fb7b3a66eb84e5f50368cfe593eaada9df132ebb4127f | sdiehl/llvm-tutorial-standalone | JIT.hs | module JIT where
import Data.Int
import Data.Word
import Foreign.Ptr ( FunPtr, castFunPtr )
import Control.Monad.Except
import LLVM.General.Target
import LLVM.General.Context
import LLVM.General.CodeModel
import LLVM.General.Module as Mod
import qualified LLVM.General.AST as AST
import LLVM.General.PassManager
import LLVM.General.Transforms
import LLVM.General.Analysis
import qualified LLVM.General.ExecutionEngine as EE
foreign import ccall "dynamic" haskFun :: FunPtr (IO Double) -> (IO Double)
run :: FunPtr a -> IO Double
run fn = haskFun (castFunPtr fn :: FunPtr (IO Double))
jit :: Context -> (EE.MCJIT -> IO a) -> IO a
jit c = EE.withMCJIT c optlevel model ptrelim fastins
where
optlevel = Just 0 -- optimization level
model = Nothing -- code model ( Default )
ptrelim = Nothing -- frame pointer elimination
fastins = Nothing -- fast instruction selection
passes :: PassSetSpec
passes = defaultCuratedPassSetSpec { optLevel = Just 3 }
runJIT :: AST.Module -> IO (Either String AST.Module)
runJIT mod = do
withContext $ \context ->
jit context $ \executionEngine ->
runExceptT $ withModuleFromAST context mod $ \m ->
withPassManager passes $ \pm -> do
-- Optimization Pass
{-runPassManager pm m-}
optmod <- moduleAST m
s <- moduleLLVMAssembly m
putStrLn s
EE.withModuleInEngine executionEngine m $ \ee -> do
mainfn <- EE.getFunction ee (AST.Name "main")
case mainfn of
Just fn -> do
res <- run fn
putStrLn $ "Evaluated to: " ++ show res
Nothing -> return ()
-- Return the optimized module
return optmod
| null | https://raw.githubusercontent.com/sdiehl/llvm-tutorial-standalone/8edcc083c8625c548ea9ce0ae76e5f5c1f13992c/src/JIT.hs | haskell | optimization level
code model ( Default )
frame pointer elimination
fast instruction selection
Optimization Pass
runPassManager pm m
Return the optimized module | module JIT where
import Data.Int
import Data.Word
import Foreign.Ptr ( FunPtr, castFunPtr )
import Control.Monad.Except
import LLVM.General.Target
import LLVM.General.Context
import LLVM.General.CodeModel
import LLVM.General.Module as Mod
import qualified LLVM.General.AST as AST
import LLVM.General.PassManager
import LLVM.General.Transforms
import LLVM.General.Analysis
import qualified LLVM.General.ExecutionEngine as EE
foreign import ccall "dynamic" haskFun :: FunPtr (IO Double) -> (IO Double)
run :: FunPtr a -> IO Double
run fn = haskFun (castFunPtr fn :: FunPtr (IO Double))
jit :: Context -> (EE.MCJIT -> IO a) -> IO a
jit c = EE.withMCJIT c optlevel model ptrelim fastins
where
passes :: PassSetSpec
passes = defaultCuratedPassSetSpec { optLevel = Just 3 }
runJIT :: AST.Module -> IO (Either String AST.Module)
runJIT mod = do
withContext $ \context ->
jit context $ \executionEngine ->
runExceptT $ withModuleFromAST context mod $ \m ->
withPassManager passes $ \pm -> do
optmod <- moduleAST m
s <- moduleLLVMAssembly m
putStrLn s
EE.withModuleInEngine executionEngine m $ \ee -> do
mainfn <- EE.getFunction ee (AST.Name "main")
case mainfn of
Just fn -> do
res <- run fn
putStrLn $ "Evaluated to: " ++ show res
Nothing -> return ()
return optmod
|
121ef7e21fbcdc68fc3eceec71c780dec908cd3f8c72c52b3e938315c939a7ed | dawidovsky/IIUWr | Wykład.rkt | #lang racket
;; expressions
(define (const? t)
(number? t))
(define (op? t)
(and (list? t)
(member (car t) '(+ - * / > < >= <= =))))
(define (op-op e)
(car e))
(define (op-args e)
(cdr e))
(define (op-cons op args)
(cons op args))
(define (op->proc op)
(cond [(eq? op '+) +]
[(eq? op '*) *]
[(eq? op '-) -]
[(eq? op '/) /]
[(eq? op '=) =]
[(eq? op '>) >]
[(eq? op '<) <]
[(eq? op '<=) <=]
[(eq? op '>=) >=]))
(define (let-def? t)
(and (list? t)
(= (length t) 2)
(symbol? (car t))))
(define (let-def-var e)
(car e))
(define (let-def-expr e)
(cadr e))
(define (let-def-cons x e)
(list x e))
(define (let? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'let)
(let-def? (cadr t))))
(define (let-def e)
(cadr e))
(define (let-expr e)
(caddr e))
(define (let-cons def e)
(list 'let def e))
(define (var? t)
(symbol? t))
(define (var-var e)
e)
(define (var-cons x)
x)
(define (arith/let-expr? t)
(or (const? t)
(and (op? t)
(andmap arith/let-expr? (op-args t)))
(and (let? t)
(arith/let-expr? (let-expr t))
(arith/let-expr? (let-def-expr (let-def t))))
(var? t)))
;; set
(define empty-set
(identity null))
(define (add-to-set x s)
(cond [(null? s) (list x)]
[(eq? x (car s)) s]
[else (cons (car s) (add-to-set x (cdr s)))]))
(define (merge-sets s1 s2)
(cond [(null? s1) s2]
[else (add-to-set (car s1) (merge-sets (cdr s1) s2))]))
(define (set-member? x s)
(member x s))
(define (set->list s)
(identity s))
;; free-variables
(define (fv e env)
(cond [(const? e) empty-set]
[(op? e) (args-fv (op-args e) env)]
[(let? e) (merge-sets
(fv (let-def-expr (let-def e)) env)
(fv (let-expr e)
(add-to-set (let-def-var (let-def e))
env)))]
[(var? e) (if (set-member? (var-var e) env)
empty-set
(add-to-set (var-var e) empty-set))]))
(define (args-fv xs env)
(cond [(null? xs) empty-set]
[else (merge-sets (fv (car xs) env)
(args-fv (cdr xs) env))]))
(define (free-vars e)
(set->list (fv e empty-set)))
;; pairs
(define (cons? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'cons)))
(define (cons-fst e)
(second e))
(define (cons-snd e)
(third e))
(define (cons-cons e1 e2)
(list 'cons e1 e2))
(define (car? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'car)))
(define (car-expr e)
(second e))
(define (cdr? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'cdr)))
(define (cdr-expr e)
(second e))
(define (exp-pair-pred? e)
(and (list? e)
(= (length e) 2)
(eq? 'pair? (car e))))
(define (exp-pair-expr e)
(second e))
;; lambdas
(define (lambda? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'lambda)
(list? (cadr t))
(andmap symbol? (cadr t))))
(define (lambda-vars e)
(cadr e))
(define (lambda-expr e)
(caddr e))
;; applications
(define (app? t)
(and (list? t)
(> (length t) 0)))
(define (app-proc e)
(car e))
(define (app-args e)
(cdr e))
;; expressions
(define (expr? t)
(or (const? t)
(exp-bool? t)
(and (op? t)
(andmap expr? (op-args t)))
(and (let? t)
(expr? (let-expr t))
(expr? (let-def-expr (let-def t))))
(var? t)
(and (cons? t)
(expr? (cons-fst t))
(expr? (cons-snd t)))
(and (car? t)
(expr? (car-expr t)))
(and (cdr? t)
(expr? (cdr-expr t)))
(and (lambda? t)
(expr? (lambda-expr t)))
(exp-null? t)
(and (exp-null-pred? t)
(expr? (exp-null-expr t)))
(and (exp-pair-pred? t)
(expr? (exp-pair-expr t)))
(and (if-pred? t)
(expr? (if-if t))
(expr? (if-true t))
(expr? (if-false t)))
(and (app? t)
(expr? (app-proc t))
(andmap expr? (app-args t)))
))
;; environments
(define empty-env
null)
(define (add-to-env x v env)
(cons (list x v) env))
(define (find-in-env x env)
(cond [(null? env) (error "undefined variable" x)]
[(eq? x (caar env)) (cadar env)]
[else (find-in-env x (cdr env))]))
;; closures
(define (closure-cons xs expr env)
(list 'closure xs expr env))
(define (closure? c)
(and (list? c)
(= (length c) 4)
(eq? (car c) 'closure)))
(define (closure-vars c)
(cadr c))
(define (closure-expr c)
(caddr c))
(define (closure-env c)
(cadddr c))
;; null
(define (exp-null? e)
(eq? e 'null))
(define (exp-null-pred? e)
(and (list? e)
(= 2 (length e))
(eq? 'null? (car e))))
(define (null-pair-cons e)
(list 'null? e))
(define (exp-null-expr e)
(second e))
(define (expr-null-cons) 'null)
;; list
(define (expr-list? e)
(and (list? e)
(> (length e) 0)
(eq? 'list (car e))))
(define expr-list-args cdr)
(define (expr-list->cons e)
(if (null? e)
(expr-null-cons)
(cons-cons (car e) (expr-list->cons (cdr e)))))
;; bools
(define (exp-bool? e)
(boolean? e))
;; and
(define (and-pred? e)
(and (list? e)
(> 0 (length e))
(eq? 'and (car e))))
;; or
(define (and-pred? e)
(and (list? e)
(> 0 (length e))
(eq? 'or (car e))))
;; if
(define (if-pred? e)
(and (list? e)
(= (length e) 4)
(eq? (car e) 'if)))
(define (if-if e)
(second e))
(define (if-true e)
(third e))
(define (if-false e)
(fourth e))
;; evaluator
(define (eval-env e env)
(cond [(const? e) e]
[(exp-bool? e) e]
[(exp-null? e) null]
[(exp-pair-pred? e) (pair? (eval-env (exp-pair-expr e) env))]
[(exp-null-pred? e) (null? (eval-env (exp-null-expr e) env))]
[(op? e)
(apply (op->proc (op-op e))
(map (lambda (a) (eval-env a env))
(op-args e)))]
[(let? e)
(eval-env (let-expr e)
(env-for-let (let-def e) env))]
[(var? e) (find-in-env (var-var e) env)]
[(cons? e)
(cons (eval-env (cons-fst e) env)
(eval-env (cons-snd e) env))]
[(expr-list? e)
(eval-env (expr-list->cons (expr-list-args e)) env)]
[(car? e)
(car (eval-env (car-expr e) env))]
[(cdr? e)
(cdr (eval-env (cdr-expr e) env))]
[(lambda? e)
(closure-cons (lambda-vars e) (lambda-expr e) env)]
[(if-pred? e)
(if (eval-env (if-if e) env)
(eval-env (if-true e) env)
(eval-env (if-false e) env))]
[(app? e)
(apply-closure
(eval-env (app-proc e) env)
(map (lambda (a) (eval-env a env))
(app-args e)))]
))
(define (apply-closure c args)
(eval-env (closure-expr c)
(env-for-closure
(closure-vars c)
args
(closure-env c))))
(define (env-for-closure xs vs env)
(cond [(and (null? xs) (null? vs)) env]
[(and (not (null? xs)) (not (null? vs)))
(add-to-env
(car xs)
(car vs)
(env-for-closure (cdr xs) (cdr vs) env))]
[else (error "arity mismatch")]))
(define (env-for-let def env)
(add-to-env
(let-def-var def)
(eval-env (let-def-expr def) env)
env))
(define (eval e)
(eval-env e empty-env)) | null | https://raw.githubusercontent.com/dawidovsky/IIUWr/73f0f65fb141f82a05dac2573f39f6fa48a81409/MP/Pracownia7/Wyk%C5%82ad.rkt | racket | expressions
set
free-variables
pairs
lambdas
applications
expressions
environments
closures
null
list
bools
and
or
if
evaluator | #lang racket
(define (const? t)
(number? t))
(define (op? t)
(and (list? t)
(member (car t) '(+ - * / > < >= <= =))))
(define (op-op e)
(car e))
(define (op-args e)
(cdr e))
(define (op-cons op args)
(cons op args))
(define (op->proc op)
(cond [(eq? op '+) +]
[(eq? op '*) *]
[(eq? op '-) -]
[(eq? op '/) /]
[(eq? op '=) =]
[(eq? op '>) >]
[(eq? op '<) <]
[(eq? op '<=) <=]
[(eq? op '>=) >=]))
(define (let-def? t)
(and (list? t)
(= (length t) 2)
(symbol? (car t))))
(define (let-def-var e)
(car e))
(define (let-def-expr e)
(cadr e))
(define (let-def-cons x e)
(list x e))
(define (let? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'let)
(let-def? (cadr t))))
(define (let-def e)
(cadr e))
(define (let-expr e)
(caddr e))
(define (let-cons def e)
(list 'let def e))
(define (var? t)
(symbol? t))
(define (var-var e)
e)
(define (var-cons x)
x)
(define (arith/let-expr? t)
(or (const? t)
(and (op? t)
(andmap arith/let-expr? (op-args t)))
(and (let? t)
(arith/let-expr? (let-expr t))
(arith/let-expr? (let-def-expr (let-def t))))
(var? t)))
(define empty-set
(identity null))
(define (add-to-set x s)
(cond [(null? s) (list x)]
[(eq? x (car s)) s]
[else (cons (car s) (add-to-set x (cdr s)))]))
(define (merge-sets s1 s2)
(cond [(null? s1) s2]
[else (add-to-set (car s1) (merge-sets (cdr s1) s2))]))
(define (set-member? x s)
(member x s))
(define (set->list s)
(identity s))
(define (fv e env)
(cond [(const? e) empty-set]
[(op? e) (args-fv (op-args e) env)]
[(let? e) (merge-sets
(fv (let-def-expr (let-def e)) env)
(fv (let-expr e)
(add-to-set (let-def-var (let-def e))
env)))]
[(var? e) (if (set-member? (var-var e) env)
empty-set
(add-to-set (var-var e) empty-set))]))
(define (args-fv xs env)
(cond [(null? xs) empty-set]
[else (merge-sets (fv (car xs) env)
(args-fv (cdr xs) env))]))
(define (free-vars e)
(set->list (fv e empty-set)))
(define (cons? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'cons)))
(define (cons-fst e)
(second e))
(define (cons-snd e)
(third e))
(define (cons-cons e1 e2)
(list 'cons e1 e2))
(define (car? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'car)))
(define (car-expr e)
(second e))
(define (cdr? t)
(and (list? t)
(= (length t) 2)
(eq? (car t) 'cdr)))
(define (cdr-expr e)
(second e))
(define (exp-pair-pred? e)
(and (list? e)
(= (length e) 2)
(eq? 'pair? (car e))))
(define (exp-pair-expr e)
(second e))
(define (lambda? t)
(and (list? t)
(= (length t) 3)
(eq? (car t) 'lambda)
(list? (cadr t))
(andmap symbol? (cadr t))))
(define (lambda-vars e)
(cadr e))
(define (lambda-expr e)
(caddr e))
(define (app? t)
(and (list? t)
(> (length t) 0)))
(define (app-proc e)
(car e))
(define (app-args e)
(cdr e))
(define (expr? t)
(or (const? t)
(exp-bool? t)
(and (op? t)
(andmap expr? (op-args t)))
(and (let? t)
(expr? (let-expr t))
(expr? (let-def-expr (let-def t))))
(var? t)
(and (cons? t)
(expr? (cons-fst t))
(expr? (cons-snd t)))
(and (car? t)
(expr? (car-expr t)))
(and (cdr? t)
(expr? (cdr-expr t)))
(and (lambda? t)
(expr? (lambda-expr t)))
(exp-null? t)
(and (exp-null-pred? t)
(expr? (exp-null-expr t)))
(and (exp-pair-pred? t)
(expr? (exp-pair-expr t)))
(and (if-pred? t)
(expr? (if-if t))
(expr? (if-true t))
(expr? (if-false t)))
(and (app? t)
(expr? (app-proc t))
(andmap expr? (app-args t)))
))
(define empty-env
null)
(define (add-to-env x v env)
(cons (list x v) env))
(define (find-in-env x env)
(cond [(null? env) (error "undefined variable" x)]
[(eq? x (caar env)) (cadar env)]
[else (find-in-env x (cdr env))]))
(define (closure-cons xs expr env)
(list 'closure xs expr env))
(define (closure? c)
(and (list? c)
(= (length c) 4)
(eq? (car c) 'closure)))
(define (closure-vars c)
(cadr c))
(define (closure-expr c)
(caddr c))
(define (closure-env c)
(cadddr c))
(define (exp-null? e)
(eq? e 'null))
(define (exp-null-pred? e)
(and (list? e)
(= 2 (length e))
(eq? 'null? (car e))))
(define (null-pair-cons e)
(list 'null? e))
(define (exp-null-expr e)
(second e))
(define (expr-null-cons) 'null)
(define (expr-list? e)
(and (list? e)
(> (length e) 0)
(eq? 'list (car e))))
(define expr-list-args cdr)
(define (expr-list->cons e)
(if (null? e)
(expr-null-cons)
(cons-cons (car e) (expr-list->cons (cdr e)))))
(define (exp-bool? e)
(boolean? e))
(define (and-pred? e)
(and (list? e)
(> 0 (length e))
(eq? 'and (car e))))
(define (and-pred? e)
(and (list? e)
(> 0 (length e))
(eq? 'or (car e))))
(define (if-pred? e)
(and (list? e)
(= (length e) 4)
(eq? (car e) 'if)))
(define (if-if e)
(second e))
(define (if-true e)
(third e))
(define (if-false e)
(fourth e))
(define (eval-env e env)
(cond [(const? e) e]
[(exp-bool? e) e]
[(exp-null? e) null]
[(exp-pair-pred? e) (pair? (eval-env (exp-pair-expr e) env))]
[(exp-null-pred? e) (null? (eval-env (exp-null-expr e) env))]
[(op? e)
(apply (op->proc (op-op e))
(map (lambda (a) (eval-env a env))
(op-args e)))]
[(let? e)
(eval-env (let-expr e)
(env-for-let (let-def e) env))]
[(var? e) (find-in-env (var-var e) env)]
[(cons? e)
(cons (eval-env (cons-fst e) env)
(eval-env (cons-snd e) env))]
[(expr-list? e)
(eval-env (expr-list->cons (expr-list-args e)) env)]
[(car? e)
(car (eval-env (car-expr e) env))]
[(cdr? e)
(cdr (eval-env (cdr-expr e) env))]
[(lambda? e)
(closure-cons (lambda-vars e) (lambda-expr e) env)]
[(if-pred? e)
(if (eval-env (if-if e) env)
(eval-env (if-true e) env)
(eval-env (if-false e) env))]
[(app? e)
(apply-closure
(eval-env (app-proc e) env)
(map (lambda (a) (eval-env a env))
(app-args e)))]
))
(define (apply-closure c args)
(eval-env (closure-expr c)
(env-for-closure
(closure-vars c)
args
(closure-env c))))
(define (env-for-closure xs vs env)
(cond [(and (null? xs) (null? vs)) env]
[(and (not (null? xs)) (not (null? vs)))
(add-to-env
(car xs)
(car vs)
(env-for-closure (cdr xs) (cdr vs) env))]
[else (error "arity mismatch")]))
(define (env-for-let def env)
(add-to-env
(let-def-var def)
(eval-env (let-def-expr def) env)
env))
(define (eval e)
(eval-env e empty-env)) |
7d99cab67cb9c5c07c45ada37d4d80a2b14d7e66c60be006b244f0c865eb8b43 | PrecursorApp/precursor | permission.cljs | (ns frontend.models.permission
(:require [datascript.core :as d]
[frontend.utils :as utils]))
(defn github-permissions [db doc]
(filter #(= (:db/id doc) (:permission/document %))
(map #(d/entity db (:e %))
(d/datoms db :avet :permission/reason :permission.reason/github-markdown))))
| null | https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src-cljs/frontend/models/permission.cljs | clojure | (ns frontend.models.permission
(:require [datascript.core :as d]
[frontend.utils :as utils]))
(defn github-permissions [db doc]
(filter #(= (:db/id doc) (:permission/document %))
(map #(d/entity db (:e %))
(d/datoms db :avet :permission/reason :permission.reason/github-markdown))))
| |
cdcd63d9c1962c8d040502d1fda5bd89d093054b2297599b116548838a9f01be | matsen/pplacer | rarefaction.ml | open Ppatteries
let merge = const incr |> flip
let lmerge = List.fold_left ((!) |- (+) |> flip) 0 |- ref
module I = Mass_map.Indiv
Convenience wrapper around the functions in Kr_distance for specifying just
* a callback with parameters for the count of edge segments below the current
* edge segment and the branch length . The return values of the callbacks are
* summed across the tree .
* a callback with parameters for the count of edge segments below the current
* edge segment and the branch length. The return values of the callbacks are
* summed across the tree. *)
let count_along_mass gt mass cb =
let partial_total id =
Kr_distance.total_along_edge
cb
(Gtree.get_bl gt id)
(IntMap.get id [] mass |> List.map I.to_pair |> List.sort compare)
merge
in
Kr_distance.total_over_tree
partial_total
(const ())
lmerge
(fun () -> ref 0)
(Gtree.get_stree gt)
let k_maps_of_placerun: int -> Newick_bark.t Placerun.t -> float IntMap.t IntMap.t
= fun k_max pr ->
let n = Placerun.get_pqueries pr |> List.length in
let n' = float_of_int n
and base_k_map = 0 -- n
|> Enum.map (identity &&& const 1.)
|> IntMap.of_enum
|> IntMap.singleton 0
in
Enum.fold
(fun k_maps k ->
let prev_map = IntMap.find k k_maps
and diff = n' -. float_of_int k in
let q_k r = (diff -. float_of_int r) /. diff *. IntMap.find r prev_map in
0 -- n
|> Enum.map (identity &&& q_k)
|> IntMap.of_enum
|> flip (IntMap.add (k + 1)) k_maps)
base_k_map
(0 --^ k_max)
(* Compute the rarefaction curve of a placerun, given a placement criterion and
* optionally the highest X value for the curve. *)
let of_placerun:
(Placement.t -> float) -> ?k_max:int -> Newick_bark.t Placerun.t
-> (int * float * float * float) Enum.t
= fun criterion ?k_max pr ->
let gt = Placerun.get_ref_tree pr |> Newick_gtree.add_zero_root_bl
and mass = I.of_placerun
Mass_map.Point
criterion
pr
in
let n = Placerun.get_pqueries pr |> List.length in
let n' = float_of_int n in
let k_max = match k_max with
| Some k when k < n -> k
| _ -> n
in
let k_maps = k_maps_of_placerun k_max pr in
let count k =
let q_k = IntMap.find k k_maps |> flip IntMap.find in
let count_fn = count_along_mass gt mass in
count_fn
(fun d bl ->
let d = !d in
let p = n - d in
(1. -. (q_k d) -. (q_k p)) *. bl),
count_fn (fun d bl -> (1. -. (q_k !d)) *. bl),
count_fn
(fun d bl ->
let d' = float_of_int !d in
bl *. d' *. (n' -. d'))
in
2 -- k_max
|> Enum.map (fun k ->
let u, r, q = count k in
let k' = float_of_int k in
let q' = q *. (k' -. 1.) /. (k' *. n' *. (n' -. 1.)) in
k, u, r, q')
let mass_induced_tree gt mass =
let edge = ref 0
and bark_map = ref IntMap.empty
and mass_counts = ref IntMap.empty in
let next_edge mass_count bl =
let x = !edge in
incr edge;
bark_map := Newick_bark.map_set_bl x bl !bark_map;
if mass_count > 0 then
mass_counts := IntMap.add x mass_count !mass_counts;
x
in
let open Stree in
let rec aux t =
let i, below = match t with
| Leaf i -> i, None
| Node (i, subtrees) -> i, Some (List.map aux subtrees)
in
let ml = IntMap.get i [] mass
|> List.map (fun {I.distal_bl} -> distal_bl)
|> List.cons 0.
|> List.group approx_compare
|> List.map
(function
| hd :: tl when hd =~ 0. -> hd, List.length tl
| hd :: tl -> hd, List.length tl + 1
| [] -> invalid_arg "ml")
and bl = Gtree.get_bl gt i in
let rec snips tree pl =
let j, tl = match pl with
| (p1, c1) :: ((p2, _) :: _ as tl) -> next_edge c1 (p2 -. p1), tl
| [p, c] -> next_edge c (bl -. p), []
| [] -> invalid_arg "snips"
in
let tree' = Some
[match tree with
| None -> leaf j
| Some subtrees -> node j subtrees]
in
match tl with
| [] -> tree'
| tl -> snips tree' tl
in
snips below ml
|> Option.get
|> List.hd
in
let st' = aux (Gtree.get_stree gt) in
!mass_counts, Gtree.gtree st' !bark_map
let distal_proximal_maps st marks_map =
let open Stree in
let rec aux = function
| Leaf i -> IntMap.singleton i (IntMap.get i 0 marks_map)
| Node (i, subtrees) ->
let distal_marks = List.map aux subtrees |> List.reduce IntMap.union in
let marks = List.enum subtrees
|> Enum.map (top_id |- flip IntMap.find distal_marks)
|> Enum.sum
|> (+) (IntMap.get i 0 marks_map)
in
IntMap.add i marks distal_marks
in
let distal_map = aux st in
let total_marks = IntMap.values marks_map |> Enum.sum in
let proximal_map = IntMap.map ((-) total_marks) distal_map in
distal_map, proximal_map
let distal_edges_map st =
let open Stree in
let rec aux = function
| Leaf i -> IntMap.singleton i IntSet.empty
| Node (i, subtrees) ->
let distal_edges = List.map aux subtrees |> List.reduce IntMap.union in
let subtree_edges = List.map top_id subtrees in
let edges = List.enum subtree_edges
|> Enum.map (flip IntMap.find distal_edges)
|> Enum.reduce IntSet.union
|> IntSet.union (IntSet.of_list subtree_edges)
in
IntMap.add i edges distal_edges
in
aux st
exception What of (int * int * int * int)
let auto_cache ?(count = 1024 * 1024) f =
curry (Cache.make_ht ~gen:(uncurry f) ~init_size:count).Cache.get
let variance_of_placerun criterion ?k_max pr =
let gt = Placerun.get_ref_tree pr |> Newick_gtree.add_zero_root_bl
and mass = I.of_placerun
Mass_map.Point
criterion
pr
in
let n = Placerun.get_pqueries pr |> List.length in
let k_max = match k_max with
| Some k when k < n -> k
| _ -> n
in
let k_maps = k_maps_of_placerun k_max pr in
let marks_map, gt' = mass_induced_tree gt mass in
let bl = Gtree.get_bl gt' in
let st' = Gtree.get_stree gt' in
let distal_marks, proximal_marks = distal_proximal_maps st' marks_map in
let distal_edges = distal_edges_map st' in
(* is i proximal to j? *)
let _is_proximal i j = IntSet.mem j (IntMap.find i distal_edges) in
let is_proximal = auto_cache _is_proximal in
let d i = IntMap.find i distal_marks
and c i = IntMap.find i proximal_marks in
let _o i j =
if is_proximal i j then c i else d i
and _s i j =
if is_proximal i j then d i else c i
and _q k x = IntMap.find k k_maps |> IntMap.find x in
let o = auto_cache _o and s = auto_cache _s and q = auto_cache _q in
let cov_without_root k i j =
let q_k = q k in
if i = j then
let cov = 1. -. q_k (d i) -. q_k (c i) in
cov -. cov ** 2.
else
q_k (o i j + o j i) -. q_k (o i j) *. q_k (o j i)
+. (1. -. q_k (o i j)) *. q_k (s j i)
+. (1. -. q_k (o j i)) *. q_k (s i j)
-. q_k (s i j) *. q_k (s j i)
and cov_with_root k i j =
let q_k = q k in
if i = j then
let cov = 1. -. q_k (d i) in
cov -. cov ** 2.
else
let union =
if is_proximal i j then d i
else if is_proximal j i then d j
else d i + d j
in
q_k union -. q_k (d i) *. q_k (d j)
in
let n_edges = Stree.top_id st' in
let var cov_fn k =
let cov_times_bl k i j =
cov_fn k i j *. bl i *. bl j
in
let diag = 0 --^ n_edges
|> Enum.map (fun i -> cov_times_bl k i i)
|> Enum.fold (+.) 0.
in
Uptri.init n_edges (cov_times_bl k)
|> Uptri.fold_left (+.) 0.
|> ( *.) 2.
|> (+.) diag
in
2 -- k_max
|> Enum.map (fun k -> k, var cov_without_root k, var cov_with_root k)
| null | https://raw.githubusercontent.com/matsen/pplacer/f40a363e962cca7131f1f2d372262e0081ff1190/pplacer_src/rarefaction.ml | ocaml | Compute the rarefaction curve of a placerun, given a placement criterion and
* optionally the highest X value for the curve.
is i proximal to j? | open Ppatteries
let merge = const incr |> flip
let lmerge = List.fold_left ((!) |- (+) |> flip) 0 |- ref
module I = Mass_map.Indiv
Convenience wrapper around the functions in Kr_distance for specifying just
* a callback with parameters for the count of edge segments below the current
* edge segment and the branch length . The return values of the callbacks are
* summed across the tree .
* a callback with parameters for the count of edge segments below the current
* edge segment and the branch length. The return values of the callbacks are
* summed across the tree. *)
let count_along_mass gt mass cb =
let partial_total id =
Kr_distance.total_along_edge
cb
(Gtree.get_bl gt id)
(IntMap.get id [] mass |> List.map I.to_pair |> List.sort compare)
merge
in
Kr_distance.total_over_tree
partial_total
(const ())
lmerge
(fun () -> ref 0)
(Gtree.get_stree gt)
let k_maps_of_placerun: int -> Newick_bark.t Placerun.t -> float IntMap.t IntMap.t
= fun k_max pr ->
let n = Placerun.get_pqueries pr |> List.length in
let n' = float_of_int n
and base_k_map = 0 -- n
|> Enum.map (identity &&& const 1.)
|> IntMap.of_enum
|> IntMap.singleton 0
in
Enum.fold
(fun k_maps k ->
let prev_map = IntMap.find k k_maps
and diff = n' -. float_of_int k in
let q_k r = (diff -. float_of_int r) /. diff *. IntMap.find r prev_map in
0 -- n
|> Enum.map (identity &&& q_k)
|> IntMap.of_enum
|> flip (IntMap.add (k + 1)) k_maps)
base_k_map
(0 --^ k_max)
let of_placerun:
(Placement.t -> float) -> ?k_max:int -> Newick_bark.t Placerun.t
-> (int * float * float * float) Enum.t
= fun criterion ?k_max pr ->
let gt = Placerun.get_ref_tree pr |> Newick_gtree.add_zero_root_bl
and mass = I.of_placerun
Mass_map.Point
criterion
pr
in
let n = Placerun.get_pqueries pr |> List.length in
let n' = float_of_int n in
let k_max = match k_max with
| Some k when k < n -> k
| _ -> n
in
let k_maps = k_maps_of_placerun k_max pr in
let count k =
let q_k = IntMap.find k k_maps |> flip IntMap.find in
let count_fn = count_along_mass gt mass in
count_fn
(fun d bl ->
let d = !d in
let p = n - d in
(1. -. (q_k d) -. (q_k p)) *. bl),
count_fn (fun d bl -> (1. -. (q_k !d)) *. bl),
count_fn
(fun d bl ->
let d' = float_of_int !d in
bl *. d' *. (n' -. d'))
in
2 -- k_max
|> Enum.map (fun k ->
let u, r, q = count k in
let k' = float_of_int k in
let q' = q *. (k' -. 1.) /. (k' *. n' *. (n' -. 1.)) in
k, u, r, q')
let mass_induced_tree gt mass =
let edge = ref 0
and bark_map = ref IntMap.empty
and mass_counts = ref IntMap.empty in
let next_edge mass_count bl =
let x = !edge in
incr edge;
bark_map := Newick_bark.map_set_bl x bl !bark_map;
if mass_count > 0 then
mass_counts := IntMap.add x mass_count !mass_counts;
x
in
let open Stree in
let rec aux t =
let i, below = match t with
| Leaf i -> i, None
| Node (i, subtrees) -> i, Some (List.map aux subtrees)
in
let ml = IntMap.get i [] mass
|> List.map (fun {I.distal_bl} -> distal_bl)
|> List.cons 0.
|> List.group approx_compare
|> List.map
(function
| hd :: tl when hd =~ 0. -> hd, List.length tl
| hd :: tl -> hd, List.length tl + 1
| [] -> invalid_arg "ml")
and bl = Gtree.get_bl gt i in
let rec snips tree pl =
let j, tl = match pl with
| (p1, c1) :: ((p2, _) :: _ as tl) -> next_edge c1 (p2 -. p1), tl
| [p, c] -> next_edge c (bl -. p), []
| [] -> invalid_arg "snips"
in
let tree' = Some
[match tree with
| None -> leaf j
| Some subtrees -> node j subtrees]
in
match tl with
| [] -> tree'
| tl -> snips tree' tl
in
snips below ml
|> Option.get
|> List.hd
in
let st' = aux (Gtree.get_stree gt) in
!mass_counts, Gtree.gtree st' !bark_map
let distal_proximal_maps st marks_map =
let open Stree in
let rec aux = function
| Leaf i -> IntMap.singleton i (IntMap.get i 0 marks_map)
| Node (i, subtrees) ->
let distal_marks = List.map aux subtrees |> List.reduce IntMap.union in
let marks = List.enum subtrees
|> Enum.map (top_id |- flip IntMap.find distal_marks)
|> Enum.sum
|> (+) (IntMap.get i 0 marks_map)
in
IntMap.add i marks distal_marks
in
let distal_map = aux st in
let total_marks = IntMap.values marks_map |> Enum.sum in
let proximal_map = IntMap.map ((-) total_marks) distal_map in
distal_map, proximal_map
let distal_edges_map st =
let open Stree in
let rec aux = function
| Leaf i -> IntMap.singleton i IntSet.empty
| Node (i, subtrees) ->
let distal_edges = List.map aux subtrees |> List.reduce IntMap.union in
let subtree_edges = List.map top_id subtrees in
let edges = List.enum subtree_edges
|> Enum.map (flip IntMap.find distal_edges)
|> Enum.reduce IntSet.union
|> IntSet.union (IntSet.of_list subtree_edges)
in
IntMap.add i edges distal_edges
in
aux st
exception What of (int * int * int * int)
let auto_cache ?(count = 1024 * 1024) f =
curry (Cache.make_ht ~gen:(uncurry f) ~init_size:count).Cache.get
let variance_of_placerun criterion ?k_max pr =
let gt = Placerun.get_ref_tree pr |> Newick_gtree.add_zero_root_bl
and mass = I.of_placerun
Mass_map.Point
criterion
pr
in
let n = Placerun.get_pqueries pr |> List.length in
let k_max = match k_max with
| Some k when k < n -> k
| _ -> n
in
let k_maps = k_maps_of_placerun k_max pr in
let marks_map, gt' = mass_induced_tree gt mass in
let bl = Gtree.get_bl gt' in
let st' = Gtree.get_stree gt' in
let distal_marks, proximal_marks = distal_proximal_maps st' marks_map in
let distal_edges = distal_edges_map st' in
let _is_proximal i j = IntSet.mem j (IntMap.find i distal_edges) in
let is_proximal = auto_cache _is_proximal in
let d i = IntMap.find i distal_marks
and c i = IntMap.find i proximal_marks in
let _o i j =
if is_proximal i j then c i else d i
and _s i j =
if is_proximal i j then d i else c i
and _q k x = IntMap.find k k_maps |> IntMap.find x in
let o = auto_cache _o and s = auto_cache _s and q = auto_cache _q in
let cov_without_root k i j =
let q_k = q k in
if i = j then
let cov = 1. -. q_k (d i) -. q_k (c i) in
cov -. cov ** 2.
else
q_k (o i j + o j i) -. q_k (o i j) *. q_k (o j i)
+. (1. -. q_k (o i j)) *. q_k (s j i)
+. (1. -. q_k (o j i)) *. q_k (s i j)
-. q_k (s i j) *. q_k (s j i)
and cov_with_root k i j =
let q_k = q k in
if i = j then
let cov = 1. -. q_k (d i) in
cov -. cov ** 2.
else
let union =
if is_proximal i j then d i
else if is_proximal j i then d j
else d i + d j
in
q_k union -. q_k (d i) *. q_k (d j)
in
let n_edges = Stree.top_id st' in
let var cov_fn k =
let cov_times_bl k i j =
cov_fn k i j *. bl i *. bl j
in
let diag = 0 --^ n_edges
|> Enum.map (fun i -> cov_times_bl k i i)
|> Enum.fold (+.) 0.
in
Uptri.init n_edges (cov_times_bl k)
|> Uptri.fold_left (+.) 0.
|> ( *.) 2.
|> (+.) diag
in
2 -- k_max
|> Enum.map (fun k -> k, var cov_without_root k, var cov_with_root k)
|
267b39df99a474d4db04f063658edc8aac68688122ee11c22327f3d070166157 | haskell/cabal | Structured.hs | # LANGUAGE CPP #
module UnitTests.Distribution.Utils.Structured (tests) where
import Data.Proxy (Proxy (..))
import Distribution.Utils.MD5 (md5FromInteger)
import Distribution.Utils.Structured (structureHash, Structured)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase, (@?=), Assertion)
import Distribution.SPDX.License (License)
import Distribution.Types.VersionRange (VersionRange)
#if MIN_VERSION_base(4,7,0)
import Distribution.Types.GenericPackageDescription (GenericPackageDescription)
import Distribution.Types.LocalBuildInfo (LocalBuildInfo)
#endif
import UnitTests.Orphans ()
tests :: TestTree
tests = testGroup "Distribution.Utils.Structured"
-- This test also verifies that structureHash doesn't loop.
[ testCase "VersionRange" $
md5Check (Proxy :: Proxy VersionRange) 0x39396fc4f2d751aaa1f94e6d843f03bd
, testCase "SPDX.License" $
md5Check (Proxy :: Proxy License) 0xd3d4a09f517f9f75bc3d16370d5a853a
-- The difference is in encoding of newtypes
#if MIN_VERSION_base(4,7,0)
, testCase "GenericPackageDescription" $
md5Check (Proxy :: Proxy GenericPackageDescription) 0xa3e9433662ecf0c7a3c26f6d75a53ba1
, testCase "LocalBuildInfo" $
md5Check (Proxy :: Proxy LocalBuildInfo) 0x91ffcd61bbd83525e8edba877435a031
#endif
]
-- -------------------------------------------------------------------- --
-- utils
md5Check :: Structured a => Proxy a -> Integer -> Assertion
md5Check proxy md5Int = structureHash proxy @?= md5FromInteger md5Int
| null | https://raw.githubusercontent.com/haskell/cabal/ed314bc2e8f7c96929ff362047b4b22a764e48cd/Cabal-tests/tests/UnitTests/Distribution/Utils/Structured.hs | haskell | This test also verifies that structureHash doesn't loop.
The difference is in encoding of newtypes
-------------------------------------------------------------------- --
utils | # LANGUAGE CPP #
module UnitTests.Distribution.Utils.Structured (tests) where
import Data.Proxy (Proxy (..))
import Distribution.Utils.MD5 (md5FromInteger)
import Distribution.Utils.Structured (structureHash, Structured)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase, (@?=), Assertion)
import Distribution.SPDX.License (License)
import Distribution.Types.VersionRange (VersionRange)
#if MIN_VERSION_base(4,7,0)
import Distribution.Types.GenericPackageDescription (GenericPackageDescription)
import Distribution.Types.LocalBuildInfo (LocalBuildInfo)
#endif
import UnitTests.Orphans ()
tests :: TestTree
tests = testGroup "Distribution.Utils.Structured"
[ testCase "VersionRange" $
md5Check (Proxy :: Proxy VersionRange) 0x39396fc4f2d751aaa1f94e6d843f03bd
, testCase "SPDX.License" $
md5Check (Proxy :: Proxy License) 0xd3d4a09f517f9f75bc3d16370d5a853a
#if MIN_VERSION_base(4,7,0)
, testCase "GenericPackageDescription" $
md5Check (Proxy :: Proxy GenericPackageDescription) 0xa3e9433662ecf0c7a3c26f6d75a53ba1
, testCase "LocalBuildInfo" $
md5Check (Proxy :: Proxy LocalBuildInfo) 0x91ffcd61bbd83525e8edba877435a031
#endif
]
md5Check :: Structured a => Proxy a -> Integer -> Assertion
md5Check proxy md5Int = structureHash proxy @?= md5FromInteger md5Int
|
0e6c75e1cdee5ae3510af314ff655c8cc8d0e4fb428fecd39be4ea85f8f14170 | satos---jp/mincaml_self_hosting | knorm.mli | open Syntax
open Debug
open Type
open Type_expr
type name = string * (ty * debug_data)
type kexp =
| KConst of Syntax.const
| KOp of Syntax.optype * (name list)
| KIf of comptype * name * name * kexp * kexp
| KLet of name * kexp * kexp
| KVar of name
| KLetRec of name * (name list) * kexp * kexp
| KApp of name * (name list)
| KTuple of (name list)
| KLetTuple of (name list) * name * kexp
val kexp_recconv : (kexp -> kexp) -> kexp -> kexp
val knorm2str : kexp -> string
val kexp_size : kexp -> int
val knorm : texp -> kexp
type hash = Vs of int * (string list) | C of const | N of hash list
val hasher : kexp -> hash
| null | https://raw.githubusercontent.com/satos---jp/mincaml_self_hosting/5fdf8b5083437d7607a924142eea52d9b1de0439/src/compiler/knorm.mli | ocaml | open Syntax
open Debug
open Type
open Type_expr
type name = string * (ty * debug_data)
type kexp =
| KConst of Syntax.const
| KOp of Syntax.optype * (name list)
| KIf of comptype * name * name * kexp * kexp
| KLet of name * kexp * kexp
| KVar of name
| KLetRec of name * (name list) * kexp * kexp
| KApp of name * (name list)
| KTuple of (name list)
| KLetTuple of (name list) * name * kexp
val kexp_recconv : (kexp -> kexp) -> kexp -> kexp
val knorm2str : kexp -> string
val kexp_size : kexp -> int
val knorm : texp -> kexp
type hash = Vs of int * (string list) | C of const | N of hash list
val hasher : kexp -> hash
| |
95219facb14233e0dc2267c5e79ec7b3d44ae2a7ba3dee7dd0c382891071edb2 | LPCIC/matita | print_grammar.ml | Copyright ( C ) 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* 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 .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM 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.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
(* $Id: print_grammar.ml 11672 2011-11-17 00:00:00Z sacerdot $ *)
open Gramext
let rec flatten_tree = function
| DeadEnd -> []
| LocAct _ -> [[]]
| Node {node = n; brother = b; son = s} ->
List.map (fun l -> n :: l) (flatten_tree s) @ flatten_tree b
let tex_of_unicode s = s
let rec clean_dummy_desc = function
| Dlevels l -> Dlevels (clean_levels l)
| x -> x
and clean_levels = function
| [] -> []
| l :: tl -> clean_level l @ clean_levels tl
and clean_level = function
| x ->
let pref = clean_tree x.lprefix in
let suff = clean_tree x.lsuffix in
match pref,suff with
| DeadEnd, DeadEnd -> []
| _ -> [{x with lprefix = pref; lsuffix = suff}]
and clean_tree = function
| Node n -> clean_node n
| x -> x
and clean_node = function
| {node=node;son=son;brother=brother} ->
let bn = is_symbol_dummy node in
let bs = is_tree_dummy son in
let bb = is_tree_dummy brother in
let son = if bs then DeadEnd else son in
let brother = if bb then DeadEnd else brother in
if bb && bs && bn then
DeadEnd
else
if bn then
Node {node=Sself;son=son;brother=brother}
else
Node {node=node;son=son;brother=brother}
and is_level_dummy = function
| {lsuffix=lsuffix;lprefix=lprefix} ->
is_tree_dummy lsuffix && is_tree_dummy lprefix
and is_desc_dummy = function
| Dlevels l -> List.for_all is_level_dummy l
| Dparser _ -> true
and is_entry_dummy = function
| {edesc=edesc} -> is_desc_dummy edesc
and is_symbol_dummy = function
| Stoken ("DUMMY", _) -> true
| Stoken _ -> false
| Smeta (_, lt, _) -> List.for_all is_symbol_dummy lt
| Snterm e | Snterml (e, _) -> is_entry_dummy e
| Slist1 x | Slist0 x -> is_symbol_dummy x
| Slist1sep (x,y,false) | Slist0sep (x,y,false) -> is_symbol_dummy x && is_symbol_dummy y
| Sopt x -> is_symbol_dummy x
| Sself | Snext -> false
| Stree t -> is_tree_dummy t
| _ -> assert false
and is_tree_dummy = function
| Node {node=node} -> is_symbol_dummy node
| _ -> true
let needs_brackets t =
let rec count_brothers = function
| Node {brother = brother} -> 1 + count_brothers brother
| _ -> 0
in
count_brothers t > 1
let visit_description desc fmt self =
let skip s = true in
let inline s = List.mem s [ "int" ] in
let rec visit_entry e ?level todo is_son =
let { ename = ename; edesc = desc } = e in
if inline ename then
visit_desc desc todo is_son
else
begin
(match level with
| None -> Format.fprintf fmt "%s " ename;
| Some _ -> Format.fprintf fmt "%s " ename;);
if skip ename then
todo
else
todo @ [e]
end
and visit_desc d todo is_son =
match d with
| Dlevels l ->
List.fold_left
(fun acc l ->
Format.fprintf fmt "@ ";
visit_level l acc is_son )
todo l;
| Dparser _ -> todo
and visit_level l todo is_son =
let { lname = name ; lsuffix = suff ; lprefix = pref } = l in
visit_tree name
(List.map
(fun x -> Sself :: x) (flatten_tree suff) @ flatten_tree pref)
todo is_son
and visit_tree name t todo is_son =
if List.for_all (List.for_all is_symbol_dummy) t then todo else (
Format.fprintf fmt "@[<v>";
(match name with
|Some name -> Format.fprintf fmt "Precedence %s:@ " name
| None -> ());
Format.fprintf fmt "@[<v>";
let todo =
List.fold_left
(fun acc x ->
if List.for_all is_symbol_dummy x then todo else (
Format.fprintf fmt "@[<h> | ";
let todo =
List.fold_left
(fun acc x ->
let todo = visit_symbol x acc true in
Format.fprintf fmt "@ ";
todo)
acc x
in
Format.fprintf fmt "@]@ ";
todo))
todo t
in
Format.fprintf fmt "@]";
Format.fprintf fmt "@]";
todo)
and visit_symbol s todo is_son =
match s with
| Smeta (name, sl, _) ->
Format.fprintf fmt "%s " name;
List.fold_left (
fun acc s ->
let todo = visit_symbol s acc is_son in
if is_son then
Format.fprintf fmt "@ ";
todo)
todo sl
| Snterm entry -> visit_entry entry todo is_son
| Snterml (entry,level) -> visit_entry entry ~level todo is_son
| Slist0 symbol ->
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @ ";
todo
| Slist0sep (symbol,sep,false) ->
Format.fprintf fmt "[@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol sep todo is_son in
Format.fprintf fmt " ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @]] @ ";
todo
| Slist1 symbol ->
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]}+ @ ";
todo
| Slist1sep (symbol,sep,false) ->
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol sep todo is_son in
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @ ";
todo
| Sopt symbol ->
Format.fprintf fmt "[@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]] @ ";
todo
| Sself -> Format.fprintf fmt "%s " self; todo
| Snext -> Format.fprintf fmt "next "; todo
| Stoken pattern ->
let constructor, keyword = pattern in
if keyword = "" then
(if constructor <> "DUMMY" then
Format.fprintf fmt "`%s' " constructor)
else
Format.fprintf fmt "%s " (tex_of_unicode keyword);
todo
| Stree tree ->
visit_tree None (flatten_tree tree) todo is_son
| _ -> assert false
in
visit_desc desc [] false
;;
let rec visit_entries fmt todo pped =
match todo with
| [] -> ()
| hd :: tl ->
let todo =
if not (List.memq hd pped) then
begin
let { ename = ename; edesc = desc } = hd in
Format.fprintf fmt "@[<hv 2>%s ::= " ename;
let desc = clean_dummy_desc desc in
let todo = visit_description desc fmt ename @ todo in
Format.fprintf fmt "@]\n\n";
todo
end
else
todo
in
let clean_todo todo =
let name_of_entry e = e.ename in
let pped = hd :: pped in
let todo = tl @ todo in
let todo = List.filter (fun e -> not(List.memq e pped)) todo in
HExtlib.list_uniq
~eq:(fun e1 e2 -> (name_of_entry e1) = (name_of_entry e2))
(List.sort
(fun e1 e2 ->
Pervasives.compare (name_of_entry e1) (name_of_entry e2))
todo),
pped
in
let todo,pped = clean_todo todo in
visit_entries fmt todo pped
;;
let ebnf_of_term status =
let g_entry = Grammar.Entry.obj (CicNotationParser.term status) in
let buff = Buffer.create 100 in
let fmt = Format.formatter_of_buffer buff in
visit_entries fmt [g_entry] [];
Format.fprintf fmt "@?";
let s = Buffer.contents buff in
s
;;
| null | https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/grafite_parser/print_grammar.ml | ocaml | $Id: print_grammar.ml 11672 2011-11-17 00:00:00Z sacerdot $ | Copyright ( C ) 2005 , HELM Team .
*
* This file is part of HELM , an Hypertextual , Electronic
* Library of Mathematics , developed at the Computer Science
* Department , University of Bologna , Italy .
*
* 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 .
*
* 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 HELM ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston ,
* MA 02111 - 1307 , USA .
*
* For details , see the HELM World - Wide - Web page ,
* /
*
* This file is part of HELM, an Hypertextual, Electronic
* Library of Mathematics, developed at the Computer Science
* Department, University of Bologna, Italy.
*
* HELM 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.
*
* HELM 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 HELM; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*
* For details, see the HELM World-Wide-Web page,
* /
*)
open Gramext
let rec flatten_tree = function
| DeadEnd -> []
| LocAct _ -> [[]]
| Node {node = n; brother = b; son = s} ->
List.map (fun l -> n :: l) (flatten_tree s) @ flatten_tree b
let tex_of_unicode s = s
let rec clean_dummy_desc = function
| Dlevels l -> Dlevels (clean_levels l)
| x -> x
and clean_levels = function
| [] -> []
| l :: tl -> clean_level l @ clean_levels tl
and clean_level = function
| x ->
let pref = clean_tree x.lprefix in
let suff = clean_tree x.lsuffix in
match pref,suff with
| DeadEnd, DeadEnd -> []
| _ -> [{x with lprefix = pref; lsuffix = suff}]
and clean_tree = function
| Node n -> clean_node n
| x -> x
and clean_node = function
| {node=node;son=son;brother=brother} ->
let bn = is_symbol_dummy node in
let bs = is_tree_dummy son in
let bb = is_tree_dummy brother in
let son = if bs then DeadEnd else son in
let brother = if bb then DeadEnd else brother in
if bb && bs && bn then
DeadEnd
else
if bn then
Node {node=Sself;son=son;brother=brother}
else
Node {node=node;son=son;brother=brother}
and is_level_dummy = function
| {lsuffix=lsuffix;lprefix=lprefix} ->
is_tree_dummy lsuffix && is_tree_dummy lprefix
and is_desc_dummy = function
| Dlevels l -> List.for_all is_level_dummy l
| Dparser _ -> true
and is_entry_dummy = function
| {edesc=edesc} -> is_desc_dummy edesc
and is_symbol_dummy = function
| Stoken ("DUMMY", _) -> true
| Stoken _ -> false
| Smeta (_, lt, _) -> List.for_all is_symbol_dummy lt
| Snterm e | Snterml (e, _) -> is_entry_dummy e
| Slist1 x | Slist0 x -> is_symbol_dummy x
| Slist1sep (x,y,false) | Slist0sep (x,y,false) -> is_symbol_dummy x && is_symbol_dummy y
| Sopt x -> is_symbol_dummy x
| Sself | Snext -> false
| Stree t -> is_tree_dummy t
| _ -> assert false
and is_tree_dummy = function
| Node {node=node} -> is_symbol_dummy node
| _ -> true
let needs_brackets t =
let rec count_brothers = function
| Node {brother = brother} -> 1 + count_brothers brother
| _ -> 0
in
count_brothers t > 1
let visit_description desc fmt self =
let skip s = true in
let inline s = List.mem s [ "int" ] in
let rec visit_entry e ?level todo is_son =
let { ename = ename; edesc = desc } = e in
if inline ename then
visit_desc desc todo is_son
else
begin
(match level with
| None -> Format.fprintf fmt "%s " ename;
| Some _ -> Format.fprintf fmt "%s " ename;);
if skip ename then
todo
else
todo @ [e]
end
and visit_desc d todo is_son =
match d with
| Dlevels l ->
List.fold_left
(fun acc l ->
Format.fprintf fmt "@ ";
visit_level l acc is_son )
todo l;
| Dparser _ -> todo
and visit_level l todo is_son =
let { lname = name ; lsuffix = suff ; lprefix = pref } = l in
visit_tree name
(List.map
(fun x -> Sself :: x) (flatten_tree suff) @ flatten_tree pref)
todo is_son
and visit_tree name t todo is_son =
if List.for_all (List.for_all is_symbol_dummy) t then todo else (
Format.fprintf fmt "@[<v>";
(match name with
|Some name -> Format.fprintf fmt "Precedence %s:@ " name
| None -> ());
Format.fprintf fmt "@[<v>";
let todo =
List.fold_left
(fun acc x ->
if List.for_all is_symbol_dummy x then todo else (
Format.fprintf fmt "@[<h> | ";
let todo =
List.fold_left
(fun acc x ->
let todo = visit_symbol x acc true in
Format.fprintf fmt "@ ";
todo)
acc x
in
Format.fprintf fmt "@]@ ";
todo))
todo t
in
Format.fprintf fmt "@]";
Format.fprintf fmt "@]";
todo)
and visit_symbol s todo is_son =
match s with
| Smeta (name, sl, _) ->
Format.fprintf fmt "%s " name;
List.fold_left (
fun acc s ->
let todo = visit_symbol s acc is_son in
if is_son then
Format.fprintf fmt "@ ";
todo)
todo sl
| Snterm entry -> visit_entry entry todo is_son
| Snterml (entry,level) -> visit_entry entry ~level todo is_son
| Slist0 symbol ->
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @ ";
todo
| Slist0sep (symbol,sep,false) ->
Format.fprintf fmt "[@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol sep todo is_son in
Format.fprintf fmt " ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @]] @ ";
todo
| Slist1 symbol ->
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]}+ @ ";
todo
| Slist1sep (symbol,sep,false) ->
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "{@[<hov2> ";
let todo = visit_symbol sep todo is_son in
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]} @ ";
todo
| Sopt symbol ->
Format.fprintf fmt "[@[<hov2> ";
let todo = visit_symbol symbol todo is_son in
Format.fprintf fmt "@]] @ ";
todo
| Sself -> Format.fprintf fmt "%s " self; todo
| Snext -> Format.fprintf fmt "next "; todo
| Stoken pattern ->
let constructor, keyword = pattern in
if keyword = "" then
(if constructor <> "DUMMY" then
Format.fprintf fmt "`%s' " constructor)
else
Format.fprintf fmt "%s " (tex_of_unicode keyword);
todo
| Stree tree ->
visit_tree None (flatten_tree tree) todo is_son
| _ -> assert false
in
visit_desc desc [] false
;;
let rec visit_entries fmt todo pped =
match todo with
| [] -> ()
| hd :: tl ->
let todo =
if not (List.memq hd pped) then
begin
let { ename = ename; edesc = desc } = hd in
Format.fprintf fmt "@[<hv 2>%s ::= " ename;
let desc = clean_dummy_desc desc in
let todo = visit_description desc fmt ename @ todo in
Format.fprintf fmt "@]\n\n";
todo
end
else
todo
in
let clean_todo todo =
let name_of_entry e = e.ename in
let pped = hd :: pped in
let todo = tl @ todo in
let todo = List.filter (fun e -> not(List.memq e pped)) todo in
HExtlib.list_uniq
~eq:(fun e1 e2 -> (name_of_entry e1) = (name_of_entry e2))
(List.sort
(fun e1 e2 ->
Pervasives.compare (name_of_entry e1) (name_of_entry e2))
todo),
pped
in
let todo,pped = clean_todo todo in
visit_entries fmt todo pped
;;
let ebnf_of_term status =
let g_entry = Grammar.Entry.obj (CicNotationParser.term status) in
let buff = Buffer.create 100 in
let fmt = Format.formatter_of_buffer buff in
visit_entries fmt [g_entry] [];
Format.fprintf fmt "@?";
let s = Buffer.contents buff in
s
;;
|
88bded98f267fa690493781c314f5c47b4449cd33e1c3871f250948e0584a5c1 | jafingerhut/clojure-benchmarks | mandelbrot.clj-8.clj | The Computer Language Benchmarks Game
;; /
contributed by
;; The function 'dot' is based on suggestions and improvements made by
these people posting to the Clojure Google group in April , 2009 :
dmitri.sotnikov , , , michael.messinides
,
change by
reduced code size by removing functions already present in Clojure
(ns mandelbrot
(:gen-class)
(:import (java.io BufferedOutputStream)))
(set! *warn-on-reflection* true)
;; Handle slight difference in function name between Clojure 1.2.0 and
1.3.0 - alpha1 .
(defmacro my-unchecked-dec-int [& args]
(if (and (== (*clojure-version* :major) 1)
(== (*clojure-version* :minor) 2))
`(unchecked-dec ~@args)
`(unchecked-dec-int ~@args)))
(defmacro my-unchecked-inc-int [& args]
(if (and (== (*clojure-version* :major) 1)
(== (*clojure-version* :minor) 2))
`(unchecked-inc ~@args)
`(unchecked-inc-int ~@args)))
(def max-iterations 50)
(def limit-square (double 4.0))
(defn dot [r i]
(let [f2 (double 2.0)
limit-square (double limit-square)
iterations-remaining (int max-iterations)
pr (double r)
pi (double i)]
The loop below is similar to the one in the Perl subroutine dot
in mandelbrot.perl , with these name correspondences :
pr < - > Cr , pi < - > Ci , , zr < - > Zr , zr2 < - > Tr , zi2 < - > Ti
(loop [zr (double 0.0)
zi (double 0.0)
i (int (my-unchecked-inc-int iterations-remaining))]
(let [zr2 (* zr zr)
zi2 (* zi zi)]
(if (and (not (zero? i))
(< (+ zr2 zi2) limit-square))
(recur (+ (- zr2 zi2) pr)
(+ (* (* f2 zr) zi) pi)
(my-unchecked-dec-int i))
(zero? i))))))
(defn index-to-val [i scale-fac offset]
(+ (* i scale-fac) offset))
(defn ubyte [val]
(if (>= val 128)
(byte (- val 256))
(byte val)))
(defn compute-row [x-vals y]
(loop [b (int 0)
num-filled-bits (int 0)
result (transient [])
x-vals x-vals]
(if-let [s (seq x-vals)]
;; then
(let [new-bit (int (if (dot (first s) y) 1 0))
new-b (int (+ (bit-shift-left b 1) new-bit))]
(if (== num-filled-bits 7)
(recur (int 0)
(int 0)
(conj! result (ubyte new-b))
(rest s))
(recur new-b
(int (inc num-filled-bits))
result
(rest s))))
;; else
(if (zero? num-filled-bits)
(persistent! result)
(persistent! (conj! result
(ubyte (bit-shift-left b (- 8 num-filled-bits)))))
))))
(defn compute-rows [size]
(let [two-over-size (double (/ 2.0 size))
x-offset (double -1.5)
y-offset (double -1.0)
x-vals (map #(index-to-val % two-over-size x-offset) (range size))]
(pmap #(compute-row x-vals
(index-to-val % two-over-size y-offset))
(range size))))
(defn do-mandelbrot [size]
(let [rows (compute-rows size)]
(printf "P4\n")
(printf "%d %d\n" size size)
(flush)
(let [ostream (BufferedOutputStream. System/out)]
(doseq [r rows]
(. ostream write (into-array Byte/TYPE r) 0 (count r)))
(. ostream close))
(flush)))
(defn usage [exit-code]
(println (format "usage: %s size" *file*))
(println (format " size must be a positive integer"))
(. System (exit exit-code)))
(defn -main [& args]
(when (not= (count args) 1)
(usage 1))
(when (not (re-matches #"^\d+$" (nth args 0)))
(usage 1))
(def size (. Integer valueOf (nth args 0) 10))
(when (< size 1)
(usage 1))
(do-mandelbrot size)
(shutdown-agents))
| null | https://raw.githubusercontent.com/jafingerhut/clojure-benchmarks/474a8a4823727dd371f1baa9809517f9e0b508d4/mandelbrot/mandelbrot.clj-8.clj | clojure | /
The function 'dot' is based on suggestions and improvements made by
Handle slight difference in function name between Clojure 1.2.0 and
then
else | The Computer Language Benchmarks Game
contributed by
these people posting to the Clojure Google group in April , 2009 :
dmitri.sotnikov , , , michael.messinides
,
change by
reduced code size by removing functions already present in Clojure
(ns mandelbrot
(:gen-class)
(:import (java.io BufferedOutputStream)))
(set! *warn-on-reflection* true)
1.3.0 - alpha1 .
(defmacro my-unchecked-dec-int [& args]
(if (and (== (*clojure-version* :major) 1)
(== (*clojure-version* :minor) 2))
`(unchecked-dec ~@args)
`(unchecked-dec-int ~@args)))
(defmacro my-unchecked-inc-int [& args]
(if (and (== (*clojure-version* :major) 1)
(== (*clojure-version* :minor) 2))
`(unchecked-inc ~@args)
`(unchecked-inc-int ~@args)))
(def max-iterations 50)
(def limit-square (double 4.0))
(defn dot [r i]
(let [f2 (double 2.0)
limit-square (double limit-square)
iterations-remaining (int max-iterations)
pr (double r)
pi (double i)]
The loop below is similar to the one in the Perl subroutine dot
in mandelbrot.perl , with these name correspondences :
pr < - > Cr , pi < - > Ci , , zr < - > Zr , zr2 < - > Tr , zi2 < - > Ti
(loop [zr (double 0.0)
zi (double 0.0)
i (int (my-unchecked-inc-int iterations-remaining))]
(let [zr2 (* zr zr)
zi2 (* zi zi)]
(if (and (not (zero? i))
(< (+ zr2 zi2) limit-square))
(recur (+ (- zr2 zi2) pr)
(+ (* (* f2 zr) zi) pi)
(my-unchecked-dec-int i))
(zero? i))))))
(defn index-to-val [i scale-fac offset]
(+ (* i scale-fac) offset))
(defn ubyte [val]
(if (>= val 128)
(byte (- val 256))
(byte val)))
(defn compute-row [x-vals y]
(loop [b (int 0)
num-filled-bits (int 0)
result (transient [])
x-vals x-vals]
(if-let [s (seq x-vals)]
(let [new-bit (int (if (dot (first s) y) 1 0))
new-b (int (+ (bit-shift-left b 1) new-bit))]
(if (== num-filled-bits 7)
(recur (int 0)
(int 0)
(conj! result (ubyte new-b))
(rest s))
(recur new-b
(int (inc num-filled-bits))
result
(rest s))))
(if (zero? num-filled-bits)
(persistent! result)
(persistent! (conj! result
(ubyte (bit-shift-left b (- 8 num-filled-bits)))))
))))
(defn compute-rows [size]
(let [two-over-size (double (/ 2.0 size))
x-offset (double -1.5)
y-offset (double -1.0)
x-vals (map #(index-to-val % two-over-size x-offset) (range size))]
(pmap #(compute-row x-vals
(index-to-val % two-over-size y-offset))
(range size))))
(defn do-mandelbrot [size]
(let [rows (compute-rows size)]
(printf "P4\n")
(printf "%d %d\n" size size)
(flush)
(let [ostream (BufferedOutputStream. System/out)]
(doseq [r rows]
(. ostream write (into-array Byte/TYPE r) 0 (count r)))
(. ostream close))
(flush)))
(defn usage [exit-code]
(println (format "usage: %s size" *file*))
(println (format " size must be a positive integer"))
(. System (exit exit-code)))
(defn -main [& args]
(when (not= (count args) 1)
(usage 1))
(when (not (re-matches #"^\d+$" (nth args 0)))
(usage 1))
(def size (. Integer valueOf (nth args 0) 10))
(when (< size 1)
(usage 1))
(do-mandelbrot size)
(shutdown-agents))
|
8b98ab97f9594994d0280d54de0fb5c481da43e56e6cea72a402d39155c7e599 | fieldstrength/aeson-deriving | Utils.hs | {-# LANGUAGE PolyKinds #-}
# LANGUAGE TypeFamilies #
module Data.Aeson.Deriving.Utils
( mapObjects
, mapField
, All
, textVal
) where
import Data.Aeson
import qualified Data.HashMap.Strict as HashMap
import Data.Kind (Constraint)
import Data.Proxy
import Data.Text
import GHC.TypeLits
mapObjects :: (Object -> Object) -> Value -> Value
mapObjects f (Object o) = Object (f o)
mapObjects _ val = val
mapField :: Text -> (Value -> Value) -> Object -> Object
mapField str f = HashMap.mapWithKey $ \s x ->
if s == str then f x else x
| Convenience constraint family . All @types@ in the list satisfy the @predicate@.
type family All (predicate :: k -> Constraint) (types :: [k]) :: Constraint where
All predicate '[] = ()
All predicate (t ': ts) = (predicate t, All predicate ts)
textVal :: KnownSymbol s => Proxy s -> Text
textVal = pack . symbolVal
| null | https://raw.githubusercontent.com/fieldstrength/aeson-deriving/861dc8ebc05792a0924e8fe6aae2ae41a59fc751/src/Data/Aeson/Deriving/Utils.hs | haskell | # LANGUAGE PolyKinds # | # LANGUAGE TypeFamilies #
module Data.Aeson.Deriving.Utils
( mapObjects
, mapField
, All
, textVal
) where
import Data.Aeson
import qualified Data.HashMap.Strict as HashMap
import Data.Kind (Constraint)
import Data.Proxy
import Data.Text
import GHC.TypeLits
mapObjects :: (Object -> Object) -> Value -> Value
mapObjects f (Object o) = Object (f o)
mapObjects _ val = val
mapField :: Text -> (Value -> Value) -> Object -> Object
mapField str f = HashMap.mapWithKey $ \s x ->
if s == str then f x else x
| Convenience constraint family . All @types@ in the list satisfy the @predicate@.
type family All (predicate :: k -> Constraint) (types :: [k]) :: Constraint where
All predicate '[] = ()
All predicate (t ': ts) = (predicate t, All predicate ts)
textVal :: KnownSymbol s => Proxy s -> Text
textVal = pack . symbolVal
|
48c70ffac9b7c7c01afae1cb0a43d1ba1fb0f8f2d97b725545c190fd1ad9320e | lingnand/VIMonad | Named.hs | # LANGUAGE FlexibleContexts , FlexibleInstances , MultiParamTypeClasses #
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Named
Copyright : ( c ) < >
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : none
-- Stability : unstable
-- Portability : unportable
--
-- A module for assigning a name to a given layout. Deprecated, use
" XMonad . Layout . Renamed " instead .
--
-----------------------------------------------------------------------------
module XMonad.Layout.Named
( -- * Usage
-- $usage
named,
nameTail
) where
import XMonad.Layout.LayoutModifier
import XMonad.Layout.Renamed
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
> import XMonad . Layout . Named
--
-- Then edit your @layoutHook@ by adding the Named layout modifier
-- to some layout:
--
-- > myLayout = named "real big" Full ||| (nameTail $ named "real big" $ Full) ||| etc..
-- > main = xmonad def { layoutHook = myLayout }
--
-- For more detailed instructions on editing the layoutHook see:
--
-- "XMonad.Doc.Extending#Editing_the_layout_hook"
--
-- Note that this module has been deprecated and may be removed in a future
release , please use " XMonad . Layout . Renamed " instead .
-- | (Deprecated) Rename a layout.
named :: String -> l a -> ModifiedLayout Rename l a
named s = renamed [Replace s]
| ( Deprecated ) Remove the first word of the name .
nameTail :: l a -> ModifiedLayout Rename l a
nameTail = renamed [CutWordsLeft 1]
| null | https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Layout/Named.hs | haskell | ---------------------------------------------------------------------------
|
Module : XMonad.Layout.Named
License : BSD3-style (see LICENSE)
Maintainer : none
Stability : unstable
Portability : unportable
A module for assigning a name to a given layout. Deprecated, use
---------------------------------------------------------------------------
* Usage
$usage
$usage
You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
Then edit your @layoutHook@ by adding the Named layout modifier
to some layout:
> myLayout = named "real big" Full ||| (nameTail $ named "real big" $ Full) ||| etc..
> main = xmonad def { layoutHook = myLayout }
For more detailed instructions on editing the layoutHook see:
"XMonad.Doc.Extending#Editing_the_layout_hook"
Note that this module has been deprecated and may be removed in a future
| (Deprecated) Rename a layout. | # LANGUAGE FlexibleContexts , FlexibleInstances , MultiParamTypeClasses #
Copyright : ( c ) < >
" XMonad . Layout . Renamed " instead .
module XMonad.Layout.Named
named,
nameTail
) where
import XMonad.Layout.LayoutModifier
import XMonad.Layout.Renamed
> import XMonad . Layout . Named
release , please use " XMonad . Layout . Renamed " instead .
named :: String -> l a -> ModifiedLayout Rename l a
named s = renamed [Replace s]
| ( Deprecated ) Remove the first word of the name .
nameTail :: l a -> ModifiedLayout Rename l a
nameTail = renamed [CutWordsLeft 1]
|
ce1674dab557f8a37823cd6165131822b7456e6b628ba08cdec6f1dcabfc060d | qiao/sicp-solutions | 2.87.scm | (define (=zero-poly? p)
(define (=zero-terms? terms)
(or (empty-termlist? terms)
(and (=zero? (coeff (first-term terms)))
(=zero-terms? (rest-terms terms)))))
(=zero-termlist? (term-list p)))
(put '=zero? 'polynomial =zero-poly?)
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter2/2.87.scm | scheme | (define (=zero-poly? p)
(define (=zero-terms? terms)
(or (empty-termlist? terms)
(and (=zero? (coeff (first-term terms)))
(=zero-terms? (rest-terms terms)))))
(=zero-termlist? (term-list p)))
(put '=zero? 'polynomial =zero-poly?)
| |
123d347ab4fba1ae6af21f7e8a94c1f9874f02e593e551c74e335a8280d4e939 | Deducteam/zenon_modulo | main.ml | Copyright 1997 INRIA
Version.add "$Id$";;
open Printf;;
open Globals;;
open Namespace;;
open Expr;;
type proof_level =
| Proof_none
| Proof_h of int
| Proof_m
| Proof_l
| Proof_lx
| Proof_coq
| Proof_coqterm
| Proof_isar
| Proof_dot of bool * int
| Proof_dk
| Proof_dkterm
;;
let proof_level = ref Proof_none;;
let default_depth = 100;;
type open_level =
| Open_none
| Open_all
| Open_first of int
| Open_last of int
;;
let keep_open = ref Open_none;;
type input_format =
| I_zenon
| I_focal
| I_tptp
| I_dk
;;
let input_format = ref I_zenon;;
let include_path = ref [Config.libdir];;
let opt_level = ref 1;;
let int_arg r arg =
let l = String.length arg in
let multiplier m =
let arg1 = String.sub arg 0 (l-1) in
r := m *. (float_of_string arg1)
in
if l = 0 then raise (Arg.Bad "bad numeric argument")
else
try
match arg.[l-1] with
| 'k' -> multiplier 1e3
| 'M' -> multiplier 1e6
| 'G' -> multiplier 1e9
| 'T' -> multiplier 1e12
| 's' -> multiplier 1.
| 'm' -> multiplier 60.
| 'h' -> multiplier 3600.
| 'd' -> multiplier 86400.
| '0'..'9' -> r := float_of_string arg
| _ -> raise (Arg.Bad "bad numeric argument")
with Failure "float_of_string" -> raise (Arg.Bad "bad numeric argument")
;;
let p_string s =
signature_name := s;;
let parse_size_time s =
let l = String.length s in
let rec loop i =
if i >= l then raise (Arg.Bad "bad size/time specification");
if s.[i] = '/' then begin
int_arg size_limit (String.sub s 0 i);
int_arg time_limit (String.sub s (i+1) (l-i-1));
end else begin
loop (i+1);
end;
in
loop 0;
;;
let short_version () =
printf "zenon_modulo version %s\n" Versionnum.full;
exit 0;
;;
let cvs_version () =
printf "zenon_modulo version %s\n" Versionnum.full;
Version.print_cvs stdout;
printf "source checksum: %s\n" Checksum.v;
exit 0;
;;
let files = ref [];;
let input_file s = files := s :: !files;;
let set_random seed =
random_flag := true;
random_seed := seed;
;;
let print_libdir () = Printf.printf "%s\n%!" Config.libdir; exit 0
let usage_msg = "Usage: zenon_modulo [options] <file>";;
let argspec = [
"-", Arg.Unit (fun () -> input_file "-"),
" read input from stdin";
"-context", Arg.Set ctx_flag,
" provide context for checking the proof independently";
"-d", Arg.Unit (fun () -> Globals.debug_flag := true;
Progress.level := Progress.No),
" debug mode";
"-errmsg", Arg.String Error.set_header,
"<message> prefix warnings and errors with <message>";
"-I", Arg.String (fun x -> include_path := x :: !include_path),
" <dir> add <dir> to the include path";
"-I-", Arg.Unit (fun () -> include_path := []),
" clear the include path";
"-icoq", Arg.Unit (fun () -> input_format := I_focal),
" read input file in Coq format";
"-idk", Arg.Unit (fun () -> input_format := I_dk),
" read input file in Dedukti format";
"-ifocal", Arg.Unit (fun () -> input_format := I_focal),
" read input file in Focal format";
"-itptp", Arg.Unit (fun () -> input_format := I_tptp),
" read input file in TPTP format";
"-iz", Arg.Unit (fun () -> input_format := I_zenon),
" read input file in Zenon format (default)";
"-k", Arg.Unit (fun () -> keep_open := Open_last 0),
" use incomplete proof attempts to instanciate";
"-kall", Arg.Unit (fun () -> keep_open := Open_all),
" keep all incomplete proof attempts";
"-kf", Arg.Int (fun n -> keep_open := Open_first n),
"<n> keep the first <n> proof attempts";
"-kl", Arg.Int (fun n -> keep_open := Open_last n),
"<n> keep the last <n> proof attempts";
"-loadpath", Arg.Set_string load_path,
sprintf " path to Zenon's coq libraries (default %s)"
Config.libdir;
"-max", Arg.String parse_size_time,
"<s>[kMGT]/<i>[kMGT]/<t>[smhd] set size, step, and time limits"
^ " (see below)";
"-max-size", Arg.String (int_arg size_limit),
"<s>[kMGT] limit heap size to <s> kilo/mega/giga/tera byte"
^ " (1G)";
"-max-step", Arg.String (int_arg step_limit),
"<i>[kMGT] limit number of steps to <i> kilo/mega/giga/tera"
^ " (10k)";
"-max-time", Arg.String (int_arg time_limit),
"<t>[smhd] limit CPU time to <t> second/minute/hour/day"
^ " (5m)";
"-ocoq", Arg.Unit (fun () -> namespace_flag := true; proof_level := Proof_coq),
" print the proof in Coq script format (force -rename)";
"-ocoqterm", Arg.Unit (fun () -> proof_level := Proof_coqterm),
" print the proof in Coq term format";
"-odk", Arg.Unit (fun () -> namespace_flag := true;
quiet_flag := true;
proof_level := Proof_dk;
opt_level := 0;
Globals.output_dk := true),
" print the proof in Dk script format (force -rename)";
"-sig", Arg.String ( p_string),
" print the proof using a signature name for each symbol";
"-odkterm", Arg.Unit (fun () -> proof_level := Proof_dkterm;
opt_level := 0;
Globals.output_dk := true),
" print the proof in DK term format";
"-oh", Arg.Int (fun n -> proof_level := Proof_h n),
"<n> print the proof in high-level format up to depth <n>";
"-oisar", Arg.Unit (fun () -> proof_level := Proof_isar),
" print the proof in Isar format";
"-ol", Arg.Unit (fun () -> proof_level := Proof_l),
" print the proof in low-level format";
"-olx", Arg.Unit (fun () -> proof_level := Proof_lx),
" print the proof in raw low-level format";
"-om", Arg.Unit (fun () -> proof_level := Proof_m),
" print the proof in middle-level format";
"-onone", Arg.Unit (fun () -> proof_level := Proof_none),
" do not print the proof (default)";
"-odot", Arg.Unit (fun () -> proof_level := Proof_dot (true, default_depth)),
" print the proof in dot format (use with -q option)";
"-odotd", Arg.Int (fun n -> proof_level := Proof_dot (true, n)),
" print the proof in dot format (use with -q option)(less verbose)";
"-odotl", Arg.Int (fun n -> proof_level := Proof_dot (false, n)),
" print the proof in dot format (use with -q option)(less verbose)";
"-opt0", Arg.Unit (fun () -> opt_level := 0),
" do not optimise the proof";
"-opt1", Arg.Unit (fun () -> opt_level := 1),
" do peephole optimisation of the proof (default)";
"-p0", Arg.Unit (fun () -> Progress.level := Progress.No),
" turn off progress bar and progress messages";
"-p1", Arg.Unit (fun () -> Progress.level := Progress.Bar),
" display progress bar (default)";
"-p2", Arg.Unit (fun () -> Progress.level := Progress.Msg),
" display progress messages";
"-q", Arg.Set quiet_flag,
" suppress proof-found/no-proof/begin-proof/end-proof";
"-rename", Arg.Set namespace_flag,
" prefix all input symbols to avoid clashes";
"-rnd", Arg.Int set_random,
"<seed> randomize proof search";
"-stats", Arg.Set stats_flag,
" print statistics";
"-short", Arg.Set short_flag,
" output a less detailed proof";
"-use-all", Arg.Set use_all_flag,
" output a proof that uses all the hypotheses";
"-v", Arg.Unit short_version,
" print version string and exit";
"-vv", Arg.Int Log.set_debug,
" set the verbose level for debug output (default 0)";
"-versions", Arg.Unit cvs_version,
" print CVS version strings and exit";
"-w", Arg.Clear Error.warnings_flag,
" suppress warnings";
"-where", Arg.Unit print_libdir,
" print the location of the zenon library and exit";
"-wout", Arg.Set_string Error.err_file,
"<file> output errors and warnings to <file> instead of stderr";
"-x", Arg.String Extension.activate,
"<ext> activate extension <ext>";
"-modulo", Arg.Set modulo,
" build the rewrite system from TPTP meta info";
"-modulo-heuri", Arg.Set modulo_heuri,
" build the rewrite system from heuristic";
"-modulo-heuri-simple", Arg.Set modulo_heuri_simple,
" build the rewrite system from heuristic simple";
"-dbg-rwrt", Arg.Set debug_rwrt,
" debug mode for rewriting"
];;
let print_usage () =
Arg.usage argspec usage_msg;
eprintf "The default include path is the following:\n";
List.iter (fun x -> eprintf " %s\n" x) !include_path;
exit 0;
;;
let do_exit code = exit (code + if !Error.got_warning then 100 else 0);;
let report_error lexbuf msg =
let p = Lexing.lexeme_start_p lexbuf in
Error.errpos p msg;
do_exit 3;
;;
let make_lexbuf stdin_opt f =
let (name, chan, close) =
match f with
| "-" when stdin_opt -> ("", stdin, ignore)
| _ -> (f, open_in f, close_in)
in
let lexbuf = Lexing.from_channel chan in
lexbuf.Lexing.lex_curr_p <- {
Lexing.pos_fname = name;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0;
};
(lexbuf, fun () -> close chan)
;;
let zparse_file f =
let (lexbuf, closer) = make_lexbuf false f in
let result = Parsezen.file Lexzen.token lexbuf in
closer ();
result
;;
let rec expand_includes incpath zphrases =
let exp p =
match p with
| Phrase.Zhyp (s, e, i) -> [Phrase.Hyp (s, e, i)]
| Phrase.Zdef (d) -> [Phrase.Def (d)]
| Phrase.Zsig (s, l, t) -> [Phrase.Sig (s, l, t)]
| Phrase.Zinductive (s, a, l, sc) -> [Phrase.Inductive (s, a, l, sc)]
| Phrase.Zinclude f ->
begin
let rec loop l =
match l with
| [] ->
eprintf "include file not found: %s\n" f;
do_exit 15;
| h::t ->
let pf = try Some (zparse_file (Filename.concat h f))
with _ -> None
in
match pf with
| Some p -> expand_includes incpath p
| None -> loop t
in
loop incpath
end
in
List.concat (List.map exp zphrases)
;;
let parse_file f =
try
let (lexbuf, closer) = make_lexbuf true f in
try
match !input_format with
| I_tptp ->
let tpphrases = Parsetptp.file Lextptp.token lexbuf in
closer ();
let d = Filename.dirname f in
let pp = Filename.parent_dir_name in
let upup = Filename.concat (Filename.concat d pp) pp in
begin
try
let tptp_env = Sys.getenv "TPTP" in
let incpath = List.rev (tptp_env :: upup :: d :: !include_path) in
let (forms, name) = Tptp.translate incpath tpphrases in
let forms = Typetptp.typecheck forms in
(name, List.map (fun x -> (x, false)) forms)
with Not_found ->
let incpath = List.rev (upup :: d :: !include_path) in
let (forms, name) = Tptp.translate incpath tpphrases in
let forms = Typetptp.typecheck forms in
(name, List.map (fun x -> (x, false)) forms)
end
| I_focal ->
let (name, result) = Parsecoq.file Lexcoq.token lexbuf in
closer ();
let typer_options =
{ Typer.default_type = Expr.type_none;
Typer.scope_warnings = true;
Typer.undeclared_functions_warning = false;
Typer.register_new_constants = true;
Typer.fully_type = false }
in
(name, Typer.phrasebl typer_options result)
| I_dk ->
let (name, result) = Parsedk.file Lexdk.token lexbuf in
closer ();
let typer_options =
{ Typer.default_type = Expr.type_none;
Typer.scope_warnings = true;
Typer.undeclared_functions_warning = true;
Typer.register_new_constants = false;
Typer.fully_type = true }
in
(name, Typer.phrasebl typer_options result)
| I_zenon ->
let zphrases = Parsezen.file Lexzen.token lexbuf in
closer ();
let incpath = List.rev (Filename.dirname f :: !include_path) in
let phrases = expand_includes incpath zphrases in
let result = List.map (fun x -> (x, false)) phrases in
let is_goal = function
| (Phrase.Hyp (name, _, _), _) -> name = goal_name
| _ -> false
in
let goal_found = List.exists is_goal result in
if not goal_found then Error.warn "no goal given";
let typer_options =
{ Typer.default_type = Expr.type_iota;
Typer.scope_warnings = false;
Typer.undeclared_functions_warning = false;
Typer.register_new_constants = false;
Typer.fully_type = false }
in
(thm_default_name, Typer.phrasebl typer_options result)
with
| Parsing.Parse_error -> report_error lexbuf "syntax error."
| Error.Lex_error msg -> report_error lexbuf msg
with Sys_error (msg) -> Error.err msg; do_exit 4;
;;
let rec extract_strong accu phr_dep =
match phr_dep with
| [] -> accu
| (p, true) :: t -> extract_strong (p::accu) t
| (_, false) :: t -> extract_strong accu t
;;
let optim p =
match !opt_level with
| 0 -> p
| 1 -> Llproof.optimise p
| _ -> assert false
;;
let main () =
Gc.set {(Gc.get ()) with
Gc.minor_heap_size = 1_000_000;
Gc.major_heap_increment = 1_000_000;
};
let file = match !files with
| [f] -> f
| _ -> Arg.usage argspec usage_msg; exit 2
in
Extension.predecl ();
let (th_name, phrases_dep) = parse_file file in
begin match !proof_level with
| Proof_coq | Proof_coqterm -> Watch.warn_unused_var phrases_dep;
| _ -> ()
end;
let retcode = ref 0 in
begin try
let phrases = List.map fst phrases_dep in
let phrases = Rewrite.select_rwrt_rules phrases in
let ppphrases = Extension.preprocess phrases in
List.iter Extension.add_phrase ppphrases;
if !Globals.debug_rwrt
then
begin
Print.print_tbl_term (Print.Chan stdout) !tbl_term;
Print.print_tbl_prop (Print.Chan stdout) !tbl_prop;
end;
let (defs, hyps) = Phrase.separate (Extension.predef ()) ppphrases in
List.iter (fun (fm, _) -> Eqrel.analyse fm) hyps;
let hyps = List.filter (fun (fm, _) -> not (Eqrel.subsumed fm)) hyps in
if !debug_flag then begin
let ph_defs = List.map (fun x -> Phrase.Def x) defs in
let ph_hyps = List.map (fun (x, y) -> Phrase.Hyp ("", x, y)) hyps in
eprintf "initial formulas:\n";
List.iter (Print.phrase (Print.Chan stderr)) (ph_defs @ ph_hyps);
eprintf "relations: ";
Eqrel.print_rels stderr;
eprintf "\n";
eprintf "typing declarations: ";
eprintf "\n";
Typer.print_constant_decls stderr;
eprintf "----\n";
flush stderr;
Gc.set {(Gc.get ()) with Gc.verbose = 0x010};
end;
let params = match !keep_open with
| Open_none -> Prove.default_params
| Open_all -> Prove.open_params None
| Open_first n -> Prove.open_params (Some n)
| Open_last n -> Prove.open_params (Some (-n))
in
let proofs = Prove.prove params defs hyps in
let proof= List.hd proofs in
let is_open = Mlproof.is_open_proof proof in
if is_open then
retcode := 12;
if not !quiet_flag then begin
if is_open then
if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n"
else
if !Globals.signature_name <> "" then () else printf "(* PROOF-FOUND *)\n";
flush stdout
end;
let llp = lazy (optim (Extension.postprocess
(Mltoll.translate th_name ppphrases proof)))
in
begin match !proof_level with
| Proof_none -> ()
| Proof_h n -> Print.hlproof (Print.Chan stdout) n proof;
| Proof_m -> Print.mlproof (Print.Chan stdout) proof;
| Proof_lx ->
let lxp = Mltoll.translate th_name ppphrases proof in
Print.llproof (Print.Chan stdout) lxp;
| Proof_l -> Print.llproof (Print.Chan stdout) (Lazy.force llp);
| Proof_coq ->
let u = Lltocoq.output stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_coqterm ->
let (p, u) = Coqterm.trproof phrases ppphrases (Lazy.force llp) in
Coqterm.print stdout p;
Watch.warn phrases_dep llp u;
| Proof_dk ->
let u = Lltodk.output stdout phrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_dkterm ->
let u = Lltodk.output_term stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_isar ->
let u = Lltoisar.output stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_dot (b, n) ->
Print.dots ~full_output:b ~max_depth:n (Print.Chan stdout) (List.rev proofs);
end;
with
| Prove.NoProof ->
retcode := 12;
if not !quiet_flag then (if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n");
| Prove.LimitsExceeded ->
retcode := 13;
if not !quiet_flag then (if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n");
end;
if !stats_flag then begin
eprintf "nodes searched: %d\n" !Globals.inferences;
eprintf "max branch formulas: %d\n" !Globals.top_num_forms;
eprintf "proof nodes created: %d\n" !Globals.proof_nodes;
eprintf "formulas created: %d\n" !Globals.num_expr;
eprintf "\n";
(*Gc.print_stat stderr;*)
end;
do_exit !retcode
;;
let parse_command_line argspec =
try Arg.parse argspec input_file usage_msg
with Not_found -> exit 2
;;
let do_main () =
try main ()
with
| Error.Abort -> do_exit 11;
| Expr.Type_Mismatch (t, t', f) ->
let s = Printexc.get_backtrace () in
Format.eprintf "Mismatched type : expected '%s' but instead received '%s' (in %s)@\nBacktrace :@\n%s@."
(Print.sexpr t) (Print.sexpr t') f s;
do_exit 11;
| Expr.Ill_typed_substitution (map) ->
let s = Printexc.get_backtrace () in
Format.eprintf "Ill-typed substitution [%s].@\nBacktrace :@\n%s@."
(String.concat
"; "
(List.map (fun (x, y) ->
Printf.sprintf "%s ↦ %s"
(Print.sexpr_t x)
(Print.sexpr_t y))
map))
s;
do_exit 11;
| e - > eprintf " Zenon error : uncaught exception % s\n " ( Printexc.to_string e ) ;
do_exit 14 ;
| e -> eprintf "Zenon error: uncaught exception %s\n" (Printexc.to_string e);
do_exit 14; *)
;;
| null | https://raw.githubusercontent.com/Deducteam/zenon_modulo/9534fbdca0d009a513cb40d9a5a2a98329835c63/main.ml | ocaml | Gc.print_stat stderr; | Copyright 1997 INRIA
Version.add "$Id$";;
open Printf;;
open Globals;;
open Namespace;;
open Expr;;
type proof_level =
| Proof_none
| Proof_h of int
| Proof_m
| Proof_l
| Proof_lx
| Proof_coq
| Proof_coqterm
| Proof_isar
| Proof_dot of bool * int
| Proof_dk
| Proof_dkterm
;;
let proof_level = ref Proof_none;;
let default_depth = 100;;
type open_level =
| Open_none
| Open_all
| Open_first of int
| Open_last of int
;;
let keep_open = ref Open_none;;
type input_format =
| I_zenon
| I_focal
| I_tptp
| I_dk
;;
let input_format = ref I_zenon;;
let include_path = ref [Config.libdir];;
let opt_level = ref 1;;
let int_arg r arg =
let l = String.length arg in
let multiplier m =
let arg1 = String.sub arg 0 (l-1) in
r := m *. (float_of_string arg1)
in
if l = 0 then raise (Arg.Bad "bad numeric argument")
else
try
match arg.[l-1] with
| 'k' -> multiplier 1e3
| 'M' -> multiplier 1e6
| 'G' -> multiplier 1e9
| 'T' -> multiplier 1e12
| 's' -> multiplier 1.
| 'm' -> multiplier 60.
| 'h' -> multiplier 3600.
| 'd' -> multiplier 86400.
| '0'..'9' -> r := float_of_string arg
| _ -> raise (Arg.Bad "bad numeric argument")
with Failure "float_of_string" -> raise (Arg.Bad "bad numeric argument")
;;
let p_string s =
signature_name := s;;
let parse_size_time s =
let l = String.length s in
let rec loop i =
if i >= l then raise (Arg.Bad "bad size/time specification");
if s.[i] = '/' then begin
int_arg size_limit (String.sub s 0 i);
int_arg time_limit (String.sub s (i+1) (l-i-1));
end else begin
loop (i+1);
end;
in
loop 0;
;;
let short_version () =
printf "zenon_modulo version %s\n" Versionnum.full;
exit 0;
;;
let cvs_version () =
printf "zenon_modulo version %s\n" Versionnum.full;
Version.print_cvs stdout;
printf "source checksum: %s\n" Checksum.v;
exit 0;
;;
let files = ref [];;
let input_file s = files := s :: !files;;
let set_random seed =
random_flag := true;
random_seed := seed;
;;
let print_libdir () = Printf.printf "%s\n%!" Config.libdir; exit 0
let usage_msg = "Usage: zenon_modulo [options] <file>";;
let argspec = [
"-", Arg.Unit (fun () -> input_file "-"),
" read input from stdin";
"-context", Arg.Set ctx_flag,
" provide context for checking the proof independently";
"-d", Arg.Unit (fun () -> Globals.debug_flag := true;
Progress.level := Progress.No),
" debug mode";
"-errmsg", Arg.String Error.set_header,
"<message> prefix warnings and errors with <message>";
"-I", Arg.String (fun x -> include_path := x :: !include_path),
" <dir> add <dir> to the include path";
"-I-", Arg.Unit (fun () -> include_path := []),
" clear the include path";
"-icoq", Arg.Unit (fun () -> input_format := I_focal),
" read input file in Coq format";
"-idk", Arg.Unit (fun () -> input_format := I_dk),
" read input file in Dedukti format";
"-ifocal", Arg.Unit (fun () -> input_format := I_focal),
" read input file in Focal format";
"-itptp", Arg.Unit (fun () -> input_format := I_tptp),
" read input file in TPTP format";
"-iz", Arg.Unit (fun () -> input_format := I_zenon),
" read input file in Zenon format (default)";
"-k", Arg.Unit (fun () -> keep_open := Open_last 0),
" use incomplete proof attempts to instanciate";
"-kall", Arg.Unit (fun () -> keep_open := Open_all),
" keep all incomplete proof attempts";
"-kf", Arg.Int (fun n -> keep_open := Open_first n),
"<n> keep the first <n> proof attempts";
"-kl", Arg.Int (fun n -> keep_open := Open_last n),
"<n> keep the last <n> proof attempts";
"-loadpath", Arg.Set_string load_path,
sprintf " path to Zenon's coq libraries (default %s)"
Config.libdir;
"-max", Arg.String parse_size_time,
"<s>[kMGT]/<i>[kMGT]/<t>[smhd] set size, step, and time limits"
^ " (see below)";
"-max-size", Arg.String (int_arg size_limit),
"<s>[kMGT] limit heap size to <s> kilo/mega/giga/tera byte"
^ " (1G)";
"-max-step", Arg.String (int_arg step_limit),
"<i>[kMGT] limit number of steps to <i> kilo/mega/giga/tera"
^ " (10k)";
"-max-time", Arg.String (int_arg time_limit),
"<t>[smhd] limit CPU time to <t> second/minute/hour/day"
^ " (5m)";
"-ocoq", Arg.Unit (fun () -> namespace_flag := true; proof_level := Proof_coq),
" print the proof in Coq script format (force -rename)";
"-ocoqterm", Arg.Unit (fun () -> proof_level := Proof_coqterm),
" print the proof in Coq term format";
"-odk", Arg.Unit (fun () -> namespace_flag := true;
quiet_flag := true;
proof_level := Proof_dk;
opt_level := 0;
Globals.output_dk := true),
" print the proof in Dk script format (force -rename)";
"-sig", Arg.String ( p_string),
" print the proof using a signature name for each symbol";
"-odkterm", Arg.Unit (fun () -> proof_level := Proof_dkterm;
opt_level := 0;
Globals.output_dk := true),
" print the proof in DK term format";
"-oh", Arg.Int (fun n -> proof_level := Proof_h n),
"<n> print the proof in high-level format up to depth <n>";
"-oisar", Arg.Unit (fun () -> proof_level := Proof_isar),
" print the proof in Isar format";
"-ol", Arg.Unit (fun () -> proof_level := Proof_l),
" print the proof in low-level format";
"-olx", Arg.Unit (fun () -> proof_level := Proof_lx),
" print the proof in raw low-level format";
"-om", Arg.Unit (fun () -> proof_level := Proof_m),
" print the proof in middle-level format";
"-onone", Arg.Unit (fun () -> proof_level := Proof_none),
" do not print the proof (default)";
"-odot", Arg.Unit (fun () -> proof_level := Proof_dot (true, default_depth)),
" print the proof in dot format (use with -q option)";
"-odotd", Arg.Int (fun n -> proof_level := Proof_dot (true, n)),
" print the proof in dot format (use with -q option)(less verbose)";
"-odotl", Arg.Int (fun n -> proof_level := Proof_dot (false, n)),
" print the proof in dot format (use with -q option)(less verbose)";
"-opt0", Arg.Unit (fun () -> opt_level := 0),
" do not optimise the proof";
"-opt1", Arg.Unit (fun () -> opt_level := 1),
" do peephole optimisation of the proof (default)";
"-p0", Arg.Unit (fun () -> Progress.level := Progress.No),
" turn off progress bar and progress messages";
"-p1", Arg.Unit (fun () -> Progress.level := Progress.Bar),
" display progress bar (default)";
"-p2", Arg.Unit (fun () -> Progress.level := Progress.Msg),
" display progress messages";
"-q", Arg.Set quiet_flag,
" suppress proof-found/no-proof/begin-proof/end-proof";
"-rename", Arg.Set namespace_flag,
" prefix all input symbols to avoid clashes";
"-rnd", Arg.Int set_random,
"<seed> randomize proof search";
"-stats", Arg.Set stats_flag,
" print statistics";
"-short", Arg.Set short_flag,
" output a less detailed proof";
"-use-all", Arg.Set use_all_flag,
" output a proof that uses all the hypotheses";
"-v", Arg.Unit short_version,
" print version string and exit";
"-vv", Arg.Int Log.set_debug,
" set the verbose level for debug output (default 0)";
"-versions", Arg.Unit cvs_version,
" print CVS version strings and exit";
"-w", Arg.Clear Error.warnings_flag,
" suppress warnings";
"-where", Arg.Unit print_libdir,
" print the location of the zenon library and exit";
"-wout", Arg.Set_string Error.err_file,
"<file> output errors and warnings to <file> instead of stderr";
"-x", Arg.String Extension.activate,
"<ext> activate extension <ext>";
"-modulo", Arg.Set modulo,
" build the rewrite system from TPTP meta info";
"-modulo-heuri", Arg.Set modulo_heuri,
" build the rewrite system from heuristic";
"-modulo-heuri-simple", Arg.Set modulo_heuri_simple,
" build the rewrite system from heuristic simple";
"-dbg-rwrt", Arg.Set debug_rwrt,
" debug mode for rewriting"
];;
let print_usage () =
Arg.usage argspec usage_msg;
eprintf "The default include path is the following:\n";
List.iter (fun x -> eprintf " %s\n" x) !include_path;
exit 0;
;;
let do_exit code = exit (code + if !Error.got_warning then 100 else 0);;
let report_error lexbuf msg =
let p = Lexing.lexeme_start_p lexbuf in
Error.errpos p msg;
do_exit 3;
;;
let make_lexbuf stdin_opt f =
let (name, chan, close) =
match f with
| "-" when stdin_opt -> ("", stdin, ignore)
| _ -> (f, open_in f, close_in)
in
let lexbuf = Lexing.from_channel chan in
lexbuf.Lexing.lex_curr_p <- {
Lexing.pos_fname = name;
Lexing.pos_lnum = 1;
Lexing.pos_bol = 0;
Lexing.pos_cnum = 0;
};
(lexbuf, fun () -> close chan)
;;
let zparse_file f =
let (lexbuf, closer) = make_lexbuf false f in
let result = Parsezen.file Lexzen.token lexbuf in
closer ();
result
;;
let rec expand_includes incpath zphrases =
let exp p =
match p with
| Phrase.Zhyp (s, e, i) -> [Phrase.Hyp (s, e, i)]
| Phrase.Zdef (d) -> [Phrase.Def (d)]
| Phrase.Zsig (s, l, t) -> [Phrase.Sig (s, l, t)]
| Phrase.Zinductive (s, a, l, sc) -> [Phrase.Inductive (s, a, l, sc)]
| Phrase.Zinclude f ->
begin
let rec loop l =
match l with
| [] ->
eprintf "include file not found: %s\n" f;
do_exit 15;
| h::t ->
let pf = try Some (zparse_file (Filename.concat h f))
with _ -> None
in
match pf with
| Some p -> expand_includes incpath p
| None -> loop t
in
loop incpath
end
in
List.concat (List.map exp zphrases)
;;
let parse_file f =
try
let (lexbuf, closer) = make_lexbuf true f in
try
match !input_format with
| I_tptp ->
let tpphrases = Parsetptp.file Lextptp.token lexbuf in
closer ();
let d = Filename.dirname f in
let pp = Filename.parent_dir_name in
let upup = Filename.concat (Filename.concat d pp) pp in
begin
try
let tptp_env = Sys.getenv "TPTP" in
let incpath = List.rev (tptp_env :: upup :: d :: !include_path) in
let (forms, name) = Tptp.translate incpath tpphrases in
let forms = Typetptp.typecheck forms in
(name, List.map (fun x -> (x, false)) forms)
with Not_found ->
let incpath = List.rev (upup :: d :: !include_path) in
let (forms, name) = Tptp.translate incpath tpphrases in
let forms = Typetptp.typecheck forms in
(name, List.map (fun x -> (x, false)) forms)
end
| I_focal ->
let (name, result) = Parsecoq.file Lexcoq.token lexbuf in
closer ();
let typer_options =
{ Typer.default_type = Expr.type_none;
Typer.scope_warnings = true;
Typer.undeclared_functions_warning = false;
Typer.register_new_constants = true;
Typer.fully_type = false }
in
(name, Typer.phrasebl typer_options result)
| I_dk ->
let (name, result) = Parsedk.file Lexdk.token lexbuf in
closer ();
let typer_options =
{ Typer.default_type = Expr.type_none;
Typer.scope_warnings = true;
Typer.undeclared_functions_warning = true;
Typer.register_new_constants = false;
Typer.fully_type = true }
in
(name, Typer.phrasebl typer_options result)
| I_zenon ->
let zphrases = Parsezen.file Lexzen.token lexbuf in
closer ();
let incpath = List.rev (Filename.dirname f :: !include_path) in
let phrases = expand_includes incpath zphrases in
let result = List.map (fun x -> (x, false)) phrases in
let is_goal = function
| (Phrase.Hyp (name, _, _), _) -> name = goal_name
| _ -> false
in
let goal_found = List.exists is_goal result in
if not goal_found then Error.warn "no goal given";
let typer_options =
{ Typer.default_type = Expr.type_iota;
Typer.scope_warnings = false;
Typer.undeclared_functions_warning = false;
Typer.register_new_constants = false;
Typer.fully_type = false }
in
(thm_default_name, Typer.phrasebl typer_options result)
with
| Parsing.Parse_error -> report_error lexbuf "syntax error."
| Error.Lex_error msg -> report_error lexbuf msg
with Sys_error (msg) -> Error.err msg; do_exit 4;
;;
let rec extract_strong accu phr_dep =
match phr_dep with
| [] -> accu
| (p, true) :: t -> extract_strong (p::accu) t
| (_, false) :: t -> extract_strong accu t
;;
let optim p =
match !opt_level with
| 0 -> p
| 1 -> Llproof.optimise p
| _ -> assert false
;;
let main () =
Gc.set {(Gc.get ()) with
Gc.minor_heap_size = 1_000_000;
Gc.major_heap_increment = 1_000_000;
};
let file = match !files with
| [f] -> f
| _ -> Arg.usage argspec usage_msg; exit 2
in
Extension.predecl ();
let (th_name, phrases_dep) = parse_file file in
begin match !proof_level with
| Proof_coq | Proof_coqterm -> Watch.warn_unused_var phrases_dep;
| _ -> ()
end;
let retcode = ref 0 in
begin try
let phrases = List.map fst phrases_dep in
let phrases = Rewrite.select_rwrt_rules phrases in
let ppphrases = Extension.preprocess phrases in
List.iter Extension.add_phrase ppphrases;
if !Globals.debug_rwrt
then
begin
Print.print_tbl_term (Print.Chan stdout) !tbl_term;
Print.print_tbl_prop (Print.Chan stdout) !tbl_prop;
end;
let (defs, hyps) = Phrase.separate (Extension.predef ()) ppphrases in
List.iter (fun (fm, _) -> Eqrel.analyse fm) hyps;
let hyps = List.filter (fun (fm, _) -> not (Eqrel.subsumed fm)) hyps in
if !debug_flag then begin
let ph_defs = List.map (fun x -> Phrase.Def x) defs in
let ph_hyps = List.map (fun (x, y) -> Phrase.Hyp ("", x, y)) hyps in
eprintf "initial formulas:\n";
List.iter (Print.phrase (Print.Chan stderr)) (ph_defs @ ph_hyps);
eprintf "relations: ";
Eqrel.print_rels stderr;
eprintf "\n";
eprintf "typing declarations: ";
eprintf "\n";
Typer.print_constant_decls stderr;
eprintf "----\n";
flush stderr;
Gc.set {(Gc.get ()) with Gc.verbose = 0x010};
end;
let params = match !keep_open with
| Open_none -> Prove.default_params
| Open_all -> Prove.open_params None
| Open_first n -> Prove.open_params (Some n)
| Open_last n -> Prove.open_params (Some (-n))
in
let proofs = Prove.prove params defs hyps in
let proof= List.hd proofs in
let is_open = Mlproof.is_open_proof proof in
if is_open then
retcode := 12;
if not !quiet_flag then begin
if is_open then
if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n"
else
if !Globals.signature_name <> "" then () else printf "(* PROOF-FOUND *)\n";
flush stdout
end;
let llp = lazy (optim (Extension.postprocess
(Mltoll.translate th_name ppphrases proof)))
in
begin match !proof_level with
| Proof_none -> ()
| Proof_h n -> Print.hlproof (Print.Chan stdout) n proof;
| Proof_m -> Print.mlproof (Print.Chan stdout) proof;
| Proof_lx ->
let lxp = Mltoll.translate th_name ppphrases proof in
Print.llproof (Print.Chan stdout) lxp;
| Proof_l -> Print.llproof (Print.Chan stdout) (Lazy.force llp);
| Proof_coq ->
let u = Lltocoq.output stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_coqterm ->
let (p, u) = Coqterm.trproof phrases ppphrases (Lazy.force llp) in
Coqterm.print stdout p;
Watch.warn phrases_dep llp u;
| Proof_dk ->
let u = Lltodk.output stdout phrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_dkterm ->
let u = Lltodk.output_term stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_isar ->
let u = Lltoisar.output stdout phrases ppphrases (Lazy.force llp) in
Watch.warn phrases_dep llp u;
| Proof_dot (b, n) ->
Print.dots ~full_output:b ~max_depth:n (Print.Chan stdout) (List.rev proofs);
end;
with
| Prove.NoProof ->
retcode := 12;
if not !quiet_flag then (if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n");
| Prove.LimitsExceeded ->
retcode := 13;
if not !quiet_flag then (if !Globals.signature_name <> "" then () else printf "(* NO-PROOF *)\n");
end;
if !stats_flag then begin
eprintf "nodes searched: %d\n" !Globals.inferences;
eprintf "max branch formulas: %d\n" !Globals.top_num_forms;
eprintf "proof nodes created: %d\n" !Globals.proof_nodes;
eprintf "formulas created: %d\n" !Globals.num_expr;
eprintf "\n";
end;
do_exit !retcode
;;
let parse_command_line argspec =
try Arg.parse argspec input_file usage_msg
with Not_found -> exit 2
;;
let do_main () =
try main ()
with
| Error.Abort -> do_exit 11;
| Expr.Type_Mismatch (t, t', f) ->
let s = Printexc.get_backtrace () in
Format.eprintf "Mismatched type : expected '%s' but instead received '%s' (in %s)@\nBacktrace :@\n%s@."
(Print.sexpr t) (Print.sexpr t') f s;
do_exit 11;
| Expr.Ill_typed_substitution (map) ->
let s = Printexc.get_backtrace () in
Format.eprintf "Ill-typed substitution [%s].@\nBacktrace :@\n%s@."
(String.concat
"; "
(List.map (fun (x, y) ->
Printf.sprintf "%s ↦ %s"
(Print.sexpr_t x)
(Print.sexpr_t y))
map))
s;
do_exit 11;
| e - > eprintf " Zenon error : uncaught exception % s\n " ( Printexc.to_string e ) ;
do_exit 14 ;
| e -> eprintf "Zenon error: uncaught exception %s\n" (Printexc.to_string e);
do_exit 14; *)
;;
|
e6aaa9396d27b9b0ad8078dbf0dd1947afc309e3e48da88ec7d82140be5f462e | S8A/htdp-exercises | ex374.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex374) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")) #f)))
; .: Data definitions :.
; An Xexpr is a list:
–
– ( cons Symbol Body )
; – (cons Symbol (cons [List-of Attribute] Body))
; where Body is short for [List-of Xexpr]
An Attribute is a list of two items :
; (cons Symbol (cons String '()))
An is ' ( word ( ( text ) ) ) .
; An XItem.v2 is one of:
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
;
; An XEnum.v2 is one of:
; – (cons 'ul [List-of XItem.v2])
; – (cons 'ul (cons [List-of Attribute] [List-of XItem.v2]))
; .: Data examples :.
(define a0 '((initial "X")))
(define e0 '(machine))
(define e1 `(machine ,a0))
(define e2 '(machine (action)))
(define e3 '(machine () (action)))
(define e4 `(machine ,a0 (action) (action)))
(define w0 '(word ((text ""))))
(define w1 '(word ((text "hello"))))
(define w2 '(word ((text "one"))))
(define w3 '(word ((text "two"))))
(define w4 '(word ((text "world"))))
(define w5 '(word ((text "good bye"))))
(define en0 `(ul (li ,w2) (li ,w3)))
(define en1 `(ul (li ,w1) (li ,en0) (li ,w4) (li ,w5)))
; .: Constants :.
(define SIZE 12) ; font size
(define COLOR "black") ; font color
(define BT ; a graphical constant
(beside (circle 1 'solid 'black) (text " " SIZE COLOR)))
(define en0-rendered
(above/align 'left
(beside/align 'center BT (text "one" SIZE COLOR))
(beside/align 'center BT (text "two" SIZE COLOR))))
(define en1-rendered
(above/align 'left
(beside/align 'center BT (text "hello" SIZE COLOR))
(beside/align 'center BT en0-rendered)
(beside/align 'center BT (text "world" SIZE COLOR))
(beside/align 'center BT (text "good bye" SIZE COLOR))))
; .: Functions :.
; Image -> Image
; marks item with bullet
(define (bulletize item)
(beside/align 'center BT item))
; XEnum.v2 -> Image
; renders an XEnum.v2 as an image
(define (render-enum xe)
(local ((define content (xexpr-content xe))
; XItem.v2 Image -> Image
(define (stack-item current rest)
(above/align 'left (render-item current) rest)))
(foldr stack-item empty-image content)))
(check-expect (render-enum en0) en0-rendered)
(check-expect (render-enum en1) en1-rendered)
; XItem.v2 -> Image
renders one XItem.v2 as an image
(define (render-item an-item)
(local ((define content (first (xexpr-content an-item))))
(bulletize
(cond
[(word? content) (text (word-text content) SIZE 'black)]
[else (render-enum content)]))))
(check-expect (render-item `(li ,w0))
(beside/align 'center BT (text "" SIZE COLOR)))
(check-expect (render-item `(li ,w1))
(beside/align 'center BT (text "hello" SIZE COLOR)))
(check-expect (render-item `(li ,w2))
(beside/align 'center BT (text "one" SIZE COLOR)))
(check-expect (render-item `(li ,en0))
(beside/align 'center BT en0-rendered))
; Xexpr -> Boolean
is xe an
(define (word? xe)
(local ((define attrs (xexpr-attr xe)))
(and (symbol=? (xexpr-name xe) 'word)
(= (length attrs) 1)
(symbol=? (first (first attrs)) 'text))))
(check-expect (word? e0) #false)
(check-expect (word? e1) #false)
(check-expect (word? e2) #false)
(check-expect (word? e3) #false)
(check-expect (word? e4) #false)
(check-expect (word? w0) #true)
(check-expect (word? w1) #true)
(check-expect (word? w2) #true)
(check-expect (word? w3) #true)
(check-expect (word? w4) #true)
(check-expect (word? w5) #true)
XWord - > String
; extracts the value of the given word's text attribute
(define (word-text w)
(find-attr 'text (xexpr-attr w)))
(check-expect (word-text w0) "")
(check-expect (word-text w1) "hello")
(check-expect (word-text w2) "one")
(check-expect (word-text w3) "two")
(check-expect (word-text w4) "world")
(check-expect (word-text w5) "good bye")
; Symbol [List-of Attribute] -> [Maybe String]
; if the given attributes list associates symbol s with a string,
; retrieve the string
(define (find-attr s loa)
(local ((define matching-attr (assq s loa)))
(if (cons? matching-attr)
(second matching-attr)
#false)))
(check-expect (find-attr 'x '()) #false)
(check-expect (find-attr 'x a0) #false)
(check-expect (find-attr 'initial a0) "X")
; Xexpr -> Symbol
; extracts the tag of the given element representation
(define (xexpr-name xe)
(first xe))
(check-expect (xexpr-name e0) 'machine)
(check-expect (xexpr-name e1) 'machine)
(check-expect (xexpr-name e2) 'machine)
(check-expect (xexpr-name e3) 'machine)
(check-expect (xexpr-name e4) 'machine)
; Xexpr -> [List-of Attribute]
; retrieves the list of attributes of xe
(define (xexpr-attr xe)
(local ((define optional-loa+content (rest xe)))
(cond
[(empty? optional-loa+content) '()]
[else (local ((define loa-or-x (first optional-loa+content)))
(if (list-of-attributes? loa-or-x)
loa-or-x
'()))])))
(check-expect (xexpr-attr e0) '())
(check-expect (xexpr-attr e1) '((initial "X")))
(check-expect (xexpr-attr e2) '())
(check-expect (xexpr-attr e3) '())
(check-expect (xexpr-attr e4) '((initial "X")))
; Xexpr -> [List-of Xexpr]
; extracts the list of content elements from the given element representation
(define (xexpr-content xe)
(local ((define optional-loa+content (rest xe)))
(cond
[(empty? optional-loa+content) '()]
[else (if (list-of-attributes? (first optional-loa+content))
(rest optional-loa+content)
optional-loa+content)])))
(check-expect (xexpr-content e0) '())
(check-expect (xexpr-content e1) '())
(check-expect (xexpr-content e2) '((action)))
(check-expect (xexpr-content e3) '((action)))
(check-expect (xexpr-content e4) '((action) (action)))
; [List-of Attribute] or Xexpr -> Boolean
; is x a list of attributes
(define (list-of-attributes? x)
(cond
[(empty? x) #true]
[else (local ((define possible-attribute (first x)))
(cons? possible-attribute))]))
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex374.rkt | racket | about the language level of this file in a form that our tools can easily process.
.: Data definitions :.
An Xexpr is a list:
– (cons Symbol (cons [List-of Attribute] Body))
where Body is short for [List-of Xexpr]
(cons Symbol (cons String '()))
An XItem.v2 is one of:
An XEnum.v2 is one of:
– (cons 'ul [List-of XItem.v2])
– (cons 'ul (cons [List-of Attribute] [List-of XItem.v2]))
.: Data examples :.
.: Constants :.
font size
font color
a graphical constant
.: Functions :.
Image -> Image
marks item with bullet
XEnum.v2 -> Image
renders an XEnum.v2 as an image
XItem.v2 Image -> Image
XItem.v2 -> Image
Xexpr -> Boolean
extracts the value of the given word's text attribute
Symbol [List-of Attribute] -> [Maybe String]
if the given attributes list associates symbol s with a string,
retrieve the string
Xexpr -> Symbol
extracts the tag of the given element representation
Xexpr -> [List-of Attribute]
retrieves the list of attributes of xe
Xexpr -> [List-of Xexpr]
extracts the list of content elements from the given element representation
[List-of Attribute] or Xexpr -> Boolean
is x a list of attributes | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex374) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp")) #f)))
–
– ( cons Symbol Body )
An Attribute is a list of two items :
An is ' ( word ( ( text ) ) ) .
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
– ( cons ' li ( cons ' ( ) ) )
– ( cons ' li ( cons [ List - of Attribute ] ( cons ' ( ) ) ) )
(define a0 '((initial "X")))
(define e0 '(machine))
(define e1 `(machine ,a0))
(define e2 '(machine (action)))
(define e3 '(machine () (action)))
(define e4 `(machine ,a0 (action) (action)))
(define w0 '(word ((text ""))))
(define w1 '(word ((text "hello"))))
(define w2 '(word ((text "one"))))
(define w3 '(word ((text "two"))))
(define w4 '(word ((text "world"))))
(define w5 '(word ((text "good bye"))))
(define en0 `(ul (li ,w2) (li ,w3)))
(define en1 `(ul (li ,w1) (li ,en0) (li ,w4) (li ,w5)))
(beside (circle 1 'solid 'black) (text " " SIZE COLOR)))
(define en0-rendered
(above/align 'left
(beside/align 'center BT (text "one" SIZE COLOR))
(beside/align 'center BT (text "two" SIZE COLOR))))
(define en1-rendered
(above/align 'left
(beside/align 'center BT (text "hello" SIZE COLOR))
(beside/align 'center BT en0-rendered)
(beside/align 'center BT (text "world" SIZE COLOR))
(beside/align 'center BT (text "good bye" SIZE COLOR))))
(define (bulletize item)
(beside/align 'center BT item))
(define (render-enum xe)
(local ((define content (xexpr-content xe))
(define (stack-item current rest)
(above/align 'left (render-item current) rest)))
(foldr stack-item empty-image content)))
(check-expect (render-enum en0) en0-rendered)
(check-expect (render-enum en1) en1-rendered)
renders one XItem.v2 as an image
(define (render-item an-item)
(local ((define content (first (xexpr-content an-item))))
(bulletize
(cond
[(word? content) (text (word-text content) SIZE 'black)]
[else (render-enum content)]))))
(check-expect (render-item `(li ,w0))
(beside/align 'center BT (text "" SIZE COLOR)))
(check-expect (render-item `(li ,w1))
(beside/align 'center BT (text "hello" SIZE COLOR)))
(check-expect (render-item `(li ,w2))
(beside/align 'center BT (text "one" SIZE COLOR)))
(check-expect (render-item `(li ,en0))
(beside/align 'center BT en0-rendered))
is xe an
(define (word? xe)
(local ((define attrs (xexpr-attr xe)))
(and (symbol=? (xexpr-name xe) 'word)
(= (length attrs) 1)
(symbol=? (first (first attrs)) 'text))))
(check-expect (word? e0) #false)
(check-expect (word? e1) #false)
(check-expect (word? e2) #false)
(check-expect (word? e3) #false)
(check-expect (word? e4) #false)
(check-expect (word? w0) #true)
(check-expect (word? w1) #true)
(check-expect (word? w2) #true)
(check-expect (word? w3) #true)
(check-expect (word? w4) #true)
(check-expect (word? w5) #true)
XWord - > String
(define (word-text w)
(find-attr 'text (xexpr-attr w)))
(check-expect (word-text w0) "")
(check-expect (word-text w1) "hello")
(check-expect (word-text w2) "one")
(check-expect (word-text w3) "two")
(check-expect (word-text w4) "world")
(check-expect (word-text w5) "good bye")
(define (find-attr s loa)
(local ((define matching-attr (assq s loa)))
(if (cons? matching-attr)
(second matching-attr)
#false)))
(check-expect (find-attr 'x '()) #false)
(check-expect (find-attr 'x a0) #false)
(check-expect (find-attr 'initial a0) "X")
(define (xexpr-name xe)
(first xe))
(check-expect (xexpr-name e0) 'machine)
(check-expect (xexpr-name e1) 'machine)
(check-expect (xexpr-name e2) 'machine)
(check-expect (xexpr-name e3) 'machine)
(check-expect (xexpr-name e4) 'machine)
(define (xexpr-attr xe)
(local ((define optional-loa+content (rest xe)))
(cond
[(empty? optional-loa+content) '()]
[else (local ((define loa-or-x (first optional-loa+content)))
(if (list-of-attributes? loa-or-x)
loa-or-x
'()))])))
(check-expect (xexpr-attr e0) '())
(check-expect (xexpr-attr e1) '((initial "X")))
(check-expect (xexpr-attr e2) '())
(check-expect (xexpr-attr e3) '())
(check-expect (xexpr-attr e4) '((initial "X")))
(define (xexpr-content xe)
(local ((define optional-loa+content (rest xe)))
(cond
[(empty? optional-loa+content) '()]
[else (if (list-of-attributes? (first optional-loa+content))
(rest optional-loa+content)
optional-loa+content)])))
(check-expect (xexpr-content e0) '())
(check-expect (xexpr-content e1) '())
(check-expect (xexpr-content e2) '((action)))
(check-expect (xexpr-content e3) '((action)))
(check-expect (xexpr-content e4) '((action) (action)))
(define (list-of-attributes? x)
(cond
[(empty? x) #true]
[else (local ((define possible-attribute (first x)))
(cons? possible-attribute))]))
|
612d356b6650b121a9b3854dbdbb8c80ba8f31f3bcde090c02dd9b26385b956a | mokus0/shapefile | Shapefile.hs | # LANGUAGE RecordWildCards #
module Database.Shapefile
( module Database.Shapefile
, module Database.Shapefile.ShapeTypes
, module Database.Shapefile.Shp
, module Database.Shapefile.Shx
, module Database.Shapefile.Shp.Handle
, module Database.Shapefile.Shx.Handle
, module Database.XBase.Dbf
, BBox(..)
) where
import Database.Shapefile.Misc
import Database.Shapefile.ShapeTypes
import Database.Shapefile.Shapes.MultiPatchPartTypes
import Database.Shapefile.Shapes.OneToOne
import Database.Shapefile.Shp
import Database.Shapefile.Shx
import Database.Shapefile.Shp.Handle
import Database.Shapefile.Shx.Handle
import Database.XBase.Dbf
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy as BS
| null | https://raw.githubusercontent.com/mokus0/shapefile/9a3821e1c6aef08b9304ed3c79cccbba09970d7d/src/Database/Shapefile.hs | haskell | # LANGUAGE RecordWildCards #
module Database.Shapefile
( module Database.Shapefile
, module Database.Shapefile.ShapeTypes
, module Database.Shapefile.Shp
, module Database.Shapefile.Shx
, module Database.Shapefile.Shp.Handle
, module Database.Shapefile.Shx.Handle
, module Database.XBase.Dbf
, BBox(..)
) where
import Database.Shapefile.Misc
import Database.Shapefile.ShapeTypes
import Database.Shapefile.Shapes.MultiPatchPartTypes
import Database.Shapefile.Shapes.OneToOne
import Database.Shapefile.Shp
import Database.Shapefile.Shx
import Database.Shapefile.Shp.Handle
import Database.Shapefile.Shx.Handle
import Database.XBase.Dbf
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy as BS
| |
54d48a9eb7a840cd4579994f7cc47cc7d0818f149061d0f47ab31374d31f3d3b | mattaudesse/haskell-99-problems | H08.hs | module Problems.H08 where
import Data.List (group)
-- |
Eliminate consecutive duplicates of list elements .
--
-- If a list contains repeated elements they should be replaced with a single
-- copy of the element. The order of the elements should not be changed.
--
-- >>> compress "aaaabccaadeeee"
-- "abcade"
compress :: Eq a => [a] -> [a]
compress [] = []
compress xs = foldr compress' [] xs where
compress' x [] = [x]
compress' x (a:as)
| x == a = a:as
| otherwise = x:a:as
-- |
( A better solution from : )
--
Eliminate consecutive duplicates of list elements .
--
-- If a list contains repeated elements they should be replaced with a single
-- copy of the element. The order of the elements should not be changed.
--
-- >>> compress'' "aaaabccaadeeee"
-- "abcade"
compress'' :: Eq a => [a] -> [a]
compress'' = map head . group
| null | https://raw.githubusercontent.com/mattaudesse/haskell-99-problems/f7d57c0bd45c245f10073cf708fbc5e2107e0e23/Problems/H08.hs | haskell | |
If a list contains repeated elements they should be replaced with a single
copy of the element. The order of the elements should not be changed.
>>> compress "aaaabccaadeeee"
"abcade"
|
If a list contains repeated elements they should be replaced with a single
copy of the element. The order of the elements should not be changed.
>>> compress'' "aaaabccaadeeee"
"abcade" | module Problems.H08 where
import Data.List (group)
Eliminate consecutive duplicates of list elements .
compress :: Eq a => [a] -> [a]
compress [] = []
compress xs = foldr compress' [] xs where
compress' x [] = [x]
compress' x (a:as)
| x == a = a:as
| otherwise = x:a:as
( A better solution from : )
Eliminate consecutive duplicates of list elements .
compress'' :: Eq a => [a] -> [a]
compress'' = map head . group
|
ea53b38f12660845b5f93e376766cec889f87076fdb1047f088b087d79adf1d6 | tommaisey/aeon | round-up.help.scm | ;; (round-up a b)
;; Rounds a up to the nearest multiple of b.
(let* ((x (mouse-x kr 60 4000 0 0.1))
(f (round-up x 100)))
(audition
(out 0 (mul (sin-osc ar f 0) 0.1))))
(let ((n (line kr 24 108 6 remove-synth)))
(audition
(out 0 (mul (saw ar (midi-cps (round-up n 1))) 0.2))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/binary-ops/round-up.help.scm | scheme | (round-up a b)
Rounds a up to the nearest multiple of b. |
(let* ((x (mouse-x kr 60 4000 0 0.1))
(f (round-up x 100)))
(audition
(out 0 (mul (sin-osc ar f 0) 0.1))))
(let ((n (line kr 24 108 6 remove-synth)))
(audition
(out 0 (mul (saw ar (midi-cps (round-up n 1))) 0.2))))
|
732aae87c32e60f5a32b46d5e8f7497b5e777e3eab4a8b4bc6e105e1f64a0ce1 | goldfirere/singletons | Wrappers.hs | # LANGUAGE DataKinds #
# LANGUAGE NoNamedWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Semigroup.Singletons.Internal.Wrappers
Copyright : ( C ) 2018
-- License : BSD-style (see LICENSE)
Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- Defines the promoted and singled versions of the @newtype@ wrappers from
-- "Data.Semigroup", all of which are reexported from the "Data.Semigroup"
-- module or imported directly by some other modules.
--
-- This module exists to avoid import cycles with
" Data . Monoid . Singletons " .
--
----------------------------------------------------------------------------
module Data.Semigroup.Singletons.Internal.Wrappers where
import Control.Monad.Singletons.Internal
import Data.Bool.Singletons
import Data.Eq.Singletons
import Data.Ord.Singletons hiding (MinSym0, MinSym1, MaxSym0, MaxSym1)
import Data.Semigroup (Dual(..), All(..), Any(..), Sum(..), Product(..))
import Data.Semigroup.Singletons.Internal.Classes
import Data.Singletons.Base.Enum
import Data.Singletons.Base.Instances
import Data.Singletons.Base.Util
import Data.Singletons.TH
import GHC.Num.Singletons
$(genSingletons semigroupBasicTypes)
$(singBoundedInstances semigroupBasicTypes)
$(singEqInstances semigroupBasicTypes)
$(singDecideInstances semigroupBasicTypes)
$(singOrdInstances semigroupBasicTypes)
$(singletonsOnly [d|
instance Applicative Dual where
pure = Dual
Dual f <*> Dual x = Dual (f x)
deriving instance Functor Dual
instance Monad Dual where
Dual a >>= k = k a
instance Semigroup a => Semigroup (Dual a) where
Dual a <> Dual b = Dual (b <> a)
instance Semigroup All where
All a <> All b = All (a && b)
instance Semigroup Any where
Any a <> Any b = Any (a || b)
instance Applicative Sum where
pure = Sum
Sum f <*> Sum x = Sum (f x)
deriving instance Functor Sum
instance Monad Sum where
Sum a >>= k = k a
instance Num a => Semigroup (Sum a) where
Sum a <> Sum b = Sum (a + b)
deriving newtype instance a = > ( Sum a )
instance Num a => Num (Sum a) where
Sum a + Sum b = Sum (a + b)
Sum a - Sum b = Sum (a - b)
Sum a * Sum b = Sum (a * b)
negate (Sum a) = Sum (negate a)
abs (Sum a) = Sum (abs a)
signum (Sum a) = Sum (signum a)
fromInteger n = Sum (fromInteger n)
instance Applicative Product where
pure = Product
Product f <*> Product x = Product (f x)
deriving instance Functor Product
instance Monad Product where
Product a >>= k = k a
instance Num a => Semigroup (Product a) where
Product a <> Product b = Product (a * b)
deriving newtype instance a = > ( Product a )
instance Num a => Num (Product a) where
Product a + Product b = Product (a + b)
Product a - Product b = Product (a - b)
Product a * Product b = Product (a * b)
negate (Product a) = Product (negate a)
abs (Product a) = Product (abs a)
signum (Product a) = Product (signum a)
fromInteger n = Product (fromInteger n)
|])
| null | https://raw.githubusercontent.com/goldfirere/singletons/68ce40b1473a6a65eb550318847b57160c86c284/singletons-base/src/Data/Semigroup/Singletons/Internal/Wrappers.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Semigroup.Singletons.Internal.Wrappers
License : BSD-style (see LICENSE)
Stability : experimental
Portability : non-portable
Defines the promoted and singled versions of the @newtype@ wrappers from
"Data.Semigroup", all of which are reexported from the "Data.Semigroup"
module or imported directly by some other modules.
This module exists to avoid import cycles with
-------------------------------------------------------------------------- | # LANGUAGE DataKinds #
# LANGUAGE NoNamedWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -Wno - orphans #
Copyright : ( C ) 2018
Maintainer :
" Data . Monoid . Singletons " .
module Data.Semigroup.Singletons.Internal.Wrappers where
import Control.Monad.Singletons.Internal
import Data.Bool.Singletons
import Data.Eq.Singletons
import Data.Ord.Singletons hiding (MinSym0, MinSym1, MaxSym0, MaxSym1)
import Data.Semigroup (Dual(..), All(..), Any(..), Sum(..), Product(..))
import Data.Semigroup.Singletons.Internal.Classes
import Data.Singletons.Base.Enum
import Data.Singletons.Base.Instances
import Data.Singletons.Base.Util
import Data.Singletons.TH
import GHC.Num.Singletons
$(genSingletons semigroupBasicTypes)
$(singBoundedInstances semigroupBasicTypes)
$(singEqInstances semigroupBasicTypes)
$(singDecideInstances semigroupBasicTypes)
$(singOrdInstances semigroupBasicTypes)
$(singletonsOnly [d|
instance Applicative Dual where
pure = Dual
Dual f <*> Dual x = Dual (f x)
deriving instance Functor Dual
instance Monad Dual where
Dual a >>= k = k a
instance Semigroup a => Semigroup (Dual a) where
Dual a <> Dual b = Dual (b <> a)
instance Semigroup All where
All a <> All b = All (a && b)
instance Semigroup Any where
Any a <> Any b = Any (a || b)
instance Applicative Sum where
pure = Sum
Sum f <*> Sum x = Sum (f x)
deriving instance Functor Sum
instance Monad Sum where
Sum a >>= k = k a
instance Num a => Semigroup (Sum a) where
Sum a <> Sum b = Sum (a + b)
deriving newtype instance a = > ( Sum a )
instance Num a => Num (Sum a) where
Sum a + Sum b = Sum (a + b)
Sum a - Sum b = Sum (a - b)
Sum a * Sum b = Sum (a * b)
negate (Sum a) = Sum (negate a)
abs (Sum a) = Sum (abs a)
signum (Sum a) = Sum (signum a)
fromInteger n = Sum (fromInteger n)
instance Applicative Product where
pure = Product
Product f <*> Product x = Product (f x)
deriving instance Functor Product
instance Monad Product where
Product a >>= k = k a
instance Num a => Semigroup (Product a) where
Product a <> Product b = Product (a * b)
deriving newtype instance a = > ( Product a )
instance Num a => Num (Product a) where
Product a + Product b = Product (a + b)
Product a - Product b = Product (a - b)
Product a * Product b = Product (a * b)
negate (Product a) = Product (negate a)
abs (Product a) = Product (abs a)
signum (Product a) = Product (signum a)
fromInteger n = Product (fromInteger n)
|])
|
397894f612eb7a2a3c0800cac77b873e49e6b7f185fc7f1c0e1f122ec7a6afac | phimuemue/lambdainterpreter_haskell | Settings.hs | needed for
module Settings where
import qualified Data.Map as Map
import System.Console.CmdArgs
import Control.Concurrent.MVar
import Expression
type Environment = Map.Map String Expression
data InteractivityMode = Full | Steps | Interactive
data Arguments = Arguments { filename :: [String]
} deriving (Data, Typeable, Show)
defaultArguments :: Arguments
defaultArguments = Arguments { filename = []
}
data Settings = Settings
{ interactivityMode :: InteractivityMode
, knowNumbers :: Bool
, environment :: Environment
, succName :: String
, clargs :: Arguments
, interruption :: MVar Bool
}
defaultSettings :: Settings
defaultSettings = Settings { interactivityMode = Steps
, knowNumbers = True
, environment = Map.empty
, succName = "SUCC"
, clargs = defaultArguments
, TODO : interruption not initialized
}
| null | https://raw.githubusercontent.com/phimuemue/lambdainterpreter_haskell/1b56487f0bce422cc2a2e448dfef800a4e0a08a4/Settings.hs | haskell | needed for
module Settings where
import qualified Data.Map as Map
import System.Console.CmdArgs
import Control.Concurrent.MVar
import Expression
type Environment = Map.Map String Expression
data InteractivityMode = Full | Steps | Interactive
data Arguments = Arguments { filename :: [String]
} deriving (Data, Typeable, Show)
defaultArguments :: Arguments
defaultArguments = Arguments { filename = []
}
data Settings = Settings
{ interactivityMode :: InteractivityMode
, knowNumbers :: Bool
, environment :: Environment
, succName :: String
, clargs :: Arguments
, interruption :: MVar Bool
}
defaultSettings :: Settings
defaultSettings = Settings { interactivityMode = Steps
, knowNumbers = True
, environment = Map.empty
, succName = "SUCC"
, clargs = defaultArguments
, TODO : interruption not initialized
}
| |
8b94bffe68925ab50eb4a84ff515a3d8aefab9452cf758eec5527ce865c2f2fc | LambdaHack/LambdaHack | Overlay.hs | # LANGUAGE RankNTypes , TupleSections #
-- | Screen overlays.
module Game.LambdaHack.Client.UI.Overlay
( -- * DisplayFont
DisplayFont, isPropFont, isSquareFont, isMonoFont, textSize
, -- * FontSetup
FontSetup(..), multiFontSetup, singleFontSetup
* AttrString
AttrString, blankAttrString, textToAS, textFgToAS, stringToAS
, attrStringToString
, (<+:>), (<\:>)
-- * AttrLine
, AttrLine, attrLine, emptyAttrLine, attrStringToAL, firstParagraph
, textToAL, textFgToAL, stringToAL, linesAttr
, splitAttrString, indentSplitAttrString
-- * Overlay
, Overlay, xytranslateOverlay, xtranslateOverlay, ytranslateOverlay
, offsetOverlay, offsetOverlayX, typesetXY
, updateLine, rectangleOfSpaces, maxYofOverlay, labDescOverlay
#ifdef EXPOSE_INTERNAL
-- * Internal operations
, nonbreakableRev, isPrefixOfNonbreakable, breakAtSpace, splitAttrPhrase
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Data.Char (isSpace)
import qualified Data.Text as T
import Game.LambdaHack.Client.UI.PointUI
import qualified Game.LambdaHack.Definition.Color as Color
-- * DisplayFont
-- | Three types of fonts used in the UI. Overlays (layers, more or less)
-- in proportional font are overwritten by layers in square font,
-- which are overwritten by layers in mono font.
-- All overlays overwrite the rendering of the game map, which is
the underlying basic UI frame , comprised of square font .
--
-- This type needs to be kept abstract to ensure that frontend-enforced
or user config - enforced font assignments in ' FontSetup '
-- (e.g., stating that the supposedly proportional font is overriden
-- to be the square font) can't be ignored. Otherwise a programmer
could use arbirary @DisplayFont@ , instead of the one taken from ' FontSetup ' ,
-- and so, e.g., calculating the width of an overlay so constructed
-- in order to decide where another overlay can start would be inconsistent
-- what what font is really eventually used when rendering.
--
-- Note that the order of constructors has limited effect,
-- but it illustrates how overwriting is explicitly implemented
-- in frontends that support all fonts.
data DisplayFont = PropFont | SquareFont | MonoFont
deriving (Show, Eq, Enum)
isPropFont, isSquareFont, isMonoFont :: DisplayFont -> Bool
isPropFont = (== PropFont)
isSquareFont = (== SquareFont)
isMonoFont = (== MonoFont)
textSize :: DisplayFont -> [a] -> Int
textSize SquareFont l = 2 * length l
textSize MonoFont l = length l
textSize PropFont _ = error "size of proportional font texts is not defined"
-- * FontSetup
data FontSetup = FontSetup
{ squareFont :: DisplayFont
, monoFont :: DisplayFont
, propFont :: DisplayFont
}
deriving (Eq, Show) -- for unit tests
multiFontSetup :: FontSetup
multiFontSetup = FontSetup SquareFont MonoFont PropFont
singleFontSetup :: FontSetup
singleFontSetup = FontSetup SquareFont SquareFont SquareFont
* AttrString
-- | String of colourful text. End of line characters permitted.
type AttrString = [Color.AttrCharW32]
blankAttrString :: Int -> AttrString
blankAttrString w = replicate w Color.spaceAttrW32
textToAS :: Text -> AttrString
textToAS !t =
let f c l = let !ac = Color.attrChar1ToW32 c
in ac : l
in T.foldr f [] t
textFgToAS :: Color.Color -> Text -> AttrString
textFgToAS !fg !t =
let f ' ' l = Color.spaceAttrW32 : l
-- for speed and simplicity (testing if char is a space)
-- we always keep the space @White@
f c l = let !ac = Color.attrChar2ToW32 fg c
in ac : l
in T.foldr f [] t
stringToAS :: String -> AttrString
stringToAS = map Color.attrChar1ToW32
| Transform ' AttrString ' type to ' String ' .
attrStringToString :: AttrString -> String
attrStringToString = map Color.charFromW32
-- Follows minimorph.<+>.
infixr 6 <+:> -- matches Monoid.<>
(<+:>) :: AttrString -> AttrString -> AttrString
(<+:>) [] l2 = l2
(<+:>) l1 [] = l1
(<+:>) l1 l2@(c2 : _) =
if isSpace (Color.charFromW32 c2) || isSpace (Color.charFromW32 (last l1))
then l1 ++ l2
else l1 ++ [Color.spaceAttrW32] ++ l2
infixr 6 <\:> -- matches Monoid.<>
(<\:>) :: AttrString -> AttrString -> AttrString
(<\:>) [] l2 = l2
(<\:>) l1 [] = l1
(<\:>) l1 l2@(c2 : _) =
if Color.charFromW32 c2 == '\n' || Color.charFromW32 (last l1) == '\n'
then l1 ++ l2
else l1 ++ stringToAS "\n" ++ l2
-- We consider only these, because they are short and form a closed category.
nonbreakableRev :: [String]
nonbreakableRev = ["eht", "a", "na", "ehT", "A", "nA", "I"]
isPrefixOfNonbreakable :: AttrString -> Bool
isPrefixOfNonbreakable s =
let isPrefixOfNb sRev nbRev = case stripPrefix nbRev sRev of
Nothing -> False
Just [] -> True
Just (c : _) -> isSpace c
in any (isPrefixOfNb $ attrStringToString s) nonbreakableRev
breakAtSpace :: AttrString -> (AttrString, AttrString)
breakAtSpace lRev =
let (pre, post) = break (== Color.spaceAttrW32) lRev
in case post of
c : rest | c == Color.spaceAttrW32 ->
if isPrefixOfNonbreakable rest
then let (pre2, post2) = breakAtSpace rest
in (pre ++ c : pre2, post2)
else (pre, post)
_ -> (pre, post) -- no space found, give up
-- * AttrLine
-- | Line of colourful text. End of line characters forbidden. Trailing
@White@ space forbidden .
newtype AttrLine = AttrLine {attrLine :: AttrString}
deriving (Show, Eq)
emptyAttrLine :: AttrLine
emptyAttrLine = AttrLine []
attrStringToAL :: AttrString -> AttrLine
attrStringToAL s =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (allB (\ac -> Color.charFromW32 ac /= '\n') s) $ -- expensive in menus
assert (null s || last s /= Color.spaceAttrW32
`blame` attrStringToString s) $
-- only expensive for menus, but often violated by code changes, so disabled
-- outside test runs
#endif
AttrLine s
firstParagraph :: AttrString -> AttrLine
firstParagraph s = case linesAttr s of
[] -> emptyAttrLine
l : _ -> l
textToAL :: Text -> AttrLine
textToAL !t =
let f '\n' _ = error $ "illegal end of line in: " ++ T.unpack t
f c l = let !ac = Color.attrChar1ToW32 c
in ac : l
s = T.foldr f [] t
in AttrLine $
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (null s || last s /= Color.spaceAttrW32 `blame` t)
#endif
s
textFgToAL :: Color.Color -> Text -> AttrLine
textFgToAL !fg !t =
let f '\n' _ = error $ "illegal end of line in: " ++ T.unpack t
f ' ' l = Color.spaceAttrW32 : l
-- for speed and simplicity (testing if char is a space)
-- we always keep the space @White@
f c l = let !ac = Color.attrChar2ToW32 fg c
in ac : l
s = T.foldr f [] t
in AttrLine $
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (null s || last s /= Color.spaceAttrW32 `blame` t)
#endif
s
stringToAL :: String -> AttrLine
stringToAL s = attrStringToAL $ map Color.attrChar1ToW32 s
-- Mimics @lines@.
linesAttr :: AttrString -> [AttrLine]
linesAttr [] = []
linesAttr l = cons (case break (\ac -> Color.charFromW32 ac == '\n') l of
(h, t) -> (attrStringToAL h, case t of
[] -> []
_ : tt -> linesAttr tt))
where
cons ~(h, t) = h : t
-- | Split a string into lines. Avoid breaking the line at a character
-- other than space. Remove the spaces on which lines are broken,
-- keep other spaces. In expensive assertions mode (dev debug mode)
-- fail at trailing spaces, but keep leading spaces, e.g., to make
distance from a text in another font . Newlines are respected .
--
Note that we only split wrt @White@ space , nothing else ,
and the width , in the first argument , is calculated in characters ,
-- not in UI (mono font) coordinates, so that taking and dropping characters
-- is performed correctly.
splitAttrString :: Int -> Int -> AttrString -> [AttrLine]
splitAttrString w0 w1 l = case linesAttr l of
[] -> []
x : xs -> splitAttrPhrase w0 w1 x ++ concatMap (splitAttrPhrase w1 w1) xs
indentSplitAttrString :: DisplayFont -> Int -> AttrString -> [AttrLine]
indentSplitAttrString font w l = assert (w > 4) $
-- Sadly this depends on how wide the space is in propotional font,
-- which varies wildly, so we err on the side of larger indent.
let nspaces = case font of
SquareFont -> 1
MonoFont -> 2
PropFont -> 4
ts = splitAttrString w (w - nspaces) l
-- Proportional spaces are very narrow.
spaces = replicate nspaces Color.spaceAttrW32
in case ts of
[] -> []
hd : tl -> hd : map (AttrLine . (spaces ++) . attrLine) tl
-- We pass empty line along for the case of appended buttons, which need
-- either space or new lines before them.
splitAttrPhrase :: Int -> Int -> AttrLine -> [AttrLine]
splitAttrPhrase w0 w1 (AttrLine xs)
| w0 >= length xs = [AttrLine xs] -- no problem, everything fits
| otherwise =
let (pre, postRaw) = splitAt w0 xs
preRev = reverse pre
((ppre, ppost), post) = case postRaw of
c : rest | c == Color.spaceAttrW32
&& not (isPrefixOfNonbreakable preRev) ->
(([], preRev), rest)
_ -> (breakAtSpace preRev, postRaw)
in if all (== Color.spaceAttrW32) ppost
then AttrLine (reverse $ dropWhile (== Color.spaceAttrW32) preRev)
: splitAttrPhrase w1 w1 (AttrLine post)
else AttrLine (reverse $ dropWhile (== Color.spaceAttrW32) ppost)
: splitAttrPhrase w1 w1 (AttrLine $ reverse ppre ++ post)
-- * Overlay
-- | A series of screen lines with start positions at which they should
-- be overlayed over the base frame or a blank screen, depending on context.
-- The position point is represented as in integer that is an index into the
-- frame character array.
-- The lines either fit the width of the screen or are intended
-- for truncation when displayed. The start positions of lines may fall outside
the length of the screen , too , unlike in @SingleFrame@. Then they are
-- simply not shown.
type Overlay = [(PointUI, AttrLine)]
xytranslateOverlay :: Int -> Int -> Overlay -> Overlay
xytranslateOverlay dx dy =
map (\(PointUI x y, al) -> (PointUI (x + dx) (y + dy), al))
xtranslateOverlay :: Int -> Overlay -> Overlay
xtranslateOverlay dx = xytranslateOverlay dx 0
ytranslateOverlay :: Int -> Overlay -> Overlay
ytranslateOverlay = xytranslateOverlay 0
offsetOverlay :: [AttrLine] -> Overlay
offsetOverlay = zipWith (curry (first $ PointUI 0)) [0..]
offsetOverlayX :: [(Int, AttrLine)] -> Overlay
offsetOverlayX = zipWith (\y (x, al) -> (PointUI x y, al)) [0..]
typesetXY :: (Int, Int) -> [AttrLine] -> Overlay
typesetXY (xoffset, yoffset) =
zipWith (\y al -> (PointUI xoffset (y + yoffset), al)) [0..]
@f@ should not enlarge the line beyond screen width nor introduce linebreaks .
updateLine :: Int -> (Int -> AttrString -> AttrString) -> Overlay -> Overlay
updateLine y f ov =
let upd (p@(PointUI px py), AttrLine l) =
if py == y then (p, AttrLine $ f px l) else (p, AttrLine l)
in map upd ov
rectangleOfSpaces :: Int -> Int -> Overlay
rectangleOfSpaces x y =
let blankAttrLine = AttrLine $ replicate x Color.nbspAttrW32
in offsetOverlay $ replicate y blankAttrLine
maxYofOverlay :: Overlay -> Int
maxYofOverlay ov = let yOfOverlay (PointUI _ y, _) = y
in maximum $ 0 : map yOfOverlay ov
labDescOverlay :: DisplayFont -> Int -> AttrString -> (Overlay, Overlay)
labDescOverlay labFont width as =
let (tLab, tDesc) = span (/= Color.spaceAttrW32) as
labLen = textSize labFont tLab
not labLen ; TODO : type more strictly
ovLab = offsetOverlay [attrStringToAL tLab]
ovDesc = offsetOverlayX $
case splitAttrString len width tDesc of
[] -> []
l : ls -> (labLen, l) : map (0,) ls
in (ovLab, ovDesc)
| null | https://raw.githubusercontent.com/LambdaHack/LambdaHack/e988fafc52a762d5471a133fe9896adf5f277c03/engine-src/Game/LambdaHack/Client/UI/Overlay.hs | haskell | | Screen overlays.
* DisplayFont
* FontSetup
* AttrLine
* Overlay
* Internal operations
* DisplayFont
| Three types of fonts used in the UI. Overlays (layers, more or less)
in proportional font are overwritten by layers in square font,
which are overwritten by layers in mono font.
All overlays overwrite the rendering of the game map, which is
This type needs to be kept abstract to ensure that frontend-enforced
(e.g., stating that the supposedly proportional font is overriden
to be the square font) can't be ignored. Otherwise a programmer
and so, e.g., calculating the width of an overlay so constructed
in order to decide where another overlay can start would be inconsistent
what what font is really eventually used when rendering.
Note that the order of constructors has limited effect,
but it illustrates how overwriting is explicitly implemented
in frontends that support all fonts.
* FontSetup
for unit tests
| String of colourful text. End of line characters permitted.
for speed and simplicity (testing if char is a space)
we always keep the space @White@
Follows minimorph.<+>.
matches Monoid.<>
matches Monoid.<>
We consider only these, because they are short and form a closed category.
no space found, give up
* AttrLine
| Line of colourful text. End of line characters forbidden. Trailing
expensive in menus
only expensive for menus, but often violated by code changes, so disabled
outside test runs
for speed and simplicity (testing if char is a space)
we always keep the space @White@
Mimics @lines@.
| Split a string into lines. Avoid breaking the line at a character
other than space. Remove the spaces on which lines are broken,
keep other spaces. In expensive assertions mode (dev debug mode)
fail at trailing spaces, but keep leading spaces, e.g., to make
not in UI (mono font) coordinates, so that taking and dropping characters
is performed correctly.
Sadly this depends on how wide the space is in propotional font,
which varies wildly, so we err on the side of larger indent.
Proportional spaces are very narrow.
We pass empty line along for the case of appended buttons, which need
either space or new lines before them.
no problem, everything fits
* Overlay
| A series of screen lines with start positions at which they should
be overlayed over the base frame or a blank screen, depending on context.
The position point is represented as in integer that is an index into the
frame character array.
The lines either fit the width of the screen or are intended
for truncation when displayed. The start positions of lines may fall outside
simply not shown. | # LANGUAGE RankNTypes , TupleSections #
module Game.LambdaHack.Client.UI.Overlay
DisplayFont, isPropFont, isSquareFont, isMonoFont, textSize
FontSetup(..), multiFontSetup, singleFontSetup
* AttrString
AttrString, blankAttrString, textToAS, textFgToAS, stringToAS
, attrStringToString
, (<+:>), (<\:>)
, AttrLine, attrLine, emptyAttrLine, attrStringToAL, firstParagraph
, textToAL, textFgToAL, stringToAL, linesAttr
, splitAttrString, indentSplitAttrString
, Overlay, xytranslateOverlay, xtranslateOverlay, ytranslateOverlay
, offsetOverlay, offsetOverlayX, typesetXY
, updateLine, rectangleOfSpaces, maxYofOverlay, labDescOverlay
#ifdef EXPOSE_INTERNAL
, nonbreakableRev, isPrefixOfNonbreakable, breakAtSpace, splitAttrPhrase
#endif
) where
import Prelude ()
import Game.LambdaHack.Core.Prelude
import Data.Char (isSpace)
import qualified Data.Text as T
import Game.LambdaHack.Client.UI.PointUI
import qualified Game.LambdaHack.Definition.Color as Color
the underlying basic UI frame , comprised of square font .
or user config - enforced font assignments in ' FontSetup '
could use arbirary @DisplayFont@ , instead of the one taken from ' FontSetup ' ,
data DisplayFont = PropFont | SquareFont | MonoFont
deriving (Show, Eq, Enum)
isPropFont, isSquareFont, isMonoFont :: DisplayFont -> Bool
isPropFont = (== PropFont)
isSquareFont = (== SquareFont)
isMonoFont = (== MonoFont)
textSize :: DisplayFont -> [a] -> Int
textSize SquareFont l = 2 * length l
textSize MonoFont l = length l
textSize PropFont _ = error "size of proportional font texts is not defined"
data FontSetup = FontSetup
{ squareFont :: DisplayFont
, monoFont :: DisplayFont
, propFont :: DisplayFont
}
multiFontSetup :: FontSetup
multiFontSetup = FontSetup SquareFont MonoFont PropFont
singleFontSetup :: FontSetup
singleFontSetup = FontSetup SquareFont SquareFont SquareFont
* AttrString
type AttrString = [Color.AttrCharW32]
blankAttrString :: Int -> AttrString
blankAttrString w = replicate w Color.spaceAttrW32
textToAS :: Text -> AttrString
textToAS !t =
let f c l = let !ac = Color.attrChar1ToW32 c
in ac : l
in T.foldr f [] t
textFgToAS :: Color.Color -> Text -> AttrString
textFgToAS !fg !t =
let f ' ' l = Color.spaceAttrW32 : l
f c l = let !ac = Color.attrChar2ToW32 fg c
in ac : l
in T.foldr f [] t
stringToAS :: String -> AttrString
stringToAS = map Color.attrChar1ToW32
| Transform ' AttrString ' type to ' String ' .
attrStringToString :: AttrString -> String
attrStringToString = map Color.charFromW32
(<+:>) :: AttrString -> AttrString -> AttrString
(<+:>) [] l2 = l2
(<+:>) l1 [] = l1
(<+:>) l1 l2@(c2 : _) =
if isSpace (Color.charFromW32 c2) || isSpace (Color.charFromW32 (last l1))
then l1 ++ l2
else l1 ++ [Color.spaceAttrW32] ++ l2
(<\:>) :: AttrString -> AttrString -> AttrString
(<\:>) [] l2 = l2
(<\:>) l1 [] = l1
(<\:>) l1 l2@(c2 : _) =
if Color.charFromW32 c2 == '\n' || Color.charFromW32 (last l1) == '\n'
then l1 ++ l2
else l1 ++ stringToAS "\n" ++ l2
nonbreakableRev :: [String]
nonbreakableRev = ["eht", "a", "na", "ehT", "A", "nA", "I"]
isPrefixOfNonbreakable :: AttrString -> Bool
isPrefixOfNonbreakable s =
let isPrefixOfNb sRev nbRev = case stripPrefix nbRev sRev of
Nothing -> False
Just [] -> True
Just (c : _) -> isSpace c
in any (isPrefixOfNb $ attrStringToString s) nonbreakableRev
breakAtSpace :: AttrString -> (AttrString, AttrString)
breakAtSpace lRev =
let (pre, post) = break (== Color.spaceAttrW32) lRev
in case post of
c : rest | c == Color.spaceAttrW32 ->
if isPrefixOfNonbreakable rest
then let (pre2, post2) = breakAtSpace rest
in (pre ++ c : pre2, post2)
else (pre, post)
@White@ space forbidden .
newtype AttrLine = AttrLine {attrLine :: AttrString}
deriving (Show, Eq)
emptyAttrLine :: AttrLine
emptyAttrLine = AttrLine []
attrStringToAL :: AttrString -> AttrLine
attrStringToAL s =
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (null s || last s /= Color.spaceAttrW32
`blame` attrStringToString s) $
#endif
AttrLine s
firstParagraph :: AttrString -> AttrLine
firstParagraph s = case linesAttr s of
[] -> emptyAttrLine
l : _ -> l
textToAL :: Text -> AttrLine
textToAL !t =
let f '\n' _ = error $ "illegal end of line in: " ++ T.unpack t
f c l = let !ac = Color.attrChar1ToW32 c
in ac : l
s = T.foldr f [] t
in AttrLine $
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (null s || last s /= Color.spaceAttrW32 `blame` t)
#endif
s
textFgToAL :: Color.Color -> Text -> AttrLine
textFgToAL !fg !t =
let f '\n' _ = error $ "illegal end of line in: " ++ T.unpack t
f ' ' l = Color.spaceAttrW32 : l
f c l = let !ac = Color.attrChar2ToW32 fg c
in ac : l
s = T.foldr f [] t
in AttrLine $
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (null s || last s /= Color.spaceAttrW32 `blame` t)
#endif
s
stringToAL :: String -> AttrLine
stringToAL s = attrStringToAL $ map Color.attrChar1ToW32 s
linesAttr :: AttrString -> [AttrLine]
linesAttr [] = []
linesAttr l = cons (case break (\ac -> Color.charFromW32 ac == '\n') l of
(h, t) -> (attrStringToAL h, case t of
[] -> []
_ : tt -> linesAttr tt))
where
cons ~(h, t) = h : t
distance from a text in another font . Newlines are respected .
Note that we only split wrt @White@ space , nothing else ,
and the width , in the first argument , is calculated in characters ,
splitAttrString :: Int -> Int -> AttrString -> [AttrLine]
splitAttrString w0 w1 l = case linesAttr l of
[] -> []
x : xs -> splitAttrPhrase w0 w1 x ++ concatMap (splitAttrPhrase w1 w1) xs
indentSplitAttrString :: DisplayFont -> Int -> AttrString -> [AttrLine]
indentSplitAttrString font w l = assert (w > 4) $
let nspaces = case font of
SquareFont -> 1
MonoFont -> 2
PropFont -> 4
ts = splitAttrString w (w - nspaces) l
spaces = replicate nspaces Color.spaceAttrW32
in case ts of
[] -> []
hd : tl -> hd : map (AttrLine . (spaces ++) . attrLine) tl
splitAttrPhrase :: Int -> Int -> AttrLine -> [AttrLine]
splitAttrPhrase w0 w1 (AttrLine xs)
| otherwise =
let (pre, postRaw) = splitAt w0 xs
preRev = reverse pre
((ppre, ppost), post) = case postRaw of
c : rest | c == Color.spaceAttrW32
&& not (isPrefixOfNonbreakable preRev) ->
(([], preRev), rest)
_ -> (breakAtSpace preRev, postRaw)
in if all (== Color.spaceAttrW32) ppost
then AttrLine (reverse $ dropWhile (== Color.spaceAttrW32) preRev)
: splitAttrPhrase w1 w1 (AttrLine post)
else AttrLine (reverse $ dropWhile (== Color.spaceAttrW32) ppost)
: splitAttrPhrase w1 w1 (AttrLine $ reverse ppre ++ post)
the length of the screen , too , unlike in @SingleFrame@. Then they are
type Overlay = [(PointUI, AttrLine)]
xytranslateOverlay :: Int -> Int -> Overlay -> Overlay
xytranslateOverlay dx dy =
map (\(PointUI x y, al) -> (PointUI (x + dx) (y + dy), al))
xtranslateOverlay :: Int -> Overlay -> Overlay
xtranslateOverlay dx = xytranslateOverlay dx 0
ytranslateOverlay :: Int -> Overlay -> Overlay
ytranslateOverlay = xytranslateOverlay 0
offsetOverlay :: [AttrLine] -> Overlay
offsetOverlay = zipWith (curry (first $ PointUI 0)) [0..]
offsetOverlayX :: [(Int, AttrLine)] -> Overlay
offsetOverlayX = zipWith (\y (x, al) -> (PointUI x y, al)) [0..]
typesetXY :: (Int, Int) -> [AttrLine] -> Overlay
typesetXY (xoffset, yoffset) =
zipWith (\y al -> (PointUI xoffset (y + yoffset), al)) [0..]
@f@ should not enlarge the line beyond screen width nor introduce linebreaks .
updateLine :: Int -> (Int -> AttrString -> AttrString) -> Overlay -> Overlay
updateLine y f ov =
let upd (p@(PointUI px py), AttrLine l) =
if py == y then (p, AttrLine $ f px l) else (p, AttrLine l)
in map upd ov
rectangleOfSpaces :: Int -> Int -> Overlay
rectangleOfSpaces x y =
let blankAttrLine = AttrLine $ replicate x Color.nbspAttrW32
in offsetOverlay $ replicate y blankAttrLine
maxYofOverlay :: Overlay -> Int
maxYofOverlay ov = let yOfOverlay (PointUI _ y, _) = y
in maximum $ 0 : map yOfOverlay ov
labDescOverlay :: DisplayFont -> Int -> AttrString -> (Overlay, Overlay)
labDescOverlay labFont width as =
let (tLab, tDesc) = span (/= Color.spaceAttrW32) as
labLen = textSize labFont tLab
not labLen ; TODO : type more strictly
ovLab = offsetOverlay [attrStringToAL tLab]
ovDesc = offsetOverlayX $
case splitAttrString len width tDesc of
[] -> []
l : ls -> (labLen, l) : map (0,) ls
in (ovLab, ovDesc)
|
90ad26cac30f972b020a4ad57f0e845fefa2810261d2a310ede5abc735598732 | commercialhaskell/path | Posix.hs | # LANGUAGE CPP #
#define PLATFORM_NAME Posix
#define IS_WINDOWS False
#include "Include.hs"
| null | https://raw.githubusercontent.com/commercialhaskell/path/2bec48c17be4b82f7dabc8e2dd167444e558e9a5/src/Path/Posix.hs | haskell | # LANGUAGE CPP #
#define PLATFORM_NAME Posix
#define IS_WINDOWS False
#include "Include.hs"
| |
8fe8547d73950b1df1ee6534e63667535f5d68ce4c3762c21ea4a20c211fd5b4 | dmitryvk/sbcl-win32-threads | vm.lisp | ;;;; miscellaneous VM definition noise for HPPA
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!VM")
;;;; Registers
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *register-names* (make-array 32 :initial-element nil)))
(macrolet ((defreg (name offset)
(let ((offset-sym (symbolicate name "-OFFSET")))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(def!constant ,offset-sym ,offset)
(setf (svref *register-names* ,offset-sym) ,(symbol-name name)))))
(defregset (name &rest regs)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter ,name
(list ,@(mapcar #'(lambda (name) (symbolicate name "-OFFSET")) regs))))))
;; Wired-zero
(defreg zero 0)
;; This gets trashed by the C call convention.
(defreg nfp 1) ;; and saved by lisp before calling C
(defreg cfunc 2)
;; These are the callee saves, so these registers are stay live over
;; call-out.
(defreg csp 3)
(defreg cfp 4)
(defreg bsp 5)
(defreg null 6)
(defreg alloc 7)
(defreg code 8)
(defreg fdefn 9)
(defreg lexenv 10)
(defreg nargs 11)
(defreg ocfp 12)
(defreg lra 13)
(defreg a0 14)
(defreg a1 15)
(defreg a2 16)
(defreg a3 17)
(defreg a4 18)
;; This is where the caller-saves registers start, but we don't
;; really care because we need to clear the above after call-out to
;; make sure no pointers into oldspace are kept around.
(defreg a5 19)
(defreg l0 20)
(defreg l1 21)
(defreg l2 22)
These are the 4 C argument registers .
(defreg nl3 23)
(defreg nl2 24)
(defreg nl1 25)
(defreg nl0 26)
;; The global Data Pointer. We just leave it alone, because we
;; don't need it.
(defreg dp 27)
These two are use for C return values .
(defreg nl4 28)
(defreg nl5 29)
(defreg nsp 30)
(defreg lip 31)
(defregset non-descriptor-regs
nl0 nl1 nl2 nl3 nl4 nl5 cfunc nargs nfp)
(defregset descriptor-regs
a0 a1 a2 a3 a4 a5 fdefn lexenv ocfp lra l0 l1 l2)
(defregset *register-arg-offsets*
a0 a1 a2 a3 a4 a5)
(defregset reserve-descriptor-regs
fdefn lexenv)
(defregset reserve-non-descriptor-regs
cfunc))
(define-storage-base registers :finite :size 32)
(define-storage-base float-registers :finite :size 64)
(define-storage-base control-stack :unbounded :size 8)
(define-storage-base non-descriptor-stack :unbounded :size 0)
(define-storage-base constant :non-packed)
(define-storage-base immediate-constant :non-packed)
;;;
;;; Handy macro so we don't have to keep changing all the numbers whenever
;;; we insert a new storage class.
;;; FIXME-lav: move this into arch-generic-helpers.lisp and rip out from arches
(defmacro !define-storage-classes (&rest classes)
(do ((forms (list 'progn)
(let* ((class (car classes))
(sc-name (car class))
(constant-name (intern (concatenate 'simple-string
(string sc-name)
"-SC-NUMBER"))))
(list* `(define-storage-class ,sc-name ,index
,@(cdr class))
`(def!constant ,constant-name ,index)
forms)))
(index 0 (1+ index))
(classes classes (cdr classes)))
((null classes)
(nreverse forms))))
(def!constant kludge-nondeterministic-catch-block-size 6)
(!define-storage-classes
;; Non-immediate constants in the constant pool
(constant constant)
;; ZERO and NULL are in registers.
(zero immediate-constant)
(null immediate-constant)
(fp-single-zero immediate-constant)
(fp-double-zero immediate-constant)
;; Anything else that can be an immediate.
(immediate immediate-constant)
;; **** The stacks.
The control stack . ( Scanned by GC )
(control-stack control-stack)
We put ANY - REG and DESCRIPTOR - REG early so that their SC - NUMBER
;; is small and therefore the error trap information is smaller.
;; Moving them up here from their previous place down below saves
~250 K in core file size . --njf , 2006 - 01 - 27
Immediate descriptor objects . Do n't have to be seen by GC , but nothing
;; bad will happen if they are. (fixnums, characters, header values, etc).
(any-reg
registers
:locations #.(append non-descriptor-regs descriptor-regs)
:reserve-locations #.(append reserve-non-descriptor-regs
reserve-descriptor-regs)
:constant-scs (constant zero immediate)
:save-p t
:alternate-scs (control-stack))
Pointer descriptor objects . Must be seen by GC .
(descriptor-reg registers
:locations #.descriptor-regs
:reserve-locations #.reserve-descriptor-regs
:constant-scs (constant null immediate)
:save-p t
:alternate-scs (control-stack))
;; The non-descriptor stacks.
( signed - byte 32 )
( unsigned - byte 32 )
(character-stack non-descriptor-stack) ; non-descriptor characters.
(sap-stack non-descriptor-stack) ; System area pointers.
(single-stack non-descriptor-stack) ; single-floats
(double-stack non-descriptor-stack
:element-size 2 :alignment 2) ; double floats.
(complex-single-stack non-descriptor-stack :element-size 2)
(complex-double-stack non-descriptor-stack :element-size 4 :alignment 2)
;; **** Things that can go in the integer registers.
;; Non-Descriptor characters
(character-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (immediate)
:save-p t
:alternate-scs (character-stack))
Non - Descriptor SAP 's ( arbitrary pointers into address space )
(sap-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (immediate)
:save-p t
:alternate-scs (sap-stack))
Non - Descriptor ( signed or unsigned ) numbers .
(signed-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (zero immediate)
:save-p t
:alternate-scs (signed-stack))
(unsigned-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (zero immediate)
:save-p t
:alternate-scs (unsigned-stack))
Random objects that must not be seen by GC . Used only as temporaries .
(non-descriptor-reg registers
:locations #.non-descriptor-regs)
Pointers to the interior of objects . Used only as an temporary .
(interior-reg registers
:locations (#.lip-offset))
;; **** Things that can go in the floating point registers.
Non - Descriptor single - floats .
(single-reg float-registers
:locations #.(loop for i from 4 to 31 collect i)
:constant-scs (fp-single-zero)
:save-p t
:alternate-scs (single-stack))
Non - Descriptor double - floats .
(double-reg float-registers
:locations #.(loop for i from 4 to 31 collect i)
:constant-scs (fp-double-zero)
:save-p t
:alternate-scs (double-stack))
(complex-single-reg float-registers
:locations #.(loop for i from 4 to 30 by 2 collect i)
:element-size 2
:constant-scs ()
:save-p t
:alternate-scs (complex-single-stack))
(complex-double-reg float-registers
:locations #.(loop for i from 4 to 30 by 2 collect i)
:element-size 2
:constant-scs ()
:save-p t
:alternate-scs (complex-double-stack))
;; A catch or unwind block.
(catch-block control-stack :element-size kludge-nondeterministic-catch-block-size)
;; floating point numbers temporarily stuck in integer registers for c-call
(single-int-carg-reg registers
:locations (26 25 24 23)
:alternate-scs ()
:constant-scs ())
(double-int-carg-reg registers
:locations (25 23)
:constant-scs ()
:alternate-scs ()
: alignment 2 ; is this needed ?
: element - size 2
))
;;;; Make some random tns for important registers.
how can we address reg L0 through L0 - offset when it is not
;;; defined here ? do all registers have an -offset and this is
;;; redundant work ?
;;;
;;; FIXME-lav: move this into arch-generic-helpers
(macrolet ((defregtn (name sc)
(let ((offset-sym (symbolicate name "-OFFSET"))
(tn-sym (symbolicate name "-TN")))
`(defparameter ,tn-sym
(make-random-tn :kind :normal
:sc (sc-or-lose ',sc)
:offset ,offset-sym)))))
;; These, we access by foo-TN only
(defregtn zero any-reg)
(defregtn nargs any-reg)
FIXME - lav : 20080820 : not a fix , but fdefn and lexenv is used in assembly - rtns
FIXME - lav , not used
FIXME - lav , not used
(defregtn nfp descriptor-reg) ; why not descriptor-reg ?
(defregtn ocfp any-reg) ; why not descriptor-reg ?
(defregtn null descriptor-reg)
(defregtn bsp any-reg)
(defregtn cfp any-reg)
(defregtn csp any-reg)
(defregtn alloc any-reg)
(defregtn nsp any-reg)
(defregtn code descriptor-reg)
(defregtn lip interior-reg))
;; And some floating point values.
(defparameter fp-single-zero-tn
(make-random-tn :kind :normal
:sc (sc-or-lose 'single-reg)
:offset 0))
(defparameter fp-double-zero-tn
(make-random-tn :kind :normal
:sc (sc-or-lose 'double-reg)
:offset 0))
If VALUE can be represented as an immediate constant , then return
the appropriate SC number , otherwise return NIL .
(!def-vm-support-routine immediate-constant-sc (value)
(typecase value
((integer 0 0)
(sc-number-or-lose 'zero))
(null
(sc-number-or-lose 'null))
((or (integer #.sb!xc:most-negative-fixnum #.sb!xc:most-positive-fixnum)
system-area-pointer character)
(sc-number-or-lose 'immediate))
(symbol
(if (static-symbol-p value)
(sc-number-or-lose 'immediate)
nil))
(single-float
(if (zerop value)
(sc-number-or-lose 'fp-single-zero)
nil))
(double-float
(if (zerop value)
(sc-number-or-lose 'fp-double-zero)
nil))))
;;;; Function Call Parameters
The SC numbers for register and stack arguments / return values .
;;;
(def!constant register-arg-scn (meta-sc-number-or-lose 'descriptor-reg))
(def!constant immediate-arg-scn (meta-sc-number-or-lose 'any-reg))
(def!constant control-stack-arg-scn (meta-sc-number-or-lose 'control-stack))
(eval-when (:compile-toplevel :load-toplevel :execute)
;;; Offsets of special stack frame locations
(def!constant ocfp-save-offset 0)
(def!constant lra-save-offset 1)
(def!constant nfp-save-offset 2)
;;; The number of arguments/return values passed in registers.
;;;
(def!constant register-arg-count 6)
;;; Names to use for the argument registers.
;;;
(defconstant-eqx register-arg-names '(a0 a1 a2 a3 a4 a5) #'equal)
EVAL - WHEN
A list of TN 's describing the register arguments .
;;;
(defparameter *register-arg-tns*
(mapcar (lambda (n)
(make-random-tn :kind :normal
:sc (sc-or-lose 'descriptor-reg)
:offset n))
*register-arg-offsets*))
;;; This is used by the debugger.
(def!constant single-value-return-byte-offset 4)
;;; This function is called by debug output routines that want a pretty name
for a TN 's location . It returns a thing that can be printed with PRINC .
(!def-vm-support-routine location-print-name (tn)
(declare (type tn tn))
(let ((sb (sb-name (sc-sb (tn-sc tn))))
(offset (tn-offset tn)))
(ecase sb
(registers (or (svref *register-names* offset)
(format nil "R~D" offset)))
(float-registers (format nil "F~D" offset))
(control-stack (format nil "CS~D" offset))
(non-descriptor-stack (format nil "NS~D" offset))
(constant (format nil "Const~D" offset))
(immediate-constant "Immed"))))
(!def-vm-support-routine combination-implementation-style (node)
(declare (type sb!c::combination node) (ignore node))
(values :default nil))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/compiler/hppa/vm.lisp | lisp | miscellaneous VM definition noise for HPPA
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
Registers
Wired-zero
This gets trashed by the C call convention.
and saved by lisp before calling C
These are the callee saves, so these registers are stay live over
call-out.
This is where the caller-saves registers start, but we don't
really care because we need to clear the above after call-out to
make sure no pointers into oldspace are kept around.
The global Data Pointer. We just leave it alone, because we
don't need it.
Handy macro so we don't have to keep changing all the numbers whenever
we insert a new storage class.
FIXME-lav: move this into arch-generic-helpers.lisp and rip out from arches
Non-immediate constants in the constant pool
ZERO and NULL are in registers.
Anything else that can be an immediate.
**** The stacks.
is small and therefore the error trap information is smaller.
Moving them up here from their previous place down below saves
bad will happen if they are. (fixnums, characters, header values, etc).
The non-descriptor stacks.
non-descriptor characters.
System area pointers.
single-floats
double floats.
**** Things that can go in the integer registers.
Non-Descriptor characters
**** Things that can go in the floating point registers.
A catch or unwind block.
floating point numbers temporarily stuck in integer registers for c-call
is this needed ?
Make some random tns for important registers.
defined here ? do all registers have an -offset and this is
redundant work ?
FIXME-lav: move this into arch-generic-helpers
These, we access by foo-TN only
why not descriptor-reg ?
why not descriptor-reg ?
And some floating point values.
Function Call Parameters
Offsets of special stack frame locations
The number of arguments/return values passed in registers.
Names to use for the argument registers.
This is used by the debugger.
This function is called by debug output routines that want a pretty name |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!VM")
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *register-names* (make-array 32 :initial-element nil)))
(macrolet ((defreg (name offset)
(let ((offset-sym (symbolicate name "-OFFSET")))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(def!constant ,offset-sym ,offset)
(setf (svref *register-names* ,offset-sym) ,(symbol-name name)))))
(defregset (name &rest regs)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter ,name
(list ,@(mapcar #'(lambda (name) (symbolicate name "-OFFSET")) regs))))))
(defreg zero 0)
(defreg cfunc 2)
(defreg csp 3)
(defreg cfp 4)
(defreg bsp 5)
(defreg null 6)
(defreg alloc 7)
(defreg code 8)
(defreg fdefn 9)
(defreg lexenv 10)
(defreg nargs 11)
(defreg ocfp 12)
(defreg lra 13)
(defreg a0 14)
(defreg a1 15)
(defreg a2 16)
(defreg a3 17)
(defreg a4 18)
(defreg a5 19)
(defreg l0 20)
(defreg l1 21)
(defreg l2 22)
These are the 4 C argument registers .
(defreg nl3 23)
(defreg nl2 24)
(defreg nl1 25)
(defreg nl0 26)
(defreg dp 27)
These two are use for C return values .
(defreg nl4 28)
(defreg nl5 29)
(defreg nsp 30)
(defreg lip 31)
(defregset non-descriptor-regs
nl0 nl1 nl2 nl3 nl4 nl5 cfunc nargs nfp)
(defregset descriptor-regs
a0 a1 a2 a3 a4 a5 fdefn lexenv ocfp lra l0 l1 l2)
(defregset *register-arg-offsets*
a0 a1 a2 a3 a4 a5)
(defregset reserve-descriptor-regs
fdefn lexenv)
(defregset reserve-non-descriptor-regs
cfunc))
(define-storage-base registers :finite :size 32)
(define-storage-base float-registers :finite :size 64)
(define-storage-base control-stack :unbounded :size 8)
(define-storage-base non-descriptor-stack :unbounded :size 0)
(define-storage-base constant :non-packed)
(define-storage-base immediate-constant :non-packed)
(defmacro !define-storage-classes (&rest classes)
(do ((forms (list 'progn)
(let* ((class (car classes))
(sc-name (car class))
(constant-name (intern (concatenate 'simple-string
(string sc-name)
"-SC-NUMBER"))))
(list* `(define-storage-class ,sc-name ,index
,@(cdr class))
`(def!constant ,constant-name ,index)
forms)))
(index 0 (1+ index))
(classes classes (cdr classes)))
((null classes)
(nreverse forms))))
(def!constant kludge-nondeterministic-catch-block-size 6)
(!define-storage-classes
(constant constant)
(zero immediate-constant)
(null immediate-constant)
(fp-single-zero immediate-constant)
(fp-double-zero immediate-constant)
(immediate immediate-constant)
The control stack . ( Scanned by GC )
(control-stack control-stack)
We put ANY - REG and DESCRIPTOR - REG early so that their SC - NUMBER
~250 K in core file size . --njf , 2006 - 01 - 27
Immediate descriptor objects . Do n't have to be seen by GC , but nothing
(any-reg
registers
:locations #.(append non-descriptor-regs descriptor-regs)
:reserve-locations #.(append reserve-non-descriptor-regs
reserve-descriptor-regs)
:constant-scs (constant zero immediate)
:save-p t
:alternate-scs (control-stack))
Pointer descriptor objects . Must be seen by GC .
(descriptor-reg registers
:locations #.descriptor-regs
:reserve-locations #.reserve-descriptor-regs
:constant-scs (constant null immediate)
:save-p t
:alternate-scs (control-stack))
( signed - byte 32 )
( unsigned - byte 32 )
(double-stack non-descriptor-stack
(complex-single-stack non-descriptor-stack :element-size 2)
(complex-double-stack non-descriptor-stack :element-size 4 :alignment 2)
(character-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (immediate)
:save-p t
:alternate-scs (character-stack))
Non - Descriptor SAP 's ( arbitrary pointers into address space )
(sap-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (immediate)
:save-p t
:alternate-scs (sap-stack))
Non - Descriptor ( signed or unsigned ) numbers .
(signed-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (zero immediate)
:save-p t
:alternate-scs (signed-stack))
(unsigned-reg registers
:locations #.non-descriptor-regs
:reserve-locations #.reserve-non-descriptor-regs
:constant-scs (zero immediate)
:save-p t
:alternate-scs (unsigned-stack))
Random objects that must not be seen by GC . Used only as temporaries .
(non-descriptor-reg registers
:locations #.non-descriptor-regs)
Pointers to the interior of objects . Used only as an temporary .
(interior-reg registers
:locations (#.lip-offset))
Non - Descriptor single - floats .
(single-reg float-registers
:locations #.(loop for i from 4 to 31 collect i)
:constant-scs (fp-single-zero)
:save-p t
:alternate-scs (single-stack))
Non - Descriptor double - floats .
(double-reg float-registers
:locations #.(loop for i from 4 to 31 collect i)
:constant-scs (fp-double-zero)
:save-p t
:alternate-scs (double-stack))
(complex-single-reg float-registers
:locations #.(loop for i from 4 to 30 by 2 collect i)
:element-size 2
:constant-scs ()
:save-p t
:alternate-scs (complex-single-stack))
(complex-double-reg float-registers
:locations #.(loop for i from 4 to 30 by 2 collect i)
:element-size 2
:constant-scs ()
:save-p t
:alternate-scs (complex-double-stack))
(catch-block control-stack :element-size kludge-nondeterministic-catch-block-size)
(single-int-carg-reg registers
:locations (26 25 24 23)
:alternate-scs ()
:constant-scs ())
(double-int-carg-reg registers
:locations (25 23)
:constant-scs ()
:alternate-scs ()
: element - size 2
))
how can we address reg L0 through L0 - offset when it is not
(macrolet ((defregtn (name sc)
(let ((offset-sym (symbolicate name "-OFFSET"))
(tn-sym (symbolicate name "-TN")))
`(defparameter ,tn-sym
(make-random-tn :kind :normal
:sc (sc-or-lose ',sc)
:offset ,offset-sym)))))
(defregtn zero any-reg)
(defregtn nargs any-reg)
FIXME - lav : 20080820 : not a fix , but fdefn and lexenv is used in assembly - rtns
FIXME - lav , not used
FIXME - lav , not used
(defregtn null descriptor-reg)
(defregtn bsp any-reg)
(defregtn cfp any-reg)
(defregtn csp any-reg)
(defregtn alloc any-reg)
(defregtn nsp any-reg)
(defregtn code descriptor-reg)
(defregtn lip interior-reg))
(defparameter fp-single-zero-tn
(make-random-tn :kind :normal
:sc (sc-or-lose 'single-reg)
:offset 0))
(defparameter fp-double-zero-tn
(make-random-tn :kind :normal
:sc (sc-or-lose 'double-reg)
:offset 0))
If VALUE can be represented as an immediate constant , then return
the appropriate SC number , otherwise return NIL .
(!def-vm-support-routine immediate-constant-sc (value)
(typecase value
((integer 0 0)
(sc-number-or-lose 'zero))
(null
(sc-number-or-lose 'null))
((or (integer #.sb!xc:most-negative-fixnum #.sb!xc:most-positive-fixnum)
system-area-pointer character)
(sc-number-or-lose 'immediate))
(symbol
(if (static-symbol-p value)
(sc-number-or-lose 'immediate)
nil))
(single-float
(if (zerop value)
(sc-number-or-lose 'fp-single-zero)
nil))
(double-float
(if (zerop value)
(sc-number-or-lose 'fp-double-zero)
nil))))
The SC numbers for register and stack arguments / return values .
(def!constant register-arg-scn (meta-sc-number-or-lose 'descriptor-reg))
(def!constant immediate-arg-scn (meta-sc-number-or-lose 'any-reg))
(def!constant control-stack-arg-scn (meta-sc-number-or-lose 'control-stack))
(eval-when (:compile-toplevel :load-toplevel :execute)
(def!constant ocfp-save-offset 0)
(def!constant lra-save-offset 1)
(def!constant nfp-save-offset 2)
(def!constant register-arg-count 6)
(defconstant-eqx register-arg-names '(a0 a1 a2 a3 a4 a5) #'equal)
EVAL - WHEN
A list of TN 's describing the register arguments .
(defparameter *register-arg-tns*
(mapcar (lambda (n)
(make-random-tn :kind :normal
:sc (sc-or-lose 'descriptor-reg)
:offset n))
*register-arg-offsets*))
(def!constant single-value-return-byte-offset 4)
for a TN 's location . It returns a thing that can be printed with PRINC .
(!def-vm-support-routine location-print-name (tn)
(declare (type tn tn))
(let ((sb (sb-name (sc-sb (tn-sc tn))))
(offset (tn-offset tn)))
(ecase sb
(registers (or (svref *register-names* offset)
(format nil "R~D" offset)))
(float-registers (format nil "F~D" offset))
(control-stack (format nil "CS~D" offset))
(non-descriptor-stack (format nil "NS~D" offset))
(constant (format nil "Const~D" offset))
(immediate-constant "Immed"))))
(!def-vm-support-routine combination-implementation-style (node)
(declare (type sb!c::combination node) (ignore node))
(values :default nil))
|
11baee7bf5eb334e048c34d53d6652f9635eb3627d921ac27c1a51f77c413d89 | jmorag/mcc | Error.hs | module Microc.Semant.Error where
import Microc.Ast
import Data.Text ( Text )
import Data.Text.Prettyprint.Doc
type Name = Text
data BindingLoc = F Function | S Struct | Toplevel deriving Show
data SemantError =
IllegalBinding Name BindingKind VarKind BindingLoc
| UndefinedSymbol Name SymbolKind Expr
| TypeError { expected :: [Type], got :: Type, errorLoc :: Statement }
| CastError { to :: Type, from :: Type, castLoc :: Statement }
| ArgError { nExpected :: Int, nGot :: Int, callSite :: Expr }
| Redeclaration Name
| NoMain
| AddressError Expr
| AssignmentError { lhs :: Expr, rhs :: Expr }
| AccessError { struct :: Expr, field :: Expr }
| DeadCode Statement -- ^ For statements in a block following a return
deriving (Show)
data BindingKind = Duplicate | Void deriving (Show)
data SymbolKind = Var | Func deriving (Show)
data VarKind = Global | Formal | Local | StructField deriving (Show, Eq, Ord)
instance Pretty VarKind where
pretty = unsafeViaShow
instance Pretty SymbolKind where
pretty = \case
Var -> "variable"
Func -> "function"
instance Pretty BindingKind where
pretty = unsafeViaShow
instance Pretty SemantError where
pretty = \case
IllegalBinding nm bindKind varKind loc ->
"Error: Illegal" <+> pretty bindKind <+> pretty varKind <+>
"binding," <+> pretty nm <+> case loc of
F f -> "in function" <+> pretty (name f)
S (Struct sname _) -> "in struct" <+> pretty sname
Toplevel -> mempty
UndefinedSymbol nm symKind expr ->
"Undefined" <+> pretty symKind <+> pretty nm <+>
"referenced in:" <> hardline <> pretty expr
TypeError expected got stmt ->
"Type error: expected one of" <+> pretty expected <+> "but got"
<+> pretty got <> ". Error occured in statement:" <> hardline <> pretty stmt
CastError to from stmt ->
"Cast error: can only cast between pointers, from ints to floats, or between pointers and ints, not from" <+> pretty from <+> "to" <+> pretty to <> ". Error occured in statement:" <> hardline <> pretty stmt
ArgError nExpected nGot callSite ->
"Argument error: function expected" <+> pretty nExpected <+>
"arguments, but was called with" <+> pretty nGot <+> "arguments"
<> ". Error occured in call:" <> hardline <> pretty callSite
Redeclaration name -> "Error: redeclaration of function" <+> pretty name
NoMain -> "Error: main function not defined"
AssignmentError lhs rhs ->
"Cannot assign" <+> pretty rhs <+> "to" <+> pretty lhs
AddressError e ->
"Cannot take address of" <> pretty e
AccessError struct field ->
"Cannot access" <+> pretty struct <+> "with" <+> pretty field
DeadCode stmt ->
"Error: nothing may follow a return. Error occured in statement:" <>
hardline <> pretty stmt
| null | https://raw.githubusercontent.com/jmorag/mcc/d412eec5e3783873ad42b74b837ed0f1047c2fde/src/Microc/Semant/Error.hs | haskell | ^ For statements in a block following a return | module Microc.Semant.Error where
import Microc.Ast
import Data.Text ( Text )
import Data.Text.Prettyprint.Doc
type Name = Text
data BindingLoc = F Function | S Struct | Toplevel deriving Show
data SemantError =
IllegalBinding Name BindingKind VarKind BindingLoc
| UndefinedSymbol Name SymbolKind Expr
| TypeError { expected :: [Type], got :: Type, errorLoc :: Statement }
| CastError { to :: Type, from :: Type, castLoc :: Statement }
| ArgError { nExpected :: Int, nGot :: Int, callSite :: Expr }
| Redeclaration Name
| NoMain
| AddressError Expr
| AssignmentError { lhs :: Expr, rhs :: Expr }
| AccessError { struct :: Expr, field :: Expr }
deriving (Show)
data BindingKind = Duplicate | Void deriving (Show)
data SymbolKind = Var | Func deriving (Show)
data VarKind = Global | Formal | Local | StructField deriving (Show, Eq, Ord)
instance Pretty VarKind where
pretty = unsafeViaShow
instance Pretty SymbolKind where
pretty = \case
Var -> "variable"
Func -> "function"
instance Pretty BindingKind where
pretty = unsafeViaShow
instance Pretty SemantError where
pretty = \case
IllegalBinding nm bindKind varKind loc ->
"Error: Illegal" <+> pretty bindKind <+> pretty varKind <+>
"binding," <+> pretty nm <+> case loc of
F f -> "in function" <+> pretty (name f)
S (Struct sname _) -> "in struct" <+> pretty sname
Toplevel -> mempty
UndefinedSymbol nm symKind expr ->
"Undefined" <+> pretty symKind <+> pretty nm <+>
"referenced in:" <> hardline <> pretty expr
TypeError expected got stmt ->
"Type error: expected one of" <+> pretty expected <+> "but got"
<+> pretty got <> ". Error occured in statement:" <> hardline <> pretty stmt
CastError to from stmt ->
"Cast error: can only cast between pointers, from ints to floats, or between pointers and ints, not from" <+> pretty from <+> "to" <+> pretty to <> ". Error occured in statement:" <> hardline <> pretty stmt
ArgError nExpected nGot callSite ->
"Argument error: function expected" <+> pretty nExpected <+>
"arguments, but was called with" <+> pretty nGot <+> "arguments"
<> ". Error occured in call:" <> hardline <> pretty callSite
Redeclaration name -> "Error: redeclaration of function" <+> pretty name
NoMain -> "Error: main function not defined"
AssignmentError lhs rhs ->
"Cannot assign" <+> pretty rhs <+> "to" <+> pretty lhs
AddressError e ->
"Cannot take address of" <> pretty e
AccessError struct field ->
"Cannot access" <+> pretty struct <+> "with" <+> pretty field
DeadCode stmt ->
"Error: nothing may follow a return. Error occured in statement:" <>
hardline <> pretty stmt
|
dd01c74db0d0009e9c847b0a397009b24b58688352e21f5f3e7f9a02ea7dc831 | morphismtech/free-categories | Functor.hs | |
Module : Data . Quiver . Functor
Description : free categories
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
Consider the category of Haskell quivers with
* objects are types of higher kind
* @p : : k - > k - > Type@
* morphisms are terms of @RankNType@ ,
* @forall x y. p x y - > q x y@
* identity is ` i d `
* composition is ` . `
There is a natural hierarchy of typeclasses for
endofunctors of the category of Haskell quivers ,
analagous to that for types .
Module: Data.Quiver.Functor
Description: free categories
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
Consider the category of Haskell quivers with
* objects are types of higher kind
* @p :: k -> k -> Type@
* morphisms are terms of @RankNType@,
* @forall x y. p x y -> q x y@
* identity is `id`
* composition is `.`
There is a natural hierarchy of typeclasses for
endofunctors of the category of Haskell quivers,
analagous to that for Haskell types.
-}
# LANGUAGE
PolyKinds
, RankNTypes
#
PolyKinds
, RankNTypes
#-}
module Data.Quiver.Functor
( QFunctor (..)
, QPointed (..)
, QFoldable (..)
, QTraversable (..)
, QMonad (..)
) where
import Control.Category
import Data.Quiver
import Prelude hiding (id, (.))
| An endfunctor of quivers .
prop > qmap i d = i d
prop > qmap ( g . f ) = .
prop> qmap id = id
prop> qmap (g . f) = qmap g . qmap f
-}
class QFunctor c where
qmap :: (forall x y. p x y -> q x y) -> c p x y -> c q x y
instance QFunctor (ProductQ p) where qmap f (ProductQ p q) = ProductQ p (f q)
instance QFunctor (HomQ p) where qmap g (HomQ f) = HomQ (g . f)
instance Functor t => QFunctor (ApQ t) where qmap f (ApQ t) = ApQ (f <$> t)
instance QFunctor OpQ where qmap f = OpQ . f . getOpQ
instance QFunctor IsoQ where qmap f (IsoQ u d) = IsoQ (f u) (f d)
instance QFunctor IQ where qmap f = IQ . f . getIQ
instance QFunctor (ComposeQ p) where qmap f (ComposeQ p q) = ComposeQ p (f q)
instance QFunctor (LeftQ p) where qmap g (LeftQ f) = LeftQ (g . f)
instance QFunctor (RightQ p) where qmap g (RightQ f) = RightQ (g . f)
| Embed a single quiver arrow with ` qsingle ` .
class QFunctor c => QPointed c where qsingle :: p x y -> c p x y
instance QPointed (HomQ p) where qsingle q = HomQ (const q)
instance Applicative t => QPointed (ApQ t) where qsingle = ApQ . pure
instance QPointed IQ where qsingle = IQ
instance Category p => QPointed (ComposeQ p) where qsingle = ComposeQ id
| Generalizing ` Foldable ` from ` Monoid`s to ` Category`s .
prop > qmap f = qfoldMap ( qsingle . f )
prop> qmap f = qfoldMap (qsingle . f)
-}
class QFunctor c => QFoldable c where
{- | Map each element of the structure to a `Category`,
and combine the results.-}
qfoldMap :: Category q => (forall x y. p x y -> q x y) -> c p x y -> q x y
{- | Combine the elements of a structure using a `Category`.-}
qfold :: Category q => c q x y -> q x y
qfold = qfoldMap id
| Right - associative fold of a structure .
In the case of ` Control . Category . Free . Path`s ,
` qfoldr ` , when applied to a binary operator ,
a starting value , and a ` Control . Category . Free . Path ` ,
reduces the ` Control . Category . Free . Path ` using the binary operator ,
from right to left :
prop ( ? ) q ( p1 :> > p2 :> > ... :> > pn :> > Done ) = = p1 ? ( p2 ? ... ( pn ? q ) ... )
In the case of `Control.Category.Free.Path`s,
`qfoldr`, when applied to a binary operator,
a starting value, and a `Control.Category.Free.Path`,
reduces the `Control.Category.Free.Path` using the binary operator,
from right to left:
prop> qfoldr (?) q (p1 :>> p2 :>> ... :>> pn :>> Done) == p1 ? (p2 ? ... (pn ? q) ...)
-}
qfoldr :: (forall x y z . p x y -> q y z -> q x z) -> q y z -> c p x y -> q x z
qfoldr (?) q c = getRightQ (qfoldMap (\ x -> RightQ (\ y -> x ? y)) c) q
| Left - associative fold of a structure .
In the case of ` Control . Category . Free . Path`s ,
` qfoldl ` , when applied to a binary operator ,
a starting value , and a ` Control . Category . Free . Path ` ,
reduces the ` Control . Category . Free . Path ` using the binary operator ,
from left to right :
prop ( ? ) q ( p1 :> > p2 :> > ... :> > pn :> > Done ) = = ( ... ( ( q ? p1 ) ? p2 ) ? ... ) ? pn
In the case of `Control.Category.Free.Path`s,
`qfoldl`, when applied to a binary operator,
a starting value, and a `Control.Category.Free.Path`,
reduces the `Control.Category.Free.Path` using the binary operator,
from left to right:
prop> qfoldl (?) q (p1 :>> p2 :>> ... :>> pn :>> Done) == (... ((q ? p1) ? p2) ? ...) ? pn
-}
qfoldl :: (forall x y z . q x y -> p y z -> q x z) -> q x y -> c p y z -> q x z
qfoldl (?) q c = getLeftQ (qfoldMap (\ x -> LeftQ (\ y -> y ? x)) c) q
{- | Map each element of the structure to a `Monoid`,
and combine the results.-}
qtoMonoid :: Monoid m => (forall x y. p x y -> m) -> c p x y -> m
qtoMonoid f = getKQ . qfoldMap (KQ . f)
{- | Map each element of the structure, and combine the results in a list.-}
qtoList :: (forall x y. p x y -> a) -> c p x y -> [a]
qtoList f = qtoMonoid (pure . f)
{- | Map each element of a structure to an `Applicative` on a `Category`,
evaluate from left to right, and combine the results.-}
qtraverse_
:: (Applicative m, Category q)
=> (forall x y. p x y -> m (q x y)) -> c p x y -> m (q x y)
qtraverse_ f = getApQ . qfoldMap (ApQ . f)
instance QFoldable (ProductQ p) where qfoldMap f (ProductQ _ q) = f q
instance QFoldable IQ where qfoldMap f (IQ c) = f c
| Generalizing ` ` to quivers .
class QFoldable c => QTraversable c where
{- | Map each element of a structure to an `Applicative` on a quiver,
evaluate from left to right, and collect the results.-}
qtraverse
:: Applicative m
=> (forall x y. p x y -> m (q x y)) -> c p x y -> m (c q x y)
instance QTraversable (ProductQ p) where
qtraverse f (ProductQ p q) = ProductQ p <$> f q
instance QTraversable IQ where qtraverse f (IQ c) = IQ <$> f c
| ` Monad ` to quivers .
Associativity and left and right identity laws hold .
prop > qjoin . qjoin = qjoin . > qjoin . = i d
prop > qjoin . qmap qsingle = i d
The functions ` qbind ` and are related as
prop i d
prop > qbind f p = qjoin ( qmap f p )
Associativity and left and right identity laws hold.
prop> qjoin . qjoin = qjoin . qmap qjoin
prop> qjoin . qsingle = id
prop> qjoin . qmap qsingle = id
The functions `qbind` and `qjoin` are related as
prop> qjoin = qbind id
prop> qbind f p = qjoin (qmap f p)
-}
class (QFunctor c, QPointed c) => QMonad c where
qjoin :: c (c p) x y -> c p x y
qjoin = qbind id
qbind :: (forall x y. p x y -> c q x y) -> c p x y -> c q x y
qbind f p = qjoin (qmap f p)
# MINIMAL qjoin | qbind #
instance QMonad (HomQ p) where
qjoin (HomQ q) = HomQ (\p -> getHomQ (q p) p)
instance Monad t => QMonad (ApQ t) where
qbind f (ApQ t) = ApQ $ do
p <- t
getApQ $ f p
instance QMonad IQ where qjoin = getIQ
instance Category p => QMonad (ComposeQ p) where
qjoin (ComposeQ yz (ComposeQ xy q)) = ComposeQ (yz . xy) q
| null | https://raw.githubusercontent.com/morphismtech/free-categories/d63837e43d5358fcfb2f7afc6b3a32a7f500912b/src/Data/Quiver/Functor.hs | haskell | | Map each element of the structure to a `Category`,
and combine the results.
| Combine the elements of a structure using a `Category`.
| Map each element of the structure to a `Monoid`,
and combine the results.
| Map each element of the structure, and combine the results in a list.
| Map each element of a structure to an `Applicative` on a `Category`,
evaluate from left to right, and combine the results.
| Map each element of a structure to an `Applicative` on a quiver,
evaluate from left to right, and collect the results. | |
Module : Data . Quiver . Functor
Description : free categories
Copyright : ( c ) , 2019
Maintainer :
Stability : experimental
Consider the category of Haskell quivers with
* objects are types of higher kind
* @p : : k - > k - > Type@
* morphisms are terms of @RankNType@ ,
* @forall x y. p x y - > q x y@
* identity is ` i d `
* composition is ` . `
There is a natural hierarchy of typeclasses for
endofunctors of the category of Haskell quivers ,
analagous to that for types .
Module: Data.Quiver.Functor
Description: free categories
Copyright: (c) Eitan Chatav, 2019
Maintainer:
Stability: experimental
Consider the category of Haskell quivers with
* objects are types of higher kind
* @p :: k -> k -> Type@
* morphisms are terms of @RankNType@,
* @forall x y. p x y -> q x y@
* identity is `id`
* composition is `.`
There is a natural hierarchy of typeclasses for
endofunctors of the category of Haskell quivers,
analagous to that for Haskell types.
-}
# LANGUAGE
PolyKinds
, RankNTypes
#
PolyKinds
, RankNTypes
#-}
module Data.Quiver.Functor
( QFunctor (..)
, QPointed (..)
, QFoldable (..)
, QTraversable (..)
, QMonad (..)
) where
import Control.Category
import Data.Quiver
import Prelude hiding (id, (.))
| An endfunctor of quivers .
prop > qmap i d = i d
prop > qmap ( g . f ) = .
prop> qmap id = id
prop> qmap (g . f) = qmap g . qmap f
-}
class QFunctor c where
qmap :: (forall x y. p x y -> q x y) -> c p x y -> c q x y
instance QFunctor (ProductQ p) where qmap f (ProductQ p q) = ProductQ p (f q)
instance QFunctor (HomQ p) where qmap g (HomQ f) = HomQ (g . f)
instance Functor t => QFunctor (ApQ t) where qmap f (ApQ t) = ApQ (f <$> t)
instance QFunctor OpQ where qmap f = OpQ . f . getOpQ
instance QFunctor IsoQ where qmap f (IsoQ u d) = IsoQ (f u) (f d)
instance QFunctor IQ where qmap f = IQ . f . getIQ
instance QFunctor (ComposeQ p) where qmap f (ComposeQ p q) = ComposeQ p (f q)
instance QFunctor (LeftQ p) where qmap g (LeftQ f) = LeftQ (g . f)
instance QFunctor (RightQ p) where qmap g (RightQ f) = RightQ (g . f)
| Embed a single quiver arrow with ` qsingle ` .
class QFunctor c => QPointed c where qsingle :: p x y -> c p x y
instance QPointed (HomQ p) where qsingle q = HomQ (const q)
instance Applicative t => QPointed (ApQ t) where qsingle = ApQ . pure
instance QPointed IQ where qsingle = IQ
instance Category p => QPointed (ComposeQ p) where qsingle = ComposeQ id
| Generalizing ` Foldable ` from ` Monoid`s to ` Category`s .
prop > qmap f = qfoldMap ( qsingle . f )
prop> qmap f = qfoldMap (qsingle . f)
-}
class QFunctor c => QFoldable c where
qfoldMap :: Category q => (forall x y. p x y -> q x y) -> c p x y -> q x y
qfold :: Category q => c q x y -> q x y
qfold = qfoldMap id
| Right - associative fold of a structure .
In the case of ` Control . Category . Free . Path`s ,
` qfoldr ` , when applied to a binary operator ,
a starting value , and a ` Control . Category . Free . Path ` ,
reduces the ` Control . Category . Free . Path ` using the binary operator ,
from right to left :
prop ( ? ) q ( p1 :> > p2 :> > ... :> > pn :> > Done ) = = p1 ? ( p2 ? ... ( pn ? q ) ... )
In the case of `Control.Category.Free.Path`s,
`qfoldr`, when applied to a binary operator,
a starting value, and a `Control.Category.Free.Path`,
reduces the `Control.Category.Free.Path` using the binary operator,
from right to left:
prop> qfoldr (?) q (p1 :>> p2 :>> ... :>> pn :>> Done) == p1 ? (p2 ? ... (pn ? q) ...)
-}
qfoldr :: (forall x y z . p x y -> q y z -> q x z) -> q y z -> c p x y -> q x z
qfoldr (?) q c = getRightQ (qfoldMap (\ x -> RightQ (\ y -> x ? y)) c) q
| Left - associative fold of a structure .
In the case of ` Control . Category . Free . Path`s ,
` qfoldl ` , when applied to a binary operator ,
a starting value , and a ` Control . Category . Free . Path ` ,
reduces the ` Control . Category . Free . Path ` using the binary operator ,
from left to right :
prop ( ? ) q ( p1 :> > p2 :> > ... :> > pn :> > Done ) = = ( ... ( ( q ? p1 ) ? p2 ) ? ... ) ? pn
In the case of `Control.Category.Free.Path`s,
`qfoldl`, when applied to a binary operator,
a starting value, and a `Control.Category.Free.Path`,
reduces the `Control.Category.Free.Path` using the binary operator,
from left to right:
prop> qfoldl (?) q (p1 :>> p2 :>> ... :>> pn :>> Done) == (... ((q ? p1) ? p2) ? ...) ? pn
-}
qfoldl :: (forall x y z . q x y -> p y z -> q x z) -> q x y -> c p y z -> q x z
qfoldl (?) q c = getLeftQ (qfoldMap (\ x -> LeftQ (\ y -> y ? x)) c) q
qtoMonoid :: Monoid m => (forall x y. p x y -> m) -> c p x y -> m
qtoMonoid f = getKQ . qfoldMap (KQ . f)
qtoList :: (forall x y. p x y -> a) -> c p x y -> [a]
qtoList f = qtoMonoid (pure . f)
qtraverse_
:: (Applicative m, Category q)
=> (forall x y. p x y -> m (q x y)) -> c p x y -> m (q x y)
qtraverse_ f = getApQ . qfoldMap (ApQ . f)
instance QFoldable (ProductQ p) where qfoldMap f (ProductQ _ q) = f q
instance QFoldable IQ where qfoldMap f (IQ c) = f c
| Generalizing ` ` to quivers .
class QFoldable c => QTraversable c where
qtraverse
:: Applicative m
=> (forall x y. p x y -> m (q x y)) -> c p x y -> m (c q x y)
instance QTraversable (ProductQ p) where
qtraverse f (ProductQ p q) = ProductQ p <$> f q
instance QTraversable IQ where qtraverse f (IQ c) = IQ <$> f c
| ` Monad ` to quivers .
Associativity and left and right identity laws hold .
prop > qjoin . qjoin = qjoin . > qjoin . = i d
prop > qjoin . qmap qsingle = i d
The functions ` qbind ` and are related as
prop i d
prop > qbind f p = qjoin ( qmap f p )
Associativity and left and right identity laws hold.
prop> qjoin . qjoin = qjoin . qmap qjoin
prop> qjoin . qsingle = id
prop> qjoin . qmap qsingle = id
The functions `qbind` and `qjoin` are related as
prop> qjoin = qbind id
prop> qbind f p = qjoin (qmap f p)
-}
class (QFunctor c, QPointed c) => QMonad c where
qjoin :: c (c p) x y -> c p x y
qjoin = qbind id
qbind :: (forall x y. p x y -> c q x y) -> c p x y -> c q x y
qbind f p = qjoin (qmap f p)
# MINIMAL qjoin | qbind #
instance QMonad (HomQ p) where
qjoin (HomQ q) = HomQ (\p -> getHomQ (q p) p)
instance Monad t => QMonad (ApQ t) where
qbind f (ApQ t) = ApQ $ do
p <- t
getApQ $ f p
instance QMonad IQ where qjoin = getIQ
instance Category p => QMonad (ComposeQ p) where
qjoin (ComposeQ yz (ComposeQ xy q)) = ComposeQ (yz . xy) q
|
b1f0e845571c2dccd6801b06562889e6fe1d4a825ed495fabedfd8a0803dca23 | Leystryku/mpbomberman_racket | bomberman_server.rkt | #lang racket
;; import
(require 2htdp/universe)
(require "game/sv_network_waiting.rkt")
(require "game/sv_network_ingame.rkt")
(require "game/sv_connect.rkt")
(require "game/sv_disconnect.rkt")
(require "game/sh_structs.rkt")
(require "game/sv_tick.rkt")
(require "game/sh_config.rkt")
;; exports
(provide launch-server)
;; [message] is called whenever we receive a message f rom a client
(define (message currentWorld connection msg)
(if (worldWaitingForPlayers currentWorld)
(messageWaiting currentWorld connection msg)
(messageIngame currentWorld connection msg)
)
)
;;[launch-server] calls universe to create the server
(define (launch-server)
(universe (serversideWorld '() #t (+ (current-seconds) (* 60 5)) "" '() '() 0)
(on-new connect-client)
(on-disconnect disconnect-client)
(on-msg message)
(on-tick gameTick (/ 1 gameServerFPS))
)
)
;;[launch-server] calls universe to create the server with port
(define (launch-server-withport ourport)
(universe (serversideWorld '() #t (+ (current-seconds) (* 60 5)) "" '() '() 0)
(on-new connect-client)
(on-disconnect disconnect-client)
(on-msg message)
(port ourport)
(on-tick gameTick (/ 1 gameServerFPS))
)
)
(define (launch-server-cmdline)
(define cmdline (current-command-line-arguments))
(if (vector-empty? cmdline)
(and
(println "Launching server for local playing")
(launch-server)
)
(and
(println "Launching server with port")
(println (vector-ref cmdline 0))
(launch-server-withport (string->number (vector-ref cmdline 0)))
)
)
)
;(launch-server-cmdline)
( launch - server - withport 27015 ) | null | https://raw.githubusercontent.com/Leystryku/mpbomberman_racket/059d95040cfad2e27237f8dd41fc32a4fc698afe/bomberman_server.rkt | racket | import
exports
[message] is called whenever we receive a message f rom a client
[launch-server] calls universe to create the server
[launch-server] calls universe to create the server with port
(launch-server-cmdline) | #lang racket
(require 2htdp/universe)
(require "game/sv_network_waiting.rkt")
(require "game/sv_network_ingame.rkt")
(require "game/sv_connect.rkt")
(require "game/sv_disconnect.rkt")
(require "game/sh_structs.rkt")
(require "game/sv_tick.rkt")
(require "game/sh_config.rkt")
(provide launch-server)
(define (message currentWorld connection msg)
(if (worldWaitingForPlayers currentWorld)
(messageWaiting currentWorld connection msg)
(messageIngame currentWorld connection msg)
)
)
(define (launch-server)
(universe (serversideWorld '() #t (+ (current-seconds) (* 60 5)) "" '() '() 0)
(on-new connect-client)
(on-disconnect disconnect-client)
(on-msg message)
(on-tick gameTick (/ 1 gameServerFPS))
)
)
(define (launch-server-withport ourport)
(universe (serversideWorld '() #t (+ (current-seconds) (* 60 5)) "" '() '() 0)
(on-new connect-client)
(on-disconnect disconnect-client)
(on-msg message)
(port ourport)
(on-tick gameTick (/ 1 gameServerFPS))
)
)
(define (launch-server-cmdline)
(define cmdline (current-command-line-arguments))
(if (vector-empty? cmdline)
(and
(println "Launching server for local playing")
(launch-server)
)
(and
(println "Launching server with port")
(println (vector-ref cmdline 0))
(launch-server-withport (string->number (vector-ref cmdline 0)))
)
)
)
( launch - server - withport 27015 ) |
1499b34e17dca2c5bda425da982ad92e1f04637c83136ac5f501f7239232c7a3 | mstksg/advent-of-code-2017 | Day22.hs | module AOC2017.Day22 (day22a, day22b) where
import AOC2017.Types (Challenge)
import Control.Lens (makeClassy, use, at, non, zoom, (+=), (<<>=))
import Control.Monad (replicateM)
import Control.Monad.Trans.State (State, state, evalState)
import qualified Data.Map as M
import qualified Linear as L
data Flag = FC | FW | FI | FF
deriving Eq
data Dir = N | E | S | W
deriving Enum
instance Monoid Dir where
mempty = N
mappend h t = toEnum $ (fromEnum h + fromEnum t) `mod` 4
data St = MkSt { _sWorld :: !(M.Map (L.V2 Int) Flag)
, _sPos :: !(L.V2 Int)
, _sDir :: !Dir
}
makeClassy ''St
delta :: Dir -> L.V2 Int
delta = \case
N -> L.V2 0 1
E -> L.V2 1 0
S -> L.V2 0 (-1)
W -> L.V2 (-1) 0
-- | Lift a 'State Flag Dir' (modify a Flag and produce a direction change)
-- to a 'State St Flag' (modify the simulation state and produce the
-- updated Flag)
step
:: State Flag Dir -- ^ Modify a Flag and produce a direction change
-> State St Flag -- ^ Modify the state and produce the updated Flag
step stF = do
p <- use sPos
turn <- zoom (sWorld . at p . non FC) stF
newDir <- sDir <<>= turn
sPos += delta newDir
use (sWorld . at p . non FC)
day22 :: State Flag Dir -> Int -> M.Map (L.V2 Int) Flag -> Int
day22 stF n w0 = length . filter (== FI)
$ evalState (replicateM n (step stF)) st0
where
st0 = MkSt w0 p0 N
p0 = (`div` 2) <$> fst (M.findMax w0)
day22a :: Challenge
day22a = show . day22 partA 1e4 . parse
where
partA :: State Flag Dir
partA = state $ \case
FC -> (W, FI) -- turn left, become Infected
FI -> (E, FC) -- turn right, become Clean
_ -> error "Shouldn't happen"
day22b :: Challenge
day22b = show . day22 partB 1e7 . parse
where
partB :: State Flag Dir
partB = state $ \case
FC -> (W, FW) -- turn left, become Weakened
FW -> (N, FI) -- no turn, become Infected
FI -> (E, FF) -- turn right, become Flagged
FF -> (S, FC) -- turn around, become Clean
parse :: String -> M.Map (L.V2 Int) Flag
parse = M.unions . zipWith mkRow [0..] . reverse . lines
where
fl = \case '#' -> FI
_ -> FC
mkRow y = M.fromList . zip ixes . map fl
where
ixes = [ L.V2 x y | x <- [0..] ]
| null | https://raw.githubusercontent.com/mstksg/advent-of-code-2017/f9e97680726e87be175cf423241da3048ef6564d/src/AOC2017/Day22.hs | haskell | | Lift a 'State Flag Dir' (modify a Flag and produce a direction change)
to a 'State St Flag' (modify the simulation state and produce the
updated Flag)
^ Modify a Flag and produce a direction change
^ Modify the state and produce the updated Flag
turn left, become Infected
turn right, become Clean
turn left, become Weakened
no turn, become Infected
turn right, become Flagged
turn around, become Clean | module AOC2017.Day22 (day22a, day22b) where
import AOC2017.Types (Challenge)
import Control.Lens (makeClassy, use, at, non, zoom, (+=), (<<>=))
import Control.Monad (replicateM)
import Control.Monad.Trans.State (State, state, evalState)
import qualified Data.Map as M
import qualified Linear as L
data Flag = FC | FW | FI | FF
deriving Eq
data Dir = N | E | S | W
deriving Enum
instance Monoid Dir where
mempty = N
mappend h t = toEnum $ (fromEnum h + fromEnum t) `mod` 4
data St = MkSt { _sWorld :: !(M.Map (L.V2 Int) Flag)
, _sPos :: !(L.V2 Int)
, _sDir :: !Dir
}
makeClassy ''St
delta :: Dir -> L.V2 Int
delta = \case
N -> L.V2 0 1
E -> L.V2 1 0
S -> L.V2 0 (-1)
W -> L.V2 (-1) 0
step
step stF = do
p <- use sPos
turn <- zoom (sWorld . at p . non FC) stF
newDir <- sDir <<>= turn
sPos += delta newDir
use (sWorld . at p . non FC)
day22 :: State Flag Dir -> Int -> M.Map (L.V2 Int) Flag -> Int
day22 stF n w0 = length . filter (== FI)
$ evalState (replicateM n (step stF)) st0
where
st0 = MkSt w0 p0 N
p0 = (`div` 2) <$> fst (M.findMax w0)
day22a :: Challenge
day22a = show . day22 partA 1e4 . parse
where
partA :: State Flag Dir
partA = state $ \case
_ -> error "Shouldn't happen"
day22b :: Challenge
day22b = show . day22 partB 1e7 . parse
where
partB :: State Flag Dir
partB = state $ \case
parse :: String -> M.Map (L.V2 Int) Flag
parse = M.unions . zipWith mkRow [0..] . reverse . lines
where
fl = \case '#' -> FI
_ -> FC
mkRow y = M.fromList . zip ixes . map fl
where
ixes = [ L.V2 x y | x <- [0..] ]
|
a28bf26d0a1b551aac1fe10df754ca43cca85c4262970c0f8b91f3ea245a2706 | svobot/janus | Evaluation.hs | -- | Implements the algorithm for evaluation of terms and defines a data type
-- ('Value') for representing an evaluated term using a higher-order syntax.
module Janus.Evaluation
( Type
, ValueEnv
, Value
( VAPair
, VAPairType
, VAUnit
, VAUnitType
, VLam
, VMPair
, VMPairType
, VMUnit
, VMUnitType
, VPi
, VSumL
, VSumR
, VSumType
, VUniverse
)
, cEval
, iEval
, vfree
, quote0
, -- * Utils
BoundEnv
) where
import Data.Bifunctor ( second )
import Janus.Semiring
import Janus.Syntax
-- | A term that has been beta-reduced to its normal form.
data Value
= VUniverse
| VNeutral Neutral
| VLam BindingName (Value -> Value)
| VPi ZeroOneMany BindingName Value (Value -> Value)
| VMPair Value Value
| VMPairType ZeroOneMany BindingName Value (Value -> Value)
| VMUnit
| VMUnitType
| VAPair Value Value
| VAPairType BindingName Value (Value -> Value)
| VAUnit
| VAUnitType
| VSumL Value
| VSumR Value
| VSumType Value Value
instance Show Value where
show = show . quote0
-- | A term whose further beta-reduction depends on a variable.
data Neutral
= NFree Name
| NApp Neutral Value
| NMPairElim
ZeroOneMany
BindingName
BindingName
BindingName
Neutral
(Value -> Value -> Value)
(Value -> Value)
| NMUnitElim
ZeroOneMany
BindingName
Neutral
Value
(Value -> Value)
| NFst Neutral
| NSnd Neutral
| NSumElim
ZeroOneMany
BindingName
Neutral
BindingName
(Value -> Value)
BindingName
(Value -> Value)
(Value -> Value)
type Type = Value
-- | List of values defined by the /let/ statement.
type ValueEnv = [(Name, Value)]
-- | List of values of the bound variables that are in scope.
--
-- This is an implementation detail of the evaluation functions and should
-- always start off empty.
type BoundEnv = [Value]
-- | Creates the 'Value' corresponding to a free variable.
vfree :: Name -> Value
vfree = VNeutral . NFree
-- | Evaluate a type-checkable term in a given environment.
--
Environment is a pair in which first element contains values of global variables
and second element contains values of local variables .
cEval :: (ValueEnv, BoundEnv) -> CTerm -> Value
cEval ctx (Inf ii ) = iEval ctx ii
cEval ctx (Lam n c) = VLam n (\x -> cEval (second (x :) ctx) c)
cEval _ Universe = VUniverse
cEval ctx (Pi p n ty ty') =
VPi p n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval ctx (MPair c c') = VMPair (cEval ctx c) (cEval ctx c')
cEval ctx (MPairType p n ty ty') =
VMPairType p n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval _ MUnit = VMUnit
cEval _ MUnitType = VMUnitType
cEval ctx (APair c c') = VAPair (cEval ctx c) (cEval ctx c')
cEval ctx (APairType n ty ty') =
VAPairType n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval _ AUnit = VAUnit
cEval _ AUnitType = VAUnitType
cEval ctx (SumL c ) = VSumL (cEval ctx c)
cEval ctx (SumR c ) = VSumR (cEval ctx c)
cEval ctx (SumType c c') = VSumType (cEval ctx c) (cEval ctx c')
-- | Evaluate a type-synthesising term in a given environment.
--
Environment is a pair in which first element contains values of global variables
and second element contains values of local variables .
iEval :: (ValueEnv, BoundEnv) -> ITerm -> Value
iEval ctx (Ann c _) = cEval ctx c
iEval ctx (Free x ) = case lookup x (fst ctx) of
Nothing -> vfree x
Just v -> v
iEval ctx (Bound ii) = snd ctx !! ii
iEval ctx (i :$: c ) = case iEval ctx i of
VLam _ f -> f val
VNeutral n -> VNeutral $ NApp n val
v -> error
("internal: Unable to apply " <> show v <> " to the value " <> show val)
where val = cEval ctx c
iEval ctx (MPairElim p zName xName yName i c c') = case iEval ctx i of
VMPair x y -> cEval (second ([y, x] ++) ctx) c
VNeutral n -> VNeutral $ NMPairElim
p
zName
xName
yName
n
(\x y -> cEval (second ([y, x] ++) ctx) c)
(\z -> cEval (second (z :) ctx) c')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (MUnitElim p xName i c c') = case iEval ctx i of
VMUnit -> cEval ctx c
VNeutral n -> VNeutral
$ NMUnitElim p xName n (cEval ctx c) (\x -> cEval (second (x :) ctx) c')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a unit")
iEval ctx (Fst i) = case iEval ctx i of
VAPair x _ -> x
VNeutral n -> VNeutral $ NFst n
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (Snd i) = case iEval ctx i of
VAPair _ y -> y
VNeutral n -> VNeutral $ NSnd n
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (SumElim p zName i xName c yName c' c'') = case iEval ctx i of
VSumL x -> cEval (second (x :) ctx) c
VSumR y -> cEval (second (y :) ctx) c'
VNeutral n -> VNeutral $ NSumElim p
zName
n
xName
(\x -> cEval (second (x :) ctx) c)
yName
(\y -> cEval (second (y :) ctx) c')
(\z -> cEval (second (z :) ctx) c'')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a sum")
-- | Convert a value to a term.
--
-- This conversion is necessary because 'Value' uses higher-order abstract
syntax , i.e. functions , to represent data members , so to show or
equate them they are first converted to terms .
quote0 :: Value -> CTerm
quote0 = quote 0
quote :: Int -> Value -> CTerm
quote ii (VLam x t) = Lam x $ quote (ii + 1) (t $ quoteArg ii)
quote _ VUniverse = Universe
quote ii (VPi p x v f) = Pi p x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote ii (VNeutral n ) = Inf $ neutralQuote ii n
quote ii (VMPair v v') = MPair (quote ii v) (quote ii v')
quote ii (VMPairType p x v f) =
MPairType p x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote _ VMUnit = MUnit
quote _ VMUnitType = MUnitType
quote ii (VAPair v v') = APair (quote ii v) (quote ii v')
quote ii (VAPairType x v f) =
APairType x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote _ VAUnit = AUnit
quote _ VAUnitType = AUnitType
quote ii (VSumL v ) = SumL $ quote ii v
quote ii (VSumR v ) = SumR $ quote ii v
quote ii (VSumType v v') = SumType (quote ii v) (quote ii v')
neutralQuote :: Int -> Neutral -> ITerm
neutralQuote ii (NFree (Quote k) ) = Bound $ (ii - k - 1) `max` 0
neutralQuote _ (NFree x ) = Free x
neutralQuote ii (NApp n v ) = neutralQuote ii n :$: quote ii v
neutralQuote ii (NMPairElim p z x y n v v') = MPairElim
p
z
x
y
(neutralQuote ii n)
(quote (ii + 2) $ v (quoteArg ii) (quoteArg $ ii + 1))
(quote (ii + 1) (v' $ quoteArg ii))
neutralQuote ii (NMUnitElim p x n v v') =
MUnitElim p x (neutralQuote ii n) (quote ii v)
$ quote (ii + 1) (v' $ quoteArg ii)
neutralQuote ii (NFst n ) = Fst $ neutralQuote ii n
neutralQuote ii (NSnd n ) = Snd $ neutralQuote ii n
neutralQuote ii (NSumElim p z n x v y v' v'') = SumElim
p
z
(neutralQuote ii n)
x
(quote (ii + 1) $ v (quoteArg $ ii + 1))
y
(quote (ii + 1) $ v' (quoteArg $ ii + 1))
(quote (ii + 1) $ v'' (quoteArg $ ii + 1))
quoteArg :: Int -> Value
quoteArg = vfree . Quote
| null | https://raw.githubusercontent.com/svobot/janus/68391b160903e967aa9c88d6b2f16b446fc7abee/src/Janus/Evaluation.hs | haskell | | Implements the algorithm for evaluation of terms and defines a data type
('Value') for representing an evaluated term using a higher-order syntax.
* Utils
| A term that has been beta-reduced to its normal form.
| A term whose further beta-reduction depends on a variable.
| List of values defined by the /let/ statement.
| List of values of the bound variables that are in scope.
This is an implementation detail of the evaluation functions and should
always start off empty.
| Creates the 'Value' corresponding to a free variable.
| Evaluate a type-checkable term in a given environment.
| Evaluate a type-synthesising term in a given environment.
| Convert a value to a term.
This conversion is necessary because 'Value' uses higher-order abstract | module Janus.Evaluation
( Type
, ValueEnv
, Value
( VAPair
, VAPairType
, VAUnit
, VAUnitType
, VLam
, VMPair
, VMPairType
, VMUnit
, VMUnitType
, VPi
, VSumL
, VSumR
, VSumType
, VUniverse
)
, cEval
, iEval
, vfree
, quote0
BoundEnv
) where
import Data.Bifunctor ( second )
import Janus.Semiring
import Janus.Syntax
data Value
= VUniverse
| VNeutral Neutral
| VLam BindingName (Value -> Value)
| VPi ZeroOneMany BindingName Value (Value -> Value)
| VMPair Value Value
| VMPairType ZeroOneMany BindingName Value (Value -> Value)
| VMUnit
| VMUnitType
| VAPair Value Value
| VAPairType BindingName Value (Value -> Value)
| VAUnit
| VAUnitType
| VSumL Value
| VSumR Value
| VSumType Value Value
instance Show Value where
show = show . quote0
data Neutral
= NFree Name
| NApp Neutral Value
| NMPairElim
ZeroOneMany
BindingName
BindingName
BindingName
Neutral
(Value -> Value -> Value)
(Value -> Value)
| NMUnitElim
ZeroOneMany
BindingName
Neutral
Value
(Value -> Value)
| NFst Neutral
| NSnd Neutral
| NSumElim
ZeroOneMany
BindingName
Neutral
BindingName
(Value -> Value)
BindingName
(Value -> Value)
(Value -> Value)
type Type = Value
type ValueEnv = [(Name, Value)]
type BoundEnv = [Value]
vfree :: Name -> Value
vfree = VNeutral . NFree
Environment is a pair in which first element contains values of global variables
and second element contains values of local variables .
cEval :: (ValueEnv, BoundEnv) -> CTerm -> Value
cEval ctx (Inf ii ) = iEval ctx ii
cEval ctx (Lam n c) = VLam n (\x -> cEval (second (x :) ctx) c)
cEval _ Universe = VUniverse
cEval ctx (Pi p n ty ty') =
VPi p n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval ctx (MPair c c') = VMPair (cEval ctx c) (cEval ctx c')
cEval ctx (MPairType p n ty ty') =
VMPairType p n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval _ MUnit = VMUnit
cEval _ MUnitType = VMUnitType
cEval ctx (APair c c') = VAPair (cEval ctx c) (cEval ctx c')
cEval ctx (APairType n ty ty') =
VAPairType n (cEval ctx ty) (\x -> cEval (second (x :) ctx) ty')
cEval _ AUnit = VAUnit
cEval _ AUnitType = VAUnitType
cEval ctx (SumL c ) = VSumL (cEval ctx c)
cEval ctx (SumR c ) = VSumR (cEval ctx c)
cEval ctx (SumType c c') = VSumType (cEval ctx c) (cEval ctx c')
Environment is a pair in which first element contains values of global variables
and second element contains values of local variables .
iEval :: (ValueEnv, BoundEnv) -> ITerm -> Value
iEval ctx (Ann c _) = cEval ctx c
iEval ctx (Free x ) = case lookup x (fst ctx) of
Nothing -> vfree x
Just v -> v
iEval ctx (Bound ii) = snd ctx !! ii
iEval ctx (i :$: c ) = case iEval ctx i of
VLam _ f -> f val
VNeutral n -> VNeutral $ NApp n val
v -> error
("internal: Unable to apply " <> show v <> " to the value " <> show val)
where val = cEval ctx c
iEval ctx (MPairElim p zName xName yName i c c') = case iEval ctx i of
VMPair x y -> cEval (second ([y, x] ++) ctx) c
VNeutral n -> VNeutral $ NMPairElim
p
zName
xName
yName
n
(\x y -> cEval (second ([y, x] ++) ctx) c)
(\z -> cEval (second (z :) ctx) c')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (MUnitElim p xName i c c') = case iEval ctx i of
VMUnit -> cEval ctx c
VNeutral n -> VNeutral
$ NMUnitElim p xName n (cEval ctx c) (\x -> cEval (second (x :) ctx) c')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a unit")
iEval ctx (Fst i) = case iEval ctx i of
VAPair x _ -> x
VNeutral n -> VNeutral $ NFst n
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (Snd i) = case iEval ctx i of
VAPair _ y -> y
VNeutral n -> VNeutral $ NSnd n
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a pair")
iEval ctx (SumElim p zName i xName c yName c' c'') = case iEval ctx i of
VSumL x -> cEval (second (x :) ctx) c
VSumR y -> cEval (second (y :) ctx) c'
VNeutral n -> VNeutral $ NSumElim p
zName
n
xName
(\x -> cEval (second (x :) ctx) c)
yName
(\y -> cEval (second (y :) ctx) c')
(\z -> cEval (second (z :) ctx) c'')
v -> error
("internal: Unable to eliminate " <> show v <> ", because it is not a sum")
syntax , i.e. functions , to represent data members , so to show or
equate them they are first converted to terms .
quote0 :: Value -> CTerm
quote0 = quote 0
quote :: Int -> Value -> CTerm
quote ii (VLam x t) = Lam x $ quote (ii + 1) (t $ quoteArg ii)
quote _ VUniverse = Universe
quote ii (VPi p x v f) = Pi p x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote ii (VNeutral n ) = Inf $ neutralQuote ii n
quote ii (VMPair v v') = MPair (quote ii v) (quote ii v')
quote ii (VMPairType p x v f) =
MPairType p x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote _ VMUnit = MUnit
quote _ VMUnitType = MUnitType
quote ii (VAPair v v') = APair (quote ii v) (quote ii v')
quote ii (VAPairType x v f) =
APairType x (quote ii v) $ quote (ii + 1) (f $ quoteArg ii)
quote _ VAUnit = AUnit
quote _ VAUnitType = AUnitType
quote ii (VSumL v ) = SumL $ quote ii v
quote ii (VSumR v ) = SumR $ quote ii v
quote ii (VSumType v v') = SumType (quote ii v) (quote ii v')
neutralQuote :: Int -> Neutral -> ITerm
neutralQuote ii (NFree (Quote k) ) = Bound $ (ii - k - 1) `max` 0
neutralQuote _ (NFree x ) = Free x
neutralQuote ii (NApp n v ) = neutralQuote ii n :$: quote ii v
neutralQuote ii (NMPairElim p z x y n v v') = MPairElim
p
z
x
y
(neutralQuote ii n)
(quote (ii + 2) $ v (quoteArg ii) (quoteArg $ ii + 1))
(quote (ii + 1) (v' $ quoteArg ii))
neutralQuote ii (NMUnitElim p x n v v') =
MUnitElim p x (neutralQuote ii n) (quote ii v)
$ quote (ii + 1) (v' $ quoteArg ii)
neutralQuote ii (NFst n ) = Fst $ neutralQuote ii n
neutralQuote ii (NSnd n ) = Snd $ neutralQuote ii n
neutralQuote ii (NSumElim p z n x v y v' v'') = SumElim
p
z
(neutralQuote ii n)
x
(quote (ii + 1) $ v (quoteArg $ ii + 1))
y
(quote (ii + 1) $ v' (quoteArg $ ii + 1))
(quote (ii + 1) $ v'' (quoteArg $ ii + 1))
quoteArg :: Int -> Value
quoteArg = vfree . Quote
|
c56f8328d1a2f816a2bdb68e680326cc1442be659cce2f892f4b896cf8c0ef58 | blockmason/lndr | Docs.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE TypeOperators #-}
# OPTIONS_GHC -fno - warn - orphans #
module Lndr.Docs where
import Data.Default
import Data.Maybe (fromJust)
import qualified Data.Map as M
import Data.Text (Text)
import Lndr.Types
import Network.Ethereum.Web3.Address
import Servant.API
import Servant.Docs
import Text.EmailAddress as Email
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LBS8
import qualified Data.Text.Lazy as LT
creditHash :: Text
creditHash = "0x7e2e9ff3a5fc148cf76261755c4c666630bfc3a28d02733cfbe721fc965aca28"
crSigned :: CreditRecord
crSigned = CreditRecord "0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
69
"test memo"
"0x11edd217a875063583dd1b638d16810c5d34d54b"
0
"0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
"0x718d7217a875063583dd1b638d16810c5d34d54b"
Nothing
Nothing
Nothing
crSettleSigned :: BilateralCreditRecord
crSettleSigned = BilateralCreditRecord crSigned "" "" (Just "0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c")
instance ToSample ConfigResponse where
toSamples _ = singleSample $
ConfigResponse (M.fromList [("USD", "0x7899b83071d9704af0b132859a04bb1698a3acaf")])
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
1000
def
5122553
instance ToSample SettlementsResponse where
toSamples _ = singleSample $ SettlementsResponse [crSigned] [crSettleSigned]
instance ToSample CreditRecord where
toSamples _ = singleSample crSigned
instance ToSample RejectRequest where
toSamples _ = singleSample $
RejectRequest "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
"0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
instance ToSample NickRequest where
toSamples _ = singleSample $
NickRequest "0x11edd217a875063583dd1b638d16810c5d34d54b" "aupiff" "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample EmailAddress where
toSamples _ = singleSample $
fromJust $ Email.emailAddressFromText ""
instance ToSample EmailRequest where
toSamples _ = singleSample $
EmailRequest "0x11edd217a875063583dd1b638d16810c5d34d54b" (fromJust $ Email.emailAddressFromText "") "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample UserInfo where
toSamples _ = singleSample $
UserInfo "0x11edd217a875063583dd1b638d16810c5d34d54b" (Just "aupiff")
instance ToSample PayPalRequest where
toSamples _ = singleSample $
PayPalRequest "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" "0x11edd217a875063583dd1b638d16810c5d34d54b" ""
instance ToSample PayPalRequestPair where
toSamples _ = singleSample $
PayPalRequestPair (UserInfo "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" (Just "Bob")) (UserInfo "0x11edd217a875063583dd1b638d16810c5d34d54b" (Just "Chuck"))
instance ToSample IssueCreditLog where
toSamples _ = singleSample $
IssueCreditLog "d5ec73eac35fc9dd6c3f440bce314779fed09f60"
"0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
69
0
"simple memo"
instance ToSample Address where
toSamples _ = singleSample "0x11edd217a875063583dd1b638d16810c5d34d54b"
instance ToSample VerifySettlementRequest where
toSamples _ = singleSample $
VerifySettlementRequest "0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
"0xf357c689de57464713697787d4c40a78feda913162911e191e545343ff769999"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample PushRequest where
toSamples _ = singleSample $
PushRequest "31279004-103e-4ba8-b4bf-65eb3eb81859" "ios"
"0x11edd217a875063583dd1b638d16810c5d34d54b" ""
instance ToSample IdentityAddress where
toSamples _ = singleSample $
IdentityAddress "street" "flatNumber" "town" "state" "postCode" "country"
instance ToSample IdentityDocument where
toSamples _ = singleSample $
IdentityDocument "idDocType" "country" (Just "file")
instance ToSample IdentityVerificationInfo where
toSamples _ = singleSample $
IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" []
instance ToSample RequiredIdentityDocuments where
toSamples _ = singleSample $
RequiredIdentityDocuments "country" []
instance ToSample IdentityDocumentType where
toSamples _ = singleSample $
IdentityDocumentType "idDocSetType" ["types"] (Just ["subTypes"])
instance ToSample IdentityVerificationRequest where
toSamples _ = singleSample $
IdentityVerificationRequest (fromJust $ Email.emailAddressFromText "")
"0x11edd217a875063583dd1b638d16810c5d34d54b"
(IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" [])
(RequiredIdentityDocuments "country" [] )
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
Nothing
instance ToSample IdentityStatusReview where
toSamples _ = singleSample $
IdentityStatusReview "reviewAnswer" "clientComment" (Just "moderationComment") (Just ["rejectLabels"]) (Just "reviewRejectType")
instance ToSample IdentityVerificationStatus where
toSamples _ = singleSample $
IdentityVerificationStatus "applicantId" "inspectionId" "correlationId" "jobId" "0x11edd217a875063583dd1b638d16810c5d34d54b" True (Just "details")
"_type" (IdentityStatusReview "reviewAnswer" "clientComment" (Just "moderationComment") (Just ["rejectLabels"]) (Just "reviewRejectType") )
instance ToSample LT.Text where
toSamples _ = singleSample $
"Hello"
instance ToSample VerificationStatusRequest where
toSamples _ = singleSample $
VerificationStatusRequest "0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample VerificationStatusEntry where
toSamples _ = singleSample $
VerificationStatusEntry "0x11edd217a875063583dd1b638d16810c5d34d54b" "bob" "Good"
instance ToSample IdentityVerificationResponse where
toSamples _ = singleSample $
IdentityVerificationResponse "id" "createdAt" "inspectionId" "clientId" "jobId" "0x11edd217a875063583dd1b638d16810c5d34d54b"
(IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" [])
(fromJust $ Email.emailAddressFromText "") "env"
(RequiredIdentityDocuments "country" [] )
instance ToSample VerificationMetaData where
toSamples _ = singleSample $
VerificationMetaData "PASSPORT" "USA"
instance ToSample ProfilePhotoRequest where
toSamples _ = singleSample $ ProfilePhotoRequest "2394" "239048"
instance ToSample Text where
toSamples _ = singleSample "aupiff"
instance ToSample Nonce where
toSamples _ = singleSample $ Nonce 1
instance ToSample Integer where
toSamples _ = singleSample 19
instance ToSample Int where
toSamples _ = singleSample 19
instance ToCapture (Capture "email" EmailAddress) where
toCapture _ =
DocCapture "email" "the email whose availability is being checked"
instance ToCapture (Capture "p1" Address) where
toCapture _ =
DocCapture "p1" "the address of the first party in a credit relationship"
instance ToCapture (Capture "p2" Address) where
toCapture _ =
DocCapture "p2" "the address of the second party in a credit relationship"
instance ToCapture (Capture "address" Address) where
toCapture _ =
DocCapture "address" "the address to which a nickname should be assigned"
instance ToCapture (Capture "user" Address) where
toCapture _ =
DocCapture "user" "the address of the user whose friends will be returned"
instance ToCapture (Capture "nick" Text) where
toCapture _ =
DocCapture "nick" "the nickname to be associated with a particular address"
instance ToCapture (Capture "email" Text) where
toCapture _ =
DocCapture "email" "the email to be associated with a particular address"
instance ToCapture (Capture "hash" Text) where
toCapture _ =
DocCapture "hash" "the hash by which to identify a credit record among candidates for resubmission"
instance ToParam (QueryParam "user" Address) where
toParam _ =
DocQueryParam "user"
[ "0x11edd217a875063583dd1b638d16810c5d34d54b"
, "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" ]
"address of user whose records to display"
Normal
instance ToParam (QueryParam "currency" Text) where
toParam _ =
DocQueryParam "currency"
[ "USD"
, "JPY" ]
"currency for which to query balance"
Normal
instance ToParam (QueryParam "txHash" Text) where
toParam _ =
DocQueryParam "txHash"
[ "0x3cb5a3890ca592a6e857f83413bef59dcc59c25445922dbcb3c5623563301639"
, "0x5c0dede3096ec95edaadc2cd258514ee837c45a55a71b05273837c123947ba0d" ]
"address of user whose records to display"
Normal
instance ToParam (QueryParam "email" EmailAddress) where
toParam _ =
DocQueryParam "email"
[ ""
, "" ]
"email whose corresponding user address is requested"
Normal
instance ToParam (QueryParam "nick" Nick) where
toParam _ =
DocQueryParam "nick"
[ "aupiff"
, "willbach" ]
"nickname whose corresponding user address is requested"
Normal
instance ToParam (QueryParam "digest" Nick) where
toParam _ =
DocQueryParam "digest"
[ "fgkjr54twrijt"
, "t4roiety34io3" ]
"digest value provided by SumSub to authenticate callback"
Normal
| null | https://raw.githubusercontent.com/blockmason/lndr/58fe5f82d5d057e463be23821454e3a0515ef9b9/lndr-backend/src/Lndr/Docs.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE TypeOperators # | # LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# OPTIONS_GHC -fno - warn - orphans #
module Lndr.Docs where
import Data.Default
import Data.Maybe (fromJust)
import qualified Data.Map as M
import Data.Text (Text)
import Lndr.Types
import Network.Ethereum.Web3.Address
import Servant.API
import Servant.Docs
import Text.EmailAddress as Email
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy.Char8 as LBS8
import qualified Data.Text.Lazy as LT
creditHash :: Text
creditHash = "0x7e2e9ff3a5fc148cf76261755c4c666630bfc3a28d02733cfbe721fc965aca28"
crSigned :: CreditRecord
crSigned = CreditRecord "0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
69
"test memo"
"0x11edd217a875063583dd1b638d16810c5d34d54b"
0
"0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
"0x718d7217a875063583dd1b638d16810c5d34d54b"
Nothing
Nothing
Nothing
crSettleSigned :: BilateralCreditRecord
crSettleSigned = BilateralCreditRecord crSigned "" "" (Just "0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c")
instance ToSample ConfigResponse where
toSamples _ = singleSample $
ConfigResponse (M.fromList [("USD", "0x7899b83071d9704af0b132859a04bb1698a3acaf")])
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
1000
def
5122553
instance ToSample SettlementsResponse where
toSamples _ = singleSample $ SettlementsResponse [crSigned] [crSettleSigned]
instance ToSample CreditRecord where
toSamples _ = singleSample crSigned
instance ToSample RejectRequest where
toSamples _ = singleSample $
RejectRequest "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
"0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
instance ToSample NickRequest where
toSamples _ = singleSample $
NickRequest "0x11edd217a875063583dd1b638d16810c5d34d54b" "aupiff" "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample EmailAddress where
toSamples _ = singleSample $
fromJust $ Email.emailAddressFromText ""
instance ToSample EmailRequest where
toSamples _ = singleSample $
EmailRequest "0x11edd217a875063583dd1b638d16810c5d34d54b" (fromJust $ Email.emailAddressFromText "") "0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample UserInfo where
toSamples _ = singleSample $
UserInfo "0x11edd217a875063583dd1b638d16810c5d34d54b" (Just "aupiff")
instance ToSample PayPalRequest where
toSamples _ = singleSample $
PayPalRequest "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" "0x11edd217a875063583dd1b638d16810c5d34d54b" ""
instance ToSample PayPalRequestPair where
toSamples _ = singleSample $
PayPalRequestPair (UserInfo "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" (Just "Bob")) (UserInfo "0x11edd217a875063583dd1b638d16810c5d34d54b" (Just "Chuck"))
instance ToSample IssueCreditLog where
toSamples _ = singleSample $
IssueCreditLog "d5ec73eac35fc9dd6c3f440bce314779fed09f60"
"0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
69
0
"simple memo"
instance ToSample Address where
toSamples _ = singleSample "0x11edd217a875063583dd1b638d16810c5d34d54b"
instance ToSample VerifySettlementRequest where
toSamples _ = singleSample $
VerifySettlementRequest "0x4358c649de5746c91673378dd4c40a78feda715166913e09ded45343ff76841c"
"0xf357c689de57464713697787d4c40a78feda913162911e191e545343ff769999"
"0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample PushRequest where
toSamples _ = singleSample $
PushRequest "31279004-103e-4ba8-b4bf-65eb3eb81859" "ios"
"0x11edd217a875063583dd1b638d16810c5d34d54b" ""
instance ToSample IdentityAddress where
toSamples _ = singleSample $
IdentityAddress "street" "flatNumber" "town" "state" "postCode" "country"
instance ToSample IdentityDocument where
toSamples _ = singleSample $
IdentityDocument "idDocType" "country" (Just "file")
instance ToSample IdentityVerificationInfo where
toSamples _ = singleSample $
IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" []
instance ToSample RequiredIdentityDocuments where
toSamples _ = singleSample $
RequiredIdentityDocuments "country" []
instance ToSample IdentityDocumentType where
toSamples _ = singleSample $
IdentityDocumentType "idDocSetType" ["types"] (Just ["subTypes"])
instance ToSample IdentityVerificationRequest where
toSamples _ = singleSample $
IdentityVerificationRequest (fromJust $ Email.emailAddressFromText "")
"0x11edd217a875063583dd1b638d16810c5d34d54b"
(IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" [])
(RequiredIdentityDocuments "country" [] )
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
Nothing
instance ToSample IdentityStatusReview where
toSamples _ = singleSample $
IdentityStatusReview "reviewAnswer" "clientComment" (Just "moderationComment") (Just ["rejectLabels"]) (Just "reviewRejectType")
instance ToSample IdentityVerificationStatus where
toSamples _ = singleSample $
IdentityVerificationStatus "applicantId" "inspectionId" "correlationId" "jobId" "0x11edd217a875063583dd1b638d16810c5d34d54b" True (Just "details")
"_type" (IdentityStatusReview "reviewAnswer" "clientComment" (Just "moderationComment") (Just ["rejectLabels"]) (Just "reviewRejectType") )
instance ToSample LT.Text where
toSamples _ = singleSample $
"Hello"
instance ToSample VerificationStatusRequest where
toSamples _ = singleSample $
VerificationStatusRequest "0x11edd217a875063583dd1b638d16810c5d34d54b"
"0x457b0db63b83199f305ef29ba2d7678820806d98abbe3f6aafe015957ecfc5892368b4432869830456c335ade4f561603499d0216cda3af7b6b6cadf6f273c101b"
instance ToSample VerificationStatusEntry where
toSamples _ = singleSample $
VerificationStatusEntry "0x11edd217a875063583dd1b638d16810c5d34d54b" "bob" "Good"
instance ToSample IdentityVerificationResponse where
toSamples _ = singleSample $
IdentityVerificationResponse "id" "createdAt" "inspectionId" "clientId" "jobId" "0x11edd217a875063583dd1b638d16810c5d34d54b"
(IdentityVerificationInfo "country" "firstName" "middleName" "lastName" "phone" "dob" "nationality" [])
(fromJust $ Email.emailAddressFromText "") "env"
(RequiredIdentityDocuments "country" [] )
instance ToSample VerificationMetaData where
toSamples _ = singleSample $
VerificationMetaData "PASSPORT" "USA"
instance ToSample ProfilePhotoRequest where
toSamples _ = singleSample $ ProfilePhotoRequest "2394" "239048"
instance ToSample Text where
toSamples _ = singleSample "aupiff"
instance ToSample Nonce where
toSamples _ = singleSample $ Nonce 1
instance ToSample Integer where
toSamples _ = singleSample 19
instance ToSample Int where
toSamples _ = singleSample 19
instance ToCapture (Capture "email" EmailAddress) where
toCapture _ =
DocCapture "email" "the email whose availability is being checked"
instance ToCapture (Capture "p1" Address) where
toCapture _ =
DocCapture "p1" "the address of the first party in a credit relationship"
instance ToCapture (Capture "p2" Address) where
toCapture _ =
DocCapture "p2" "the address of the second party in a credit relationship"
instance ToCapture (Capture "address" Address) where
toCapture _ =
DocCapture "address" "the address to which a nickname should be assigned"
instance ToCapture (Capture "user" Address) where
toCapture _ =
DocCapture "user" "the address of the user whose friends will be returned"
instance ToCapture (Capture "nick" Text) where
toCapture _ =
DocCapture "nick" "the nickname to be associated with a particular address"
instance ToCapture (Capture "email" Text) where
toCapture _ =
DocCapture "email" "the email to be associated with a particular address"
instance ToCapture (Capture "hash" Text) where
toCapture _ =
DocCapture "hash" "the hash by which to identify a credit record among candidates for resubmission"
instance ToParam (QueryParam "user" Address) where
toParam _ =
DocQueryParam "user"
[ "0x11edd217a875063583dd1b638d16810c5d34d54b"
, "0x6a362e5cee1cf5a5408ff1e12b0bc546618dffcb" ]
"address of user whose records to display"
Normal
instance ToParam (QueryParam "currency" Text) where
toParam _ =
DocQueryParam "currency"
[ "USD"
, "JPY" ]
"currency for which to query balance"
Normal
instance ToParam (QueryParam "txHash" Text) where
toParam _ =
DocQueryParam "txHash"
[ "0x3cb5a3890ca592a6e857f83413bef59dcc59c25445922dbcb3c5623563301639"
, "0x5c0dede3096ec95edaadc2cd258514ee837c45a55a71b05273837c123947ba0d" ]
"address of user whose records to display"
Normal
instance ToParam (QueryParam "email" EmailAddress) where
toParam _ =
DocQueryParam "email"
[ ""
, "" ]
"email whose corresponding user address is requested"
Normal
instance ToParam (QueryParam "nick" Nick) where
toParam _ =
DocQueryParam "nick"
[ "aupiff"
, "willbach" ]
"nickname whose corresponding user address is requested"
Normal
instance ToParam (QueryParam "digest" Nick) where
toParam _ =
DocQueryParam "digest"
[ "fgkjr54twrijt"
, "t4roiety34io3" ]
"digest value provided by SumSub to authenticate callback"
Normal
|
b06416e6ddb71bef60f009244dad55118377994df3b67337b2f7bce960214c73 | plum-umd/c-strider | escape.ml |
*
* Copyright ( c ) 2003 ,
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2003,
* Ben Liblit <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
(** OCaml types used to represent wide characters and strings *)
type wchar = int64
type wstring = wchar list
let escape_char = function
| '\007' -> "\\a"
| '\b' -> "\\b"
| '\t' -> "\\t"
| '\n' -> "\\n"
| '\011' -> "\\v"
| '\012' -> "\\f"
| '\r' -> "\\r"
| '"' -> "\\\""
| '\'' -> "\\'"
| '\\' -> "\\\\"
| ' ' .. '~' as printable -> String.make 1 printable
| unprintable -> Printf.sprintf "\\%03o" (Char.code unprintable)
let escape_string str =
let length = String.length str in
let buffer = Buffer.create length in
for index = 0 to length - 1 do
Buffer.add_string buffer (escape_char (String.get str index))
done;
Buffer.contents buffer
a wide char represented as an int64
let escape_wchar =
(* limit checks whether upper > probe *)
let limit upper probe = (Int64.to_float (Int64.sub upper probe)) > 0.5 in
let fits_byte = limit (Int64.of_int 0x100) in
let fits_octal_escape = limit (Int64.of_int 0o1000) in
let fits_universal_4 = limit (Int64.of_int 0x10000) in
let fits_universal_8 = limit (Int64.of_string "0x100000000") in
fun charcode ->
if fits_byte charcode then
escape_char (Char.chr (Int64.to_int charcode))
else if fits_octal_escape charcode then
Printf.sprintf "\\%03Lo" charcode
else if fits_universal_4 charcode then
Printf.sprintf "\\u%04Lx" charcode
else if fits_universal_8 charcode then
Printf.sprintf "\\u%04Lx" charcode
else
invalid_arg "Cprint.escape_string_intlist"
(* a wide string represented as a list of int64s *)
let escape_wstring (str : int64 list) =
let length = List.length str in
let buffer = Buffer.create length in
let append charcode =
let addition = escape_wchar charcode in
Buffer.add_string buffer addition
in
List.iter append str;
Buffer.contents buffer
| null | https://raw.githubusercontent.com/plum-umd/c-strider/3d3a3743bc28456eb6d50e01805ce484ab3c04e6/tools/cil-1.3.7/src/escape.ml | ocaml | * OCaml types used to represent wide characters and strings
limit checks whether upper > probe
a wide string represented as a list of int64s |
*
* Copyright ( c ) 2003 ,
* < >
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are
* met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS
* IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED
* TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL ,
* EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO ,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
* PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
* NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
*
* Copyright (c) 2003,
* Ben Liblit <>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of the contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
type wchar = int64
type wstring = wchar list
let escape_char = function
| '\007' -> "\\a"
| '\b' -> "\\b"
| '\t' -> "\\t"
| '\n' -> "\\n"
| '\011' -> "\\v"
| '\012' -> "\\f"
| '\r' -> "\\r"
| '"' -> "\\\""
| '\'' -> "\\'"
| '\\' -> "\\\\"
| ' ' .. '~' as printable -> String.make 1 printable
| unprintable -> Printf.sprintf "\\%03o" (Char.code unprintable)
let escape_string str =
let length = String.length str in
let buffer = Buffer.create length in
for index = 0 to length - 1 do
Buffer.add_string buffer (escape_char (String.get str index))
done;
Buffer.contents buffer
a wide char represented as an int64
let escape_wchar =
let limit upper probe = (Int64.to_float (Int64.sub upper probe)) > 0.5 in
let fits_byte = limit (Int64.of_int 0x100) in
let fits_octal_escape = limit (Int64.of_int 0o1000) in
let fits_universal_4 = limit (Int64.of_int 0x10000) in
let fits_universal_8 = limit (Int64.of_string "0x100000000") in
fun charcode ->
if fits_byte charcode then
escape_char (Char.chr (Int64.to_int charcode))
else if fits_octal_escape charcode then
Printf.sprintf "\\%03Lo" charcode
else if fits_universal_4 charcode then
Printf.sprintf "\\u%04Lx" charcode
else if fits_universal_8 charcode then
Printf.sprintf "\\u%04Lx" charcode
else
invalid_arg "Cprint.escape_string_intlist"
let escape_wstring (str : int64 list) =
let length = List.length str in
let buffer = Buffer.create length in
let append charcode =
let addition = escape_wchar charcode in
Buffer.add_string buffer addition
in
List.iter append str;
Buffer.contents buffer
|
315f842beb4010352869e962c465fe5011fad9f3702da4b23d41814c2d08cb94 | malcolmreynolds/GSLL | gaussian.lisp | Gaussian distribution
, Sun Jul 16 2006 - 22:09
Time - stamp : < 2009 - 05 - 24 16:42:13EDT gaussian.lisp >
$ Id$
(in-package :gsl)
;;; /usr/include/gsl/gsl_randist.h
;;; /usr/include/gsl/gsl_cdf.h
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian))
&key sigma)
"gsl_ran_gaussian"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"A Gaussian random variate, with mean zero and
standard deviation sigma. The probability distribution for
Gaussian random variates is
p(x) dx = {1 \over \sqrt{2 \pi \sigma^2}} \exp (-x^2 / 2\sigma^2) dx
for x in the range -\infty to +\infty. Use the
transformation z = \mu + x on the numbers returned by
#'gaussian to obtain a Gaussian distribution with mean
mu. This function uses the Box-Mueller algorithm which requires two
calls to the random number generator r.")
(defmfun gaussian-pdf (x sigma)
"gsl_ran_gaussian_pdf" ((x :double) (sigma :double))
:c-return :double
"Compute the probability density p(x) at x
for a Gaussian distribution with standard deviation sigma.")
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian-ziggurat))
&key sigma)
"gsl_ran_gaussian_ziggurat"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"Compute a Gaussian random variate using the alternative
Marsaglia-Tsang ziggurat method. The Ziggurat algorithm
is the fastest available algorithm in most cases.")
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian-ratio-method))
&key sigma)
"gsl_ran_gaussian_ratio_method"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"Compute a Gaussian random variate using the Kinderman-Monahan-Leva
ratio method.")
(defmfun sample
((generator random-number-generator) (type (eql 'ugaussian)) &key)
"gsl_ran_ugaussian" (((mpointer generator) :pointer))
:definition :method
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian with a standard deviation of one,
sigma = 1.")
(defmfun ugaussian-pdf (x)
"gsl_ran_ugaussian_pdf" ((x :double))
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian-pdf with a standard deviation of one,
sigma = 1.")
(defmfun sample
((generator random-number-generator) (type (eql 'ugaussian-ratio-method))
&key)
"gsl_ran_ugaussian_ratio_method"
(((mpointer generator) :pointer))
:definition :method
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian-ration-method with a
standard deviation of one, sigma = 1.")
(defmfun gaussian-P (x sigma)
"gsl_cdf_gaussian_P" ((x :double) (sigma :double))
:c-return :double
"The cumulative distribution function P(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Q (x sigma)
"gsl_cdf_gaussian_Q" ((x :double) (sigma :double))
:c-return :double
"The cumulative distribution function Q(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Pinv (P sigma)
"gsl_cdf_gaussian_Pinv" ((P :double) (sigma :double))
:c-return :double
"The inverse cumulative distribution function P(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Qinv (Q sigma)
"gsl_cdf_gaussian_Qinv" ((Q :double) (sigma :double))
:c-return :double
"The inverse cumulative distribution function Q(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun ugaussian-P (x)
"gsl_cdf_ugaussian_P" ((x :double))
:c-return :double
"The cumulative distribution function P(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Q (x)
"gsl_cdf_ugaussian_Q" ((x :double))
:c-return :double
"The cumulative distribution function Q(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Pinv (P)
"gsl_cdf_ugaussian_Pinv" ((P :double))
:c-return :double
"The inverse cumulative distribution function P(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Qinv (Q)
"gsl_cdf_ugaussian_Qinv" ((Q :double))
:c-return :double
"The inverse cumulative distribution function Q(x) for the Gaussian
distribution with unit standard deviation.")
;;; Examples and unit test
(save-test
gaussian
(let ((rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng 'gaussian :sigma 10.0d0)))
(gaussian-pdf 0.0d0 10.0d0)
(let ((rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng 'gaussian-ziggurat :sigma 10.0d0)))
Given in examples in GSL documentation
(ugaussian-p 2.0d0)
(ugaussian-q 2.0d0)
(ugaussian-pinv 0.9772498680518208d0)
(ugaussian-qinv 0.02275013194817921d0))
| null | https://raw.githubusercontent.com/malcolmreynolds/GSLL/2f722f12f1d08e1b9550a46e2a22adba8e1e52c4/random/gaussian.lisp | lisp | /usr/include/gsl/gsl_randist.h
/usr/include/gsl/gsl_cdf.h
Examples and unit test | Gaussian distribution
, Sun Jul 16 2006 - 22:09
Time - stamp : < 2009 - 05 - 24 16:42:13EDT gaussian.lisp >
$ Id$
(in-package :gsl)
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian))
&key sigma)
"gsl_ran_gaussian"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"A Gaussian random variate, with mean zero and
standard deviation sigma. The probability distribution for
Gaussian random variates is
p(x) dx = {1 \over \sqrt{2 \pi \sigma^2}} \exp (-x^2 / 2\sigma^2) dx
for x in the range -\infty to +\infty. Use the
transformation z = \mu + x on the numbers returned by
#'gaussian to obtain a Gaussian distribution with mean
mu. This function uses the Box-Mueller algorithm which requires two
calls to the random number generator r.")
(defmfun gaussian-pdf (x sigma)
"gsl_ran_gaussian_pdf" ((x :double) (sigma :double))
:c-return :double
"Compute the probability density p(x) at x
for a Gaussian distribution with standard deviation sigma.")
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian-ziggurat))
&key sigma)
"gsl_ran_gaussian_ziggurat"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"Compute a Gaussian random variate using the alternative
Marsaglia-Tsang ziggurat method. The Ziggurat algorithm
is the fastest available algorithm in most cases.")
(defmfun sample
((generator random-number-generator) (type (eql 'gaussian-ratio-method))
&key sigma)
"gsl_ran_gaussian_ratio_method"
(((mpointer generator) :pointer) (sigma :double))
:definition :method
:c-return :double
"Compute a Gaussian random variate using the Kinderman-Monahan-Leva
ratio method.")
(defmfun sample
((generator random-number-generator) (type (eql 'ugaussian)) &key)
"gsl_ran_ugaussian" (((mpointer generator) :pointer))
:definition :method
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian with a standard deviation of one,
sigma = 1.")
(defmfun ugaussian-pdf (x)
"gsl_ran_ugaussian_pdf" ((x :double))
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian-pdf with a standard deviation of one,
sigma = 1.")
(defmfun sample
((generator random-number-generator) (type (eql 'ugaussian-ratio-method))
&key)
"gsl_ran_ugaussian_ratio_method"
(((mpointer generator) :pointer))
:definition :method
:c-return :double
"Compute results for the unit Gaussian distribution,
equivalent to the #'gaussian-ration-method with a
standard deviation of one, sigma = 1.")
(defmfun gaussian-P (x sigma)
"gsl_cdf_gaussian_P" ((x :double) (sigma :double))
:c-return :double
"The cumulative distribution function P(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Q (x sigma)
"gsl_cdf_gaussian_Q" ((x :double) (sigma :double))
:c-return :double
"The cumulative distribution function Q(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Pinv (P sigma)
"gsl_cdf_gaussian_Pinv" ((P :double) (sigma :double))
:c-return :double
"The inverse cumulative distribution function P(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun gaussian-Qinv (Q sigma)
"gsl_cdf_gaussian_Qinv" ((Q :double) (sigma :double))
:c-return :double
"The inverse cumulative distribution function Q(x) for the Gaussian
distribution with standard deviation sigma.")
(defmfun ugaussian-P (x)
"gsl_cdf_ugaussian_P" ((x :double))
:c-return :double
"The cumulative distribution function P(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Q (x)
"gsl_cdf_ugaussian_Q" ((x :double))
:c-return :double
"The cumulative distribution function Q(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Pinv (P)
"gsl_cdf_ugaussian_Pinv" ((P :double))
:c-return :double
"The inverse cumulative distribution function P(x) for the Gaussian
distribution with unit standard deviation.")
(defmfun ugaussian-Qinv (Q)
"gsl_cdf_ugaussian_Qinv" ((Q :double))
:c-return :double
"The inverse cumulative distribution function Q(x) for the Gaussian
distribution with unit standard deviation.")
(save-test
gaussian
(let ((rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng 'gaussian :sigma 10.0d0)))
(gaussian-pdf 0.0d0 10.0d0)
(let ((rng (make-random-number-generator +mt19937+ 0)))
(loop for i from 0 to 10
collect
(sample rng 'gaussian-ziggurat :sigma 10.0d0)))
Given in examples in GSL documentation
(ugaussian-p 2.0d0)
(ugaussian-q 2.0d0)
(ugaussian-pinv 0.9772498680518208d0)
(ugaussian-qinv 0.02275013194817921d0))
|
0e74fb23e1c288a9dd3d83069c0b09836269726b1d7437a79cc78b85f242364e | vivid-inc/ash-ra-template | project.clj | ; Run either with
; $ lein ring server
; or in a REPL:
; $ lein repl
hello.core= > ( ring.adapter.jetty/run-jetty app - handler { : port 3000 } )
;
; and then visit
; :3000/?nickname=beatrix
(defproject ring-server "1.0.0-SNAPSHOT"
:description "Minimal demonstration rendering responses in Ring handlers using ART templates."
:dependencies [[org.clojure/clojure "1.10.0"]
[ring/ring-core "1.9.5"]
[ring/ring-jetty-adapter "1.9.5"]
[net.vivid-inc/art "0.6.1"]]
:main hello.core
:plugins [[lein-ring "0.12.6"]]
:ring {:handler hello.core/app-handler})
| null | https://raw.githubusercontent.com/vivid-inc/ash-ra-template/f64be7efd6f52ccd451cddb851f02511d1665b11/examples/ring-server/project.clj | clojure | Run either with
$ lein ring server
or in a REPL:
$ lein repl
and then visit
:3000/?nickname=beatrix | hello.core= > ( ring.adapter.jetty/run-jetty app - handler { : port 3000 } )
(defproject ring-server "1.0.0-SNAPSHOT"
:description "Minimal demonstration rendering responses in Ring handlers using ART templates."
:dependencies [[org.clojure/clojure "1.10.0"]
[ring/ring-core "1.9.5"]
[ring/ring-jetty-adapter "1.9.5"]
[net.vivid-inc/art "0.6.1"]]
:main hello.core
:plugins [[lein-ring "0.12.6"]]
:ring {:handler hello.core/app-handler})
|
733d6d87b4ae9f4c7c7275d108797e66d03a156b7a4b112667529231fe5b3e34 | UU-ComputerScience/uhc | ForeignPtr.hs | # LANGUAGE NoImplicitPrelude , CPP #
# OPTIONS_GHC -XNoImplicitPrelude #
# EXCLUDE_IF_TARGET js #
{-# EXCLUDE_IF_TARGET cr #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.ForeignPtr
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- The 'ForeignPtr' type and operations. This module is part of the
Foreign Function Interface ( FFI ) and will usually be imported via
-- the "Foreign" module.
--
-----------------------------------------------------------------------------
module Foreign.ForeignPtr
(
-- * Finalised data pointers
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
-- ** Basic operations
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
-- ** Low-level operations
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
-- ** Allocating managed memory
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IOBase
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#ifdef __UHC__
import UHC.ForeignPtr
import UHC.Base
import UHC.IOBase
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__) && !defined(__UHC__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
-- ^Turns a plain memory reference into a foreign pointer, and
-- associates a finaliser with the reference. The finaliser will be executed
-- after the last reference to the foreign object is dropped. Note that there
-- is no guarantee on how soon the finaliser is executed after the last
reference was dropped ; this depends on the details of the storage
-- manager. Indeed, there is no guarantee that the finalizer is executed at
-- all; a program may exit with finalizers outstanding. (This is true
of GHC , other implementations may give stronger guarantees ) .
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
-- ^This is a way to look at the pointer living inside a
-- foreign object. This function takes a function which is
-- applied to that pointer. The resulting 'IO' action is then
-- executed. The foreign object is kept alive at least during
-- the whole action, even if it is not used directly
-- inside. Note that it is not safe to return the pointer from
-- the action and use it after the action completes. All uses
-- of the pointer should be inside the
-- 'withForeignPtr' bracket. The reason for
-- this unsafeness is the same as for
-- 'unsafeForeignPtrToPtr' below: the finalizer
-- may run earlier than expected, because the compiler can only
-- track usage of the 'ForeignPtr' object, not
-- a 'Ptr' object made from it.
--
-- This function is normally used for marshalling data to
-- or from the object pointed to by the
-- 'ForeignPtr', using the operations from the
-- 'Storable' class.
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
| This variant of ' newForeignPtr ' adds a finalizer that expects an
-- environment in addition to the finalized pointer. The environment
that will be passed to the finalizer is fixed by the second argument to
-- 'newForeignPtrEnv'.
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifndef __UHC__
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
#endif /* !__UHC__ */
| This function is similar to ' Foreign . Marshal . Array.mallocArray ' ,
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
-- | This function is similar to 'Foreign.Marshal.Array.mallocArray0',
-- but yields a memory area that has a finalizer attached that releases
-- the memory area. As with 'mallocForeignPtr', it is not guaranteed that
-- the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/ehclib/uhcbase/Foreign/ForeignPtr.hs | haskell | # EXCLUDE_IF_TARGET cr #
---------------------------------------------------------------------------
|
Module : Foreign.ForeignPtr
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
The 'ForeignPtr' type and operations. This module is part of the
the "Foreign" module.
---------------------------------------------------------------------------
* Finalised data pointers
** Basic operations
** Low-level operations
** Allocating managed memory
^Turns a plain memory reference into a foreign pointer, and
associates a finaliser with the reference. The finaliser will be executed
after the last reference to the foreign object is dropped. Note that there
is no guarantee on how soon the finaliser is executed after the last
manager. Indeed, there is no guarantee that the finalizer is executed at
all; a program may exit with finalizers outstanding. (This is true
^This is a way to look at the pointer living inside a
foreign object. This function takes a function which is
applied to that pointer. The resulting 'IO' action is then
executed. The foreign object is kept alive at least during
the whole action, even if it is not used directly
inside. Note that it is not safe to return the pointer from
the action and use it after the action completes. All uses
of the pointer should be inside the
'withForeignPtr' bracket. The reason for
this unsafeness is the same as for
'unsafeForeignPtrToPtr' below: the finalizer
may run earlier than expected, because the compiler can only
track usage of the 'ForeignPtr' object, not
a 'Ptr' object made from it.
This function is normally used for marshalling data to
or from the object pointed to by the
'ForeignPtr', using the operations from the
'Storable' class.
environment in addition to the finalized pointer. The environment
'newForeignPtrEnv'.
but yields a memory area that has a finalizer attached that releases
the memory area. As with 'mallocForeignPtr', it is not guaranteed that
the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'.
| This function is similar to 'Foreign.Marshal.Array.mallocArray0',
but yields a memory area that has a finalizer attached that releases
the memory area. As with 'mallocForeignPtr', it is not guaranteed that
the block of memory was allocated by 'Foreign.Marshal.Alloc.malloc'. | # LANGUAGE NoImplicitPrelude , CPP #
# OPTIONS_GHC -XNoImplicitPrelude #
# EXCLUDE_IF_TARGET js #
Copyright : ( c ) The University of Glasgow 2001
Maintainer :
Foreign Function Interface ( FFI ) and will usually be imported via
module Foreign.ForeignPtr
(
ForeignPtr
, FinalizerPtr
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, FinalizerEnvPtr
#endif
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
, newForeignPtrEnv
, addForeignPtrFinalizerEnv
#endif
, withForeignPtr
#ifdef __GLASGOW_HASKELL__
, finalizeForeignPtr
#endif
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, mallocForeignPtr
, mallocForeignPtrBytes
, mallocForeignPtrArray
, mallocForeignPtrArray0
)
where
import Foreign.Ptr
#ifdef __NHC__
import NHC.FFI
( ForeignPtr
, FinalizerPtr
, newForeignPtr
, newForeignPtr_
, addForeignPtrFinalizer
, withForeignPtr
, unsafeForeignPtrToPtr
, touchForeignPtr
, castForeignPtr
, Storable(sizeOf)
, malloc, mallocBytes, finalizerFree
)
#endif
#ifdef __HUGS__
import Hugs.ForeignPtr
#endif
#ifndef __NHC__
import Foreign.Storable ( Storable(sizeOf) )
#endif
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IOBase
import GHC.Num
import GHC.Err ( undefined )
import GHC.ForeignPtr
#endif
#ifdef __UHC__
import UHC.ForeignPtr
import UHC.Base
import UHC.IOBase
#endif
#if !defined(__NHC__) && !defined(__GLASGOW_HASKELL__) && !defined(__UHC__)
import Foreign.Marshal.Alloc ( malloc, mallocBytes, finalizerFree )
instance Eq (ForeignPtr a) where
p == q = unsafeForeignPtrToPtr p == unsafeForeignPtrToPtr q
instance Ord (ForeignPtr a) where
compare p q = compare (unsafeForeignPtrToPtr p) (unsafeForeignPtrToPtr q)
instance Show (ForeignPtr a) where
showsPrec p f = showsPrec p (unsafeForeignPtrToPtr f)
#endif
#ifndef __NHC__
newForeignPtr :: FinalizerPtr a -> Ptr a -> IO (ForeignPtr a)
reference was dropped ; this depends on the details of the storage
of GHC , other implementations may give stronger guarantees ) .
newForeignPtr finalizer p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizer finalizer fObj
return fObj
withForeignPtr :: ForeignPtr a -> (Ptr a -> IO b) -> IO b
withForeignPtr fo io
= do r <- io (unsafeForeignPtrToPtr fo)
touchForeignPtr fo
return r
#endif /* ! __NHC__ */
#if defined(__HUGS__) || defined(__GLASGOW_HASKELL__)
| This variant of ' newForeignPtr ' adds a finalizer that expects an
that will be passed to the finalizer is fixed by the second argument to
newForeignPtrEnv ::
FinalizerEnvPtr env a -> Ptr env -> Ptr a -> IO (ForeignPtr a)
newForeignPtrEnv finalizer env p
= do fObj <- newForeignPtr_ p
addForeignPtrFinalizerEnv finalizer env fObj
return fObj
#endif /* __HUGS__ */
#ifndef __UHC__
#ifndef __GLASGOW_HASKELL__
mallocForeignPtr :: Storable a => IO (ForeignPtr a)
mallocForeignPtr = do
r <- malloc
newForeignPtr finalizerFree r
mallocForeignPtrBytes :: Int -> IO (ForeignPtr a)
mallocForeignPtrBytes n = do
r <- mallocBytes n
newForeignPtr finalizerFree r
#endif /* !__GLASGOW_HASKELL__ */
#endif /* !__UHC__ */
| This function is similar to ' Foreign . Marshal . Array.mallocArray ' ,
mallocForeignPtrArray :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray = doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocForeignPtrBytes (size * sizeOf dummy)
mallocForeignPtrArray0 :: Storable a => Int -> IO (ForeignPtr a)
mallocForeignPtrArray0 size = mallocForeignPtrArray (size + 1)
|
92520f33afee680a0f2326fbb2c230dc39ace950b4ca5d4e429f96903a0e928b | pierric/neural-network | Gen.hs | # LANGUAGE FlexibleInstances , FlexibleContexts #
module Test.Gen where
import Test.Utils
import Test.QuickCheck
import Control.Monad
import qualified Numeric.LinearAlgebra as L
import Numeric.LinearAlgebra.Devel
import qualified Data.Vector.Storable as V
squared_real_matrices :: Int -> Gen (L.Matrix Float)
squared_real_matrices k = do
vs <- sequence (replicate (k*k) arbitrary) :: Gen [Float]
return $ L.reshape k $ V.fromList vs
small_matrices :: Gen (L.Matrix Float)
small_matrices = do
n <- choose (2,10)
squared_real_matrices n
pair :: Gen a -> Gen b -> Gen (a,b)
pair = liftM2 (,)
| null | https://raw.githubusercontent.com/pierric/neural-network/406ecaf334cde9b10c9324e1f6c4b8663eae58d7/Backend-blashs/Test/Gen.hs | haskell | # LANGUAGE FlexibleInstances , FlexibleContexts #
module Test.Gen where
import Test.Utils
import Test.QuickCheck
import Control.Monad
import qualified Numeric.LinearAlgebra as L
import Numeric.LinearAlgebra.Devel
import qualified Data.Vector.Storable as V
squared_real_matrices :: Int -> Gen (L.Matrix Float)
squared_real_matrices k = do
vs <- sequence (replicate (k*k) arbitrary) :: Gen [Float]
return $ L.reshape k $ V.fromList vs
small_matrices :: Gen (L.Matrix Float)
small_matrices = do
n <- choose (2,10)
squared_real_matrices n
pair :: Gen a -> Gen b -> Gen (a,b)
pair = liftM2 (,)
| |
6a53191bea3eea52c2ffcccb6b85ef79bc615bebc043dfed13cb00782f777d19 | facebookarchive/pfff | xdebug.ml | (*s: xdebug.ml *)
(*s: Facebook copyright *)
*
* Copyright ( C ) 2009 , 2010 , 2011 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file license.txt .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* license.txt for more details .
*
* Copyright (C) 2009, 2010, 2011 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)
(*e: Facebook copyright *)
open Common2
open Common
open Ast_php
module Ast = Ast_php
(*****************************************************************************)
(* Prelude *)
(*****************************************************************************)
* Wrappers around the really good debugger / profiler / tracer for PHP :
*
* /
*
* To enable xdebug , you need to add the loading of xdebug.so in one
* of the php config .ini file , for instance add in php.ini :
*
* zend_extension=/usr / local / php / lib / php / extensions / no - debug - non - zts-20060613 / xdebug.so
*
* Then php -v should display something like :
*
* Zend Engine v2.2.0 , Copyright ( c ) 1998 - 2007 Zend Technologies
* with v2.0.3.fb1 , Copyright ( c ) 2002 - 2007 , by
*
* php -d xdebug.collect_params=3
* = > full variable contents with the limits respected by
* xdebug.var_display_max_children , max_data , max_depth
*
* But the dumped file can be huge :
* - for unit tested flib / core/ 1.8 Go
* - for unit tested flib/ 5Go ...
*
* so had to optimize a few things :
*
* - use compiled regexp ,
* - fast - path parser for expression .
* - use iterator interface instead of using lists .
*
* See -index_db_xdebug and Database_php_build for the code using
* this module .
* See also dynamic_analysis.ml .
*
* Wrappers around the really good debugger/profiler/tracer for PHP:
*
* /
*
* To enable xdebug, you need to add the loading of xdebug.so in one
* of the php config .ini file, for instance add in php.ini:
*
* zend_extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so
*
* Then php -v should display something like:
*
* Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
* with Xdebug v2.0.3.fb1, Copyright (c) 2002-2007, by Derick Rethans
*
* php -d xdebug.collect_params=3
* => full variable contents with the limits respected by
* xdebug.var_display_max_children, max_data, max_depth
*
* But the dumped file can be huge:
* - for unit tested flib/core/ 1.8 Go
* - for unit tested flib/ 5Go ...
*
* so had to optimize a few things:
*
* - use compiled regexp,
* - fast-path parser for expression.
* - use iterator interface instead of using lists.
*
* See -index_db_xdebug and Database_php_build for the code using
* this module.
* See also dynamic_analysis.ml.
*
*)
(*****************************************************************************)
(* Wrappers *)
(*****************************************************************************)
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
type kind_call =
| FunCall of string
| ObjectCall of string (* class *) * string (* method *)
| ClassCall of string (* module *) * string
Depending on config below , some of the fields may be incomplete
* ( e.g. f_return will be None when cfg.collect_return = false
* (e.g. f_return will be None when cfg.collect_return = false *)
type call_trace = {
f_call: kind_call;
f_file: Common.filename;
f_line: int;
f_params: Ast_php.expr list;
f_return: Ast_php.expr option;
(* f_type: *)
}
let xdebug_main_name = "xdebug_main"
type config = {
auto_trace: int;
trace_options: int;
trace_format: int;
collect_params: params_mode;
collect_return: bool;
var_display_max_children: int;
val_display_max_data: int;
var_display_max_depth: int;
}
(* see *)
and params_mode =
| NoParam
| TypeAndArity
| TypeAndArityAndTooltip
| FullParam
| FullParamAndVar
(* with tarzan *)
let default_config = {
auto_trace = 1;
trace_options = 1;
trace_format = 0;
collect_params = FullParam;
collect_return = true;
default = 128
default = 512
default = 3
}
(*****************************************************************************)
(* String of *)
(*****************************************************************************)
let s_of_kind_call = function
| FunCall s -> s
| ObjectCall (s1, s2) -> s1 ^ "->" ^ s2
| ClassCall (s1, s2) -> s1 ^ "::" ^ s2
let string_of_call_trace x =
spf "%s:%d: call = %s"
x.f_file x.f_line (s_of_kind_call x.f_call)
let intval_of_params_mode = function
| NoParam -> 0
| TypeAndArity -> 1
| TypeAndArityAndTooltip -> 2
| FullParam -> 3
| FullParamAndVar -> 4
let hash_of_config cfg =
match cfg with
{
auto_trace = v_auto_trace;
trace_options = v_trace_options;
trace_format = v_trace_format;
collect_params = v_collect_params;
collect_return = v_collect_return;
var_display_max_children = v_var_display_max_children;
val_display_max_data = v_val_display_max_data;
var_display_max_depth = v_var_display_max_depth
} ->
(* emacs macro generated *)
Common.hash_of_list [
"auto_trace", i_to_s v_auto_trace;
"trace_options", i_to_s v_trace_options;
"trace_format", i_to_s v_trace_format;
"collect_params", i_to_s (intval_of_params_mode v_collect_params);
"collect_return", if v_collect_return then "1" else "0";
"var_display_max_children", i_to_s v_var_display_max_children;
"val_display_max_data", i_to_s v_val_display_max_data;
"var_display_max_depth", i_to_s v_var_display_max_depth
]
let cmdline_args_of_config cfg =
hash_of_config cfg
+> Common.hash_to_list
+> List.map (fun (s, d) -> spf "-d xdebug.%s=%s" s d)
+> Common.join " "
(*****************************************************************************)
(* Small wrapper over php interpreter *)
(*****************************************************************************)
let php_cmd_with_xdebug_on ?(config = default_config) ~trace_file () =
let (d, b, e) = Common2.dbe_of_filename trace_file in
if e <> "xt"
then failwith "the xdebug trace file must end in .xt";
if Sys.file_exists trace_file && Common2.filesize trace_file > 0
then pr2 (spf "WARNING: %s already exists, xdebug will concatenate data"
trace_file);
let options = cmdline_args_of_config config in
spf "php %s -d xdebug.trace_output_dir=%s -d xdebug.trace_output_name=%s"
options
d
xdebug will automatically appends a " .xt " to the filename
let php_has_xdebug_extension () =
let xs = Common.cmd_to_list "php -v 2>&1" in
xs +> List.exists (fun s -> s =~ ".*with Xdebug v.*")
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let sanitize_xdebug_expr_for_parser2 _str =
Str is buggy
let str = Str.global_replace
( Str.regexp " class\b " ) " class_xdebug " str
in
( * bug in xdebug output
let str = Str.global_replace
(Str.regexp "class\b") "class_xdebug" str
in
(* bug in xdebug output *)
let str = Str.global_replace
(Str.regexp ")[ \t]*}") ");}" str
in
str
*)
let str = Pcre.replace ~pat:"\\?\\?\\ ? " ~templ : " ... " str in
let str = Pcre.replace ~pat:"class " ~templ:"class_xdebug " str in
let str = Pcre.replace
~pat:"resource\\([^)]*\\ ) of type \\([^)]*\\ ) "
~templ:"resource_xdebug " str
in
( * bug in xdebug output
let str = Pcre.replace ~pat:"\\?\\?\\?" ~templ:"..." str in
let str = Pcre.replace ~pat:"class" ~templ:"class_xdebug" str in
let str = Pcre.replace
~pat:"resource\\([^)]*\\) of type \\([^)]*\\)"
~templ:"resource_xdebug" str
in
(* bug in xdebug output *)
let str = Pcre.replace ~pat:"([^{ \t])[ \t]+}" ~itempl:(Pcre.subst "$1;}") str in
str
*)
failwith "TODO: deprecated code, we removed the dependencies to PCRE"
let sanitize_xdebug_expr_for_parser a =
Common.profile_code "sanitize" (fun () -> sanitize_xdebug_expr_for_parser2 a)
bench :
* on toy.xt :
* - 0.157s with regular expr parser
* - 0.002 with in memory parser that do nt call xhp , tag file info , etc
* on flib_core.xt : 44s in native mode
* on toy.xt:
* - 0.157s with regular expr parser
* - 0.002 with in memory parser that dont call xhp, tag file info, etc
* on flib_core.xt: 44s in native mode
*)
let parse_xdebug_expr2 s =
(* Parse_php.expr_of_string s *)
Parse_php.xdebug_expr_of_string s
let parse_xdebug_expr a =
Common.profile_code "Xdebug.parse" (fun () -> parse_xdebug_expr2 a)
(*****************************************************************************)
(* Parsing regexps *)
(*****************************************************************************)
examples :
* 0.0009 99800 - > { main } ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:0
* 0.0009 99800 - > main ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:41
* 0.0006 97600 - > A->__construct(4 ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / object_values.php:24
* TODO ModuleStack::current ( )
*
* update : can also get :
*
* 1.9389 140618888 - > strtolower ( ) /data / users / pad / www - git / flib / web / haste / transform.php(77 ) : regexp code:1
*
* 0.0009 99800 -> {main}() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:0
* 0.0009 99800 -> main() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:41
* 0.0006 97600 -> A->__construct(4) /home/pad/mobile/project-facebook/pfff/tests/xdebug/object_values.php:24
* TODO ModuleStack::current()
*
* update: can also get:
*
* 1.9389 140618888 -> strtolower() /data/users/pad/www-git/flib/web/haste/transform.php(77) : regexp code:1
*
*)
let regexp_in =
Str.regexp
1 , everything before the arrow
"[ \t]+" ^
2 3 , time and nbcall ?
"[ \t]+" ^
"\\)" ^ (* end of before arrow *)
"->[ \t]+" ^
4 , funcname or
5 , arguments
6 , filename . was /. * but can get weird lines
* such as above with the ' regexp code:1 ' which
* then got ' : ' matched at the wrong place .
* such as above with the 'regexp code:1' which
* then got ':' matched at the wrong place.
*)
":" ^
7 , line
"")
examples :
* > = > 8
* >=> 8
*)
let regexp_out =
Str.regexp
1 , spacing
">=> " ^
2 , returned expression
)
example :
* 0.0009 99800 - > { main } ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:0
* 0.0009 99800 -> {main}() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:0
*)
let _regexp_special_main =
Str.regexp ".*-> {main}()"
let regexp_last_time =
Str.regexp (
"^[ \t]+[0-9]+\\.[0-9]+[ \t]+[0-9]+$"
)
let regexp_meth_call =
Str.regexp (
"\\([A-Za-z_0-9]+\\)->\\(.*\\)"
)
let regexp_class_call =
Str.regexp (
"\\([A-Za-z_0-9]+\\)::\\(.*\\)"
)
let regexp_fun_call =
Str.regexp (
"[A-Za-z_0-9]+$"
)
(*****************************************************************************)
(* Main entry point *)
(*****************************************************************************)
(* Can not have a parse_dumpfile, because it is usually too big *)
let iter_dumpfile2
?(config=default_config)
?(show_progress=true)
?(fatal_when_exn=false)
callback file =
pr2 (spf "computing number of lines of %s" file);
let nblines = Common2.nblines_with_wc file in
pr2 (spf "nb lines = %d" nblines);
let nb_fails = ref 0 in
Console.execute_and_show_progress ~show:show_progress nblines (fun k ->
Common.with_open_infile file (fun (chan) ->
let stack = ref [] in
let line_no = ref 0 in
try
while true do
let line = input_line chan in
incr line_no;
k ();
match line with
most common case first
| _ when line ==~ regexp_in ->
(* pr2 "IN:"; *)
let (before_arrow, _time, _nbcall, call, args, file, lineno) =
Common.matched7 line
in
let trace_opt =
(try
let kind_call =
match () with
| _ when call ==~ regexp_meth_call ->
let (sclass, smethod) = Common.matched2 call in
ObjectCall(sclass, smethod)
| _ when call ==~ regexp_class_call ->
let (sclass, smethod) = Common.matched2 call in
ClassCall(sclass, smethod)
| _ when call ==~ regexp_fun_call ->
FunCall(call)
(* We do not want to expose such funcall to the callback,
* but we to parse it and match its return. It will be
* filtered later.
*)
| _ when call = "{main}" ->
FunCall(xdebug_main_name)
| _ ->
failwith ("not a funcall: " ^ call)
in
(* require/include calls have not a valid PHP syntax in xdebug
* ouput, e.g. require_once(/data/users/pad/www-git/foo.php)
* which do not contain enclosing '"' so have to
* filter them here.
*)
(match kind_call with
| FunCall "require_once"
| FunCall "include_once"
| FunCall "include"
| FunCall "require"
-> None
| _ ->
let args =
if config.collect_params = NoParam
then []
else
let str = sanitize_xdebug_expr_for_parser args in
let str = "foo(" ^ str ^ ")" in
let expr = parse_xdebug_expr str in
match expr with
| Call (Id name, args_paren) ->
assert(Ast.str_of_name name = "foo");
Ast.unparen args_paren
+> Ast.uncomma
+> List.map (function
| Arg e -> e
| _ -> raise Impossible
)
| _ -> raise Impossible
in
let trace = {
f_call = kind_call;
f_file = file;
f_line = s_to_i lineno;
f_params = args;
f_return = None; (* filled later for regexp_out *)
}
in
Some trace
)
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "php parsing pb: exn = %s, s = %s"
(Common.exn_to_s exn) args);
incr nb_fails;
if fatal_when_exn then raise exn
else
None
)
in
trace_opt +> Common.do_option (fun trace ->
if not config.collect_return then
(try
if trace.f_call = FunCall(xdebug_main_name)
then ()
else
callback trace
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "callback pb: exn = %s, line = %s"
(Common.exn_to_s exn) line);
raise exn
)
else
Common.push (String.length before_arrow, trace) stack;
)
| _ when line ==~ regexp_out ->
(* pr2 "OUT:"; *)
let (before_arrow, return_expr) = Common.matched2 line in
let str = sanitize_xdebug_expr_for_parser return_expr in
(* the return line is indented with an extra space, so have
* to correct it here with the -1 *)
let depth_here = String.length before_arrow - 1 in
(try
let expr = parse_xdebug_expr str in
match !stack with
| [] -> failwith "empty call stack"
| (depth_call, trace)::rest ->
(match depth_call <=> depth_here with
| Common2.Equal ->
stack := rest;
let caller = trace.f_call in
if caller = FunCall(xdebug_main_name)
then ()
else
(try
let trace = { trace with f_return = Some expr } in
callback trace
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "callback pb: exn = %s, line = %s"
(Common.exn_to_s exn) line);
raise exn
)
| Common2.Inf ->
raise Todo
| Common2.Sup ->
raise Todo
)
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "php parsing pb: exn = %s, str = %s, line = %d "
(Common.exn_to_s exn) str !line_no);
incr nb_fails;
if fatal_when_exn then raise exn;
)
| _ when line =~ "^TRACE" -> ()
| _ when line ==~ regexp_last_time -> ()
| _ when line = "" -> ()
| _ ->
(* TODO error recovery ? *)
pr2 ("parsing pb: " ^ line);
incr nb_fails;
done
with End_of_file -> ()
));
pr2 (spf "nb xdebug parsing fails = %d" !nb_fails);
()
let iter_dumpfile ?config ?show_progress ?fatal_when_exn a b =
Common.profile_code "Xdebug.iter_dumpfile" (fun () ->
iter_dumpfile2 ?config ?show_progress ?fatal_when_exn a b)
(*e: xdebug.ml *)
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/lang_php/analyze/tools/xdebug.ml | ocaml | s: xdebug.ml
s: Facebook copyright
e: Facebook copyright
***************************************************************************
Prelude
***************************************************************************
***************************************************************************
Wrappers
***************************************************************************
***************************************************************************
Types
***************************************************************************
class
method
module
f_type:
see
with tarzan
***************************************************************************
String of
***************************************************************************
emacs macro generated
***************************************************************************
Small wrapper over php interpreter
***************************************************************************
***************************************************************************
Helpers
***************************************************************************
bug in xdebug output
bug in xdebug output
Parse_php.expr_of_string s
***************************************************************************
Parsing regexps
***************************************************************************
end of before arrow
***************************************************************************
Main entry point
***************************************************************************
Can not have a parse_dumpfile, because it is usually too big
pr2 "IN:";
We do not want to expose such funcall to the callback,
* but we to parse it and match its return. It will be
* filtered later.
require/include calls have not a valid PHP syntax in xdebug
* ouput, e.g. require_once(/data/users/pad/www-git/foo.php)
* which do not contain enclosing '"' so have to
* filter them here.
filled later for regexp_out
pr2 "OUT:";
the return line is indented with an extra space, so have
* to correct it here with the -1
TODO error recovery ?
e: xdebug.ml |
*
* Copyright ( C ) 2009 , 2010 , 2011 Facebook
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation , with the
* special exception on linking described in file license.txt .
*
* This library is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the file
* license.txt for more details .
*
* Copyright (C) 2009, 2010, 2011 Facebook
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation, with the
* special exception on linking described in file license.txt.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
* license.txt for more details.
*)
open Common2
open Common
open Ast_php
module Ast = Ast_php
* Wrappers around the really good debugger / profiler / tracer for PHP :
*
* /
*
* To enable xdebug , you need to add the loading of xdebug.so in one
* of the php config .ini file , for instance add in php.ini :
*
* zend_extension=/usr / local / php / lib / php / extensions / no - debug - non - zts-20060613 / xdebug.so
*
* Then php -v should display something like :
*
* Zend Engine v2.2.0 , Copyright ( c ) 1998 - 2007 Zend Technologies
* with v2.0.3.fb1 , Copyright ( c ) 2002 - 2007 , by
*
* php -d xdebug.collect_params=3
* = > full variable contents with the limits respected by
* xdebug.var_display_max_children , max_data , max_depth
*
* But the dumped file can be huge :
* - for unit tested flib / core/ 1.8 Go
* - for unit tested flib/ 5Go ...
*
* so had to optimize a few things :
*
* - use compiled regexp ,
* - fast - path parser for expression .
* - use iterator interface instead of using lists .
*
* See -index_db_xdebug and Database_php_build for the code using
* this module .
* See also dynamic_analysis.ml .
*
* Wrappers around the really good debugger/profiler/tracer for PHP:
*
* /
*
* To enable xdebug, you need to add the loading of xdebug.so in one
* of the php config .ini file, for instance add in php.ini:
*
* zend_extension=/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so
*
* Then php -v should display something like:
*
* Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
* with Xdebug v2.0.3.fb1, Copyright (c) 2002-2007, by Derick Rethans
*
* php -d xdebug.collect_params=3
* => full variable contents with the limits respected by
* xdebug.var_display_max_children, max_data, max_depth
*
* But the dumped file can be huge:
* - for unit tested flib/core/ 1.8 Go
* - for unit tested flib/ 5Go ...
*
* so had to optimize a few things:
*
* - use compiled regexp,
* - fast-path parser for expression.
* - use iterator interface instead of using lists.
*
* See -index_db_xdebug and Database_php_build for the code using
* this module.
* See also dynamic_analysis.ml.
*
*)
type kind_call =
| FunCall of string
Depending on config below , some of the fields may be incomplete
* ( e.g. f_return will be None when cfg.collect_return = false
* (e.g. f_return will be None when cfg.collect_return = false *)
type call_trace = {
f_call: kind_call;
f_file: Common.filename;
f_line: int;
f_params: Ast_php.expr list;
f_return: Ast_php.expr option;
}
let xdebug_main_name = "xdebug_main"
type config = {
auto_trace: int;
trace_options: int;
trace_format: int;
collect_params: params_mode;
collect_return: bool;
var_display_max_children: int;
val_display_max_data: int;
var_display_max_depth: int;
}
and params_mode =
| NoParam
| TypeAndArity
| TypeAndArityAndTooltip
| FullParam
| FullParamAndVar
let default_config = {
auto_trace = 1;
trace_options = 1;
trace_format = 0;
collect_params = FullParam;
collect_return = true;
default = 128
default = 512
default = 3
}
let s_of_kind_call = function
| FunCall s -> s
| ObjectCall (s1, s2) -> s1 ^ "->" ^ s2
| ClassCall (s1, s2) -> s1 ^ "::" ^ s2
let string_of_call_trace x =
spf "%s:%d: call = %s"
x.f_file x.f_line (s_of_kind_call x.f_call)
let intval_of_params_mode = function
| NoParam -> 0
| TypeAndArity -> 1
| TypeAndArityAndTooltip -> 2
| FullParam -> 3
| FullParamAndVar -> 4
let hash_of_config cfg =
match cfg with
{
auto_trace = v_auto_trace;
trace_options = v_trace_options;
trace_format = v_trace_format;
collect_params = v_collect_params;
collect_return = v_collect_return;
var_display_max_children = v_var_display_max_children;
val_display_max_data = v_val_display_max_data;
var_display_max_depth = v_var_display_max_depth
} ->
Common.hash_of_list [
"auto_trace", i_to_s v_auto_trace;
"trace_options", i_to_s v_trace_options;
"trace_format", i_to_s v_trace_format;
"collect_params", i_to_s (intval_of_params_mode v_collect_params);
"collect_return", if v_collect_return then "1" else "0";
"var_display_max_children", i_to_s v_var_display_max_children;
"val_display_max_data", i_to_s v_val_display_max_data;
"var_display_max_depth", i_to_s v_var_display_max_depth
]
let cmdline_args_of_config cfg =
hash_of_config cfg
+> Common.hash_to_list
+> List.map (fun (s, d) -> spf "-d xdebug.%s=%s" s d)
+> Common.join " "
let php_cmd_with_xdebug_on ?(config = default_config) ~trace_file () =
let (d, b, e) = Common2.dbe_of_filename trace_file in
if e <> "xt"
then failwith "the xdebug trace file must end in .xt";
if Sys.file_exists trace_file && Common2.filesize trace_file > 0
then pr2 (spf "WARNING: %s already exists, xdebug will concatenate data"
trace_file);
let options = cmdline_args_of_config config in
spf "php %s -d xdebug.trace_output_dir=%s -d xdebug.trace_output_name=%s"
options
d
xdebug will automatically appends a " .xt " to the filename
let php_has_xdebug_extension () =
let xs = Common.cmd_to_list "php -v 2>&1" in
xs +> List.exists (fun s -> s =~ ".*with Xdebug v.*")
let sanitize_xdebug_expr_for_parser2 _str =
Str is buggy
let str = Str.global_replace
( Str.regexp " class\b " ) " class_xdebug " str
in
( * bug in xdebug output
let str = Str.global_replace
(Str.regexp "class\b") "class_xdebug" str
in
let str = Str.global_replace
(Str.regexp ")[ \t]*}") ");}" str
in
str
*)
let str = Pcre.replace ~pat:"\\?\\?\\ ? " ~templ : " ... " str in
let str = Pcre.replace ~pat:"class " ~templ:"class_xdebug " str in
let str = Pcre.replace
~pat:"resource\\([^)]*\\ ) of type \\([^)]*\\ ) "
~templ:"resource_xdebug " str
in
( * bug in xdebug output
let str = Pcre.replace ~pat:"\\?\\?\\?" ~templ:"..." str in
let str = Pcre.replace ~pat:"class" ~templ:"class_xdebug" str in
let str = Pcre.replace
~pat:"resource\\([^)]*\\) of type \\([^)]*\\)"
~templ:"resource_xdebug" str
in
let str = Pcre.replace ~pat:"([^{ \t])[ \t]+}" ~itempl:(Pcre.subst "$1;}") str in
str
*)
failwith "TODO: deprecated code, we removed the dependencies to PCRE"
let sanitize_xdebug_expr_for_parser a =
Common.profile_code "sanitize" (fun () -> sanitize_xdebug_expr_for_parser2 a)
bench :
* on toy.xt :
* - 0.157s with regular expr parser
* - 0.002 with in memory parser that do nt call xhp , tag file info , etc
* on flib_core.xt : 44s in native mode
* on toy.xt:
* - 0.157s with regular expr parser
* - 0.002 with in memory parser that dont call xhp, tag file info, etc
* on flib_core.xt: 44s in native mode
*)
let parse_xdebug_expr2 s =
Parse_php.xdebug_expr_of_string s
let parse_xdebug_expr a =
Common.profile_code "Xdebug.parse" (fun () -> parse_xdebug_expr2 a)
examples :
* 0.0009 99800 - > { main } ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:0
* 0.0009 99800 - > main ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:41
* 0.0006 97600 - > A->__construct(4 ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / object_values.php:24
* TODO ModuleStack::current ( )
*
* update : can also get :
*
* 1.9389 140618888 - > strtolower ( ) /data / users / pad / www - git / flib / web / haste / transform.php(77 ) : regexp code:1
*
* 0.0009 99800 -> {main}() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:0
* 0.0009 99800 -> main() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:41
* 0.0006 97600 -> A->__construct(4) /home/pad/mobile/project-facebook/pfff/tests/xdebug/object_values.php:24
* TODO ModuleStack::current()
*
* update: can also get:
*
* 1.9389 140618888 -> strtolower() /data/users/pad/www-git/flib/web/haste/transform.php(77) : regexp code:1
*
*)
let regexp_in =
Str.regexp
1 , everything before the arrow
"[ \t]+" ^
2 3 , time and nbcall ?
"[ \t]+" ^
"->[ \t]+" ^
4 , funcname or
5 , arguments
6 , filename . was /. * but can get weird lines
* such as above with the ' regexp code:1 ' which
* then got ' : ' matched at the wrong place .
* such as above with the 'regexp code:1' which
* then got ':' matched at the wrong place.
*)
":" ^
7 , line
"")
examples :
* > = > 8
* >=> 8
*)
let regexp_out =
Str.regexp
1 , spacing
">=> " ^
2 , returned expression
)
example :
* 0.0009 99800 - > { main } ( ) /home / pad / mobile / project - facebook / pfff / tests / xdebug / basic_values.php:0
* 0.0009 99800 -> {main}() /home/pad/mobile/project-facebook/pfff/tests/xdebug/basic_values.php:0
*)
let _regexp_special_main =
Str.regexp ".*-> {main}()"
let regexp_last_time =
Str.regexp (
"^[ \t]+[0-9]+\\.[0-9]+[ \t]+[0-9]+$"
)
let regexp_meth_call =
Str.regexp (
"\\([A-Za-z_0-9]+\\)->\\(.*\\)"
)
let regexp_class_call =
Str.regexp (
"\\([A-Za-z_0-9]+\\)::\\(.*\\)"
)
let regexp_fun_call =
Str.regexp (
"[A-Za-z_0-9]+$"
)
let iter_dumpfile2
?(config=default_config)
?(show_progress=true)
?(fatal_when_exn=false)
callback file =
pr2 (spf "computing number of lines of %s" file);
let nblines = Common2.nblines_with_wc file in
pr2 (spf "nb lines = %d" nblines);
let nb_fails = ref 0 in
Console.execute_and_show_progress ~show:show_progress nblines (fun k ->
Common.with_open_infile file (fun (chan) ->
let stack = ref [] in
let line_no = ref 0 in
try
while true do
let line = input_line chan in
incr line_no;
k ();
match line with
most common case first
| _ when line ==~ regexp_in ->
let (before_arrow, _time, _nbcall, call, args, file, lineno) =
Common.matched7 line
in
let trace_opt =
(try
let kind_call =
match () with
| _ when call ==~ regexp_meth_call ->
let (sclass, smethod) = Common.matched2 call in
ObjectCall(sclass, smethod)
| _ when call ==~ regexp_class_call ->
let (sclass, smethod) = Common.matched2 call in
ClassCall(sclass, smethod)
| _ when call ==~ regexp_fun_call ->
FunCall(call)
| _ when call = "{main}" ->
FunCall(xdebug_main_name)
| _ ->
failwith ("not a funcall: " ^ call)
in
(match kind_call with
| FunCall "require_once"
| FunCall "include_once"
| FunCall "include"
| FunCall "require"
-> None
| _ ->
let args =
if config.collect_params = NoParam
then []
else
let str = sanitize_xdebug_expr_for_parser args in
let str = "foo(" ^ str ^ ")" in
let expr = parse_xdebug_expr str in
match expr with
| Call (Id name, args_paren) ->
assert(Ast.str_of_name name = "foo");
Ast.unparen args_paren
+> Ast.uncomma
+> List.map (function
| Arg e -> e
| _ -> raise Impossible
)
| _ -> raise Impossible
in
let trace = {
f_call = kind_call;
f_file = file;
f_line = s_to_i lineno;
f_params = args;
}
in
Some trace
)
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "php parsing pb: exn = %s, s = %s"
(Common.exn_to_s exn) args);
incr nb_fails;
if fatal_when_exn then raise exn
else
None
)
in
trace_opt +> Common.do_option (fun trace ->
if not config.collect_return then
(try
if trace.f_call = FunCall(xdebug_main_name)
then ()
else
callback trace
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "callback pb: exn = %s, line = %s"
(Common.exn_to_s exn) line);
raise exn
)
else
Common.push (String.length before_arrow, trace) stack;
)
| _ when line ==~ regexp_out ->
let (before_arrow, return_expr) = Common.matched2 line in
let str = sanitize_xdebug_expr_for_parser return_expr in
let depth_here = String.length before_arrow - 1 in
(try
let expr = parse_xdebug_expr str in
match !stack with
| [] -> failwith "empty call stack"
| (depth_call, trace)::rest ->
(match depth_call <=> depth_here with
| Common2.Equal ->
stack := rest;
let caller = trace.f_call in
if caller = FunCall(xdebug_main_name)
then ()
else
(try
let trace = { trace with f_return = Some expr } in
callback trace
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "callback pb: exn = %s, line = %s"
(Common.exn_to_s exn) line);
raise exn
)
| Common2.Inf ->
raise Todo
| Common2.Sup ->
raise Todo
)
with
| Timeout -> raise Timeout
| exn ->
pr2(spf "php parsing pb: exn = %s, str = %s, line = %d "
(Common.exn_to_s exn) str !line_no);
incr nb_fails;
if fatal_when_exn then raise exn;
)
| _ when line =~ "^TRACE" -> ()
| _ when line ==~ regexp_last_time -> ()
| _ when line = "" -> ()
| _ ->
pr2 ("parsing pb: " ^ line);
incr nb_fails;
done
with End_of_file -> ()
));
pr2 (spf "nb xdebug parsing fails = %d" !nb_fails);
()
let iter_dumpfile ?config ?show_progress ?fatal_when_exn a b =
Common.profile_code "Xdebug.iter_dumpfile" (fun () ->
iter_dumpfile2 ?config ?show_progress ?fatal_when_exn a b)
|
be391ef555d66fd20c919b89ff89599ffe26f1f076779ab859df0777269783be | replikativ/replikativ | connect.cljc | (ns replikativ.connect
"Connection management middleware."
(:require [replikativ.environ :refer [*id-fn*]]
[replikativ.core :refer [wire]]
[kabel.peer :refer [drain]]
[konserve.core :as k]
#?(:clj [kabel.platform-log :refer [debug info warn error]])
[clojure.set :as set]
#?(:clj [superv.async :refer [<? <<? go-try go-loop-try alt? >?
go-for go-loop-super go-super
restarting-supervisor]]
:cljs [superv.async :refer [restarting-supervisor]])
[kabel.client :refer [client-connect!]]
#?(:clj [clojure.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]
:cljs [cljs.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]))
#?(:cljs (:require-macros [cljs.core.async.macros :refer (go go-loop alt!)]
[superv.async :refer [<<? <? go-for go-try go-loop-try alt? >?
go-for go-loop-super go-super]]
[kabel.platform-log :refer [debug info warn error]])))
(defn handshake-middleware [url id subs extend? out [S peer [c-in c-out]]]
(let [new-out (chan)
subed-ch (chan)
sub-id (*id-fn*)
;; we intercept and track the subscription process
p (pub new-out (fn [{:keys [type] :as m}]
#_(prn "SENDING NEW_OUT" m)
(or ({:sub/identities-ack :sub/identities-ack} type)
:unrelated)))]
(sub p :sub/identities-ack subed-ch)
;; pass through
(sub p :sub/identities-ack c-out)
(sub p :unrelated c-out)
;; start handshake
(go-try S
(try
(>? S c-out {:type :sub/identities
:identities subs
:id sub-id
:extend? extend?})
(debug {:event :connect-started-handshake :sub-id sub-id})
;; wait for ack on backsubscription
(<? S (go-loop-try S [{id :id :as c} (<? S subed-ch)]
(debug {:event :connect-backsubscription
:sub-id sub-id :ack-msg c})
(when (and c (not= id sub-id))
(recur (<? S subed-ch)))))
(async/close! subed-ch)
;; notify initiator of the connection
(>? S out {:type :connect/peer-ack
:url url
:close-ch c-in
:id id})
(catch #?(:clj Exception :cljs js/Error) e
(>? S out {:type :connect/peer-ack
:url url
:id id}))))
[S peer [c-in new-out]]))
(defn handle-connection-request
"Service connection requests. Waits for ack on initial subscription,
also ensuring you have the remote state of your subscriptions
locally replicated."
[S peer conn-ch out]
(go-loop-super S [{:keys [url id retries] :as c} (<? S conn-ch)]
;; keep connection scope for reconnects
(when c
(restarting-supervisor
(fn [S]
(go-super S
(info {:event :connecting-to :peer (:id @peer) :url url})
(let [{{:keys [log middleware serialization-middleware]
{:keys [read-handlers write-handlers] :as store} :cold-store} :volatile
pn :id} @peer
subs (<? S (k/get-in store [:peer-config :sub :subscriptions]))
extend? (<? S (k/get-in store [:peer-config :sub :extend?]))]
(debug {:event :connection-pending :url url})
;; build middleware pipeline with channel pair
;; from client-connect
(->> [S peer (<? S (client-connect! S url id
read-handlers
write-handlers))]
serialization-middleware
(handshake-middleware url id subs extend? out)
middleware
wire
drain))))
:delay (* 10 1000)
:retries retries
:supervisor S
:log-fn (fn [level msg]
(case level
:error (error msg)
:warn (warn msg)
:debug (debug msg)
:info (info msg)
(debug msg)))))
(recur (<? S conn-ch))))
(defn connect
[[S peer [in out]]]
(let [new-in (chan)]
(go-try S
(let [p (pub in (fn [{:keys [type]}]
(or ({:connect/peer :connect/peer} type)
:unrelated)))
conn-ch (chan)]
(sub p :connect/peer conn-ch)
(handle-connection-request S peer conn-ch out)
(sub p :unrelated new-in true)))
[S peer [new-in out]]))
| null | https://raw.githubusercontent.com/replikativ/replikativ/1533a7e43e46bfb70e8c8eb34dc5708e611a478d/src/replikativ/connect.cljc | clojure | we intercept and track the subscription process
pass through
start handshake
wait for ack on backsubscription
notify initiator of the connection
keep connection scope for reconnects
build middleware pipeline with channel pair
from client-connect | (ns replikativ.connect
"Connection management middleware."
(:require [replikativ.environ :refer [*id-fn*]]
[replikativ.core :refer [wire]]
[kabel.peer :refer [drain]]
[konserve.core :as k]
#?(:clj [kabel.platform-log :refer [debug info warn error]])
[clojure.set :as set]
#?(:clj [superv.async :refer [<? <<? go-try go-loop-try alt? >?
go-for go-loop-super go-super
restarting-supervisor]]
:cljs [superv.async :refer [restarting-supervisor]])
[kabel.client :refer [client-connect!]]
#?(:clj [clojure.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]
:cljs [cljs.core.async :as async
:refer [>! timeout chan put! pub sub unsub close!]]))
#?(:cljs (:require-macros [cljs.core.async.macros :refer (go go-loop alt!)]
[superv.async :refer [<<? <? go-for go-try go-loop-try alt? >?
go-for go-loop-super go-super]]
[kabel.platform-log :refer [debug info warn error]])))
(defn handshake-middleware [url id subs extend? out [S peer [c-in c-out]]]
(let [new-out (chan)
subed-ch (chan)
sub-id (*id-fn*)
p (pub new-out (fn [{:keys [type] :as m}]
#_(prn "SENDING NEW_OUT" m)
(or ({:sub/identities-ack :sub/identities-ack} type)
:unrelated)))]
(sub p :sub/identities-ack subed-ch)
(sub p :sub/identities-ack c-out)
(sub p :unrelated c-out)
(go-try S
(try
(>? S c-out {:type :sub/identities
:identities subs
:id sub-id
:extend? extend?})
(debug {:event :connect-started-handshake :sub-id sub-id})
(<? S (go-loop-try S [{id :id :as c} (<? S subed-ch)]
(debug {:event :connect-backsubscription
:sub-id sub-id :ack-msg c})
(when (and c (not= id sub-id))
(recur (<? S subed-ch)))))
(async/close! subed-ch)
(>? S out {:type :connect/peer-ack
:url url
:close-ch c-in
:id id})
(catch #?(:clj Exception :cljs js/Error) e
(>? S out {:type :connect/peer-ack
:url url
:id id}))))
[S peer [c-in new-out]]))
(defn handle-connection-request
"Service connection requests. Waits for ack on initial subscription,
also ensuring you have the remote state of your subscriptions
locally replicated."
[S peer conn-ch out]
(go-loop-super S [{:keys [url id retries] :as c} (<? S conn-ch)]
(when c
(restarting-supervisor
(fn [S]
(go-super S
(info {:event :connecting-to :peer (:id @peer) :url url})
(let [{{:keys [log middleware serialization-middleware]
{:keys [read-handlers write-handlers] :as store} :cold-store} :volatile
pn :id} @peer
subs (<? S (k/get-in store [:peer-config :sub :subscriptions]))
extend? (<? S (k/get-in store [:peer-config :sub :extend?]))]
(debug {:event :connection-pending :url url})
(->> [S peer (<? S (client-connect! S url id
read-handlers
write-handlers))]
serialization-middleware
(handshake-middleware url id subs extend? out)
middleware
wire
drain))))
:delay (* 10 1000)
:retries retries
:supervisor S
:log-fn (fn [level msg]
(case level
:error (error msg)
:warn (warn msg)
:debug (debug msg)
:info (info msg)
(debug msg)))))
(recur (<? S conn-ch))))
(defn connect
[[S peer [in out]]]
(let [new-in (chan)]
(go-try S
(let [p (pub in (fn [{:keys [type]}]
(or ({:connect/peer :connect/peer} type)
:unrelated)))
conn-ch (chan)]
(sub p :connect/peer conn-ch)
(handle-connection-request S peer conn-ch out)
(sub p :unrelated new-in true)))
[S peer [new-in out]]))
|
98816140bdb3216245ceeed2da5e548287dbe0198877fb114aeb240a86d59183 | f-f/markiki | db.cljs | (ns markiki.db)
;; -- Default app-db Value ---------------------------------------------------
;;
When the application first starts , this will be the value put in app - db
;; Look in core.cljs for "(dispatch-sync [:initialise-db])"
;;
(def default-value
{:articles [] ;; Vector containing all the articles.
;; Each article has the following properties:
;; :title :text :last-modified :path
Vector containing the 10 articles that better
;; matched the last search query, ordered by score (DESC)
:last-article {} ;; A single article - the last loaded
:articles-tree {} ;; A map tree containing all the articles, in which
;; a category is a new level of maps. It gets parsed
;; to build the home index
:title "" ;; The title of the wiki
:description "" ;; Optional description for the homepage
:loading? true }) ;; If it's loading display the spinning cog
| null | https://raw.githubusercontent.com/f-f/markiki/7a4fc37068c08e9f5566294af7b47339604886d5/src/markiki/db.cljs | clojure | -- Default app-db Value ---------------------------------------------------
Look in core.cljs for "(dispatch-sync [:initialise-db])"
Vector containing all the articles.
Each article has the following properties:
:title :text :last-modified :path
matched the last search query, ordered by score (DESC)
A single article - the last loaded
A map tree containing all the articles, in which
a category is a new level of maps. It gets parsed
to build the home index
The title of the wiki
Optional description for the homepage
If it's loading display the spinning cog | (ns markiki.db)
When the application first starts , this will be the value put in app - db
(def default-value
Vector containing the 10 articles that better
|
4bdb83d1caba0873af15f731a26aee2c68b408b17af53b46fe4d510e27f7b3fa | shenxs/about-scheme | operator.rkt | #lang racket
(require "tensor.rkt")
(provide (all-defined-out))
;; in 输入 list of tensor 例如 (list x y)
op 计算函数 function 参数对应计算的数量 参数为 tensor中的值
gradient 梯度下降函数
(define (make-operator in op gradient)
(define (abstract-op) (apply op (map tensor-get in)) )
(define result (make-tensor (abstract-op)))
(define (abstract-gradient) (apply gradient
(cons (tensor-get-delta result)
(map tensor-get in))))
(for ([i in])
(tensor-add-forward i
(lambda ()
(tensor-set! result (abstract-op)))))
(tensor-add-backward result abstract-gradient)
result)
(define (ADD x y)
(define (add-op _x _y)
(+ _x _y))
(define (gradient delta _x _y)
(tensor-update! x delta)
(tensor-update! y delta))
(make-operator (list x y) add-op gradient)
)
(define (MUL x y)
(define (mul-op _x _y)
(* _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta _y))
(tensor-update! y (* delta _x)))
(make-operator (list x y) mul-op gradient)
)
(define (DIV x y)
(define (div-op _x _y)
(/ _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta (/ 1 _y)))
(tensor-update! y (* delta (- (/ _x (sqr _y))))))
(make-operator (list x y) div-op gradient)
)
(define (MINUS x y)
(define (minus-op _x _y)
(- _x _y))
(define (gradient delta _x _y)
(tensor-update! x delta)
(tensor-update! y (- delta)))
(make-operator (list x y) minus-op gradient))
(define (SIN x)
(define (sin-op _x)
(sin _x))
(define (gradient delta _x)
(tensor-update! x (* (cos _x) delta)))
(make-operator (list x) sin-op gradient)
)
(define (COS x)
(define (cos-op _x)
(cos _x))
(define (gradient delta _x)
(tensor-update! x (* delta (- (sin _x)))))
(make-operator (list x) cos-op gradient)
)
(define (TAN x)
(define (tan-op _x)
(tensor-set! x (tan _x)))
(define (gradient delta _x)
(tensor-update! x (* delta (/ 1 (sqr (cos _x))))))
(make-operator (list x) tan-op gradient)
)
(define (LN x)
(define (ln-op _x)
(log _x))
(define (gradient delta _x)
(tensor-update! x (* delta (/ 1 _x))))
(make-operator (list x) ln-op gradient)
)
(define (EXP x)
(define (exp-op _x)
(exp _x))
(define (gradient delta _x)
(tensor-update! x (* delta (exp _x))))
(make-operator (list x) exp-op gradient)
)
(define (EXPT x y)
(define (power-op _x _y)
(expt _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta (* _y (expt _x (- _y 1)))))
(tensor-update! y (* delta (* (log _x)
(exp (* _y (log _x)))))))
(make-operator (list x y) power-op gradient))
(define (LOG x y)
(define (log-op _x _y)
(/ (log (tensor-get _x))
(log (tensor-get _y))))
(define (gradient delta _x _y)
(tensor-update! x (* delta (- (/ (log _y)
(* _x (sqr (log _x)))))))
(tensor-update! y (* delta (/ 1 (* _y (log _x))))))
(make-operator (list x y) log-op gradient))
| null | https://raw.githubusercontent.com/shenxs/about-scheme/d458776a62cb0bbcbfbb2a044ed18b849f26fd0f/bp/operator.rkt | racket | in 输入 list of tensor 例如 (list x y) | #lang racket
(require "tensor.rkt")
(provide (all-defined-out))
op 计算函数 function 参数对应计算的数量 参数为 tensor中的值
gradient 梯度下降函数
(define (make-operator in op gradient)
(define (abstract-op) (apply op (map tensor-get in)) )
(define result (make-tensor (abstract-op)))
(define (abstract-gradient) (apply gradient
(cons (tensor-get-delta result)
(map tensor-get in))))
(for ([i in])
(tensor-add-forward i
(lambda ()
(tensor-set! result (abstract-op)))))
(tensor-add-backward result abstract-gradient)
result)
(define (ADD x y)
(define (add-op _x _y)
(+ _x _y))
(define (gradient delta _x _y)
(tensor-update! x delta)
(tensor-update! y delta))
(make-operator (list x y) add-op gradient)
)
(define (MUL x y)
(define (mul-op _x _y)
(* _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta _y))
(tensor-update! y (* delta _x)))
(make-operator (list x y) mul-op gradient)
)
(define (DIV x y)
(define (div-op _x _y)
(/ _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta (/ 1 _y)))
(tensor-update! y (* delta (- (/ _x (sqr _y))))))
(make-operator (list x y) div-op gradient)
)
(define (MINUS x y)
(define (minus-op _x _y)
(- _x _y))
(define (gradient delta _x _y)
(tensor-update! x delta)
(tensor-update! y (- delta)))
(make-operator (list x y) minus-op gradient))
(define (SIN x)
(define (sin-op _x)
(sin _x))
(define (gradient delta _x)
(tensor-update! x (* (cos _x) delta)))
(make-operator (list x) sin-op gradient)
)
(define (COS x)
(define (cos-op _x)
(cos _x))
(define (gradient delta _x)
(tensor-update! x (* delta (- (sin _x)))))
(make-operator (list x) cos-op gradient)
)
(define (TAN x)
(define (tan-op _x)
(tensor-set! x (tan _x)))
(define (gradient delta _x)
(tensor-update! x (* delta (/ 1 (sqr (cos _x))))))
(make-operator (list x) tan-op gradient)
)
(define (LN x)
(define (ln-op _x)
(log _x))
(define (gradient delta _x)
(tensor-update! x (* delta (/ 1 _x))))
(make-operator (list x) ln-op gradient)
)
(define (EXP x)
(define (exp-op _x)
(exp _x))
(define (gradient delta _x)
(tensor-update! x (* delta (exp _x))))
(make-operator (list x) exp-op gradient)
)
(define (EXPT x y)
(define (power-op _x _y)
(expt _x _y))
(define (gradient delta _x _y)
(tensor-update! x (* delta (* _y (expt _x (- _y 1)))))
(tensor-update! y (* delta (* (log _x)
(exp (* _y (log _x)))))))
(make-operator (list x y) power-op gradient))
(define (LOG x y)
(define (log-op _x _y)
(/ (log (tensor-get _x))
(log (tensor-get _y))))
(define (gradient delta _x _y)
(tensor-update! x (* delta (- (/ (log _y)
(* _x (sqr (log _x)))))))
(tensor-update! y (* delta (/ 1 (* _y (log _x))))))
(make-operator (list x y) log-op gradient))
|
2fc80e919b5a0d1960a8590e7ae5be209d3b4d1d2d637032358a7cda73fdd422 | brandonchinn178/advent-of-code | Day01.hs | import Data.List (groupBy, sort)
import Data.Ord (Down (..))
import Data.Time
main :: IO ()
main = withTimer $ do
input <- lines <$> readFile "2022/data/Day01.txt"
let elves = filter (/= [""]) $ groupBy (\a b -> not (null a || null b)) input
case map getDown $ sort $ map (Down . sum . map read) elves of
a:b:c:_ -> print a >> print (a + b + c)
withTimer :: IO () -> IO ()
withTimer m = do
start <- getCurrentTime
m
end <- getCurrentTime
putStrLn $ "Elapsed: " <> show (end `diffUTCTime` start)
| null | https://raw.githubusercontent.com/brandonchinn178/advent-of-code/025cbb91bd4cd257be2dd49b50f8bf4414e5d05e/2022/Day01.hs | haskell | import Data.List (groupBy, sort)
import Data.Ord (Down (..))
import Data.Time
main :: IO ()
main = withTimer $ do
input <- lines <$> readFile "2022/data/Day01.txt"
let elves = filter (/= [""]) $ groupBy (\a b -> not (null a || null b)) input
case map getDown $ sort $ map (Down . sum . map read) elves of
a:b:c:_ -> print a >> print (a + b + c)
withTimer :: IO () -> IO ()
withTimer m = do
start <- getCurrentTime
m
end <- getCurrentTime
putStrLn $ "Elapsed: " <> show (end `diffUTCTime` start)
| |
60d5c5e8c5789d48c221e7db7f62fcb07f9629584c5576d716655d278e24a133 | suvash/one-time | hotp.clj | (ns one-time.hotp
(:import java.nio.ByteBuffer
javax.crypto.spec.SecretKeySpec
javax.crypto.Mac)
(:require [one-time.codec :as codec]))
(declare hmac-sha-digest)
(declare get-hmac-sha-type-string)
(defn get-token
"Return a HOTP token (HMAC-Based One-Time Password Algorithm)
based on a secret and a counter, as specified in
"
([secret counter]
Use HMAC - SHA-1 as default when not provided
(get-token secret counter :hmac-sha-1))
([secret counter hmac-sha-type]
(let [digest (hmac-sha-digest secret counter hmac-sha-type)
offset (bit-and (digest 19) 0xf)
code (bit-or (bit-shift-left (bit-and (digest offset) 0x7f) 24)
(bit-shift-left (bit-and (digest (+ offset 1)) 0xff) 16)
(bit-shift-left (bit-and (digest (+ offset 2)) 0xff) 8)
(bit-and (digest (+ offset 3)) 0xff))]
(rem code 1000000))))
(defn- hmac-sha-digest
"Return the HMAC-SHA-xxx digest for a given secret, counter and a sha type."
[secret counter hmac-sha-type]
(let [secret-binary (codec/decode-binary secret)
data (.array (.putLong (ByteBuffer/allocate 8) counter))
hmac-sha-type-string (get-hmac-sha-type-string hmac-sha-type)
spec (SecretKeySpec. secret-binary hmac-sha-type-string)
sha-mac (let [mac (Mac/getInstance hmac-sha-type-string)]
(.init mac spec) ; mutating api
mac)
hash (into [] (.doFinal sha-mac data))] ; mutating api
hash))
(defn- get-hmac-sha-type-string
"Return the correct hmac sha type string as expected by the library,
with safe default of hmac-sha-1 in case of bad input."
[hmac-sha-type]
(let [hmac-sha-type-string {:hmac-sha-1 "HmacSHA1"
:hmac-sha-256 "HmacSHA256"
:hmac-sha-512 "HmacSHA512"}]
(get hmac-sha-type-string hmac-sha-type "HmacSHA1")))
| null | https://raw.githubusercontent.com/suvash/one-time/63981bbe1a27eaac80a2bda1b1887c4262c2a61f/src/one_time/hotp.clj | clojure | mutating api
mutating api | (ns one-time.hotp
(:import java.nio.ByteBuffer
javax.crypto.spec.SecretKeySpec
javax.crypto.Mac)
(:require [one-time.codec :as codec]))
(declare hmac-sha-digest)
(declare get-hmac-sha-type-string)
(defn get-token
"Return a HOTP token (HMAC-Based One-Time Password Algorithm)
based on a secret and a counter, as specified in
"
([secret counter]
Use HMAC - SHA-1 as default when not provided
(get-token secret counter :hmac-sha-1))
([secret counter hmac-sha-type]
(let [digest (hmac-sha-digest secret counter hmac-sha-type)
offset (bit-and (digest 19) 0xf)
code (bit-or (bit-shift-left (bit-and (digest offset) 0x7f) 24)
(bit-shift-left (bit-and (digest (+ offset 1)) 0xff) 16)
(bit-shift-left (bit-and (digest (+ offset 2)) 0xff) 8)
(bit-and (digest (+ offset 3)) 0xff))]
(rem code 1000000))))
(defn- hmac-sha-digest
"Return the HMAC-SHA-xxx digest for a given secret, counter and a sha type."
[secret counter hmac-sha-type]
(let [secret-binary (codec/decode-binary secret)
data (.array (.putLong (ByteBuffer/allocate 8) counter))
hmac-sha-type-string (get-hmac-sha-type-string hmac-sha-type)
spec (SecretKeySpec. secret-binary hmac-sha-type-string)
sha-mac (let [mac (Mac/getInstance hmac-sha-type-string)]
mac)
hash))
(defn- get-hmac-sha-type-string
"Return the correct hmac sha type string as expected by the library,
with safe default of hmac-sha-1 in case of bad input."
[hmac-sha-type]
(let [hmac-sha-type-string {:hmac-sha-1 "HmacSHA1"
:hmac-sha-256 "HmacSHA256"
:hmac-sha-512 "HmacSHA512"}]
(get hmac-sha-type-string hmac-sha-type "HmacSHA1")))
|
ac1a5191ffe5161ad3e2759da0feb2a450cc1e4e22ab5b0b83b3ece695aa9204 | janestreet/base_quickcheck | shrinker_example.ml | open Core
module Shrinker = Quickcheck.Shrinker
module Generator = Quickcheck.Generator
module Sorted_list = struct
type t = int list [@@deriving sexp]
let of_list list = List.stable_sort ~compare:Int.compare list
let to_list t = t
let quickcheck_generator elt =
let open Generator.Monad_infix in
List.quickcheck_generator elt >>| of_list
;;
let custom_int_shrinker =
Shrinker.create (fun n ->
if n = 0 then Sequence.empty else Sequence.singleton (n / 2))
;;
let quickcheck_shrinker =
let list_shrinker = List.quickcheck_shrinker custom_int_shrinker in
Shrinker.map list_shrinker ~f:of_list ~f_inverse:to_list
;;
let invariant t =
if List.is_sorted t ~compare:Int.compare
then ()
else failwiths ~here:[%here] "sorted_list isn't sorted" t sexp_of_t
;;
let invalid_merge t_a t_b = List.append t_a t_b
let merge t_a t_b = List.merge t_a t_b ~compare:Int.compare
end
let%test_module "sorted list" =
(module struct
let sorted_list_tuple_gen =
let int_gen = Int.gen_incl (-100) 100 in
let sorted_list_gen = Sorted_list.quickcheck_generator int_gen in
Generator.tuple2 sorted_list_gen sorted_list_gen
;;
let sorted_list_tuple_shrinker =
Shrinker.tuple2 Sorted_list.quickcheck_shrinker Sorted_list.quickcheck_shrinker
;;
let test f (a, b) = f a b |> Sorted_list.invariant
let sexp_of_sorted_list_tuple = [%sexp_of: Sorted_list.t * Sorted_list.t]
let%test_unit "Invalid merge \"should\" produce a valid sorted list (without \
shrinking)"
=
let run () =
Quickcheck.test
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.invalid_merge)
in
(* Swap which line is commented below to see error message with shrinking. *)
assert (does_raise run)
;;
(* run () *)
let%test_unit "Invalid merge \"should\" produce a valid sorted list (with shrinking)" =
let run () =
Quickcheck.test
~shrinker:sorted_list_tuple_shrinker
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.invalid_merge)
in
(* Swap which line is commented below to see error message with shrinking. *)
assert (does_raise run)
;;
(* run () *)
let%test_unit "Valid merge should produce a valid sorted list (with shrinking)" =
Quickcheck.test
~shrinker:sorted_list_tuple_shrinker
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.merge)
;;
end)
;;
| null | https://raw.githubusercontent.com/janestreet/base_quickcheck/b3dc5bda5084253f62362293977e451a6c4257de/examples/shrinker_example.ml | ocaml | Swap which line is commented below to see error message with shrinking.
run ()
Swap which line is commented below to see error message with shrinking.
run () | open Core
module Shrinker = Quickcheck.Shrinker
module Generator = Quickcheck.Generator
module Sorted_list = struct
type t = int list [@@deriving sexp]
let of_list list = List.stable_sort ~compare:Int.compare list
let to_list t = t
let quickcheck_generator elt =
let open Generator.Monad_infix in
List.quickcheck_generator elt >>| of_list
;;
let custom_int_shrinker =
Shrinker.create (fun n ->
if n = 0 then Sequence.empty else Sequence.singleton (n / 2))
;;
let quickcheck_shrinker =
let list_shrinker = List.quickcheck_shrinker custom_int_shrinker in
Shrinker.map list_shrinker ~f:of_list ~f_inverse:to_list
;;
let invariant t =
if List.is_sorted t ~compare:Int.compare
then ()
else failwiths ~here:[%here] "sorted_list isn't sorted" t sexp_of_t
;;
let invalid_merge t_a t_b = List.append t_a t_b
let merge t_a t_b = List.merge t_a t_b ~compare:Int.compare
end
let%test_module "sorted list" =
(module struct
let sorted_list_tuple_gen =
let int_gen = Int.gen_incl (-100) 100 in
let sorted_list_gen = Sorted_list.quickcheck_generator int_gen in
Generator.tuple2 sorted_list_gen sorted_list_gen
;;
let sorted_list_tuple_shrinker =
Shrinker.tuple2 Sorted_list.quickcheck_shrinker Sorted_list.quickcheck_shrinker
;;
let test f (a, b) = f a b |> Sorted_list.invariant
let sexp_of_sorted_list_tuple = [%sexp_of: Sorted_list.t * Sorted_list.t]
let%test_unit "Invalid merge \"should\" produce a valid sorted list (without \
shrinking)"
=
let run () =
Quickcheck.test
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.invalid_merge)
in
assert (does_raise run)
;;
let%test_unit "Invalid merge \"should\" produce a valid sorted list (with shrinking)" =
let run () =
Quickcheck.test
~shrinker:sorted_list_tuple_shrinker
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.invalid_merge)
in
assert (does_raise run)
;;
let%test_unit "Valid merge should produce a valid sorted list (with shrinking)" =
Quickcheck.test
~shrinker:sorted_list_tuple_shrinker
~sexp_of:sexp_of_sorted_list_tuple
sorted_list_tuple_gen
~f:(test Sorted_list.merge)
;;
end)
;;
|
9381f36f55cc8a63f588aada526e30dd6b78df410e228569033dbbffb0fea2b9 | haskell-works/avro | Schema.hs | module Avro.Gen.Schema
where
import Data.Avro.Schema.Schema
import Hedgehog
import qualified Hedgehog.Gen as Gen
import Hedgehog.Range (Range)
import qualified Hedgehog.Range as Range
null :: MonadGen m => m Schema
null = pure Null
boolean :: MonadGen m => m Schema
boolean = pure Boolean
decimalGen :: MonadGen m => m Decimal
decimalGen = Decimal
<$> Gen.integral (Range.linear 0 10)
<*> Gen.integral (Range.linear 0 10)
int :: MonadGen m => m Schema
int = do
dec <- decimalGen
Int <$> Gen.maybe (Gen.element [DecimalI dec, Date, TimeMillis])
long :: MonadGen m => m Schema
long = do
dec <- decimalGen
Long <$> Gen.maybe (Gen.element
[DecimalL dec, TimeMicros, TimestampMillis,
TimestampMicros, LocalTimestampMillis, LocalTimestampMicros])
| null | https://raw.githubusercontent.com/haskell-works/avro/cee0869ce9e52db8942deb86aa66dd7355508d3c/test/Avro/Gen/Schema.hs | haskell | module Avro.Gen.Schema
where
import Data.Avro.Schema.Schema
import Hedgehog
import qualified Hedgehog.Gen as Gen
import Hedgehog.Range (Range)
import qualified Hedgehog.Range as Range
null :: MonadGen m => m Schema
null = pure Null
boolean :: MonadGen m => m Schema
boolean = pure Boolean
decimalGen :: MonadGen m => m Decimal
decimalGen = Decimal
<$> Gen.integral (Range.linear 0 10)
<*> Gen.integral (Range.linear 0 10)
int :: MonadGen m => m Schema
int = do
dec <- decimalGen
Int <$> Gen.maybe (Gen.element [DecimalI dec, Date, TimeMillis])
long :: MonadGen m => m Schema
long = do
dec <- decimalGen
Long <$> Gen.maybe (Gen.element
[DecimalL dec, TimeMicros, TimestampMillis,
TimestampMicros, LocalTimestampMillis, LocalTimestampMicros])
| |
500db36dcecf35dfcc01ff02193ce53d44b919c6bd54337d27b8c600df2348d9 | JohnnyJayJay/slash | gateway_test.clj | (ns slash.gateway-test
(:require [slash.gateway :refer :all]
[clojure.test :refer :all]))
(deftest nop-test
(is (nil? (nop :arg))))
(def handler (constantly "foo"))
(def respond-fn (partial str "bar"))
(deftest return-mw-test
(is (= "barfoo" ((wrap-response-return handler respond-fn) :any))))
| null | https://raw.githubusercontent.com/JohnnyJayJay/slash/b62f3dbca65b37d31ac78a30611027cd4177267b/test/slash/gateway_test.clj | clojure | (ns slash.gateway-test
(:require [slash.gateway :refer :all]
[clojure.test :refer :all]))
(deftest nop-test
(is (nil? (nop :arg))))
(def handler (constantly "foo"))
(def respond-fn (partial str "bar"))
(deftest return-mw-test
(is (= "barfoo" ((wrap-response-return handler respond-fn) :any))))
| |
72c3aeb4649f512d4eeaecdf3bf501592212269dd37e2bfaef07fd3a147c5ec7 | prikhi/bodyweight-server | Main.hs | module Main where
import Network.Wai.Handler.Warp (run)
import System.Environment (lookupEnv)
import Database.Persist.Postgresql (runSqlPool)
import Config (defaultConfig, Config(..), Environment(..), setLogger, makePool)
import Api (app)
import Models (doMigrations)
| Grab Settings From Environmental Variables , Connect to the Database ,
-- & Launch the Web Server.
main :: IO ()
main = do
env <- lookupSetting "ENV" Development
port <- lookupSetting "PORT" 8080
pool <- makePool env
let cfg = defaultConfig { getPool = pool, getEnv = env }
runSqlPool doMigrations pool
run port $ setLogger env $ app cfg
where lookupSetting env def =
maybe def read <$> lookupEnv env
| null | https://raw.githubusercontent.com/prikhi/bodyweight-server/4c5bc92d3c35db676c94b6f32d3245231f97eb66/app/Main.hs | haskell | & Launch the Web Server. | module Main where
import Network.Wai.Handler.Warp (run)
import System.Environment (lookupEnv)
import Database.Persist.Postgresql (runSqlPool)
import Config (defaultConfig, Config(..), Environment(..), setLogger, makePool)
import Api (app)
import Models (doMigrations)
| Grab Settings From Environmental Variables , Connect to the Database ,
main :: IO ()
main = do
env <- lookupSetting "ENV" Development
port <- lookupSetting "PORT" 8080
pool <- makePool env
let cfg = defaultConfig { getPool = pool, getEnv = env }
runSqlPool doMigrations pool
run port $ setLogger env $ app cfg
where lookupSetting env def =
maybe def read <$> lookupEnv env
|
f825b4243a852e1561eb1ae440edb0d960ed21b61ad3ea7327a8d7fd19576c0e | intermine/bluegenes | bootstrap.cljs | (ns bluegenes.components.bootstrap
(:require [reagent.core :as reagent]
[reagent.dom :as dom]
[reagent.dom.server :refer [render-to-static-markup]]
[oops.core :refer [ocall oapply oget oset!]]))
; TODO - Retire this version and use poppable instead
(defn popover
"Reagent wrapper for bootstrap's popover component. It accepts
hiccup-style syntax in its :data-content attribute.
Usage:
[popover [:li {:data-trigger hover
:data-placement right
:data-content [:div [:h1 Hello] [:h4 Goodbye]]} Hover-Over-Me]]"
[]
(reagent/create-class
{:component-did-mount
(fn [this]
(let [node (dom/dom-node this)] (ocall (-> node js/$) "popover")))
:component-will-unmount
(fn [this]
(let [node (dom/dom-node this)] (ocall (-> "popover" js/$) "remove")))
:reagent-render
(fn [[element attributes & rest]]
[element (-> attributes
(assoc :data-html true)
(assoc :data-container "body")
(update :data-content render-to-static-markup)) rest])}))
(defn poppable
"Reagent wrapper for bootstrap's popover component. It accepts
hiccup-style syntax in its :data-content attribute."
[]
(comment "Usage" [poppable {:data [:span "I am some HTML text"]
:children [:a "I have a popover"]}])
(let [dom-node (reagent/atom nil)]
(reagent/create-class
{:component-did-mount
(fn [this]
(-> @dom-node js/$ (ocall "popover")))
:component-will-unmount
(fn [this]
(-> @dom-node js/$ (ocall "popover" "hide")))
:component-did-update
(fn [this]
(let [po (-> @dom-node js/$ (ocall "popover") (ocall "data" "bs.popover"))]
(-> po (ocall "setContent"))
(-> po (oget "$tip") (ocall :addClass "auto"))))
:reagent-render
(fn [{:keys [data children options]}]
[:span (-> {:ref (fn [e] (reset! dom-node e))
:data-placement "auto"
:data-trigger "hover"
:data-html true
:data-container "body"
:data-content (render-to-static-markup data)}
(merge options))
children])})))
(defn tooltip
"Reagent wrapper for bootstrap's tooltip component.
Usage:
[tooltip {:title \"Your fabulous tooltip content goes here, m'dear\"}
;; svg below is the clickable content - e.g. an icon and/or words to go
;; along with it. Implemented as the 'remaining' arg below.
[:svg.icon.icon-question
[:use {:xlinkHref \"#icon-question\"}]]]"
[]
(let [dom (reagent/atom nil)]
(reagent/create-class
{:name "Tooltip"
:reagent-render (fn [props & [remaining]]
[:a
(merge {:data-trigger "hover"
:data-html true
:data-toggle "tooltip"
:data-container "body"
:title nil
:data-placement "auto bottom"
:ref (fn [el] (some->> el js/$ (reset! dom)))}
props)
remaining])})))
| null | https://raw.githubusercontent.com/intermine/bluegenes/417ea23b2d00fdca20ce4810bb2838326a09010e/src/cljs/bluegenes/components/bootstrap.cljs | clojure | TODO - Retire this version and use poppable instead
svg below is the clickable content - e.g. an icon and/or words to go
along with it. Implemented as the 'remaining' arg below. | (ns bluegenes.components.bootstrap
(:require [reagent.core :as reagent]
[reagent.dom :as dom]
[reagent.dom.server :refer [render-to-static-markup]]
[oops.core :refer [ocall oapply oget oset!]]))
(defn popover
"Reagent wrapper for bootstrap's popover component. It accepts
hiccup-style syntax in its :data-content attribute.
Usage:
[popover [:li {:data-trigger hover
:data-placement right
:data-content [:div [:h1 Hello] [:h4 Goodbye]]} Hover-Over-Me]]"
[]
(reagent/create-class
{:component-did-mount
(fn [this]
(let [node (dom/dom-node this)] (ocall (-> node js/$) "popover")))
:component-will-unmount
(fn [this]
(let [node (dom/dom-node this)] (ocall (-> "popover" js/$) "remove")))
:reagent-render
(fn [[element attributes & rest]]
[element (-> attributes
(assoc :data-html true)
(assoc :data-container "body")
(update :data-content render-to-static-markup)) rest])}))
(defn poppable
"Reagent wrapper for bootstrap's popover component. It accepts
hiccup-style syntax in its :data-content attribute."
[]
(comment "Usage" [poppable {:data [:span "I am some HTML text"]
:children [:a "I have a popover"]}])
(let [dom-node (reagent/atom nil)]
(reagent/create-class
{:component-did-mount
(fn [this]
(-> @dom-node js/$ (ocall "popover")))
:component-will-unmount
(fn [this]
(-> @dom-node js/$ (ocall "popover" "hide")))
:component-did-update
(fn [this]
(let [po (-> @dom-node js/$ (ocall "popover") (ocall "data" "bs.popover"))]
(-> po (ocall "setContent"))
(-> po (oget "$tip") (ocall :addClass "auto"))))
:reagent-render
(fn [{:keys [data children options]}]
[:span (-> {:ref (fn [e] (reset! dom-node e))
:data-placement "auto"
:data-trigger "hover"
:data-html true
:data-container "body"
:data-content (render-to-static-markup data)}
(merge options))
children])})))
(defn tooltip
"Reagent wrapper for bootstrap's tooltip component.
Usage:
[tooltip {:title \"Your fabulous tooltip content goes here, m'dear\"}
[:svg.icon.icon-question
[:use {:xlinkHref \"#icon-question\"}]]]"
[]
(let [dom (reagent/atom nil)]
(reagent/create-class
{:name "Tooltip"
:reagent-render (fn [props & [remaining]]
[:a
(merge {:data-trigger "hover"
:data-html true
:data-toggle "tooltip"
:data-container "body"
:title nil
:data-placement "auto bottom"
:ref (fn [el] (some->> el js/$ (reset! dom)))}
props)
remaining])})))
|
5d49836613b592d767bade40737211fb6002d41e7fa0ea07d370e3b65d072fa5 | rroohhh/guix_packages | horizon.scm | (define-module (vup horizon)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system glib-or-gtk)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages linux)
#:use-module (gnu packages serialization)
#:use-module (gnu packages gcc)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages gtk)
#:use-module (gnu packages backup)
#:use-module (gnu packages curl)
#:use-module (gnu packages glib)
#:use-module (gnu packages compression)
#:use-module (gnu packages version-control)
#:use-module (gnu packages maths)
#:use-module (gnu packages gnome)
#:use-module (gnu packages networking)
#:use-module (gnu packages python)
#:use-module (gnu packages boost)
#:use-module (gnu packages pdf)
#:use-module (gnu packages base)
#:use-module (gnu packages tbb)
#:use-module (gnu packages engineering)
#:use-module ((guix licenses) #:prefix license:))
;; (define-public opencascade-occt-fixed
( ( package - input - rewriting / spec ` ( ( " tbb " . , ( const tbb-2020 ) ) ) ) opencascade - occt ) )
(define-public horizon
(let ((commit "750111e829cd6f3563ef8040c224ce147808c27d"))
(package
(name "horizon")
(version (string-append "2.4.0+" (string-take commit 7)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-eda/horizon")
(commit commit)
(recursive? #t)))
(file-name (git-file-name name version))
(sha256
(base32
"0vx3ba4m1knjq53dylj9n3l38cnqihgj6x4jvkr0zmzspic4n6j3"))))
(build-system glib-or-gtk-build-system)
(inputs `(("pkg-config" ,pkg-config) ("util-linux" ,util-linux) ("yaml-cpp" ,yaml-cpp)
("sqlite" ,sqlite) ("gtkmm" ,gtkmm-3) ("curl" ,curl) ("glib" ,glib)
("glib:bin" ,glib "bin") ("libzip" ,libzip) ("libgit2" ,libgit2)
("glm" ,glm) ("librsvg" ,librsvg) ("zeromq" ,zeromq) ("python3" ,python)
("boost" ,boost) ("opencascade" ,opencascade-occt)
("cppzmq" ,cppzmq)
("podofo" ,podofo) ("coreutils" ,coreutils) ("hicolor-icon-theme" ,hicolor-icon-theme)
("librsvg" ,librsvg) ("gcc" ,gcc-11) ("libsigc++" ,libsigc++) ("glibmm" ,glibmm)
("libarchive" ,libarchive) ("libspnav" ,libspnav)))
(arguments
`(#:make-flags (list "GOLD=" "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases (modify-phases %standard-phases
(delete 'configure)
(delete 'check) ; no tests?
(add-after 'unpack 'patch-makefile
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "Makefile"
(("/usr/bin/install") (string-append (assoc-ref inputs "coreutils") "/bin/install")))
#t))
(add-before 'build 'set-casroot
(lambda* (#:key inputs #:allow-other-keys)
(setenv "CASROOT" (assoc-ref inputs "opencascade"))
#t)))))
(synopsis "Horizon is a free EDA package")
(description "Horizon EDA is an Electronic Design Automation package supporting an integrated end-to-end workflow for printed circuit board design including parts management and schematic entry.")
(home-page "-eda.org/")
(license license:gpl3))))
horizon
| null | https://raw.githubusercontent.com/rroohhh/guix_packages/117480ede867def846fa3120766864ed634e9321/vup/horizon.scm | scheme | (define-public opencascade-occt-fixed
no tests? | (define-module (vup horizon)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system glib-or-gtk)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages linux)
#:use-module (gnu packages serialization)
#:use-module (gnu packages gcc)
#:use-module (gnu packages sqlite)
#:use-module (gnu packages gtk)
#:use-module (gnu packages backup)
#:use-module (gnu packages curl)
#:use-module (gnu packages glib)
#:use-module (gnu packages compression)
#:use-module (gnu packages version-control)
#:use-module (gnu packages maths)
#:use-module (gnu packages gnome)
#:use-module (gnu packages networking)
#:use-module (gnu packages python)
#:use-module (gnu packages boost)
#:use-module (gnu packages pdf)
#:use-module (gnu packages base)
#:use-module (gnu packages tbb)
#:use-module (gnu packages engineering)
#:use-module ((guix licenses) #:prefix license:))
( ( package - input - rewriting / spec ` ( ( " tbb " . , ( const tbb-2020 ) ) ) ) opencascade - occt ) )
(define-public horizon
(let ((commit "750111e829cd6f3563ef8040c224ce147808c27d"))
(package
(name "horizon")
(version (string-append "2.4.0+" (string-take commit 7)))
(source (origin
(method git-fetch)
(uri (git-reference
(url "-eda/horizon")
(commit commit)
(recursive? #t)))
(file-name (git-file-name name version))
(sha256
(base32
"0vx3ba4m1knjq53dylj9n3l38cnqihgj6x4jvkr0zmzspic4n6j3"))))
(build-system glib-or-gtk-build-system)
(inputs `(("pkg-config" ,pkg-config) ("util-linux" ,util-linux) ("yaml-cpp" ,yaml-cpp)
("sqlite" ,sqlite) ("gtkmm" ,gtkmm-3) ("curl" ,curl) ("glib" ,glib)
("glib:bin" ,glib "bin") ("libzip" ,libzip) ("libgit2" ,libgit2)
("glm" ,glm) ("librsvg" ,librsvg) ("zeromq" ,zeromq) ("python3" ,python)
("boost" ,boost) ("opencascade" ,opencascade-occt)
("cppzmq" ,cppzmq)
("podofo" ,podofo) ("coreutils" ,coreutils) ("hicolor-icon-theme" ,hicolor-icon-theme)
("librsvg" ,librsvg) ("gcc" ,gcc-11) ("libsigc++" ,libsigc++) ("glibmm" ,glibmm)
("libarchive" ,libarchive) ("libspnav" ,libspnav)))
(arguments
`(#:make-flags (list "GOLD=" "CC=gcc" (string-append "PREFIX=" (assoc-ref %outputs "out")))
#:phases (modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'patch-makefile
(lambda* (#:key inputs #:allow-other-keys)
(substitute* "Makefile"
(("/usr/bin/install") (string-append (assoc-ref inputs "coreutils") "/bin/install")))
#t))
(add-before 'build 'set-casroot
(lambda* (#:key inputs #:allow-other-keys)
(setenv "CASROOT" (assoc-ref inputs "opencascade"))
#t)))))
(synopsis "Horizon is a free EDA package")
(description "Horizon EDA is an Electronic Design Automation package supporting an integrated end-to-end workflow for printed circuit board design including parts management and schematic entry.")
(home-page "-eda.org/")
(license license:gpl3))))
horizon
|
a1df826b4141795eb9c78ab74d66625106682fa0dd497570250c46a9023f9bb4 | picty/concerto | writeLine.ml | open FileOps
let _ =
if Array.length Sys.argv < 5 then exit 1;
let ops = prepare_data_dir Sys.argv.(1) in
ops.write_line Sys.argv.(2) Sys.argv.(3) (Array.to_list (Array.sub Sys.argv 4 ((Array.length Sys.argv) - 4)))
| null | https://raw.githubusercontent.com/picty/concerto/fac5dd04a5a3dcd91782e17b7bd3e0f4a9ddd2e0/writeLine.ml | ocaml | open FileOps
let _ =
if Array.length Sys.argv < 5 then exit 1;
let ops = prepare_data_dir Sys.argv.(1) in
ops.write_line Sys.argv.(2) Sys.argv.(3) (Array.to_list (Array.sub Sys.argv 4 ((Array.length Sys.argv) - 4)))
| |
5436ed4136be958900cc169ab50b6d11b38e25376acd5e94afdc6dc289892531 | tweag/ormolu | super-classes.hs | class () => Foo a
class Foo a => Bar a
class (Foo a,Bar a) =>
Baz a
class (
Foo a, -- Foo?
Bar a, -- Bar?
) => BarBar a
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/class/super-classes.hs | haskell | Foo?
Bar? | class () => Foo a
class Foo a => Bar a
class (Foo a,Bar a) =>
Baz a
class (
) => BarBar a
|
ab2d3087796d0466f153bbc8514b4b6045809e8f4d2241bdf5702021650d4bc8 | weblocks-framework/weblocks | presentation.lisp |
(in-package :weblocks)
(export '(presentation))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod view-argument-quoting-strategy ((arg-name (eql :present-as)))
:list)
(setf (gethash :present-as *custom-view-field-argument-compilers*)
(lambda (slot-name presentation)
(let ((presentation (ensure-list presentation)))
`(setf (view-field-presentation ,slot-name)
(funcall #'make-instance (presentation-class-name ',(car presentation))
,@(quote-property-list-arguments
(cdr presentation))))))))
(defclass presentation ()
()
(:documentation "Base class for all presentations. Exists in order
to help manage CSS and JavaScript dependencies for presentations."))
;; by default presentations have no dependencies, so the primary method
;; returns nil
(defmethod dependencies append ((obj presentation))
())
| null | https://raw.githubusercontent.com/weblocks-framework/weblocks/fe96152458c8eb54d74751b3201db42dafe1708b/src/views/view/presentation.lisp | lisp | by default presentations have no dependencies, so the primary method
returns nil |
(in-package :weblocks)
(export '(presentation))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod view-argument-quoting-strategy ((arg-name (eql :present-as)))
:list)
(setf (gethash :present-as *custom-view-field-argument-compilers*)
(lambda (slot-name presentation)
(let ((presentation (ensure-list presentation)))
`(setf (view-field-presentation ,slot-name)
(funcall #'make-instance (presentation-class-name ',(car presentation))
,@(quote-property-list-arguments
(cdr presentation))))))))
(defclass presentation ()
()
(:documentation "Base class for all presentations. Exists in order
to help manage CSS and JavaScript dependencies for presentations."))
(defmethod dependencies append ((obj presentation))
())
|
f9f0723dbe9f1be0e9d183b420c56390441aac1257be0fa1ee6226c5fcac1569 | gowthamk/ocaml-irmin | test_merge4.ml | original = | |
q1 =
q2 = |5||6|
q1 = |5|
q2 = |5||6| *)
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n")
end
(* Queue *)
let _ =
U.print_header "Heap4";
let module Atom = struct
type t = int64
let t = Irmin.Type.int64
let compare x y = Int64.to_int @@ Int64.sub x y
let to_string = Int64.to_string
let of_string = Int64.of_string
end in
let module H = Heap_leftlist.Make(Atom) in
let original = H.empty |> H.insert (Int64.of_int 2) |> H.insert (Int64.of_int 3) |> H.insert (Int64.of_int 4) in
let q1 = original |> H.delete_min in
let q2 = original |> H.delete_min in
let m = H.merge3 original q1 q2 in
H.print_heap H.print_int64 m;
print_newline();
print_float !H.merge_time
| null | https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/heap_leftist/mem/test_merge4.ml | ocaml | Queue | original = | |
q1 =
q2 = |5||6|
q1 = |5|
q2 = |5||6| *)
module U = struct
let string_of_list f l = "[ " ^ List.fold_left (fun a b -> a ^ (f b) ^ "; ") "" l ^ "]"
let print_header h = Printf.printf "%s" ("\n" ^ h ^ "\n")
end
let _ =
U.print_header "Heap4";
let module Atom = struct
type t = int64
let t = Irmin.Type.int64
let compare x y = Int64.to_int @@ Int64.sub x y
let to_string = Int64.to_string
let of_string = Int64.of_string
end in
let module H = Heap_leftlist.Make(Atom) in
let original = H.empty |> H.insert (Int64.of_int 2) |> H.insert (Int64.of_int 3) |> H.insert (Int64.of_int 4) in
let q1 = original |> H.delete_min in
let q2 = original |> H.delete_min in
let m = H.merge3 original q1 q2 in
H.print_heap H.print_int64 m;
print_newline();
print_float !H.merge_time
|
630e29b931974770702b4874718592d97150476ea1c4c671e4daf933a02b3f84 | spechub/Hets | HasCASL2THF0Buildins.hs | |
Module : ./THF / HasCASL2THF0Buildins.hs
Description : create legal THF mixfix identifier
Copyright : ( c ) , DFKI Bremen 2011
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
translations for the buildins of HasCasl
Module : ./THF/HasCASL2THF0Buildins.hs
Description : create legal THF mixfix identifier
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
translations for the buildins of HasCasl
-}
module THF.HasCASL2THF0Buildins where
import Common.AS_Annotation
import Common.DocUtils
import Common.Result
import Common.Id
import HasCASL.Builtin
import THF.As
import THF.Cons
import THF.Sign
import THF.ParseTHF
import THF.Translate
import THF.PrintTHF ()
import Text.ParserCombinators.Parsec
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
-----------------------------------------------------------------------------
Assumps
----------------------------------------------------------------------------- -}
preDefHCAssumps :: Set.Set Id -> ConstMap
preDefHCAssumps ids =
let asl = [ (botId, botci)
, (defId, defci)
, (notId, o2ci)
, (negId, o2ci)
-- , (whenElse, "hcc" ++ show whenElse)
, (trueId, o1ci)
, (falseId, o1ci)
, (eqId, a2o1ci)
, (exEq, a2o1ci)
, (resId, resci)
, (andId, o3ci)
, (orId, o3ci)
, (eqvId, o3ci)
, (implId, o3ci)
, (infixIf, o3ci) ]
in Map.fromList $ map
(\ (i, tf) -> let c = (fromJust . maybeResult . transAssumpId) i
in (c , tf c))
(filter (\ (i, _) -> Set.member i ids) asl)
o1ci :: Constant -> ConstInfo
o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constAnno = Null }
o2ci :: Constant -> ConstInfo
o2ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType OType
, constAnno = Null }
o3ci :: Constant -> ConstInfo
o3ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType (MapType OType OType)
, constAnno = Null }
a2o1ci :: Constant -> ConstInfo
a2o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A")
(MapType (VType $ mkSimpleId "A") OType)
, constAnno = Null }
resci :: Constant -> ConstInfo
resci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A")
(MapType (VType $ mkSimpleId "B")
(VType $ mkSimpleId "A"))
, constAnno = Null }
botci :: Constant -> ConstInfo
botci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constAnno = Null }
defci :: Constant -> ConstInfo
defci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A") OType
, constAnno = Null }
-----------------------------------------------------------------------------
Axioms
-----------------------------------------------------------------------------
Axioms
----------------------------------------------------------------------------- -}
preDefAxioms :: Set.Set Id -> [Named THFFormula]
preDefAxioms ids =
let axl = [ (notId, notFS)
, (negId, notFS)
, (trueId, trueFS)
, (falseId, falseFS)
, (andId, andFS)
, (orId, orFS)
, (eqvId, eqvFS)
, (implId, implFS)
, (infixIf, ifFS)
, (resId, resFS)
, (botId, botFS)
, (defId, defFS)
{- , (whenElse, "hcc" ++ show whenElse) -} ]
in map (\ (i, fs) -> mkNSD
(fromJust $ maybeResult $ transAssumpId i) fs)
(filter (\ (i, _) -> Set.member i ids) axl)
mkNSD :: Constant -> (Constant -> String) -> Named THFFormula
mkNSD c f = (makeNamed (show . pretty . mkDefName $ c) $ genTHFFormula c f)
{ isDef = True }
genTHFFormula :: Constant -> (Constant -> String) -> THFFormula
genTHFFormula c f = case parse parseTHF "" (f c) of
Left msg -> error (unlines
["Fatal error while generating the predefined Sentence"
++ " for: " ++ show (pretty c),
"Parsing " ++ show (f c) ++ " failed with message",
show msg])
Right x -> thfFormulaAF $ head x
{- -----------------------------------------------------------------------------
formulas as Strings
----------------------------------------------------------------------------- -}
notFS :: Constant -> String
notFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [A : $o] : ~(A))")
falseFS :: Constant -> String
falseFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
trueFS :: Constant -> String
trueFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $true")
andFS :: Constant -> String
andFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X & Y))")
orFS :: Constant -> String
orFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X | Y))")
eqvFS :: Constant -> String
eqvFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X <=> Y))")
implFS :: Constant -> String
implFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X => Y))")
ifFS :: Constant -> String
ifFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (Y => X))")
resFS :: Constant -> String
resFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A, Y : B] : X)")
botFS :: Constant -> String
botFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
defFS :: Constant -> String
defFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A] : $true)")
defnS :: String
defnS = ", definition, "
encTHF :: String -> String
encTHF s = "thf(" ++ s ++ ")."
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/THF/HasCASL2THF0Buildins.hs | haskell | ---------------------------------------------------------------------------
--------------------------------------------------------------------------- -}
, (whenElse, "hcc" ++ show whenElse)
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--------------------------------------------------------------------------- -}
, (whenElse, "hcc" ++ show whenElse)
-----------------------------------------------------------------------------
formulas as Strings
----------------------------------------------------------------------------- | |
Module : ./THF / HasCASL2THF0Buildins.hs
Description : create legal THF mixfix identifier
Copyright : ( c ) , DFKI Bremen 2011
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
translations for the buildins of HasCasl
Module : ./THF/HasCASL2THF0Buildins.hs
Description : create legal THF mixfix identifier
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
translations for the buildins of HasCasl
-}
module THF.HasCASL2THF0Buildins where
import Common.AS_Annotation
import Common.DocUtils
import Common.Result
import Common.Id
import HasCASL.Builtin
import THF.As
import THF.Cons
import THF.Sign
import THF.ParseTHF
import THF.Translate
import THF.PrintTHF ()
import Text.ParserCombinators.Parsec
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
Assumps
preDefHCAssumps :: Set.Set Id -> ConstMap
preDefHCAssumps ids =
let asl = [ (botId, botci)
, (defId, defci)
, (notId, o2ci)
, (negId, o2ci)
, (trueId, o1ci)
, (falseId, o1ci)
, (eqId, a2o1ci)
, (exEq, a2o1ci)
, (resId, resci)
, (andId, o3ci)
, (orId, o3ci)
, (eqvId, o3ci)
, (implId, o3ci)
, (infixIf, o3ci) ]
in Map.fromList $ map
(\ (i, tf) -> let c = (fromJust . maybeResult . transAssumpId) i
in (c , tf c))
(filter (\ (i, _) -> Set.member i ids) asl)
o1ci :: Constant -> ConstInfo
o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constAnno = Null }
o2ci :: Constant -> ConstInfo
o2ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType OType
, constAnno = Null }
o3ci :: Constant -> ConstInfo
o3ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType OType (MapType OType OType)
, constAnno = Null }
a2o1ci :: Constant -> ConstInfo
a2o1ci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A")
(MapType (VType $ mkSimpleId "A") OType)
, constAnno = Null }
resci :: Constant -> ConstInfo
resci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A")
(MapType (VType $ mkSimpleId "B")
(VType $ mkSimpleId "A"))
, constAnno = Null }
botci :: Constant -> ConstInfo
botci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = OType
, constAnno = Null }
defci :: Constant -> ConstInfo
defci c = ConstInfo
{ constId = c
, constName = mkConstsName c
, constType = MapType (VType $ mkSimpleId "A") OType
, constAnno = Null }
Axioms
Axioms
preDefAxioms :: Set.Set Id -> [Named THFFormula]
preDefAxioms ids =
let axl = [ (notId, notFS)
, (negId, notFS)
, (trueId, trueFS)
, (falseId, falseFS)
, (andId, andFS)
, (orId, orFS)
, (eqvId, eqvFS)
, (implId, implFS)
, (infixIf, ifFS)
, (resId, resFS)
, (botId, botFS)
, (defId, defFS)
in map (\ (i, fs) -> mkNSD
(fromJust $ maybeResult $ transAssumpId i) fs)
(filter (\ (i, _) -> Set.member i ids) axl)
mkNSD :: Constant -> (Constant -> String) -> Named THFFormula
mkNSD c f = (makeNamed (show . pretty . mkDefName $ c) $ genTHFFormula c f)
{ isDef = True }
genTHFFormula :: Constant -> (Constant -> String) -> THFFormula
genTHFFormula c f = case parse parseTHF "" (f c) of
Left msg -> error (unlines
["Fatal error while generating the predefined Sentence"
++ " for: " ++ show (pretty c),
"Parsing " ++ show (f c) ++ " failed with message",
show msg])
Right x -> thfFormulaAF $ head x
notFS :: Constant -> String
notFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [A : $o] : ~(A))")
falseFS :: Constant -> String
falseFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
trueFS :: Constant -> String
trueFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $true")
andFS :: Constant -> String
andFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X & Y))")
orFS :: Constant -> String
orFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X | Y))")
eqvFS :: Constant -> String
eqvFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X <=> Y))")
implFS :: Constant -> String
implFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (X => Y))")
ifFS :: Constant -> String
ifFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : $o, Y : $o] : (Y => X))")
resFS :: Constant -> String
resFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A, Y : B] : X)")
botFS :: Constant -> String
botFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = $false")
defFS :: Constant -> String
defFS c =
let ns = (show . pretty . mkDefName) c
cs = (show . pretty) c
in encTHF (ns ++ defnS ++ cs ++ " = (^ [X : A] : $true)")
defnS :: String
defnS = ", definition, "
encTHF :: String -> String
encTHF s = "thf(" ++ s ++ ")."
|
6533259ef3d7d716e84fc4e2a3c3dc626c37f15b56add39d83134ad4c3baa9ca | input-output-hk/hydra | Main.hs | module Main where
import Hydra.Prelude
import qualified HydraTestUtilsSpec
import Test.Hspec.Runner
import Test.Hydra.Prelude (combinedHspecFormatter)
main :: IO ()
main = hspecWith defaultConfig{configFormat = Just (combinedHspecFormatter "hydra-test-utils")} HydraTestUtilsSpec.spec
| null | https://raw.githubusercontent.com/input-output-hk/hydra/2e01e0422d0d0fe08fb2c5437678ea4f5087faec/hydra-test-utils/test/Main.hs | haskell | module Main where
import Hydra.Prelude
import qualified HydraTestUtilsSpec
import Test.Hspec.Runner
import Test.Hydra.Prelude (combinedHspecFormatter)
main :: IO ()
main = hspecWith defaultConfig{configFormat = Just (combinedHspecFormatter "hydra-test-utils")} HydraTestUtilsSpec.spec
| |
70b25ac8a85ffc0276a56f6427fa6436357c573a26843b2db0fd93d899cb62eb | w3ntao/sicp-solution | 3-33.rkt | #lang racket
(require (combine-in (only-in "../ToolBox/ConstraintSystem/connector.rkt"
make-connector
set-value!
constant
probe)
(only-in "../ToolBox/ConstraintSystem/constraint.rkt"
adder
multiplier)))
(define (averager a b avg)
(let ((sum (make-connector))
(half (make-connector)))
(adder a b sum)
(multiplier sum half avg)
(constant 0.5 half)
'OK))
(define a (make-connector))
(define b (make-connector))
(define avg (make-connector))
(averager a b avg)
(probe "arg a" a)
(probe "arg b" b)
(probe "average" avg)
(set-value! a 10 'usr)
(set-value! b 20 'usr) | null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-3/3-33.rkt | racket | #lang racket
(require (combine-in (only-in "../ToolBox/ConstraintSystem/connector.rkt"
make-connector
set-value!
constant
probe)
(only-in "../ToolBox/ConstraintSystem/constraint.rkt"
adder
multiplier)))
(define (averager a b avg)
(let ((sum (make-connector))
(half (make-connector)))
(adder a b sum)
(multiplier sum half avg)
(constant 0.5 half)
'OK))
(define a (make-connector))
(define b (make-connector))
(define avg (make-connector))
(averager a b avg)
(probe "arg a" a)
(probe "arg b" b)
(probe "average" avg)
(set-value! a 10 'usr)
(set-value! b 20 'usr) | |
105f98ef58f5b51ea1c364d698446178667355d5866c8fc89b128db1ee781c68 | onedata/op-worker | monitoring_event_handler.erl | %%%-------------------------------------------------------------------
@author
( C ) 2016 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc Module containing functions used to handle monitoring events.
%%% @end
%%%-------------------------------------------------------------------
-module(monitoring_event_handler).
-author("Michal Wrona").
-include("modules/events/definitions.hrl").
-include("modules/monitoring/events.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include_lib("ctool/include/logging.hrl").
%% API Handling
-export([handle_monitoring_events/2]).
%% API Aggregation
-export([aggregate_monitoring_events/2]).
%%%===================================================================
%%% API Handling
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Processes monitoring related events.
%% @end
%%--------------------------------------------------------------------
-spec handle_monitoring_events(Evts :: [event:type()], Ctx :: map()) ->
[ok | {error, Reason :: term()}].
handle_monitoring_events(Evts, Ctx) ->
SpaceIds = get_space_ids(Evts),
MissingEvents = missing_events(SpaceIds, Evts),
Result = lists:map(fun maybe_handle_monitoring_event/1, Evts ++ MissingEvents),
case Ctx of
#{notify := Fun} -> Fun(Result);
_ -> ok
end,
Result.
%%%===================================================================
%%% API Aggregation
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Aggregates monitoring related events.
%% @end
%%--------------------------------------------------------------------
-spec aggregate_monitoring_events(OldEvt :: event:type(), Evt :: event:type()) ->
NewEvt :: event:type().
aggregate_monitoring_events(#monitoring_event{type = #storage_used_updated{} = T1} = E1,
#monitoring_event{type = #storage_used_updated{} = T2}) ->
E1#monitoring_event{type = T2#storage_used_updated{
size_difference = T1#storage_used_updated.size_difference +
T2#storage_used_updated.size_difference
}};
aggregate_monitoring_events(#monitoring_event{type = #od_space_updated{}} = E1,
#monitoring_event{type = #od_space_updated{} = T2}) ->
E1#monitoring_event{type = T2};
aggregate_monitoring_events(#monitoring_event{type = #file_operations_statistics{} = T1} = E1,
#monitoring_event{type = #file_operations_statistics{} = T2}) ->
E1#monitoring_event{type = T2#file_operations_statistics{
data_access_read = T1#file_operations_statistics.data_access_read +
T2#file_operations_statistics.data_access_read,
data_access_write = T1#file_operations_statistics.data_access_write +
T2#file_operations_statistics.data_access_write,
block_access_read = T1#file_operations_statistics.block_access_read +
T2#file_operations_statistics.block_access_read,
block_access_write = T1#file_operations_statistics.block_access_write +
T2#file_operations_statistics.block_access_write
}};
aggregate_monitoring_events(#monitoring_event{type = #rtransfer_statistics{} = T1} = E1,
#monitoring_event{type = #rtransfer_statistics{} = T2}) ->
E1#monitoring_event{type = T2#rtransfer_statistics{
transfer_in = T1#rtransfer_statistics.transfer_in +
T2#rtransfer_statistics.transfer_in
}}.
%%%===================================================================
Internal functions
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
Get list of SpaceIds of events
%% @end
%%--------------------------------------------------------------------
-spec get_space_ids(Evts :: [event:type()]) -> [od_space:id()].
get_space_ids([]) ->
[];
get_space_ids([#monitoring_event{
type = #storage_used_updated{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #od_space_updated{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #file_operations_statistics{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #rtransfer_statistics{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]].
%%--------------------------------------------------------------------
@private
%% @doc
%% Generate events with empty values for each missing event category.
%% @end
%%--------------------------------------------------------------------
-spec missing_events([od_space:id()], [event:type()]) -> [event:type()].
missing_events([], _Evts) ->
[];
missing_events([SpaceId | Rest], Evts) ->
EmptyStorageUsedUpdated = #monitoring_event{type = #storage_used_updated{
space_id = SpaceId,
size_difference = 0
}},
MissingStorageUsedUpdated = missing_event(fun(#monitoring_event{
type = #storage_used_updated{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyStorageUsedUpdated),
EmptyOdSpaceUpdated = #monitoring_event{type = #od_space_updated{
space_id = SpaceId
}},
MissingOdSpaceUpdated = missing_event(fun(#monitoring_event{
type = #od_space_updated{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyOdSpaceUpdated ),
EmptyFileOperationsStatistics = #monitoring_event{type = #file_operations_statistics{
space_id = SpaceId
}},
MissingFileOperationsStatistics = missing_event(fun(#monitoring_event{
type = #file_operations_statistics{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyFileOperationsStatistics ),
EmptyRtransferStatistics = #monitoring_event{type = #rtransfer_statistics{
space_id = SpaceId
}},
MissingRtransferStatistics = missing_event(fun(#monitoring_event{
type = #rtransfer_statistics{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyRtransferStatistics ),
MissingStorageUsedUpdated ++ MissingOdSpaceUpdated
++ MissingFileOperationsStatistics ++ MissingRtransferStatistics ++
missing_events(Rest, Evts).
%%--------------------------------------------------------------------
@private
%% @doc
%% Returns [EmptyEvent] if none of given events fulfills given precondition.
%% Otherwise returns an empty list.
%% @end
%%--------------------------------------------------------------------
-spec missing_event(Precondition :: function(), Evts :: [event:type()],
EmptyEvent :: event:type()) -> [event:type()].
missing_event(Precondition, Events, EmptyEvent) ->
case lists:any(Precondition, Events) of
true -> [];
false -> [EmptyEvent]
end.
%%--------------------------------------------------------------------
@private
%% @doc
Processes monitoring related event if at least one of supporting
%% storages is NOT read-only.
%% @end
%%--------------------------------------------------------------------
-spec maybe_handle_monitoring_event(Evt :: event:type()) ->
ok | {error, Reason :: term()}.
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #storage_used_updated{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #od_space_updated{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #file_operations_statistics{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #rtransfer_statistics{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt).
%%--------------------------------------------------------------------
@private
%% @doc
Processes monitoring related event if at least one of supporting
%% storages is NOT read-only.
%% @end
%%--------------------------------------------------------------------
-spec maybe_handle_monitoring_event(od_space:id(), Evt :: event:type()) ->
ok | {error, Reason :: term()}.
maybe_handle_monitoring_event(SpaceId, Evt) ->
case are_all_local_storages_readonly(SpaceId) of
true -> ok;
_ -> handle_monitoring_event(Evt)
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% Processes monitoring related event.
%% @end
%%--------------------------------------------------------------------
-spec handle_monitoring_event(Evts :: event:type()) ->
ok | {error, Reason :: term()}.
handle_monitoring_event(#monitoring_event{type = #storage_used_updated{
user_id = undefined, space_id = SpaceId}}) ->
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_used
});
handle_monitoring_event(#monitoring_event{type = #storage_used_updated{} = Evt}) ->
SpaceId = Evt#storage_used_updated.space_id,
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_used,
secondary_subject_type = user,
secondary_subject_id = Evt#storage_used_updated.user_id
}, #{size_difference => Evt#storage_used_updated.size_difference});
handle_monitoring_event(#monitoring_event{type = #od_space_updated{space_id = SpaceId}}) ->
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_quota
}),
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = connected_users
});
handle_monitoring_event(#monitoring_event{type = #file_operations_statistics{} = Evt}) ->
#file_operations_statistics{
space_id = SpaceId,
user_id = UserId,
data_access_read = DataAccessRead,
data_access_write = DataAccessWrite,
block_access_read = BlockAccessRead,
block_access_write = BlockAccessWrite
} = Evt,
MonitoringId = get_monitoring_id(SpaceId, UserId),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = data_access
}, #{read_counter => DataAccessRead, write_counter => DataAccessWrite}),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = block_access
}, #{read_operations_counter => BlockAccessRead,
write_operations_counter => BlockAccessWrite});
handle_monitoring_event(#monitoring_event{type = #rtransfer_statistics{} = Evt}) ->
#rtransfer_statistics{
space_id = SpaceId,
user_id = UserId,
transfer_in = TransferIn
} = Evt,
MonitoringId = get_monitoring_id(SpaceId, UserId),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = remote_transfer}, #{transfer_in => TransferIn}).
%%--------------------------------------------------------------------
@private
%% @doc Returns monitoring id without metric for given user and space.
%% @end
%%--------------------------------------------------------------------
-spec get_monitoring_id(SpaceId :: od_space:id(), UserId :: od_user:id()) ->
Id :: #monitoring_id{}.
get_monitoring_id(SpaceId, UserId) ->
MonitoringIdWithSpace = #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId
},
case UserId of
undefined ->
MonitoringIdWithSpace;
_ ->
MonitoringIdWithSpace#monitoring_id{
secondary_subject_id = UserId,
secondary_subject_type = user
}
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% Checks if all local storages supporting given space are readonly.
%% @end
%%--------------------------------------------------------------------
-spec are_all_local_storages_readonly(od_space:id()) -> boolean().
are_all_local_storages_readonly(SpaceId) ->
{ok, StorageIds} = space_logic:get_local_storages(SpaceId),
lists:all(fun storage:should_skip_storage_detection/1, StorageIds).
| null | https://raw.githubusercontent.com/onedata/op-worker/b09f05b6928121cec4d6b41ce8037fe056e6b4b3/src/modules/monitoring/event/monitoring_event_handler.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc Module containing functions used to handle monitoring events.
@end
-------------------------------------------------------------------
API Handling
API Aggregation
===================================================================
API Handling
===================================================================
--------------------------------------------------------------------
@doc
Processes monitoring related events.
@end
--------------------------------------------------------------------
===================================================================
API Aggregation
===================================================================
--------------------------------------------------------------------
@doc
Aggregates monitoring related events.
@end
--------------------------------------------------------------------
===================================================================
===================================================================
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Generate events with empty values for each missing event category.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Returns [EmptyEvent] if none of given events fulfills given precondition.
Otherwise returns an empty list.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
storages is NOT read-only.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
storages is NOT read-only.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Processes monitoring related event.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc Returns monitoring id without metric for given user and space.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Checks if all local storages supporting given space are readonly.
@end
-------------------------------------------------------------------- | @author
( C ) 2016 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(monitoring_event_handler).
-author("Michal Wrona").
-include("modules/events/definitions.hrl").
-include("modules/monitoring/events.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include_lib("ctool/include/logging.hrl").
-export([handle_monitoring_events/2]).
-export([aggregate_monitoring_events/2]).
-spec handle_monitoring_events(Evts :: [event:type()], Ctx :: map()) ->
[ok | {error, Reason :: term()}].
handle_monitoring_events(Evts, Ctx) ->
SpaceIds = get_space_ids(Evts),
MissingEvents = missing_events(SpaceIds, Evts),
Result = lists:map(fun maybe_handle_monitoring_event/1, Evts ++ MissingEvents),
case Ctx of
#{notify := Fun} -> Fun(Result);
_ -> ok
end,
Result.
-spec aggregate_monitoring_events(OldEvt :: event:type(), Evt :: event:type()) ->
NewEvt :: event:type().
aggregate_monitoring_events(#monitoring_event{type = #storage_used_updated{} = T1} = E1,
#monitoring_event{type = #storage_used_updated{} = T2}) ->
E1#monitoring_event{type = T2#storage_used_updated{
size_difference = T1#storage_used_updated.size_difference +
T2#storage_used_updated.size_difference
}};
aggregate_monitoring_events(#monitoring_event{type = #od_space_updated{}} = E1,
#monitoring_event{type = #od_space_updated{} = T2}) ->
E1#monitoring_event{type = T2};
aggregate_monitoring_events(#monitoring_event{type = #file_operations_statistics{} = T1} = E1,
#monitoring_event{type = #file_operations_statistics{} = T2}) ->
E1#monitoring_event{type = T2#file_operations_statistics{
data_access_read = T1#file_operations_statistics.data_access_read +
T2#file_operations_statistics.data_access_read,
data_access_write = T1#file_operations_statistics.data_access_write +
T2#file_operations_statistics.data_access_write,
block_access_read = T1#file_operations_statistics.block_access_read +
T2#file_operations_statistics.block_access_read,
block_access_write = T1#file_operations_statistics.block_access_write +
T2#file_operations_statistics.block_access_write
}};
aggregate_monitoring_events(#monitoring_event{type = #rtransfer_statistics{} = T1} = E1,
#monitoring_event{type = #rtransfer_statistics{} = T2}) ->
E1#monitoring_event{type = T2#rtransfer_statistics{
transfer_in = T1#rtransfer_statistics.transfer_in +
T2#rtransfer_statistics.transfer_in
}}.
Internal functions
@private
Get list of SpaceIds of events
-spec get_space_ids(Evts :: [event:type()]) -> [od_space:id()].
get_space_ids([]) ->
[];
get_space_ids([#monitoring_event{
type = #storage_used_updated{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #od_space_updated{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #file_operations_statistics{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]];
get_space_ids([#monitoring_event{
type = #rtransfer_statistics{space_id = SpaceId}
} | Rest]) ->
[SpaceId | get_space_ids(Rest) -- [SpaceId]].
@private
-spec missing_events([od_space:id()], [event:type()]) -> [event:type()].
missing_events([], _Evts) ->
[];
missing_events([SpaceId | Rest], Evts) ->
EmptyStorageUsedUpdated = #monitoring_event{type = #storage_used_updated{
space_id = SpaceId,
size_difference = 0
}},
MissingStorageUsedUpdated = missing_event(fun(#monitoring_event{
type = #storage_used_updated{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyStorageUsedUpdated),
EmptyOdSpaceUpdated = #monitoring_event{type = #od_space_updated{
space_id = SpaceId
}},
MissingOdSpaceUpdated = missing_event(fun(#monitoring_event{
type = #od_space_updated{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyOdSpaceUpdated ),
EmptyFileOperationsStatistics = #monitoring_event{type = #file_operations_statistics{
space_id = SpaceId
}},
MissingFileOperationsStatistics = missing_event(fun(#monitoring_event{
type = #file_operations_statistics{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyFileOperationsStatistics ),
EmptyRtransferStatistics = #monitoring_event{type = #rtransfer_statistics{
space_id = SpaceId
}},
MissingRtransferStatistics = missing_event(fun(#monitoring_event{
type = #rtransfer_statistics{space_id = Id}
}) -> SpaceId =:= Id;
(_) -> false
end, Evts, EmptyRtransferStatistics ),
MissingStorageUsedUpdated ++ MissingOdSpaceUpdated
++ MissingFileOperationsStatistics ++ MissingRtransferStatistics ++
missing_events(Rest, Evts).
@private
-spec missing_event(Precondition :: function(), Evts :: [event:type()],
EmptyEvent :: event:type()) -> [event:type()].
missing_event(Precondition, Events, EmptyEvent) ->
case lists:any(Precondition, Events) of
true -> [];
false -> [EmptyEvent]
end.
@private
Processes monitoring related event if at least one of supporting
-spec maybe_handle_monitoring_event(Evt :: event:type()) ->
ok | {error, Reason :: term()}.
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #storage_used_updated{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #od_space_updated{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #file_operations_statistics{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt);
maybe_handle_monitoring_event(Evt = #monitoring_event{
type = #rtransfer_statistics{space_id = SpaceId}
}) ->
maybe_handle_monitoring_event(SpaceId, Evt).
@private
Processes monitoring related event if at least one of supporting
-spec maybe_handle_monitoring_event(od_space:id(), Evt :: event:type()) ->
ok | {error, Reason :: term()}.
maybe_handle_monitoring_event(SpaceId, Evt) ->
case are_all_local_storages_readonly(SpaceId) of
true -> ok;
_ -> handle_monitoring_event(Evt)
end.
@private
-spec handle_monitoring_event(Evts :: event:type()) ->
ok | {error, Reason :: term()}.
handle_monitoring_event(#monitoring_event{type = #storage_used_updated{
user_id = undefined, space_id = SpaceId}}) ->
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_used
});
handle_monitoring_event(#monitoring_event{type = #storage_used_updated{} = Evt}) ->
SpaceId = Evt#storage_used_updated.space_id,
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_used,
secondary_subject_type = user,
secondary_subject_id = Evt#storage_used_updated.user_id
}, #{size_difference => Evt#storage_used_updated.size_difference});
handle_monitoring_event(#monitoring_event{type = #od_space_updated{space_id = SpaceId}}) ->
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = storage_quota
}),
monitoring_utils:create_and_update(SpaceId, #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId,
metric_type = connected_users
});
handle_monitoring_event(#monitoring_event{type = #file_operations_statistics{} = Evt}) ->
#file_operations_statistics{
space_id = SpaceId,
user_id = UserId,
data_access_read = DataAccessRead,
data_access_write = DataAccessWrite,
block_access_read = BlockAccessRead,
block_access_write = BlockAccessWrite
} = Evt,
MonitoringId = get_monitoring_id(SpaceId, UserId),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = data_access
}, #{read_counter => DataAccessRead, write_counter => DataAccessWrite}),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = block_access
}, #{read_operations_counter => BlockAccessRead,
write_operations_counter => BlockAccessWrite});
handle_monitoring_event(#monitoring_event{type = #rtransfer_statistics{} = Evt}) ->
#rtransfer_statistics{
space_id = SpaceId,
user_id = UserId,
transfer_in = TransferIn
} = Evt,
MonitoringId = get_monitoring_id(SpaceId, UserId),
monitoring_utils:create_and_update(SpaceId, MonitoringId#monitoring_id{
metric_type = remote_transfer}, #{transfer_in => TransferIn}).
@private
-spec get_monitoring_id(SpaceId :: od_space:id(), UserId :: od_user:id()) ->
Id :: #monitoring_id{}.
get_monitoring_id(SpaceId, UserId) ->
MonitoringIdWithSpace = #monitoring_id{
main_subject_type = space,
main_subject_id = SpaceId
},
case UserId of
undefined ->
MonitoringIdWithSpace;
_ ->
MonitoringIdWithSpace#monitoring_id{
secondary_subject_id = UserId,
secondary_subject_type = user
}
end.
@private
-spec are_all_local_storages_readonly(od_space:id()) -> boolean().
are_all_local_storages_readonly(SpaceId) ->
{ok, StorageIds} = space_logic:get_local_storages(SpaceId),
lists:all(fun storage:should_skip_storage_detection/1, StorageIds).
|
79a1e738f26bab02e996c2968571efc26f49d10b31f27d99b11edcee7b6ed4be | informatimago/commands | insulte.lisp | -*- mode : lisp ; coding : utf-8 -*-
(defparameter insults
'(
("accapareur" (nm))
("aérolithe" (nm))
("amiral de bateaulavoir" (gnm))
("amphitryon" (nm))
("anacoluthe" (nf))
("analphabète" (n a))
("anthracite" (nm))
("anthropophage" (nm a))
("anthropopithèque" (nm))
("apache" (nm))
("apprenti dictateur à la noix de coco" (gnm))
("arlequin" (nm))
("astronaute d'eau douce" (gn))
("athlète complet" (n))
("autocrate" (nm))
("autodidacte" (n a))
("azteque" (nm))
("babouin" (nm))
("bachibouzouk" (nm))
("bande de" (|...|))
("bandit" (nm))
("bayadère" (nf))
("bibendum" (nm))
("boitsanssoif" (ni))
("brontosaure" (nm))
("bougre de" (|...|))
("brute" (nf))
("bulldozer à réaction" (gnm))
("vieux" (a))
("cachalot" (nm))
("canaille" (nf))
("canaque" (nm a))
("cannibale" (nm))
("carnaval" (nm))
("catachrèse" (nf))
("cataplasme" (nm))
("cercopithèque" (nm))
("chauffard" (nm))
("chenapan" (nm))
("choléra" (nm))
("chouette mal empaillée" (gnf))
("cloporte" (nm))
("clysopompe" (nm))
("coléoptère" (nm))
("coloquinte" (nf))
("coquin" (n a))
("cornemuse" (nf))
("cornichon" (nm))
("corsaire" (nm))
("coupejarret" (nm))
("cowboy de la route" (gnm))
("crétin des alpes" (gnm))
("Cromagnon" (np))
("cyanure" (nm))
("cyclone" (nm))
("cyclotron" (nm))
("Cyrano à quatre pattes" (gnm))
("diablesse" (nf))
("diplodocus" (nm))
("doryphore" (nm))
("dynamiteur" (nm))
("ecornifleur" (nm))
("ecraseur" (nm))
("ectoplasme" (nm))
("egoïste" (nm))
("emplatre" (nm))
("empoisonneur" (nm a))
("enragé" (nm a))
("épouvantail" (nm))
("équilibriste" (nm))
("esclavagiste" (nm))
("escogriffe" (nm))
("espèce de" (|...|))
("extrait de" (|...|))
("graine de" (|...|))
("tersorium" (nm))
("faux jeton" (nm))
("flibustier" (nm))
("forban" (nm))
("frères de la côte" (gnm))
("froussard" (nm a))
("galopin" (nm))
("gangster" (nm))
("gardecôte à la mie de pain" (gnm))
("gargarisme" (nm))
("garnement" (nm))
("gibier de potence" (nm))
("goujat" (nm))
("gredin" (nm))
("grenouille" (nf))
("gros plein de soupe" (gnm))
("gyroscope" (nm))
("hérétique" (n a))
("horslaloi" (nm))
("huluberlu" (nm))
("hydrocarbure" (nm))
("iconoclaste" (nm a))
("incas de carnaval" (gnmp))
("individou de général" (gnm))
("invertébré" (nm))
("ivrogne" (n))
("jet d'eau ambulant" (gnm))
("jocrisse" (nm))
("judas" (nm))
("jus de réglisse" (gnm))
("kroumir" (nm))
("ku klux klan" (gnm))
("lâche" (nm))
("lépidoptère" (nm))
("logarithme" (nm))
("loupgarou à la graisse de renoncule" (gnm))
("macaque" (nm))
("macrocéphale" (nm))
("malappris" (n a))
("malotru" (n))
("mamelouk" (nm))
("marchand de guano" (gnm))
("marchand de tapis" (gnm))
("marin d'eau douce" (gnm))
("marmotte" (nf))
("mégalomane" (nm a))
("mégacycle" (nm))
("mercanti" (nm))
("mercenaire" (nm a))
("mérinos" (nm))
("mille sabords" (gnmp))
("misérable" (a))
("mitrailleur à bavette" (gnm))
("moratorium" (nm))
("moricaud" (nm a))
("mouchard" (nm))
("moujik" (nm))
("moule à gaufres" (gnm))
("moussaillon" (nm))
("mrkrpxzkrmtfrz" (nm))
("mufle" (nm))
("Mussolini de carnaval" (nm))
("naufrageur" (nm))
("négrier" (nm))
("noix de coco" (gnm))
("nyctalope" (n a))
("olibrius" (nm))
("ophicléïde" (nm))
("ornithorynque" (nm))
("oryctérope" (nm))
("ostrogoth" (n a))
("ours mal lèché" (gnm))
("pacte à quatre" (gnm))
("paltoquet" (nm))
("pantoufle" (nf))
("Papous" (nm))
("paranoïaque" (nm a))
("parasite" (nm a))
("Patagon" (nm))
("patapouf" (nm))
("patate" (nf))
("péronnelle" (nf))
("perruche bavarde" (gnf))
("phénomène" (nm))
("phlébotome" (nm))
("phylactère" (nm))
("phylloxéra" (nm))
("pignouf" (nm))
("pirate" (nm))
("Polichinelle" (nm))
("polygraphe" (nm))
("porcépic mal embouché" (gnm))
("potentat emplumé" (gnm))
("poussière" (nf))
("profiteur" (nm))
("projectile guidé" (gnm))
("protozoaire" (nm))
("pyromane" (nm))
("pyrophore" (nm))
("rapace" (nm))
("rat" (nm))
("Ravachol" (nm))
("renégat" (nm))
("rhizopode" (nm))
("Rocambole" (nm))
("sacripant" (nm))
("sajou" (nm))
("saltimbanque" (nm))
("sapajou" (nm))
("satané bazar de fourbi de truc" (gnm))
("satrape" (nm))
("sauvage" (n a))
("scélérat" (nm))
("schizophrène" (n a))
("scolopendre" (nf))
("scorpion" (nm))
("serpent" (nm))
("simili martien à la graisse de cabestan" (gnm))
("sinapisme" (nm))
("soulographe" (nm))
("squatter" (nm))
("tchouktchouknougat" (nm))
("technocrate" (nm))
("tête de lard" (gnf))
("tête de mule" (gnf))
("tigresse" (nf))
("tonnerre de Brest" (gnm))
("topinanbour" (nm))
("tortionnaire" (nm))
("traficant de chair humaine" (gnm))
("trainepotence" (nm))
("traitre" (nm a))
("troglodyte" (nm))
("trompelamort" (nm))
("vampire" (nm))
("vandale" (nm a))
("vanupieds" (nm))
("vaurien" (nm))
("végétarien" (nm))
("Vercingétorix de carnaval" (nm))
("ver de terre" (gnm))
("vermicelle" (nm))
("vermine" (nm))
("vipère" (nf))
("vivisectionniste" (nm))
("voleur" (nm))
("wisigoth" (n a))
("zapotèque" (nm))
("zèbre" (nm))
("zigomar" (nm))
("zouave" (nm))
("Zoulou" (nm))
));;insults
(defparameter nm (remove-if-not (lambda (x) (intersection '(n np nm gnm) (second x))) insults))
(defparameter nf (remove-if-not (lambda (x) (intersection '(nf np) (second x))) insults))
(defparameter ad (remove-if-not (lambda (x) (member 'a (second x))) insults))
(defun insulte ()
(let* ((ga (format nil " ~A" (first (elt ad (random (length ad))))))
(gn (let ((n (random (+ (length nf) (length nm)))))
(if (>= n (length nm))
(prog1
(first (elt nf (- n (length nm))))
(cond
((= 0 (length ga)))
((string= "e" ga :start2 (1- (length ga))))
((string= "eux" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (- (length ga) 2)) "ille")))
((string= "eur" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (1- (length ga))) "se")))
(t
(setf ga (concatenate 'string ga "e")))))
(first (elt nm n)))))
(conj (if (position (aref gn 0) "aeiouyh") "d'" "de "))
(ins (case (random 4)
((0) (concatenate 'string "espèce " conj gn ga))
((1) (concatenate 'string "bande " conj gn ga))
(otherwise (concatenate 'string gn ga)))))
(concatenate 'string
(string-capitalize (subseq ins 0 1))
(subseq ins 1)
" !")))
(defun main (arguments)
(declare (ignore arguments))
(setf *random-state* (make-random-state t))
(princ (insulte))
(terpri)
ex-ok)
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/commands/65d0d6385269f3e210aed4943aefdbb5372706b9/sources/commands/insulte.lisp | lisp | coding : utf-8 -*-
insults
THE END ;;;; |
(defparameter insults
'(
("accapareur" (nm))
("aérolithe" (nm))
("amiral de bateaulavoir" (gnm))
("amphitryon" (nm))
("anacoluthe" (nf))
("analphabète" (n a))
("anthracite" (nm))
("anthropophage" (nm a))
("anthropopithèque" (nm))
("apache" (nm))
("apprenti dictateur à la noix de coco" (gnm))
("arlequin" (nm))
("astronaute d'eau douce" (gn))
("athlète complet" (n))
("autocrate" (nm))
("autodidacte" (n a))
("azteque" (nm))
("babouin" (nm))
("bachibouzouk" (nm))
("bande de" (|...|))
("bandit" (nm))
("bayadère" (nf))
("bibendum" (nm))
("boitsanssoif" (ni))
("brontosaure" (nm))
("bougre de" (|...|))
("brute" (nf))
("bulldozer à réaction" (gnm))
("vieux" (a))
("cachalot" (nm))
("canaille" (nf))
("canaque" (nm a))
("cannibale" (nm))
("carnaval" (nm))
("catachrèse" (nf))
("cataplasme" (nm))
("cercopithèque" (nm))
("chauffard" (nm))
("chenapan" (nm))
("choléra" (nm))
("chouette mal empaillée" (gnf))
("cloporte" (nm))
("clysopompe" (nm))
("coléoptère" (nm))
("coloquinte" (nf))
("coquin" (n a))
("cornemuse" (nf))
("cornichon" (nm))
("corsaire" (nm))
("coupejarret" (nm))
("cowboy de la route" (gnm))
("crétin des alpes" (gnm))
("Cromagnon" (np))
("cyanure" (nm))
("cyclone" (nm))
("cyclotron" (nm))
("Cyrano à quatre pattes" (gnm))
("diablesse" (nf))
("diplodocus" (nm))
("doryphore" (nm))
("dynamiteur" (nm))
("ecornifleur" (nm))
("ecraseur" (nm))
("ectoplasme" (nm))
("egoïste" (nm))
("emplatre" (nm))
("empoisonneur" (nm a))
("enragé" (nm a))
("épouvantail" (nm))
("équilibriste" (nm))
("esclavagiste" (nm))
("escogriffe" (nm))
("espèce de" (|...|))
("extrait de" (|...|))
("graine de" (|...|))
("tersorium" (nm))
("faux jeton" (nm))
("flibustier" (nm))
("forban" (nm))
("frères de la côte" (gnm))
("froussard" (nm a))
("galopin" (nm))
("gangster" (nm))
("gardecôte à la mie de pain" (gnm))
("gargarisme" (nm))
("garnement" (nm))
("gibier de potence" (nm))
("goujat" (nm))
("gredin" (nm))
("grenouille" (nf))
("gros plein de soupe" (gnm))
("gyroscope" (nm))
("hérétique" (n a))
("horslaloi" (nm))
("huluberlu" (nm))
("hydrocarbure" (nm))
("iconoclaste" (nm a))
("incas de carnaval" (gnmp))
("individou de général" (gnm))
("invertébré" (nm))
("ivrogne" (n))
("jet d'eau ambulant" (gnm))
("jocrisse" (nm))
("judas" (nm))
("jus de réglisse" (gnm))
("kroumir" (nm))
("ku klux klan" (gnm))
("lâche" (nm))
("lépidoptère" (nm))
("logarithme" (nm))
("loupgarou à la graisse de renoncule" (gnm))
("macaque" (nm))
("macrocéphale" (nm))
("malappris" (n a))
("malotru" (n))
("mamelouk" (nm))
("marchand de guano" (gnm))
("marchand de tapis" (gnm))
("marin d'eau douce" (gnm))
("marmotte" (nf))
("mégalomane" (nm a))
("mégacycle" (nm))
("mercanti" (nm))
("mercenaire" (nm a))
("mérinos" (nm))
("mille sabords" (gnmp))
("misérable" (a))
("mitrailleur à bavette" (gnm))
("moratorium" (nm))
("moricaud" (nm a))
("mouchard" (nm))
("moujik" (nm))
("moule à gaufres" (gnm))
("moussaillon" (nm))
("mrkrpxzkrmtfrz" (nm))
("mufle" (nm))
("Mussolini de carnaval" (nm))
("naufrageur" (nm))
("négrier" (nm))
("noix de coco" (gnm))
("nyctalope" (n a))
("olibrius" (nm))
("ophicléïde" (nm))
("ornithorynque" (nm))
("oryctérope" (nm))
("ostrogoth" (n a))
("ours mal lèché" (gnm))
("pacte à quatre" (gnm))
("paltoquet" (nm))
("pantoufle" (nf))
("Papous" (nm))
("paranoïaque" (nm a))
("parasite" (nm a))
("Patagon" (nm))
("patapouf" (nm))
("patate" (nf))
("péronnelle" (nf))
("perruche bavarde" (gnf))
("phénomène" (nm))
("phlébotome" (nm))
("phylactère" (nm))
("phylloxéra" (nm))
("pignouf" (nm))
("pirate" (nm))
("Polichinelle" (nm))
("polygraphe" (nm))
("porcépic mal embouché" (gnm))
("potentat emplumé" (gnm))
("poussière" (nf))
("profiteur" (nm))
("projectile guidé" (gnm))
("protozoaire" (nm))
("pyromane" (nm))
("pyrophore" (nm))
("rapace" (nm))
("rat" (nm))
("Ravachol" (nm))
("renégat" (nm))
("rhizopode" (nm))
("Rocambole" (nm))
("sacripant" (nm))
("sajou" (nm))
("saltimbanque" (nm))
("sapajou" (nm))
("satané bazar de fourbi de truc" (gnm))
("satrape" (nm))
("sauvage" (n a))
("scélérat" (nm))
("schizophrène" (n a))
("scolopendre" (nf))
("scorpion" (nm))
("serpent" (nm))
("simili martien à la graisse de cabestan" (gnm))
("sinapisme" (nm))
("soulographe" (nm))
("squatter" (nm))
("tchouktchouknougat" (nm))
("technocrate" (nm))
("tête de lard" (gnf))
("tête de mule" (gnf))
("tigresse" (nf))
("tonnerre de Brest" (gnm))
("topinanbour" (nm))
("tortionnaire" (nm))
("traficant de chair humaine" (gnm))
("trainepotence" (nm))
("traitre" (nm a))
("troglodyte" (nm))
("trompelamort" (nm))
("vampire" (nm))
("vandale" (nm a))
("vanupieds" (nm))
("vaurien" (nm))
("végétarien" (nm))
("Vercingétorix de carnaval" (nm))
("ver de terre" (gnm))
("vermicelle" (nm))
("vermine" (nm))
("vipère" (nf))
("vivisectionniste" (nm))
("voleur" (nm))
("wisigoth" (n a))
("zapotèque" (nm))
("zèbre" (nm))
("zigomar" (nm))
("zouave" (nm))
("Zoulou" (nm))
(defparameter nm (remove-if-not (lambda (x) (intersection '(n np nm gnm) (second x))) insults))
(defparameter nf (remove-if-not (lambda (x) (intersection '(nf np) (second x))) insults))
(defparameter ad (remove-if-not (lambda (x) (member 'a (second x))) insults))
(defun insulte ()
(let* ((ga (format nil " ~A" (first (elt ad (random (length ad))))))
(gn (let ((n (random (+ (length nf) (length nm)))))
(if (>= n (length nm))
(prog1
(first (elt nf (- n (length nm))))
(cond
((= 0 (length ga)))
((string= "e" ga :start2 (1- (length ga))))
((string= "eux" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (- (length ga) 2)) "ille")))
((string= "eur" ga :start2 (- (length ga) 3))
(setf ga (concatenate 'string
(subseq ga 0 (1- (length ga))) "se")))
(t
(setf ga (concatenate 'string ga "e")))))
(first (elt nm n)))))
(conj (if (position (aref gn 0) "aeiouyh") "d'" "de "))
(ins (case (random 4)
((0) (concatenate 'string "espèce " conj gn ga))
((1) (concatenate 'string "bande " conj gn ga))
(otherwise (concatenate 'string gn ga)))))
(concatenate 'string
(string-capitalize (subseq ins 0 1))
(subseq ins 1)
" !")))
(defun main (arguments)
(declare (ignore arguments))
(setf *random-state* (make-random-state t))
(princ (insulte))
(terpri)
ex-ok)
|
d27a9cb047ea9fa766aca33b06d00ec59ee5b8e8fffece435b486c471930dcba | mhuebert/yawn | hooks.cljs | (ns yawn.hooks
(:require ["react" :as react]
["use-sync-external-store/shim" :refer [useSyncExternalStore]]
[applied-science.js-interop :as j]))
;; a type for wrapping react/useState to support reset! and swap!
(deftype AtomLike [st]
IIndexed
(-nth [coll i] (aget st i))
(-nth [coll i nf] (or (aget st i) nf))
IDeref
(-deref [^js this] (aget st 0))
IReset
(-reset! [^js this new-value]
;; `constantly` allows functions to be passed as `new-value`
;; (use `swap!` to pass a function that should be applied to prev value)
((aget st 1) (constantly new-value)))
ISwap
(-swap! [this f] ((aget st 1) f))
(-swap! [this f a] ((aget st 1) #(f % a)))
(-swap! [this f a b] ((aget st 1) #(f % a b)))
(-swap! [this f a b xs] ((aget st 1) #(apply f % a b xs))))
(defn- as-array [x] (cond-> x (not (array? x)) to-array))
(defn use-memo
"React hook: useMemo. Defaults to an empty `deps` array."
([f] (react/useMemo f #js[]))
([f deps] (react/useMemo f (as-array deps))))
(defn use-callback
"React hook: useCallback. Defaults to an empty `deps` array."
([x] (use-callback x #js[]))
([x deps] (react/useCallback x (to-array deps))))
(defn- wrap-effect
;; utility for wrapping function to return `js/undefined` for non-functions
[f] #(let [v (f)] (if (fn? v) v js/undefined)))
(defn use-effect
"React hook: useEffect. Defaults to an empty `deps` array.
Wraps `f` to return js/undefined for any non-function value."
([f] (react/useEffect (wrap-effect f) #js[]))
([f deps] (react/useEffect (wrap-effect f) (as-array deps))))
(defn use-state
"React hook: useState. Can be used like react/useState but also behaves like an atom."
[init]
(AtomLike. (react/useState init)))
(deftype Ref [current]
IDeref
(-deref [^js this] current)
IReset
(-reset! [^js this new-value]
;; we must use the (.-current ^js this) form here to ensure that
;; `current` is not renamed by the closure compiler
;; (react needs to see it)
(set! (.-current ^js this) new-value))
ISwap
(-swap! [o f] (reset! o (f o)))
(-swap! [o f a] (reset! o (f o a)))
(-swap! [o f a b] (reset! o (f o a b)))
(-swap! [o f a b xs] (reset! o (apply f o a b xs))))
(defn use-ref
"React hook: useRef. Can also be used like an atom."
([] (use-ref nil))
([init] (react/useCallback (Ref. init) #js[])))
(defn use-sync-external-store [subscribe get-snapshot]
(useSyncExternalStore subscribe get-snapshot))
(comment
(defn use-deps
"Wraps a value to pass as React `deps`, using a custom equal? check (default: clojure.core/=)"
([deps] (use-deps deps =))
([deps equal?]
(let [!counter (use-ref 0)
!prev-deps (use-ref deps)
changed? (not (equal? deps @!prev-deps))]
(reset! !prev-deps deps)
(when changed? (swap! !counter inc))
#js[@!counter]))))
(defn use-deps
"Wraps a value to pass as React `deps`, using a custom equal? check (default: clojure.core/=)"
([deps] (use-deps deps =))
([deps equal?]
(let [counter (react/useRef 0)
prev-deps (react/useRef deps)
changed? (not (equal? deps (j/get prev-deps :current)))]
(j/assoc! prev-deps :current deps)
(when changed? (j/update! counter :current inc))
(array (j/get counter :current)))))
(defn- invoke-fn
"Invoke (f x) if f is a function, otherwise return f"
[f x]
(if (fn? f)
(f x)
f))
(defn use-force-update []
(-> (react/useReducer inc 0)
(aget 1)))
(defn use-state-with-deps
;; see -state-with-deps/blob/main/src/index.ts
"React hook: like `use-state` but will reset state to `init` when `deps` change.
- init may be a function, receiving previous state
- deps will be compared using clojure ="
[init deps]
(let [!state (use-ref
(use-memo
#(invoke-fn init nil)))
!prev-deps (use-ref deps)
_ (when-not (= deps @!prev-deps)
(reset! !state (invoke-fn init @!state))
(reset! !prev-deps deps))
force-update! (use-force-update)
update-fn (use-callback
(fn [x]
(let [prev-state @!state
next-state (invoke-fn x prev-state)]
(when (not= prev-state next-state)
(reset! !state next-state)
(force-update!))
next-state)))]
(AtomLike. #js[@!state update-fn])))
(defn use-deref [x]
(let [id (use-callback #js{})]
(use-sync-external-store
(react/useCallback
(fn [changed!]
(add-watch x id (fn [_ _ _ _] (changed!)))
#(remove-watch x id))
#js[x])
#(deref x))))
(defn ^:deprecated use-atom [x] (use-deref x)) | null | https://raw.githubusercontent.com/mhuebert/yawn/ec725be4808dd08f60ec8770a02f19df5ae3af43/src/main/yawn/hooks.cljs | clojure | a type for wrapping react/useState to support reset! and swap!
`constantly` allows functions to be passed as `new-value`
(use `swap!` to pass a function that should be applied to prev value)
utility for wrapping function to return `js/undefined` for non-functions
we must use the (.-current ^js this) form here to ensure that
`current` is not renamed by the closure compiler
(react needs to see it)
see -state-with-deps/blob/main/src/index.ts | (ns yawn.hooks
(:require ["react" :as react]
["use-sync-external-store/shim" :refer [useSyncExternalStore]]
[applied-science.js-interop :as j]))
(deftype AtomLike [st]
IIndexed
(-nth [coll i] (aget st i))
(-nth [coll i nf] (or (aget st i) nf))
IDeref
(-deref [^js this] (aget st 0))
IReset
(-reset! [^js this new-value]
((aget st 1) (constantly new-value)))
ISwap
(-swap! [this f] ((aget st 1) f))
(-swap! [this f a] ((aget st 1) #(f % a)))
(-swap! [this f a b] ((aget st 1) #(f % a b)))
(-swap! [this f a b xs] ((aget st 1) #(apply f % a b xs))))
(defn- as-array [x] (cond-> x (not (array? x)) to-array))
(defn use-memo
"React hook: useMemo. Defaults to an empty `deps` array."
([f] (react/useMemo f #js[]))
([f deps] (react/useMemo f (as-array deps))))
(defn use-callback
"React hook: useCallback. Defaults to an empty `deps` array."
([x] (use-callback x #js[]))
([x deps] (react/useCallback x (to-array deps))))
(defn- wrap-effect
[f] #(let [v (f)] (if (fn? v) v js/undefined)))
(defn use-effect
"React hook: useEffect. Defaults to an empty `deps` array.
Wraps `f` to return js/undefined for any non-function value."
([f] (react/useEffect (wrap-effect f) #js[]))
([f deps] (react/useEffect (wrap-effect f) (as-array deps))))
(defn use-state
"React hook: useState. Can be used like react/useState but also behaves like an atom."
[init]
(AtomLike. (react/useState init)))
(deftype Ref [current]
IDeref
(-deref [^js this] current)
IReset
(-reset! [^js this new-value]
(set! (.-current ^js this) new-value))
ISwap
(-swap! [o f] (reset! o (f o)))
(-swap! [o f a] (reset! o (f o a)))
(-swap! [o f a b] (reset! o (f o a b)))
(-swap! [o f a b xs] (reset! o (apply f o a b xs))))
(defn use-ref
"React hook: useRef. Can also be used like an atom."
([] (use-ref nil))
([init] (react/useCallback (Ref. init) #js[])))
(defn use-sync-external-store [subscribe get-snapshot]
(useSyncExternalStore subscribe get-snapshot))
(comment
(defn use-deps
"Wraps a value to pass as React `deps`, using a custom equal? check (default: clojure.core/=)"
([deps] (use-deps deps =))
([deps equal?]
(let [!counter (use-ref 0)
!prev-deps (use-ref deps)
changed? (not (equal? deps @!prev-deps))]
(reset! !prev-deps deps)
(when changed? (swap! !counter inc))
#js[@!counter]))))
(defn use-deps
"Wraps a value to pass as React `deps`, using a custom equal? check (default: clojure.core/=)"
([deps] (use-deps deps =))
([deps equal?]
(let [counter (react/useRef 0)
prev-deps (react/useRef deps)
changed? (not (equal? deps (j/get prev-deps :current)))]
(j/assoc! prev-deps :current deps)
(when changed? (j/update! counter :current inc))
(array (j/get counter :current)))))
(defn- invoke-fn
"Invoke (f x) if f is a function, otherwise return f"
[f x]
(if (fn? f)
(f x)
f))
(defn use-force-update []
(-> (react/useReducer inc 0)
(aget 1)))
(defn use-state-with-deps
"React hook: like `use-state` but will reset state to `init` when `deps` change.
- init may be a function, receiving previous state
- deps will be compared using clojure ="
[init deps]
(let [!state (use-ref
(use-memo
#(invoke-fn init nil)))
!prev-deps (use-ref deps)
_ (when-not (= deps @!prev-deps)
(reset! !state (invoke-fn init @!state))
(reset! !prev-deps deps))
force-update! (use-force-update)
update-fn (use-callback
(fn [x]
(let [prev-state @!state
next-state (invoke-fn x prev-state)]
(when (not= prev-state next-state)
(reset! !state next-state)
(force-update!))
next-state)))]
(AtomLike. #js[@!state update-fn])))
(defn use-deref [x]
(let [id (use-callback #js{})]
(use-sync-external-store
(react/useCallback
(fn [changed!]
(add-watch x id (fn [_ _ _ _] (changed!)))
#(remove-watch x id))
#js[x])
#(deref x))))
(defn ^:deprecated use-atom [x] (use-deref x)) |
76d366bf0aa8c350f2b717872e554356344a01a6cdb28fc8939740fdef48afff | lispbuilder/lispbuilder | rwops.lisp |
(in-package #:lispbuilder-sdl-cffi)
(cffi:defcstruct SDL-RWops
(seek :pointer)
(read :pointer)
(write :pointer)
(close :pointer)
(type :unsigned-int)
(hidden :pointer))
(cffi:defcunion SDL_RWops_hidden
#+win32(SDL_RWops_win32io :pointer)
#-win32(SDL_RWops_have_stdio_h :pointer)
(mem :pointer)
(unknown :pointer))
(cffi:defcstruct SDL_RWops_win32io
(append :int)
(h :pointer)
(buffer :pointer))
(cffi:defcstruct SDL_RWops_buffer
(data :pointer)
(size :int)
(left :int))
(cffi:defcstruct SDL_RWops_have_stdio_h
(autoclose :int)
(file :pointer))
(cffi:defcstruct SDL_RWops_hidden_unknown
(data1 :pointer))
(cffi:defcstruct SDL_RWops_hidden_mem
(base :pointer)
(here :pointer)
(stop :pointer))
(cffi:defcfun ("SDL_RWFromFile" sdl-RW-From-File) :pointer
(file sdl-string)
(mode sdl-string))
(cffi:defcfun ("SDL_RWFromMem" SDL-RW-From-Mem) :pointer
(mem :pointer)
(size :int))
(cffi:defcfun ("SDL_RWFromConstMem" SDL-RW-From-Const-Mem) :pointer
(mem :pointer)
(size :int))
(cffi:defcfun ("SDL_AllocRW" SDL-Alloc-RW) :pointer)
(cffi:defcfun ("SDL_FreeRW" SDL-Free-RW) :void
(area :pointer))
(cl:defconstant RW-SEEK-SET 0)
(cl:defconstant RW-SEEK-CUR 1)
(cl:defconstant RW-SEEK-END 2)
(cffi:defcfun ("SDL_ReadLE16" SDL_ReadLE16) :unsigned-short
(src :pointer))
(cffi:defcfun ("SDL_ReadBE16" SDL_ReadBE16) :unsigned-short
(src :pointer))
(cffi:defcfun ("SDL_ReadLE32" SDL_ReadLE32) :unsigned-int
(src :pointer))
(cffi:defcfun ("SDL_ReadBE32" SDL_ReadBE32) :unsigned-int
(src :pointer))
(cffi:defcfun ("SDL_ReadLE64" SDL_ReadLE64) :pointer
(src :pointer))
(cffi:defcfun ("SDL_ReadBE64" SDL_ReadBE64) :pointer
(src :pointer))
(cffi:defcfun ("SDL_WriteLE16" SDL_WriteLE16) :int
(dst :pointer)
(value :unsigned-short))
(cffi:defcfun ("SDL_WriteBE16" SDL_WriteBE16) :int
(dst :pointer)
(value :unsigned-short))
(cffi:defcfun ("SDL_WriteLE32" SDL_WriteLE32) :int
(dst :pointer)
(value :unsigned-int))
(cffi:defcfun ("SDL_WriteBE32" SDL_WriteBE32) :int
(dst :pointer)
(value :unsigned-int))
(cffi:defcfun ("SDL_WriteLE64" SDL_WriteLE64) :int
(dst :pointer)
(value :pointer))
(cffi:defcfun ("SDL_WriteBE64" SDL_WriteBE64) :int
(dst :pointer)
(value :pointer))
| null | https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/cffi/rwops.lisp | lisp |
(in-package #:lispbuilder-sdl-cffi)
(cffi:defcstruct SDL-RWops
(seek :pointer)
(read :pointer)
(write :pointer)
(close :pointer)
(type :unsigned-int)
(hidden :pointer))
(cffi:defcunion SDL_RWops_hidden
#+win32(SDL_RWops_win32io :pointer)
#-win32(SDL_RWops_have_stdio_h :pointer)
(mem :pointer)
(unknown :pointer))
(cffi:defcstruct SDL_RWops_win32io
(append :int)
(h :pointer)
(buffer :pointer))
(cffi:defcstruct SDL_RWops_buffer
(data :pointer)
(size :int)
(left :int))
(cffi:defcstruct SDL_RWops_have_stdio_h
(autoclose :int)
(file :pointer))
(cffi:defcstruct SDL_RWops_hidden_unknown
(data1 :pointer))
(cffi:defcstruct SDL_RWops_hidden_mem
(base :pointer)
(here :pointer)
(stop :pointer))
(cffi:defcfun ("SDL_RWFromFile" sdl-RW-From-File) :pointer
(file sdl-string)
(mode sdl-string))
(cffi:defcfun ("SDL_RWFromMem" SDL-RW-From-Mem) :pointer
(mem :pointer)
(size :int))
(cffi:defcfun ("SDL_RWFromConstMem" SDL-RW-From-Const-Mem) :pointer
(mem :pointer)
(size :int))
(cffi:defcfun ("SDL_AllocRW" SDL-Alloc-RW) :pointer)
(cffi:defcfun ("SDL_FreeRW" SDL-Free-RW) :void
(area :pointer))
(cl:defconstant RW-SEEK-SET 0)
(cl:defconstant RW-SEEK-CUR 1)
(cl:defconstant RW-SEEK-END 2)
(cffi:defcfun ("SDL_ReadLE16" SDL_ReadLE16) :unsigned-short
(src :pointer))
(cffi:defcfun ("SDL_ReadBE16" SDL_ReadBE16) :unsigned-short
(src :pointer))
(cffi:defcfun ("SDL_ReadLE32" SDL_ReadLE32) :unsigned-int
(src :pointer))
(cffi:defcfun ("SDL_ReadBE32" SDL_ReadBE32) :unsigned-int
(src :pointer))
(cffi:defcfun ("SDL_ReadLE64" SDL_ReadLE64) :pointer
(src :pointer))
(cffi:defcfun ("SDL_ReadBE64" SDL_ReadBE64) :pointer
(src :pointer))
(cffi:defcfun ("SDL_WriteLE16" SDL_WriteLE16) :int
(dst :pointer)
(value :unsigned-short))
(cffi:defcfun ("SDL_WriteBE16" SDL_WriteBE16) :int
(dst :pointer)
(value :unsigned-short))
(cffi:defcfun ("SDL_WriteLE32" SDL_WriteLE32) :int
(dst :pointer)
(value :unsigned-int))
(cffi:defcfun ("SDL_WriteBE32" SDL_WriteBE32) :int
(dst :pointer)
(value :unsigned-int))
(cffi:defcfun ("SDL_WriteLE64" SDL_WriteLE64) :int
(dst :pointer)
(value :pointer))
(cffi:defcfun ("SDL_WriteBE64" SDL_WriteBE64) :int
(dst :pointer)
(value :pointer))
| |
4da2715b7adf575693943a0cf421dde472291349d663163666d1f6dbde55fda0 | vikram/lisplibraries | request-handler-utils.lisp |
(in-package :weblocks-test)
(defun with-request-template (body &key
(title "Hello")
render-debug-toolbar-p widget-stylesheets)
(format nil "~
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ~
\"-strict.dtd\">~%~
<html xmlns=''>~
<head>~
<title>~A</title>~
charset = utf-8 ' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/layout.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/main.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/dialog.css' />~
~A~
~A~
<script src='/pub/scripts/prototype.js' type='text/javascript'></script>~
<script src='/pub/scripts/scriptaculous.js' type='text/javascript'></script>~
<script src='/pub/scripts/shortcut.js' type='text/javascript'></script>~
<script src='/pub/scripts/weblocks.js' type='text/javascript'></script>~
<script src='/pub/scripts/dialog.js' type='text/javascript'></script>~
~A~
</head>~
<body>~
<div class='page-wrapper'>~
<div class='page-extra-top-1'><!-- empty --></div>~
<div class='page-extra-top-2'><!-- empty --></div>~
<div class='page-extra-top-3'><!-- empty --></div>~
<div class='widget composite' id='root'>~
~A~
</div>~
<div class='page-extra-bottom-1'><!-- empty --></div>~
<div class='page-extra-bottom-2'><!-- empty --></div>~
<div class='page-extra-bottom-3'><!-- empty --></div>~
</div>~
~A~
<div id='ajax-progress'> </div>~
</body>~
</html>"
title
(apply #'concatenate
'string
(loop for i in widget-stylesheets
collect (format
nil
"<link rel='stylesheet' type='text/css' href='/pub/stylesheets/~A.css' />" i)))
(if render-debug-toolbar-p (format nil "~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/debug-toolbar.css' />")
"")
(if render-debug-toolbar-p (format nil "~
<script src='/pub/scripts/weblocks-debug.js' type='text/javascript'></script>")
"")
(format nil body)
(if render-debug-toolbar-p (format nil "~
<div class='debug-toolbar'>~
<a href='/foo/bar?action=debug-reset-sessions' title='Reset Sessions'>~
<img src='/pub/images/reset.png' alt='Reset Sessions' /></a>~
</div>")
"")))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/test/request-handler-utils.lisp | lisp | </div>~ |
(in-package :weblocks-test)
(defun with-request-template (body &key
(title "Hello")
render-debug-toolbar-p widget-stylesheets)
(format nil "~
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ~
\"-strict.dtd\">~%~
<html xmlns=''>~
<head>~
<title>~A</title>~
charset = utf-8 ' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/layout.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/main.css' />~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/dialog.css' />~
~A~
~A~
<script src='/pub/scripts/prototype.js' type='text/javascript'></script>~
<script src='/pub/scripts/scriptaculous.js' type='text/javascript'></script>~
<script src='/pub/scripts/shortcut.js' type='text/javascript'></script>~
<script src='/pub/scripts/weblocks.js' type='text/javascript'></script>~
<script src='/pub/scripts/dialog.js' type='text/javascript'></script>~
~A~
</head>~
<body>~
<div class='page-wrapper'>~
<div class='page-extra-top-1'><!-- empty --></div>~
<div class='page-extra-top-2'><!-- empty --></div>~
<div class='page-extra-top-3'><!-- empty --></div>~
<div class='widget composite' id='root'>~
~A~
</div>~
<div class='page-extra-bottom-1'><!-- empty --></div>~
<div class='page-extra-bottom-2'><!-- empty --></div>~
<div class='page-extra-bottom-3'><!-- empty --></div>~
</div>~
~A~
</body>~
</html>"
title
(apply #'concatenate
'string
(loop for i in widget-stylesheets
collect (format
nil
"<link rel='stylesheet' type='text/css' href='/pub/stylesheets/~A.css' />" i)))
(if render-debug-toolbar-p (format nil "~
<link rel='stylesheet' type='text/css' href='/pub/stylesheets/debug-toolbar.css' />")
"")
(if render-debug-toolbar-p (format nil "~
<script src='/pub/scripts/weblocks-debug.js' type='text/javascript'></script>")
"")
(format nil body)
(if render-debug-toolbar-p (format nil "~
<div class='debug-toolbar'>~
<a href='/foo/bar?action=debug-reset-sessions' title='Reset Sessions'>~
<img src='/pub/images/reset.png' alt='Reset Sessions' /></a>~
</div>")
"")))
|
0854507628a813a392d96478d85b5634d9a26e67dacd8d09cc1e6bb0fda57781 | openeuler-mirror/secGear | Edger8r.ml |
* Copyright ( C ) 2011 - 2021 Intel Corporation . All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions
* are met :
*
* * Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
* * Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution .
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
* LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
* LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
* DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
* ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* Copyright (C) 2011-2021 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
let main =
let progname = Sys.argv.(0) in
let argc = Array.length Sys.argv in
let args = if argc = 1 then [||] else Array.sub Sys.argv 1 (argc-1) in
let cmd_params = Util.parse_cmdline progname (Array.to_list args) in
let real_ast_handler fname =
try
CodeGen.gen_enclave_code (CodeGen.start_parsing fname) cmd_params
with
Failure s -> (Printf.eprintf "error: %s\n" s; exit (-1))
in
if cmd_params.Util.input_files = [] then Util.usage progname
else List.iter real_ast_handler cmd_params.Util.input_files
| null | https://raw.githubusercontent.com/openeuler-mirror/secGear/23fc7f043ba8c6a5114c6dc79261b3d7bad1bd98/tools/codegener/intel/Edger8r.ml | ocaml |
* Copyright ( C ) 2011 - 2021 Intel Corporation . All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions
* are met :
*
* * Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
* * Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution .
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
* LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
* SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
* LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
* DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
* ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
*
* Copyright (C) 2011-2021 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*)
let main =
let progname = Sys.argv.(0) in
let argc = Array.length Sys.argv in
let args = if argc = 1 then [||] else Array.sub Sys.argv 1 (argc-1) in
let cmd_params = Util.parse_cmdline progname (Array.to_list args) in
let real_ast_handler fname =
try
CodeGen.gen_enclave_code (CodeGen.start_parsing fname) cmd_params
with
Failure s -> (Printf.eprintf "error: %s\n" s; exit (-1))
in
if cmd_params.Util.input_files = [] then Util.usage progname
else List.iter real_ast_handler cmd_params.Util.input_files
| |
e1103b5e28e2b60f5266e5143af22ab81af2a46a2436533db33bc0a15d16f3fa | eslick/cl-stdutils | plotutils.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: plotutils.lisp
Purpose : Extensions to 's interface
Programmer :
Date Started : January 2005
(in-package :utils)
;; -------------------
;; General plot utils
;; -------------------
(defun-exported add-titles-to-data (titles datums)
(assert (>= (length titles) (length datums)))
(mapcar (lambda (title dlist)
(cons title dlist))
titles
datums))
;; ----------------------------
;; Data manipulation utilities
;; ----------------------------
(defun find-all-classes (list class-fn &key key)
(labels ((get-element-class (element)
(funcall class-fn
(if key (funcall key element) element)))
(rec (rlist classes)
(if (null rlist)
classes
(let ((candidate (get-element-class (car rlist))))
(if (find candidate classes)
(rec (cdr rlist) classes)
(rec (cdr rlist) (cons candidate classes)))))))
(rec list nil)))
;; -------------------------
;; Top level plot functions
;; -------------------------
(defun-exported compute-multiple-class-histogram (list class-fn
&rest opts &key (num-bins nil) (key nil) (classes nil) (normalize nil)
&allow-other-keys &aux (bsize nil) (clss nil))
"Classifies and plots data elements in the list according to the
value returned by class-fn when applied to an element of the list.
Accepts plot keyword options"
(labels ((num-bins () (if num-bins num-bins 20))
(total-size () (length list))
(bin-size () (if bsize bsize (setq bsize (ceiling (total-size) (num-bins)))))
(get-classes ()
(if classes classes
(if clss clss
(setq clss (find-all-classes list class-fn :key key)))))
(make-bins ()
(repeat-fn (lambda ()
(mapcar (lambda (class)
(cons class 0))
(get-classes)))
(num-bins)))
(get-series (class bins)
(mapcar (lambda (bin)
(let ((count (cdr (assoc class bin))))
;; (format t "count: ~A norm: ~A~%" count norm)
(if normalize
(ceiling count (bin-size))
count)))
bins))
(get-element-class (element)
(funcall class-fn
(if key (funcall key element) element))))
(let ((bins (make-bins)))
(loop
with bin = 0
for count from 0
for elt in list do
(aif (assoc (get-element-class elt)
(nth bin bins))
(incf (cdr it)))
(if (= 0 (mod count (bin-size))) (incf bin)))
(let ((plist (mapcar (lambda (class)
(cons class (get-series class bins)))
(get-classes))))
(apply #'cllib:plot-lists
`(,plist
,@(rem-keywords opts '(:num-bins :key :classes :normalize))
:xlabel "Counts"))))))
| null | https://raw.githubusercontent.com/eslick/cl-stdutils/4a4e5a4036b815318282da5dee2a22825369137b/src/plotutils.lisp | lisp | Syntax : ANSI - Common - Lisp ; Base : 10 ; Package : utils -*-
*************************************************************************
FILE IDENTIFICATION
Name: plotutils.lisp
-------------------
General plot utils
-------------------
----------------------------
Data manipulation utilities
----------------------------
-------------------------
Top level plot functions
-------------------------
(format t "count: ~A norm: ~A~%" count norm) | Purpose : Extensions to 's interface
Programmer :
Date Started : January 2005
(in-package :utils)
(defun-exported add-titles-to-data (titles datums)
(assert (>= (length titles) (length datums)))
(mapcar (lambda (title dlist)
(cons title dlist))
titles
datums))
(defun find-all-classes (list class-fn &key key)
(labels ((get-element-class (element)
(funcall class-fn
(if key (funcall key element) element)))
(rec (rlist classes)
(if (null rlist)
classes
(let ((candidate (get-element-class (car rlist))))
(if (find candidate classes)
(rec (cdr rlist) classes)
(rec (cdr rlist) (cons candidate classes)))))))
(rec list nil)))
(defun-exported compute-multiple-class-histogram (list class-fn
&rest opts &key (num-bins nil) (key nil) (classes nil) (normalize nil)
&allow-other-keys &aux (bsize nil) (clss nil))
"Classifies and plots data elements in the list according to the
value returned by class-fn when applied to an element of the list.
Accepts plot keyword options"
(labels ((num-bins () (if num-bins num-bins 20))
(total-size () (length list))
(bin-size () (if bsize bsize (setq bsize (ceiling (total-size) (num-bins)))))
(get-classes ()
(if classes classes
(if clss clss
(setq clss (find-all-classes list class-fn :key key)))))
(make-bins ()
(repeat-fn (lambda ()
(mapcar (lambda (class)
(cons class 0))
(get-classes)))
(num-bins)))
(get-series (class bins)
(mapcar (lambda (bin)
(let ((count (cdr (assoc class bin))))
(if normalize
(ceiling count (bin-size))
count)))
bins))
(get-element-class (element)
(funcall class-fn
(if key (funcall key element) element))))
(let ((bins (make-bins)))
(loop
with bin = 0
for count from 0
for elt in list do
(aif (assoc (get-element-class elt)
(nth bin bins))
(incf (cdr it)))
(if (= 0 (mod count (bin-size))) (incf bin)))
(let ((plist (mapcar (lambda (class)
(cons class (get-series class bins)))
(get-classes))))
(apply #'cllib:plot-lists
`(,plist
,@(rem-keywords opts '(:num-bins :key :classes :normalize))
:xlabel "Counts"))))))
|
1324c0be6b827ca603d013faa6f00edd5c30622dac01153acd054a2f5c473eee | Andromedans/andromeda | nucleus_json.ml | (** Conversion to JSON *)
open Nucleus_types
let assumptions { free_var ; free_meta ; bound_var ; bound_meta } =
let free_var =
if Nonce.map_is_empty free_var
then []
else [("free_var", Nonce.Json.map free_var)]
and free_meta =
if Nonce.map_is_empty free_meta
then []
else [("free_meta", Nonce.Json.map free_meta)]
and bound_var =
if Bound_set.is_empty bound_var
then []
else [("bound_var", Json.List (List.map (fun k -> Json.Int k) (Bound_set.elements bound_var)))]
and bound_meta =
if Bound_set.is_empty bound_meta
then []
else [("bound_meta", Json.List (List.map (fun k -> Json.Int k) (Bound_set.elements bound_meta)))]
in
Json.record (free_var @ free_meta @ bound_var @ bound_meta)
let rec is_term e =
let e =
match e with
| TermAtom {atom_nonce=x; atom_type=t} -> Json.tag "TermAtom" [Nonce.Json.nonce x; is_type t]
| TermBoundVar b -> Json.tag "TermBoundVar" [Json.Int b]
| TermConstructor (c, lst) -> Json.tag "TermConstructor" (Ident.Json.ident c :: arguments lst)
| TermMeta (mv, lst) ->
Json.tag "TermMeta" (meta mv :: (List.map is_term lst))
| TermConvert (e, asmp, t) -> Json.tag "TermConvert" [is_term e; assumptions asmp; is_type t]
in Json.tag "IsTerm" [e]
and is_type t =
let t =
match t with
| TypeConstructor (c, lst) -> Json.tag "TypeConstructor" (Ident.Json.ident c :: arguments lst)
| TypeMeta (mv, lst) ->
Json.tag "TypeMeta" (meta mv :: (List.map is_term lst))
in Json.tag "IsType" [t]
and meta = function
| MetaFree {meta_nonce; _} -> Json.tag "MetaFree" [Nonce.Json.nonce meta_nonce]
| MetaBound k -> Json.tag "MetaBound" [Json.Int k]
and argument arg =
let rec fold xs = function
| Arg_Abstract (x, arg) -> fold (x :: xs) arg
| Arg_NotAbstract jdg ->
let xs = List.map Name.Json.name (List.rev xs) in
Json.tag "Argument" [Json.tuple xs ; judgement jdg]
in
fold [] arg
and arguments lst = List.map argument lst
and judgement = function
| JudgementIsType t -> Json.tag "JudgementIsType" [is_type t]
| JudgementIsTerm e -> Json.tag "JudgementIsTerm" [is_term e]
| JudgementEqType _ -> Json.tag "JudgementEqType" []
| JudgementEqTerm _ -> Json.tag "JudgementEqTerm" []
let rec abstraction json_u xts =
function
| Abstract (x, t, abstr) ->
abstraction json_u ((x, t) :: xts) abstr
| NotAbstract u ->
let xts = List.map (fun (x, t) -> Json.List [Name.Json.name x; is_type t]) (List.rev xts) in
[Json.tuple xts ; json_u u]
let boundary = function
| BoundaryIsType abstr ->
Json.tag "BoundaryIsType" []
| BoundaryIsTerm t ->
Json.tag "BoundaryIsTerm" [is_type t]
| BoundaryEqType (t1, t2) ->
Json.tag "BoundaryIsType" [is_type t1; is_type t2]
| BoundaryEqTerm (e1, e2, t) ->
Json.tag "BoundaryEqTerm" [is_term e1; is_term e2; is_type t]
let judgement_abstraction abstr = Json.List (abstraction judgement [] abstr)
let boundary_abstraction abstr = Json.List (abstraction boundary [] abstr)
| null | https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/src/nucleus/nucleus_json.ml | ocaml | * Conversion to JSON |
open Nucleus_types
let assumptions { free_var ; free_meta ; bound_var ; bound_meta } =
let free_var =
if Nonce.map_is_empty free_var
then []
else [("free_var", Nonce.Json.map free_var)]
and free_meta =
if Nonce.map_is_empty free_meta
then []
else [("free_meta", Nonce.Json.map free_meta)]
and bound_var =
if Bound_set.is_empty bound_var
then []
else [("bound_var", Json.List (List.map (fun k -> Json.Int k) (Bound_set.elements bound_var)))]
and bound_meta =
if Bound_set.is_empty bound_meta
then []
else [("bound_meta", Json.List (List.map (fun k -> Json.Int k) (Bound_set.elements bound_meta)))]
in
Json.record (free_var @ free_meta @ bound_var @ bound_meta)
let rec is_term e =
let e =
match e with
| TermAtom {atom_nonce=x; atom_type=t} -> Json.tag "TermAtom" [Nonce.Json.nonce x; is_type t]
| TermBoundVar b -> Json.tag "TermBoundVar" [Json.Int b]
| TermConstructor (c, lst) -> Json.tag "TermConstructor" (Ident.Json.ident c :: arguments lst)
| TermMeta (mv, lst) ->
Json.tag "TermMeta" (meta mv :: (List.map is_term lst))
| TermConvert (e, asmp, t) -> Json.tag "TermConvert" [is_term e; assumptions asmp; is_type t]
in Json.tag "IsTerm" [e]
and is_type t =
let t =
match t with
| TypeConstructor (c, lst) -> Json.tag "TypeConstructor" (Ident.Json.ident c :: arguments lst)
| TypeMeta (mv, lst) ->
Json.tag "TypeMeta" (meta mv :: (List.map is_term lst))
in Json.tag "IsType" [t]
and meta = function
| MetaFree {meta_nonce; _} -> Json.tag "MetaFree" [Nonce.Json.nonce meta_nonce]
| MetaBound k -> Json.tag "MetaBound" [Json.Int k]
and argument arg =
let rec fold xs = function
| Arg_Abstract (x, arg) -> fold (x :: xs) arg
| Arg_NotAbstract jdg ->
let xs = List.map Name.Json.name (List.rev xs) in
Json.tag "Argument" [Json.tuple xs ; judgement jdg]
in
fold [] arg
and arguments lst = List.map argument lst
and judgement = function
| JudgementIsType t -> Json.tag "JudgementIsType" [is_type t]
| JudgementIsTerm e -> Json.tag "JudgementIsTerm" [is_term e]
| JudgementEqType _ -> Json.tag "JudgementEqType" []
| JudgementEqTerm _ -> Json.tag "JudgementEqTerm" []
let rec abstraction json_u xts =
function
| Abstract (x, t, abstr) ->
abstraction json_u ((x, t) :: xts) abstr
| NotAbstract u ->
let xts = List.map (fun (x, t) -> Json.List [Name.Json.name x; is_type t]) (List.rev xts) in
[Json.tuple xts ; json_u u]
let boundary = function
| BoundaryIsType abstr ->
Json.tag "BoundaryIsType" []
| BoundaryIsTerm t ->
Json.tag "BoundaryIsTerm" [is_type t]
| BoundaryEqType (t1, t2) ->
Json.tag "BoundaryIsType" [is_type t1; is_type t2]
| BoundaryEqTerm (e1, e2, t) ->
Json.tag "BoundaryEqTerm" [is_term e1; is_term e2; is_type t]
let judgement_abstraction abstr = Json.List (abstraction judgement [] abstr)
let boundary_abstraction abstr = Json.List (abstraction boundary [] abstr)
|
48ad60230f69f3eac454395e8e1828f93c2078e2ae796de590c6da9cc76f422f | purebred-mua/purebred | Client.hs | -- This file is part of purebred
Copyright ( C ) 2022 and
--
-- purebred is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
--
You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see </>.
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Purebred.Storage.Client
(
-- * API
-- ** Threads
getThreads
, getThreadMessages
, countMessages
-- ** Messages
, messageTagModify
, mailFilepath
, indexFilePath
, unindexFilePath
-- * Re-exports
, Server
) where
import Control.Concurrent (ThreadId, forkIO)
import Control.Concurrent.STM (atomically , newEmptyTMVarIO, readTMVar)
import Control.Lens (firstOf, folded, view)
import Control.Monad ((<=<), void, when)
import Control.Monad.Except (ExceptT, MonadError, liftEither, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Foldable (toList)
import Data.Function (on)
import Data.Functor.Compose (Compose(..))
import Data.Maybe (fromMaybe)
import Data.List (nub, sort)
import qualified Data.Text as T
import Data.Traversable (for)
import qualified System.Directory
import System.IO.Unsafe (unsafeInterleaveIO)
import qualified Data.Vector as V
import qualified Notmuch
import Purebred.Storage.Server
import Purebred.Storage.Tags (TagOp, tagItem, tags)
import Purebred.System (tryIO)
import Purebred.Types (NotmuchThread(..), NotmuchMail(..), decodeLenient, mailId, thId)
import Purebred.Types.Error (Error(MessageNotFound, ThreadNotFound))
import Purebred.Types.Items (Items, fromList)
---
--- Interacting with server
---
type Call params result =
forall m. (MonadIO m, MonadError Error m)
=> params -> Server -> m result
type Call2 param1 param2 result =
forall m. (MonadIO m, MonadError Error m)
=> param1 -> param2 -> Server -> m result
-- | Send command and await result
runCommand
:: (MonadError Error m, MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a) -> Server -> m a
runCommand core server = do
result <- liftIO $ do
box <- newEmptyTMVarIO
enqueue server $ Command core (Just box)
atomically $ readTMVar box
liftEither result
-- | Enqueue command and return immediately, discarding result
_sendCommand
:: (MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a) -> Server -> m ()
_sendCommand core server = void . liftIO . enqueue server $ Command core Nothing
-- | Enqueue command and fork an unbound thread to handle the result.
-- Returns 'ThreadId' of the result handler thread.
_runCommandWithHandler
:: (MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a)
-> (Either Error a -> IO ())
-> Server -> m ThreadId
_runCommandWithHandler core handler server =
liftIO $ do
box <- newEmptyTMVarIO
enqueue server $ Command core (Just box)
forkIO $ do
r <- atomically $ readTMVar box
handler r
---
--- Database actions
---
-- | Apply tag operations on all given mails and write the resulting
-- tags to the database
messageTagModify
:: (Traversable t)
=> Call2 [TagOp] (t NotmuchMail) (t NotmuchMail)
messageTagModify ops msgs = runCommand $ \db ->
for msgs $ \m -> do
let m' = tagItem ops m
-- only act if tags actually changed
when (((/=) `on` (sort . nub . view tags)) m m') $
getMessage db (view mailId m')
>>= Notmuch.messageSetTags (view tags m')
pure m'
-- | Returns the absolute path to the email. Typically used by the
-- email parser.
--
mailFilepath :: Call NotmuchMail FilePath
mailFilepath m = runCommand $ \db ->
getMessage db (view mailId m) >>= Notmuch.messageFilename
-- | Return the number of messages for the given free-form search term
countMessages :: Call T.Text Int
countMessages expr = runCommand $ \db ->
Notmuch.query db (Notmuch.Bare $ T.unpack expr)
>>= Notmuch.queryCountMessages
-- | Creates a vector of threads from a free-form search term
--
getThreads :: Call T.Text (Items NotmuchThread)
getThreads expr = runCommand $ \db ->
Notmuch.query db (Notmuch.Bare $ T.unpack expr)
>>= Notmuch.threads
note : we use lazyTraverse and " chunked " construction , but
-- whether it will actually be lazy depends on the variant of
-- 'Items' in use. For a Vector, it is strict and non-chunked.
>>= liftIO . fmap (fromList 128) . lazyTraverse threadToThread
where
threadToThread :: Notmuch.Thread a -> IO NotmuchThread
threadToThread m = do
tgs <- Notmuch.tags m
auth <- Notmuch.threadAuthors m
NotmuchThread
<$> (fixupWhitespace . decodeLenient <$> Notmuch.threadSubject m)
<*> pure (view Notmuch.matchedAuthors auth)
<*> Notmuch.threadNewestDate m
<*> pure tgs
<*> Notmuch.threadTotalMessages m
<*> Notmuch.threadId m
-- | Returns a vector of *all* messages belonging to a collection of threads
--
getThreadMessages :: (Traversable t) => Call (t NotmuchThread) (V.Vector NotmuchMail)
getThreadMessages threads = runCommand $ \db -> do
msgs <- Compose -- 'collapse' nested 't ([] a)'
<$> traverse (Notmuch.messages <=< getThread db . view thId) threads
mails <- traverse (liftIO . messageToMail) msgs
pure . V.fromList . toList $ mails
where
-- Retrieve thread by ID. libnotmuch does not provide a direct
-- way to query a thread. Perform a general query and pop the
first result , or fail if the result is empty .
--
getThread db tid = do
t <- Notmuch.query db (Notmuch.Thread tid) >>= Notmuch.threads
maybe (throwError (ThreadNotFound tid)) pure (firstOf folded t)
messageToMail m = do
tgs <- Notmuch.tags m
NotmuchMail
<$> (fixupWhitespace . decodeLenient . fromMaybe "" <$> Notmuch.messageHeader "Subject" m)
<*> (decodeLenient . fromMaybe "" <$> Notmuch.messageHeader "From" m)
<*> Notmuch.messageDate m
<*> pure tgs
<*> Notmuch.messageId m
indexFilePath :: Call2 FilePath [Notmuch.Tag] ()
indexFilePath path tags_ = runCommand $ \db ->
Notmuch.indexFile db path >>= Notmuch.messageSetTags tags_
unindexFilePath :: Call FilePath ()
unindexFilePath path = runCommand $ \db ->
void $ Notmuch.removeFile db path *> tryIO (System.Directory.removeFile path)
---
--- Helper functions
---
lazyTraverse :: (a -> IO b) -> [a] -> IO [b]
lazyTraverse f =
foldr (\x ys -> (:) <$> f x <*> unsafeInterleaveIO ys) (pure [])
fixupWhitespace :: T.Text -> T.Text
fixupWhitespace = T.map f . T.filter (/= '\n')
where f '\t' = ' '
f c = c
-- | Get message by message ID, throwing MessageNotFound if not found
--
getMessage
:: (MonadError Error m, MonadIO m)
=> Notmuch.Database mode -> Notmuch.MessageId -> m (Notmuch.Message 0 mode)
getMessage db msgId =
Notmuch.findMessage db msgId
>>= maybe (throwError (MessageNotFound msgId)) pure
| null | https://raw.githubusercontent.com/purebred-mua/purebred/5240c08a3ca1555d9e18635e54520a2dfa6d21d4/src/Purebred/Storage/Client.hs | haskell | This file is part of purebred
purebred 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 Affero General Public License for more details.
along with this program. If not, see </>.
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
* API
** Threads
** Messages
* Re-exports
-
- Interacting with server
-
| Send command and await result
| Enqueue command and return immediately, discarding result
| Enqueue command and fork an unbound thread to handle the result.
Returns 'ThreadId' of the result handler thread.
-
- Database actions
-
| Apply tag operations on all given mails and write the resulting
tags to the database
only act if tags actually changed
| Returns the absolute path to the email. Typically used by the
email parser.
| Return the number of messages for the given free-form search term
| Creates a vector of threads from a free-form search term
whether it will actually be lazy depends on the variant of
'Items' in use. For a Vector, it is strict and non-chunked.
| Returns a vector of *all* messages belonging to a collection of threads
'collapse' nested 't ([] a)'
Retrieve thread by ID. libnotmuch does not provide a direct
way to query a thread. Perform a general query and pop the
-
- Helper functions
-
| Get message by message ID, throwing MessageNotFound if not found
| Copyright ( C ) 2022 and
it under the terms of the GNU Affero 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 Affero General Public License
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Purebred.Storage.Client
(
getThreads
, getThreadMessages
, countMessages
, messageTagModify
, mailFilepath
, indexFilePath
, unindexFilePath
, Server
) where
import Control.Concurrent (ThreadId, forkIO)
import Control.Concurrent.STM (atomically , newEmptyTMVarIO, readTMVar)
import Control.Lens (firstOf, folded, view)
import Control.Monad ((<=<), void, when)
import Control.Monad.Except (ExceptT, MonadError, liftEither, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Foldable (toList)
import Data.Function (on)
import Data.Functor.Compose (Compose(..))
import Data.Maybe (fromMaybe)
import Data.List (nub, sort)
import qualified Data.Text as T
import Data.Traversable (for)
import qualified System.Directory
import System.IO.Unsafe (unsafeInterleaveIO)
import qualified Data.Vector as V
import qualified Notmuch
import Purebred.Storage.Server
import Purebred.Storage.Tags (TagOp, tagItem, tags)
import Purebred.System (tryIO)
import Purebred.Types (NotmuchThread(..), NotmuchMail(..), decodeLenient, mailId, thId)
import Purebred.Types.Error (Error(MessageNotFound, ThreadNotFound))
import Purebred.Types.Items (Items, fromList)
type Call params result =
forall m. (MonadIO m, MonadError Error m)
=> params -> Server -> m result
type Call2 param1 param2 result =
forall m. (MonadIO m, MonadError Error m)
=> param1 -> param2 -> Server -> m result
runCommand
:: (MonadError Error m, MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a) -> Server -> m a
runCommand core server = do
result <- liftIO $ do
box <- newEmptyTMVarIO
enqueue server $ Command core (Just box)
atomically $ readTMVar box
liftEither result
_sendCommand
:: (MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a) -> Server -> m ()
_sendCommand core server = void . liftIO . enqueue server $ Command core Nothing
_runCommandWithHandler
:: (MonadIO m)
=> (Notmuch.Database Notmuch.RW -> ExceptT Error IO a)
-> (Either Error a -> IO ())
-> Server -> m ThreadId
_runCommandWithHandler core handler server =
liftIO $ do
box <- newEmptyTMVarIO
enqueue server $ Command core (Just box)
forkIO $ do
r <- atomically $ readTMVar box
handler r
messageTagModify
:: (Traversable t)
=> Call2 [TagOp] (t NotmuchMail) (t NotmuchMail)
messageTagModify ops msgs = runCommand $ \db ->
for msgs $ \m -> do
let m' = tagItem ops m
when (((/=) `on` (sort . nub . view tags)) m m') $
getMessage db (view mailId m')
>>= Notmuch.messageSetTags (view tags m')
pure m'
mailFilepath :: Call NotmuchMail FilePath
mailFilepath m = runCommand $ \db ->
getMessage db (view mailId m) >>= Notmuch.messageFilename
countMessages :: Call T.Text Int
countMessages expr = runCommand $ \db ->
Notmuch.query db (Notmuch.Bare $ T.unpack expr)
>>= Notmuch.queryCountMessages
getThreads :: Call T.Text (Items NotmuchThread)
getThreads expr = runCommand $ \db ->
Notmuch.query db (Notmuch.Bare $ T.unpack expr)
>>= Notmuch.threads
note : we use lazyTraverse and " chunked " construction , but
>>= liftIO . fmap (fromList 128) . lazyTraverse threadToThread
where
threadToThread :: Notmuch.Thread a -> IO NotmuchThread
threadToThread m = do
tgs <- Notmuch.tags m
auth <- Notmuch.threadAuthors m
NotmuchThread
<$> (fixupWhitespace . decodeLenient <$> Notmuch.threadSubject m)
<*> pure (view Notmuch.matchedAuthors auth)
<*> Notmuch.threadNewestDate m
<*> pure tgs
<*> Notmuch.threadTotalMessages m
<*> Notmuch.threadId m
getThreadMessages :: (Traversable t) => Call (t NotmuchThread) (V.Vector NotmuchMail)
getThreadMessages threads = runCommand $ \db -> do
<$> traverse (Notmuch.messages <=< getThread db . view thId) threads
mails <- traverse (liftIO . messageToMail) msgs
pure . V.fromList . toList $ mails
where
first result , or fail if the result is empty .
getThread db tid = do
t <- Notmuch.query db (Notmuch.Thread tid) >>= Notmuch.threads
maybe (throwError (ThreadNotFound tid)) pure (firstOf folded t)
messageToMail m = do
tgs <- Notmuch.tags m
NotmuchMail
<$> (fixupWhitespace . decodeLenient . fromMaybe "" <$> Notmuch.messageHeader "Subject" m)
<*> (decodeLenient . fromMaybe "" <$> Notmuch.messageHeader "From" m)
<*> Notmuch.messageDate m
<*> pure tgs
<*> Notmuch.messageId m
indexFilePath :: Call2 FilePath [Notmuch.Tag] ()
indexFilePath path tags_ = runCommand $ \db ->
Notmuch.indexFile db path >>= Notmuch.messageSetTags tags_
unindexFilePath :: Call FilePath ()
unindexFilePath path = runCommand $ \db ->
void $ Notmuch.removeFile db path *> tryIO (System.Directory.removeFile path)
lazyTraverse :: (a -> IO b) -> [a] -> IO [b]
lazyTraverse f =
foldr (\x ys -> (:) <$> f x <*> unsafeInterleaveIO ys) (pure [])
fixupWhitespace :: T.Text -> T.Text
fixupWhitespace = T.map f . T.filter (/= '\n')
where f '\t' = ' '
f c = c
getMessage
:: (MonadError Error m, MonadIO m)
=> Notmuch.Database mode -> Notmuch.MessageId -> m (Notmuch.Message 0 mode)
getMessage db msgId =
Notmuch.findMessage db msgId
>>= maybe (throwError (MessageNotFound msgId)) pure
|
dcbc77337137b13fc7311cc754ecc5a05b272f281e9a4e8d3a6e62d47a06e325 | kelsey-sorrels/robinson | inventory_test.clj | (ns robinson.inventory-test
(:require [robinson.common :as rc]
[robinson.inventory :as ri]
[robinson.monstergen :as mg]
[robinson.itemgen :as ig]
[clojure.test :as t
:refer (is are deftest with-test run-tests testing)]))
(deftest test-add-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory []}}}]
(are
[items expected]
; expected = actual
(= expected
(ri/player-inventory (ri/add-to-inventory state items)))
; items
(let [item-ids [:rope
:stick
:feather
:knife
:bamboo
:rock]
rat (mg/id->monster :rat)
rat-corpse (ig/gen-corpse rat)
rat-bones (ig/gen-bones rat-corpse)]
(println rat-corpse)
(println rat-bones)
(concat [rat-corpse
rat-bones]
(map ig/gen-item item-ids)))
; inventory
[{:item/id :rat-corpse,
:type :food,
:race :rat,
:name "rat corpse",
:name-plural "rat corpses",
:hunger 12.079181246047625
:weight 0.2
:hotkey \A}
{:item/id :rat-bones,
:race :rat,
:name "rat bones",
:name-plural "rat bones",
:weight 0.2
:properties #{:tube-like :stick-like},
:hotkey \B}
{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:properties #{:flexible}
:hotkey \C}
{:item/id :stick,
:name "stick",
:name-plural "sticks",
:fuel 100,
:utility 100,
:weight 0.5,
:properties #{:stick-like :handled},
:item/materials #{:wood}
:hotkey \D}
{:item/id :feather,
:name "feather",
:name-plural "feathers"
:hotkey \E}
{:item/id :knife,
:name "knife",
:name-plural "knives",
:attack :knife,
:utility 100,
:roundness 0.01
:properties #{:edged :handled}
:hotkey \F}
{:item/id :bamboo,
:name "bamboo",
:name-plural "bamboo",
:fuel 100,
:properties #{:tube-like :stick-like}
:hotkey \G}
{:item/id :rock,
:name "rock",
:name-plural "rocks",
:attack :blunt,
:ranged-attack :airborn-item
:ammunition-id :rock
:roundness 0.8
:weight 0.5
:hotkey \H}])))
(deftest test-dec-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory [
{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:count 10
:properties #{:flexible}
:hotkey \C}]}}}]
(are
[expected]
; expected = actual
(= expected
(-> state
(ri/dec-item-count \C)
ri/player-inventory))
; items
[{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:count 9
:properties #{:flexible}
:hotkey \C}])))
(deftest test-add-additional-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory []}}}]
(are
[items expected]
; expected = actual
(= expected
(-> state
(ri/add-to-inventory (map ig/gen-item [:rope :knife]))
(ri/add-to-inventory items)
ri/player-inventory))
; items
(let [rat (mg/id->monster :rat)
rat-corpse (ig/gen-corpse rat)
rat-bones (ig/gen-bones rat-corpse)]
(println rat-corpse)
(println rat-bones)
[rat-corpse
rat-bones])
; inventory
[{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:properties #{:flexible}
:hotkey \A}
{:item/id :knife,
:name "knife",
:name-plural "knives",
:attack :knife,
:utility 100,
:roundness 0.01
:properties #{:edged :handled}
:hotkey \B}
{:item/id :rat-corpse,
:type :food,
:race :rat,
:name "rat corpse",
:name-plural "rat corpses",
:hunger 12.079181246047625
:weight 0.2
:hotkey \C}
{:item/id :rat-bones,
:race :rat,
:name "rat bones",
:name-plural "rat bones",
:weight 0.2
:properties #{:tube-like :stick-like},
:hotkey \D}])))
| null | https://raw.githubusercontent.com/kelsey-sorrels/robinson/337fd2646882708331257d1f3db78a3074ccc67a/test/clj/robinson/inventory_test.clj | clojure | expected = actual
items
inventory
expected = actual
items
expected = actual
items
inventory | (ns robinson.inventory-test
(:require [robinson.common :as rc]
[robinson.inventory :as ri]
[robinson.monstergen :as mg]
[robinson.itemgen :as ig]
[clojure.test :as t
:refer (is are deftest with-test run-tests testing)]))
(deftest test-add-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory []}}}]
(are
[items expected]
(= expected
(ri/player-inventory (ri/add-to-inventory state items)))
(let [item-ids [:rope
:stick
:feather
:knife
:bamboo
:rock]
rat (mg/id->monster :rat)
rat-corpse (ig/gen-corpse rat)
rat-bones (ig/gen-bones rat-corpse)]
(println rat-corpse)
(println rat-bones)
(concat [rat-corpse
rat-bones]
(map ig/gen-item item-ids)))
[{:item/id :rat-corpse,
:type :food,
:race :rat,
:name "rat corpse",
:name-plural "rat corpses",
:hunger 12.079181246047625
:weight 0.2
:hotkey \A}
{:item/id :rat-bones,
:race :rat,
:name "rat bones",
:name-plural "rat bones",
:weight 0.2
:properties #{:tube-like :stick-like},
:hotkey \B}
{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:properties #{:flexible}
:hotkey \C}
{:item/id :stick,
:name "stick",
:name-plural "sticks",
:fuel 100,
:utility 100,
:weight 0.5,
:properties #{:stick-like :handled},
:item/materials #{:wood}
:hotkey \D}
{:item/id :feather,
:name "feather",
:name-plural "feathers"
:hotkey \E}
{:item/id :knife,
:name "knife",
:name-plural "knives",
:attack :knife,
:utility 100,
:roundness 0.01
:properties #{:edged :handled}
:hotkey \F}
{:item/id :bamboo,
:name "bamboo",
:name-plural "bamboo",
:fuel 100,
:properties #{:tube-like :stick-like}
:hotkey \G}
{:item/id :rock,
:name "rock",
:name-plural "rocks",
:attack :blunt,
:ranged-attack :airborn-item
:ammunition-id :rock
:roundness 0.8
:weight 0.5
:hotkey \H}])))
(deftest test-dec-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory [
{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:count 10
:properties #{:flexible}
:hotkey \C}]}}}]
(are
[expected]
(= expected
(-> state
(ri/dec-item-count \C)
ri/player-inventory))
[{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:count 9
:properties #{:flexible}
:hotkey \C}])))
(deftest test-add-additional-items
(let [state {:world {
:time 0
:remaining-hotkeys rc/hotkeys
:player {
:inventory []}}}]
(are
[items expected]
(= expected
(-> state
(ri/add-to-inventory (map ig/gen-item [:rope :knife]))
(ri/add-to-inventory items)
ri/player-inventory))
(let [rat (mg/id->monster :rat)
rat-corpse (ig/gen-corpse rat)
rat-bones (ig/gen-bones rat-corpse)]
(println rat-corpse)
(println rat-bones)
[rat-corpse
rat-bones])
[{:item/id :rope,
:name "rope",
:name-plural "ropes",
:fuel 10,
:properties #{:flexible}
:hotkey \A}
{:item/id :knife,
:name "knife",
:name-plural "knives",
:attack :knife,
:utility 100,
:roundness 0.01
:properties #{:edged :handled}
:hotkey \B}
{:item/id :rat-corpse,
:type :food,
:race :rat,
:name "rat corpse",
:name-plural "rat corpses",
:hunger 12.079181246047625
:weight 0.2
:hotkey \C}
{:item/id :rat-bones,
:race :rat,
:name "rat bones",
:name-plural "rat bones",
:weight 0.2
:properties #{:tube-like :stick-like},
:hotkey \D}])))
|
086773cfbb6647ed1b6f8e1a81963f5143e19b0fda7c25c0d8a35b0ad44d4f16 | Armael/conch | types.ml | open Common
type tybase = Tvoid | Tint8 | Tint16
type ty =
| Tbase of tybase
| Tptr of ty
(* in bytes *)
let sizeof = function
| Tbase Tvoid -> 0
| Tbase Tint8 -> 1
| Tbase Tint16 | Tptr _ -> 2
let type_of_const = function
| C8 _ -> Tbase Tint8
| C16 _ -> Tbase Tint16
(* printing *)
let pp_tybase fmt = function
| Tvoid -> Format.fprintf fmt "void"
| Tint8 -> Format.fprintf fmt "u8"
| Tint16 -> Format.fprintf fmt "u16"
let rec pp_ty fmt = function
| Tbase ty -> pp_tybase fmt ty
| Tptr ty -> Format.fprintf fmt "*%a" pp_ty ty
let pp_ty fmt ty = pp_ty fmt ty
let string_of_ty ty =
Format.asprintf ":%a" pp_ty ty
| null | https://raw.githubusercontent.com/Armael/conch/8a72f98a8d29cb8f678a69db95d5b68964304053/lib/types.ml | ocaml | in bytes
printing | open Common
type tybase = Tvoid | Tint8 | Tint16
type ty =
| Tbase of tybase
| Tptr of ty
let sizeof = function
| Tbase Tvoid -> 0
| Tbase Tint8 -> 1
| Tbase Tint16 | Tptr _ -> 2
let type_of_const = function
| C8 _ -> Tbase Tint8
| C16 _ -> Tbase Tint16
let pp_tybase fmt = function
| Tvoid -> Format.fprintf fmt "void"
| Tint8 -> Format.fprintf fmt "u8"
| Tint16 -> Format.fprintf fmt "u16"
let rec pp_ty fmt = function
| Tbase ty -> pp_tybase fmt ty
| Tptr ty -> Format.fprintf fmt "*%a" pp_ty ty
let pp_ty fmt ty = pp_ty fmt ty
let string_of_ty ty =
Format.asprintf ":%a" pp_ty ty
|
c96982ed66a77bb1479c03001d933d2fdac64f8f2e87c6289afc763da244c72d | ollef/sixty | Telescope.hs | {-# LANGUAGE OverloadedStrings #-}
module Core.Domain.Telescope where
import Core.Binding (Binding)
import qualified Core.Domain as Domain
import Monad
import Plicity
import Protolude
data Telescope base
= Empty !base
| Extend !Binding !Domain.Type !Plicity (Domain.Value -> M (Telescope base))
apply :: Telescope k -> [(Plicity, Domain.Value)] -> M (Telescope k)
apply tele args =
case (tele, args) of
(_, []) ->
pure tele
(Extend _ _ plicity1 teleFun, (plicity2, arg) : args')
| plicity1 == plicity2 -> do
tele' <- teleFun arg
apply tele' args'
_ ->
panic "Core.Domain.Telescope.apply"
| null | https://raw.githubusercontent.com/ollef/sixty/2582551f3c12f84489afb961b800f0d7cfa74844/src/Core/Domain/Telescope.hs | haskell | # LANGUAGE OverloadedStrings # |
module Core.Domain.Telescope where
import Core.Binding (Binding)
import qualified Core.Domain as Domain
import Monad
import Plicity
import Protolude
data Telescope base
= Empty !base
| Extend !Binding !Domain.Type !Plicity (Domain.Value -> M (Telescope base))
apply :: Telescope k -> [(Plicity, Domain.Value)] -> M (Telescope k)
apply tele args =
case (tele, args) of
(_, []) ->
pure tele
(Extend _ _ plicity1 teleFun, (plicity2, arg) : args')
| plicity1 == plicity2 -> do
tele' <- teleFun arg
apply tele' args'
_ ->
panic "Core.Domain.Telescope.apply"
|
bd90e5aac278e5b0c14172089defcb9a9ecbda8303a7891c4d848e0a1361d1e1 | returntocorp/semgrep | Test_dataflow_tainting.ml | open Common
module G = AST_generic
module RM = Range_with_metavars
module DataflowX = Dataflow_core.Make (struct
type node = IL.node
type edge = IL.edge
type flow = (node, edge) CFG.t
let short_string_of_node n = Display_IL.short_string_of_node_kind n.IL.n
end)
let pr2_ranges file rwms =
rwms
|> List.iter (fun rwm ->
let code_text = Range.content_at_range file rwm.RM.r in
let line_str =
let pm = rwm.RM.origin in
let loc1, _ = pm.Pattern_match.range_loc in
string_of_int loc1.Parse_info.line
in
Common.pr2 (code_text ^ " @l." ^ line_str))
let test_tainting lang file options config def =
Common.pr2 "\nDataflow";
Common.pr2 "--------";
let flow, mapping =
Match_tainting_mode.check_fundef lang options config None def
in
let taint_to_str taint =
let show_taint t =
match t.Taint.orig with
| Taint.Src src ->
let tok1, tok2 = (fst (Taint.pm_of_trace src.call_trace)).range_loc in
let r = Range.range_of_token_locations tok1 tok2 in
Range.content_at_range file r
| Taint.Arg (s, i) -> spf "arg %s %d" s i
in
taint |> Taint.Taint_set.elements |> Common.map show_taint
|> String.concat ", "
|> fun str -> "{ " ^ str ^ " }"
in
DataflowX.display_mapping flow mapping (Taint_lval_env.to_string taint_to_str)
let test_dfg_tainting rules_file file =
let lang = List.hd (Lang.langs_of_filename file) in
let rules =
try Parse_rule.parse rules_file with
| exn ->
failwith
(spf "fail to parse tainting rules %s (exn = %s)" rules_file
(Common.exn_to_s exn))
in
let ast =
try Parse_target.parse_and_resolve_name_warn_if_partial lang file with
| exn ->
failwith (spf "fail to parse %s (exn = %s)" file (Common.exn_to_s exn))
in
let rules =
rules
|> List.filter (fun r ->
match r.Rule.languages with
| Xlang.L (x, xs) -> List.mem lang (x :: xs)
| _ -> false)
in
let _search_rules, taint_rules, _extract_rules = Rule.partition_rules rules in
let rule = List.hd taint_rules in
pr2 "Tainting";
pr2 "========";
let handle_findings _ _ _ = () in
let xconf = Match_env.default_xconfig in
let xconf = Match_env.adjust_xconfig_with_rule_options xconf rule.options in
let config, debug_taint, _exps =
Match_tainting_mode.taint_config_of_rule xconf file (ast, []) rule
handle_findings
in
Common.pr2 "\nSources";
Common.pr2 "-------";
pr2_ranges file (debug_taint.sources |> Common.map fst);
Common.pr2 "\nSanitizers";
Common.pr2 "----------";
pr2_ranges file debug_taint.sanitizers;
Common.pr2 "\nSinks";
Common.pr2 "-----";
pr2_ranges file (debug_taint.sinks |> Common.map fst);
let v =
object
inherit [_] AST_generic.iter_no_id_info as super
method! visit_function_definition env def =
test_tainting lang file xconf.config config def;
(* go into nested functions *)
super#visit_function_definition env def
end
in
(* Check each function definition. *)
v#visit_program () ast
let actions () =
[
( "-dfg_tainting",
"<rules> <target>",
Arg_helpers.mk_action_2_arg test_dfg_tainting );
]
| null | https://raw.githubusercontent.com/returntocorp/semgrep/ab09346ea6471a5c7f4db0791657d35d6de61817/src/engine/Test_dataflow_tainting.ml | ocaml | go into nested functions
Check each function definition. | open Common
module G = AST_generic
module RM = Range_with_metavars
module DataflowX = Dataflow_core.Make (struct
type node = IL.node
type edge = IL.edge
type flow = (node, edge) CFG.t
let short_string_of_node n = Display_IL.short_string_of_node_kind n.IL.n
end)
let pr2_ranges file rwms =
rwms
|> List.iter (fun rwm ->
let code_text = Range.content_at_range file rwm.RM.r in
let line_str =
let pm = rwm.RM.origin in
let loc1, _ = pm.Pattern_match.range_loc in
string_of_int loc1.Parse_info.line
in
Common.pr2 (code_text ^ " @l." ^ line_str))
let test_tainting lang file options config def =
Common.pr2 "\nDataflow";
Common.pr2 "--------";
let flow, mapping =
Match_tainting_mode.check_fundef lang options config None def
in
let taint_to_str taint =
let show_taint t =
match t.Taint.orig with
| Taint.Src src ->
let tok1, tok2 = (fst (Taint.pm_of_trace src.call_trace)).range_loc in
let r = Range.range_of_token_locations tok1 tok2 in
Range.content_at_range file r
| Taint.Arg (s, i) -> spf "arg %s %d" s i
in
taint |> Taint.Taint_set.elements |> Common.map show_taint
|> String.concat ", "
|> fun str -> "{ " ^ str ^ " }"
in
DataflowX.display_mapping flow mapping (Taint_lval_env.to_string taint_to_str)
let test_dfg_tainting rules_file file =
let lang = List.hd (Lang.langs_of_filename file) in
let rules =
try Parse_rule.parse rules_file with
| exn ->
failwith
(spf "fail to parse tainting rules %s (exn = %s)" rules_file
(Common.exn_to_s exn))
in
let ast =
try Parse_target.parse_and_resolve_name_warn_if_partial lang file with
| exn ->
failwith (spf "fail to parse %s (exn = %s)" file (Common.exn_to_s exn))
in
let rules =
rules
|> List.filter (fun r ->
match r.Rule.languages with
| Xlang.L (x, xs) -> List.mem lang (x :: xs)
| _ -> false)
in
let _search_rules, taint_rules, _extract_rules = Rule.partition_rules rules in
let rule = List.hd taint_rules in
pr2 "Tainting";
pr2 "========";
let handle_findings _ _ _ = () in
let xconf = Match_env.default_xconfig in
let xconf = Match_env.adjust_xconfig_with_rule_options xconf rule.options in
let config, debug_taint, _exps =
Match_tainting_mode.taint_config_of_rule xconf file (ast, []) rule
handle_findings
in
Common.pr2 "\nSources";
Common.pr2 "-------";
pr2_ranges file (debug_taint.sources |> Common.map fst);
Common.pr2 "\nSanitizers";
Common.pr2 "----------";
pr2_ranges file debug_taint.sanitizers;
Common.pr2 "\nSinks";
Common.pr2 "-----";
pr2_ranges file (debug_taint.sinks |> Common.map fst);
let v =
object
inherit [_] AST_generic.iter_no_id_info as super
method! visit_function_definition env def =
test_tainting lang file xconf.config config def;
super#visit_function_definition env def
end
in
v#visit_program () ast
let actions () =
[
( "-dfg_tainting",
"<rules> <target>",
Arg_helpers.mk_action_2_arg test_dfg_tainting );
]
|
8aa0825b1e664aaecc6a7d42fb555c80776178c9beb1a6e78ec7a9a4c8538d9b | alexpeits/harg | Subcommands.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
module Options.Harg.Subcommands
( Subcommands (..),
)
where
import qualified Barbies as B
import Data.Functor.Compose (Compose (..))
import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
import qualified Options.Applicative as Optparse
import Options.Harg.Cmdline (mkOptparseParser)
import Options.Harg.Het.All (All)
import Options.Harg.Het.HList (AssocListF (..))
import Options.Harg.Het.Nat
import Options.Harg.Het.Proofs (Proof (..), hgcastWith, type (++))
import Options.Harg.Het.Variant (InjectPosF (..), VariantF)
import Options.Harg.Sources (accumSourceResults)
import Options.Harg.Sources.Types
import Options.Harg.Types
| This class can be used with an ' AssocList ' . It returns the appropriate
list of ' Optparse . CommandFields ' in order to create a subcommand parser .
-- Given the sources to use and the association list between the command string
-- and the command type, it returns the list of command field modifiers and a
-- list of errors.
--
-- The result can be used as follows:
--
-- @
-- ...
-- (errs, commands) = 'mapSubcommand' sources opts
-- parser = 'Optparse.subparser' ('mconcat' commands)
-- ...
-- @
--
-- In order to be able to create a subcommand parser for a heterogeneous list
-- of options (rather than a sum with different constructors), the return type
-- should also be heterogeneous. Here, we return a Variant, which is a more
-- generic version of 'Either'. In order to do that, 'mapSubcommand' traverses
-- the association list and creates an injection into the Variant, according to
the current position . So an ' AssocList ' like this :
--
-- @
opts : : AssocList ' [ " run " , " test " ] ' [ RunConfig , TestConfig ] Opt
-- opts = ...
-- @
--
Should return @VariantF ' [ RunConfig , TestConfig ] Identity@. In order to do
that , it will inject @RunConfig@ based on its position ( 0 ) using ,
and @TestConfig@ using @ThereF . HereF@ because its position is 1 .
class
Subcommands
(ts :: [Symbol])
(xs :: [(Type -> Type) -> Type])
where
mapSubcommand ::
( All (RunSource s) xs,
Applicative f
) =>
s ->
AssocListF ts xs (Compose Opt f) ->
([SourceRunError], [Optparse.Mod Optparse.CommandFields (VariantF xs f)])
instance ExplSubcommands Z ts xs '[] => Subcommands ts xs where
mapSubcommand = explMapSubcommand @Z @ts @xs @'[] SZ
-- | More general version of 'Subcommands'.
class
ExplSubcommands
(n :: Nat)
(ts :: [Symbol])
(xs :: [(Type -> Type) -> Type])
(acc :: [(Type -> Type) -> Type])
where
explMapSubcommand ::
( All (RunSource s) xs,
Applicative f
) =>
SNat n ->
s ->
AssocListF ts xs (Compose Opt f) ->
([SourceRunError], [Optparse.Mod Optparse.CommandFields (VariantF (acc ++ xs) f)])
instance ExplSubcommands n '[] '[] acc where
explMapSubcommand _ _ _ = ([], [])
-- ok wait
-- hear me out:
instance
( ExplSubcommands (S n) ts xs (as ++ '[x]),
-- get the correct injection into the variant by position
InjectPosF n x (as ++ (x ': xs)),
B.TraversableB x,
B.ApplicativeB x,
KnownSymbol t,
-- prove that xs ++ (y : ys) ~ (xs ++ [y]) ++ ys
Proof as x xs
) =>
ExplSubcommands n (t ': ts) (x ': xs) as
where
explMapSubcommand n srcs (ACons opt opts) =
(thisErr ++ restErr, sc : rest)
where
(thisErr, sc) =
subcommand
(restErr, rest) =
hgcastWith (proof @as @x @xs) $
explMapSubcommand
@(S n)
@ts
@xs
@(as ++ '[x])
(SS n)
srcs
opts
subcommand =
let (errs, src) =
accumSourceResults $ runSource srcs opt
parser =
mkOptparseParser src opt
tag =
symbolVal (Proxy :: Proxy t)
cmd =
Optparse.command tag $
injectPosF n
<$> Optparse.info (Optparse.helper <*> parser) mempty
in (errs, cmd)
| null | https://raw.githubusercontent.com/alexpeits/harg/a5a684ba974a788f97836888e8631199c550a73f/src/Options/Harg/Subcommands.hs | haskell | Given the sources to use and the association list between the command string
and the command type, it returns the list of command field modifiers and a
list of errors.
The result can be used as follows:
@
...
(errs, commands) = 'mapSubcommand' sources opts
parser = 'Optparse.subparser' ('mconcat' commands)
...
@
In order to be able to create a subcommand parser for a heterogeneous list
of options (rather than a sum with different constructors), the return type
should also be heterogeneous. Here, we return a Variant, which is a more
generic version of 'Either'. In order to do that, 'mapSubcommand' traverses
the association list and creates an injection into the Variant, according to
@
opts = ...
@
| More general version of 'Subcommands'.
ok wait
hear me out:
get the correct injection into the variant by position
prove that xs ++ (y : ys) ~ (xs ++ [y]) ++ ys | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE UndecidableInstances #
module Options.Harg.Subcommands
( Subcommands (..),
)
where
import qualified Barbies as B
import Data.Functor.Compose (Compose (..))
import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
import qualified Options.Applicative as Optparse
import Options.Harg.Cmdline (mkOptparseParser)
import Options.Harg.Het.All (All)
import Options.Harg.Het.HList (AssocListF (..))
import Options.Harg.Het.Nat
import Options.Harg.Het.Proofs (Proof (..), hgcastWith, type (++))
import Options.Harg.Het.Variant (InjectPosF (..), VariantF)
import Options.Harg.Sources (accumSourceResults)
import Options.Harg.Sources.Types
import Options.Harg.Types
| This class can be used with an ' AssocList ' . It returns the appropriate
list of ' Optparse . CommandFields ' in order to create a subcommand parser .
the current position . So an ' AssocList ' like this :
opts : : AssocList ' [ " run " , " test " ] ' [ RunConfig , TestConfig ] Opt
Should return @VariantF ' [ RunConfig , TestConfig ] Identity@. In order to do
that , it will inject @RunConfig@ based on its position ( 0 ) using ,
and @TestConfig@ using @ThereF . HereF@ because its position is 1 .
class
Subcommands
(ts :: [Symbol])
(xs :: [(Type -> Type) -> Type])
where
mapSubcommand ::
( All (RunSource s) xs,
Applicative f
) =>
s ->
AssocListF ts xs (Compose Opt f) ->
([SourceRunError], [Optparse.Mod Optparse.CommandFields (VariantF xs f)])
instance ExplSubcommands Z ts xs '[] => Subcommands ts xs where
mapSubcommand = explMapSubcommand @Z @ts @xs @'[] SZ
class
ExplSubcommands
(n :: Nat)
(ts :: [Symbol])
(xs :: [(Type -> Type) -> Type])
(acc :: [(Type -> Type) -> Type])
where
explMapSubcommand ::
( All (RunSource s) xs,
Applicative f
) =>
SNat n ->
s ->
AssocListF ts xs (Compose Opt f) ->
([SourceRunError], [Optparse.Mod Optparse.CommandFields (VariantF (acc ++ xs) f)])
instance ExplSubcommands n '[] '[] acc where
explMapSubcommand _ _ _ = ([], [])
instance
( ExplSubcommands (S n) ts xs (as ++ '[x]),
InjectPosF n x (as ++ (x ': xs)),
B.TraversableB x,
B.ApplicativeB x,
KnownSymbol t,
Proof as x xs
) =>
ExplSubcommands n (t ': ts) (x ': xs) as
where
explMapSubcommand n srcs (ACons opt opts) =
(thisErr ++ restErr, sc : rest)
where
(thisErr, sc) =
subcommand
(restErr, rest) =
hgcastWith (proof @as @x @xs) $
explMapSubcommand
@(S n)
@ts
@xs
@(as ++ '[x])
(SS n)
srcs
opts
subcommand =
let (errs, src) =
accumSourceResults $ runSource srcs opt
parser =
mkOptparseParser src opt
tag =
symbolVal (Proxy :: Proxy t)
cmd =
Optparse.command tag $
injectPosF n
<$> Optparse.info (Optparse.helper <*> parser) mempty
in (errs, cmd)
|
610140f0ad4315c4b69f7d854e06a75cca4e6d3b0a1019ee0434cca18437fcf3 | pixlsus/registry.gimp.org_static | resize-match-dpi_0.scm | ; Resize-match-dpi - Scales an image and its DPI
Copyright ( C ) 2010
; This software is released under the terms of the
GNU General Public License version 3.0 or later
(define (resize-match-dpi image drawable newwidth newheight)
(let* (
(oldwidth (car (gimp-image-width image)))
(oldheight (car (gimp-image-height image)))
(newdpi 0)
)
(if (= newheight 0)
(set! newheight (round (* (/ oldheight oldwidth) newwidth)))
()
)
(if (= newwidth 0)
(set! newwidth (round (* (/ oldwidth oldheight) newheight)))
()
)
(set! newdpi (/ (* newwidth (car (gimp-image-get-resolution image))) oldwidth))
(gimp-image-undo-group-start image)
(gimp-image-scale image newwidth newheight)
(gimp-image-set-resolution image newdpi newdpi)
(gimp-image-undo-group-end image)
))
(define (resize_match_dpi filename output newwidth newheight)
(let* ((image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
)
(resize-match-dpi image drawable newwidth newheight)
(gimp-file-save RUN-NONINTERACTIVE image drawable output output)
(gimp-image-delete image)
))
(define (resize_match_dpi_multi pattern outdir newwidth newheight)
(let* ((filelist (cadr (file-glob pattern 1))))
(while (not (null? filelist))
(let* ((filename (car filelist))
(image (car (gimp-file-load RUN-NONINTERACTIVE
filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
(outf (string-append outdir "/" filename)))
(resize-match-dpi image drawable newwidth newheight)
(gimp-file-save RUN-NONINTERACTIVE image drawable outf outf)
(gimp-image-delete image))
(set! filelist (cdr filelist)))))
(script-fu-register "resize-match-dpi"
"<Image>/Script-Fu/Resize Match DPI"
"Resize and match DPI"
"odie5533"
"odie5533"
"2010-05-16"
"RGB*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-VALUE "New width" "1280"
SF-VALUE "New height" "0"
)
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/resize-match-dpi_0.scm | scheme | Resize-match-dpi - Scales an image and its DPI
This software is released under the terms of the
| Copyright ( C ) 2010
GNU General Public License version 3.0 or later
(define (resize-match-dpi image drawable newwidth newheight)
(let* (
(oldwidth (car (gimp-image-width image)))
(oldheight (car (gimp-image-height image)))
(newdpi 0)
)
(if (= newheight 0)
(set! newheight (round (* (/ oldheight oldwidth) newwidth)))
()
)
(if (= newwidth 0)
(set! newwidth (round (* (/ oldwidth oldheight) newheight)))
()
)
(set! newdpi (/ (* newwidth (car (gimp-image-get-resolution image))) oldwidth))
(gimp-image-undo-group-start image)
(gimp-image-scale image newwidth newheight)
(gimp-image-set-resolution image newdpi newdpi)
(gimp-image-undo-group-end image)
))
(define (resize_match_dpi filename output newwidth newheight)
(let* ((image (car (gimp-file-load RUN-NONINTERACTIVE filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
)
(resize-match-dpi image drawable newwidth newheight)
(gimp-file-save RUN-NONINTERACTIVE image drawable output output)
(gimp-image-delete image)
))
(define (resize_match_dpi_multi pattern outdir newwidth newheight)
(let* ((filelist (cadr (file-glob pattern 1))))
(while (not (null? filelist))
(let* ((filename (car filelist))
(image (car (gimp-file-load RUN-NONINTERACTIVE
filename filename)))
(drawable (car (gimp-image-get-active-layer image)))
(outf (string-append outdir "/" filename)))
(resize-match-dpi image drawable newwidth newheight)
(gimp-file-save RUN-NONINTERACTIVE image drawable outf outf)
(gimp-image-delete image))
(set! filelist (cdr filelist)))))
(script-fu-register "resize-match-dpi"
"<Image>/Script-Fu/Resize Match DPI"
"Resize and match DPI"
"odie5533"
"odie5533"
"2010-05-16"
"RGB*"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-VALUE "New width" "1280"
SF-VALUE "New height" "0"
)
|
bd9d46453d29f0056e59beba2d30d51be775ec0ade00d2e7ed996cd4e090fbef | gsakkas/rite | 2492.ml |
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr* expr
| Times of expr* expr
| Thresh of expr* expr* expr* expr
| Thresh2 of expr* expr
| Thresh3 of expr* expr;;
let pi = 4.0 *. (atan 1.0);;
let rec eval (e,x,y) =
let rec evalhelper e x y =
match e with
| VarX -> x
| VarY -> y
| Sine p1 -> sin (pi *. (evalhelper p1 x y))
| Cosine p1 -> cos (pi *. (evalhelper p1 x y))
| Average (p1,p2) -> ((evalhelper p1 x y) +. (evalhelper p2 x y)) /. 2.0
| Times (p1,p2) -> (evalhelper p1 x y) *. (evalhelper p2 x y)
| Thresh (p1,p2,p3,p4) ->
if (evalhelper p1 x y) < (evalhelper p2 x y)
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 (p1,p2) ->
if (evalhelper p1 x y) < (evalhelper p2 x y) then 1 else 0
| Thresh3 (p1,p2) ->
if (evalhelper p1 x y) > (evalhelper p2 x y) then 0 else (-1) in
evalhelper e x y;;
fix
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr * expr
| Times of expr * expr
| Thresh of expr * expr * expr * expr
| Thresh2 of expr * expr
| Thresh3 of expr * expr ; ;
let pi = 4.0 * . ( atan 1.0 ) ; ;
let rec eval ( e , x , y ) =
let e x y =
match e with
| VarX - > x
| VarY - > y
| Sine p1 - > sin ( pi * . ( evalhelper ) )
| Cosine p1 - > cos ( pi * . ( evalhelper ) )
| Average ( p1,p2 ) - > ( ( evalhelper y ) + . ( evalhelper p2 x y ) ) /. 2.0
| Times ( p1,p2 ) - > ( evalhelper y ) * . ( evalhelper p2 x y )
| Thresh ( p1,p2,p3,p4 ) - >
if ( evalhelper y ) < ( evalhelper p2 x y )
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 ( p1,p2 ) - >
if ( evalhelper y ) < ( evalhelper p2 x y ) then 1.0 else 0.0
| Thresh3 ( p1,p2 ) - >
if ( evalhelper y ) > ( evalhelper p2 x y ) then 0.0 else ( -1.0 ) in
evalhelper e x y ; ;
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr* expr
| Times of expr* expr
| Thresh of expr* expr* expr* expr
| Thresh2 of expr* expr
| Thresh3 of expr* expr;;
let pi = 4.0 *. (atan 1.0);;
let rec eval (e,x,y) =
let rec evalhelper e x y =
match e with
| VarX -> x
| VarY -> y
| Sine p1 -> sin (pi *. (evalhelper p1 x y))
| Cosine p1 -> cos (pi *. (evalhelper p1 x y))
| Average (p1,p2) -> ((evalhelper p1 x y) +. (evalhelper p2 x y)) /. 2.0
| Times (p1,p2) -> (evalhelper p1 x y) *. (evalhelper p2 x y)
| Thresh (p1,p2,p3,p4) ->
if (evalhelper p1 x y) < (evalhelper p2 x y)
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 (p1,p2) ->
if (evalhelper p1 x y) < (evalhelper p2 x y) then 1.0 else 0.0
| Thresh3 (p1,p2) ->
if (evalhelper p1 x y) > (evalhelper p2 x y) then 0.0 else (-1.0) in
evalhelper e x y;;
*)
changed spans
( 29,59)-(29,60 )
1.0
LitG
( 29,66)-(29,67 )
0.0
LitG
( 31,59)-(31,60 )
0.0
LitG
( 31,66)-(31,70 )
( - 1.0 )
UopG LitG
(29,59)-(29,60)
1.0
LitG
(29,66)-(29,67)
0.0
LitG
(31,59)-(31,60)
0.0
LitG
(31,66)-(31,70)
(- 1.0)
UopG LitG
*)
type error slice
( 17,5)-(31,70 )
( 20,18)-(20,21 )
( 20,18)-(20,49 )
( 29,9)-(29,67 )
( 29,66)-(29,67 )
( 31,9)-(31,70 )
( 31,66)-(31,70 )
(17,5)-(31,70)
(20,18)-(20,21)
(20,18)-(20,49)
(29,9)-(29,67)
(29,66)-(29,67)
(31,9)-(31,70)
(31,66)-(31,70)
*)
| null | https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/data/sp14/2492.ml | ocaml |
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr* expr
| Times of expr* expr
| Thresh of expr* expr* expr* expr
| Thresh2 of expr* expr
| Thresh3 of expr* expr;;
let pi = 4.0 *. (atan 1.0);;
let rec eval (e,x,y) =
let rec evalhelper e x y =
match e with
| VarX -> x
| VarY -> y
| Sine p1 -> sin (pi *. (evalhelper p1 x y))
| Cosine p1 -> cos (pi *. (evalhelper p1 x y))
| Average (p1,p2) -> ((evalhelper p1 x y) +. (evalhelper p2 x y)) /. 2.0
| Times (p1,p2) -> (evalhelper p1 x y) *. (evalhelper p2 x y)
| Thresh (p1,p2,p3,p4) ->
if (evalhelper p1 x y) < (evalhelper p2 x y)
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 (p1,p2) ->
if (evalhelper p1 x y) < (evalhelper p2 x y) then 1 else 0
| Thresh3 (p1,p2) ->
if (evalhelper p1 x y) > (evalhelper p2 x y) then 0 else (-1) in
evalhelper e x y;;
fix
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr * expr
| Times of expr * expr
| Thresh of expr * expr * expr * expr
| Thresh2 of expr * expr
| Thresh3 of expr * expr ; ;
let pi = 4.0 * . ( atan 1.0 ) ; ;
let rec eval ( e , x , y ) =
let e x y =
match e with
| VarX - > x
| VarY - > y
| Sine p1 - > sin ( pi * . ( evalhelper ) )
| Cosine p1 - > cos ( pi * . ( evalhelper ) )
| Average ( p1,p2 ) - > ( ( evalhelper y ) + . ( evalhelper p2 x y ) ) /. 2.0
| Times ( p1,p2 ) - > ( evalhelper y ) * . ( evalhelper p2 x y )
| Thresh ( p1,p2,p3,p4 ) - >
if ( evalhelper y ) < ( evalhelper p2 x y )
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 ( p1,p2 ) - >
if ( evalhelper y ) < ( evalhelper p2 x y ) then 1.0 else 0.0
| Thresh3 ( p1,p2 ) - >
if ( evalhelper y ) > ( evalhelper p2 x y ) then 0.0 else ( -1.0 ) in
evalhelper e x y ; ;
type expr =
| VarX
| VarY
| Sine of expr
| Cosine of expr
| Average of expr* expr
| Times of expr* expr
| Thresh of expr* expr* expr* expr
| Thresh2 of expr* expr
| Thresh3 of expr* expr;;
let pi = 4.0 *. (atan 1.0);;
let rec eval (e,x,y) =
let rec evalhelper e x y =
match e with
| VarX -> x
| VarY -> y
| Sine p1 -> sin (pi *. (evalhelper p1 x y))
| Cosine p1 -> cos (pi *. (evalhelper p1 x y))
| Average (p1,p2) -> ((evalhelper p1 x y) +. (evalhelper p2 x y)) /. 2.0
| Times (p1,p2) -> (evalhelper p1 x y) *. (evalhelper p2 x y)
| Thresh (p1,p2,p3,p4) ->
if (evalhelper p1 x y) < (evalhelper p2 x y)
then evalhelper p3 x y
else evalhelper p4 x y
| Thresh2 (p1,p2) ->
if (evalhelper p1 x y) < (evalhelper p2 x y) then 1.0 else 0.0
| Thresh3 (p1,p2) ->
if (evalhelper p1 x y) > (evalhelper p2 x y) then 0.0 else (-1.0) in
evalhelper e x y;;
*)
changed spans
( 29,59)-(29,60 )
1.0
LitG
( 29,66)-(29,67 )
0.0
LitG
( 31,59)-(31,60 )
0.0
LitG
( 31,66)-(31,70 )
( - 1.0 )
UopG LitG
(29,59)-(29,60)
1.0
LitG
(29,66)-(29,67)
0.0
LitG
(31,59)-(31,60)
0.0
LitG
(31,66)-(31,70)
(- 1.0)
UopG LitG
*)
type error slice
( 17,5)-(31,70 )
( 20,18)-(20,21 )
( 20,18)-(20,49 )
( 29,9)-(29,67 )
( 29,66)-(29,67 )
( 31,9)-(31,70 )
( 31,66)-(31,70 )
(17,5)-(31,70)
(20,18)-(20,21)
(20,18)-(20,49)
(29,9)-(29,67)
(29,66)-(29,67)
(31,9)-(31,70)
(31,66)-(31,70)
*)
| |
a8c7271e8418eed61d79b7088b79b9a5720bffbb9c2cba3822d71a72a9ee42a4 | kazzmir/master-of-magic | option.ml |
* Option - functions for the option type
* Copyright ( C ) 2003
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Option - functions for the option type
* Copyright (C) 2003 Nicolas Cannasse
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
exception No_value
let may f = function
| None -> ()
| Some v -> f v
let map f = function
| None -> None
| Some v -> Some (f v)
let default v = function
| None -> v
| Some v -> v
let is_some = function
| None -> false
| _ -> true
let is_none = function
| None -> true
| _ -> false
let get = function
| None -> raise No_value
| Some v -> v
let map_default f v = function
| None -> v
| Some v2 -> f v2
| null | https://raw.githubusercontent.com/kazzmir/master-of-magic/830bfd1c549a5ac7370fa6a72bb06be5d3435fa0/lib/extlib-1.5/option.ml | ocaml |
* Option - functions for the option type
* Copyright ( C ) 2003
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Option - functions for the option type
* Copyright (C) 2003 Nicolas Cannasse
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
exception No_value
let may f = function
| None -> ()
| Some v -> f v
let map f = function
| None -> None
| Some v -> Some (f v)
let default v = function
| None -> v
| Some v -> v
let is_some = function
| None -> false
| _ -> true
let is_none = function
| None -> true
| _ -> false
let get = function
| None -> raise No_value
| Some v -> v
let map_default f v = function
| None -> v
| Some v2 -> f v2
| |
6561b7910364f99a7651da68d24650bfa8f3c82f13c2e9de812daf57da5d492e | bcc32/projecteuler-ocaml | euler_solutions.mli | open! Core
open! Import
val all : (string, (module Solution.S)) List.Assoc.t
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/sol/euler_solutions.mli | ocaml | open! Core
open! Import
val all : (string, (module Solution.S)) List.Assoc.t
| |
389b5738311590a7e4dc4147fdd91a31ea2486395d8b4566396a2ff7122fc34b | polysemy-research/polysemy | PluginSpec.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
module PluginSpec where
import Data.Functor.Identity
import GHC.Exts
import Polysemy
import Polysemy.Error
import Polysemy.State
import Polysemy.Output
import Test.Hspec
import Unsafe.Coerce
idState :: Member (State s) r => Sem r ()
idState = do
s <- get
put s
intState :: Member (State Int) r => Sem r ()
intState = put 10
numState :: Num a => Member (State a) r => Sem r ()
numState = put 10
strState :: Member (State String) r => Sem r ()
strState = put "hello"
oStrState :: IsString a => Member (State a) r => Sem r ()
oStrState = put "hello"
err :: Member (Error e) r => Sem r Bool
err =
catch
(throw undefined)
(\_ -> pure True)
errState :: Num s => Members '[Error e, State s] r => Sem r Bool
errState = do
numState
err
lifted :: Monad m => Member (Embed m) r => Sem r ()
lifted = embed $ pure ()
newtype MyString = MyString String
deriving (IsString, Eq, Show)
data Janky = forall s. Janky (forall i. Sem '[State s] ())
jankyState :: Janky
jankyState = Janky $ put True
unsafeUnjank :: Janky -> Sem '[State Bool] ()
unsafeUnjank (Janky sem) = unsafeCoerce sem
spec :: Spec
spec = do
describe "State effect" $ do
describe "get/put" $ do
it "should work in simple cases" $ do
flipShouldBe (True, ()) . run $ runState True idState
it "should, when polymorphic, eliminate the first matching effect" $ do
flipShouldBe (False, (True, ())) . run $ runState False $ runState True idState
it "should, when polymorphic, not eliminate unmatching effects" $ do
flipShouldBe (True, Right @Int ()) . run $ runState True $ runError idState
describe "numbers" $ do
it "should interpret against concrete Int" $ do
flipShouldBe (10, ()) . run $ runState 0 intState
describe "polymorphic Num constraint" $ do
it "should interpret against Int" $ do
flipShouldBe (10 :: Int, ()) . run $ runState 0 numState
it "should interpret against Float" $ do
flipShouldBe (10 :: Float, ()) . run $ runState 0 numState
it "should interpret against Double" $ do
flipShouldBe (10 :: Double, ()) . run $ runState 0 numState
it "should interpret against Integer" $ do
flipShouldBe (10 :: Integer, ()) . run $ runState 0 numState
describe "strings" $ do
it "concrete interpret against concrete String" $ do
flipShouldBe ("hello", ()) . run $ runState "nothing" strState
describe "polymorphic IsString constraint" $ do
it "should interpret against String" $ do
flipShouldBe ("hello" :: String, ()) . run $ runState "nothing" oStrState
it "should interpret against MyString" $ do
flipShouldBe ("hello" :: MyString, ()) . run $ runState "nothing" oStrState
describe "existential state" $ do
it "JankyState should compile" $ do
flipShouldBe (True, ()) . run $ runState False $ unsafeUnjank jankyState
describe "Error effect" $ do
it "should interpret against Int" $ do
flipShouldBe (Right @Int True) . run $ runError err
it "should interpret against Bool" $ do
flipShouldBe (Right @Bool True) . run $ runError err
describe "State/Error effect" $ do
it "should interpret against Int/String" $ do
flipShouldBe (10 :: Int, Right @String True) . run $ runState 0 $ runError errState
it "should interpret against Float/Bool" $ do
flipShouldBe (10 :: Float, Right @Bool True) . run $ runState 0 $ runError errState
describe "Error/State effect" $ do
it "should interpret against String/Int" $ do
flipShouldBe (Right @String (10 :: Int, True)) . run $ runError $ runState 0 errState
it "should interpret against Bool/Float" $ do
flipShouldBe (Right @Bool (10 :: Float, True)) . run $ runError $ runState 0 errState
describe "Output effect" $ do
it "should unify recursively with tyvars" $ do
flipShouldBe 11 . sum . fst . run . runOutputMonoid id $ do
output [1]
output $ replicate 2 5
describe "Embed effect" $ do
it "should interpret against IO" $ do
res <- runM lifted
res `shouldBe` ()
it "should interpret against Identity" $ do
let res = runM lifted
res `shouldBe` Identity ()
flipShouldBe :: (Show a, Eq a) => a -> a -> Expectation
flipShouldBe = flip shouldBe
| null | https://raw.githubusercontent.com/polysemy-research/polysemy/43a67061fb2a6cd2f545c5bd5e8320f2a228fb6b/polysemy-plugin/test/PluginSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE GeneralizedNewtypeDeriving #
module PluginSpec where
import Data.Functor.Identity
import GHC.Exts
import Polysemy
import Polysemy.Error
import Polysemy.State
import Polysemy.Output
import Test.Hspec
import Unsafe.Coerce
idState :: Member (State s) r => Sem r ()
idState = do
s <- get
put s
intState :: Member (State Int) r => Sem r ()
intState = put 10
numState :: Num a => Member (State a) r => Sem r ()
numState = put 10
strState :: Member (State String) r => Sem r ()
strState = put "hello"
oStrState :: IsString a => Member (State a) r => Sem r ()
oStrState = put "hello"
err :: Member (Error e) r => Sem r Bool
err =
catch
(throw undefined)
(\_ -> pure True)
errState :: Num s => Members '[Error e, State s] r => Sem r Bool
errState = do
numState
err
lifted :: Monad m => Member (Embed m) r => Sem r ()
lifted = embed $ pure ()
newtype MyString = MyString String
deriving (IsString, Eq, Show)
data Janky = forall s. Janky (forall i. Sem '[State s] ())
jankyState :: Janky
jankyState = Janky $ put True
unsafeUnjank :: Janky -> Sem '[State Bool] ()
unsafeUnjank (Janky sem) = unsafeCoerce sem
spec :: Spec
spec = do
describe "State effect" $ do
describe "get/put" $ do
it "should work in simple cases" $ do
flipShouldBe (True, ()) . run $ runState True idState
it "should, when polymorphic, eliminate the first matching effect" $ do
flipShouldBe (False, (True, ())) . run $ runState False $ runState True idState
it "should, when polymorphic, not eliminate unmatching effects" $ do
flipShouldBe (True, Right @Int ()) . run $ runState True $ runError idState
describe "numbers" $ do
it "should interpret against concrete Int" $ do
flipShouldBe (10, ()) . run $ runState 0 intState
describe "polymorphic Num constraint" $ do
it "should interpret against Int" $ do
flipShouldBe (10 :: Int, ()) . run $ runState 0 numState
it "should interpret against Float" $ do
flipShouldBe (10 :: Float, ()) . run $ runState 0 numState
it "should interpret against Double" $ do
flipShouldBe (10 :: Double, ()) . run $ runState 0 numState
it "should interpret against Integer" $ do
flipShouldBe (10 :: Integer, ()) . run $ runState 0 numState
describe "strings" $ do
it "concrete interpret against concrete String" $ do
flipShouldBe ("hello", ()) . run $ runState "nothing" strState
describe "polymorphic IsString constraint" $ do
it "should interpret against String" $ do
flipShouldBe ("hello" :: String, ()) . run $ runState "nothing" oStrState
it "should interpret against MyString" $ do
flipShouldBe ("hello" :: MyString, ()) . run $ runState "nothing" oStrState
describe "existential state" $ do
it "JankyState should compile" $ do
flipShouldBe (True, ()) . run $ runState False $ unsafeUnjank jankyState
describe "Error effect" $ do
it "should interpret against Int" $ do
flipShouldBe (Right @Int True) . run $ runError err
it "should interpret against Bool" $ do
flipShouldBe (Right @Bool True) . run $ runError err
describe "State/Error effect" $ do
it "should interpret against Int/String" $ do
flipShouldBe (10 :: Int, Right @String True) . run $ runState 0 $ runError errState
it "should interpret against Float/Bool" $ do
flipShouldBe (10 :: Float, Right @Bool True) . run $ runState 0 $ runError errState
describe "Error/State effect" $ do
it "should interpret against String/Int" $ do
flipShouldBe (Right @String (10 :: Int, True)) . run $ runError $ runState 0 errState
it "should interpret against Bool/Float" $ do
flipShouldBe (Right @Bool (10 :: Float, True)) . run $ runError $ runState 0 errState
describe "Output effect" $ do
it "should unify recursively with tyvars" $ do
flipShouldBe 11 . sum . fst . run . runOutputMonoid id $ do
output [1]
output $ replicate 2 5
describe "Embed effect" $ do
it "should interpret against IO" $ do
res <- runM lifted
res `shouldBe` ()
it "should interpret against Identity" $ do
let res = runM lifted
res `shouldBe` Identity ()
flipShouldBe :: (Show a, Eq a) => a -> a -> Expectation
flipShouldBe = flip shouldBe
|
37ef8806b619050feb245696ee62899519cb3625be29b2e454895c1893f14dc1 | dyzsr/ocaml-selectml | pr6651_ok.ml | (* TEST
flags = " -w -a "
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
*)
module type S = sig
module type T
module X : T
end
module F (X : S) = X.X
module M = struct
module type T = sig type t end
module X = struct type t = int end
end
type t = F(M).t
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-modules-bugs/pr6651_ok.ml | ocaml | TEST
flags = " -w -a "
* setup-ocamlc.byte-build-env
** ocamlc.byte
*** check-ocamlc.byte-output
|
module type S = sig
module type T
module X : T
end
module F (X : S) = X.X
module M = struct
module type T = sig type t end
module X = struct type t = int end
end
type t = F(M).t
|
ec31dd9a8130a35736b189d6db907ac7d911b395298edda60b401cbf468aef89 | patricoferris/ocaml-multicore-monorepo | log.ml | This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
(* Among other things, this module wraps the Logs library so as to prepend
request ids to log messages.
However, instead of prepending the id at the front end of Logs, in the
wrappers, we prepend the id at the back end instead - in the reporter. The
rationale for this is that we want to (try to) prepend the id even to strings
that don't come from Dream or the user's Dream app, and thus *definitely* do
not call this module's wrappers.
The wrappers try to get the request id from their argument ~request, and pass
it down to the reporter in a Logs tag.
The reporter reads the tag and uses that request id if it is available. If
the request id is not available, it is because the log message comes from a
point in the Dream app where an id has not been assigned to the request, or
because the log message comes from another dependency (or a sloppy call
site!). In that case, the reporter tries to retrieve the id from the
promise-chain-local storage of Lwt.
This is sufficient for attaching a request id to most log messages, in
practice. *)
module Message = Dream_pure.Message
module Method = Dream_pure.Method
module Status = Dream_pure.Status
type log_level = [
| `Error
| `Warning
| `Info
| `Debug
]
(* The logging middleware assigns request ids to requests, and tries to show
them in the logs. The scheme works as follows:
- Request ids are strings stored in request-local variables.
- The automatically assigned request ids are taken from a simple global
sequence.
- The user can override the automatic request id by assigning a request id
in a middleware that runs before the logger. User-provided request ids can
be per-thread, can come from a proxy header, etc.
- The logger makes a best effort to forward the request id to all logging
statements that are being formatted. If the ~request argument is provided
during a logging call, that request's id is shown. To handle all other
cases, the logger puts the request's id into an Lwt sequence-associated
storage key, and the log message formatter tries to get it from there. *)
(* TODO Necessary helpers for the user setting the request id are not yet
exposed in the API, pending some other refactoring (request mutability). *)
let request_id_label = "dream.request_id"
Logs library tag uesd to pass an i d from a request provided through
~request .
~request. *)
let logs_lib_tag : string Logs.Tag.def =
Logs.Tag.def
request_id_label
Format.pp_print_string
(* Lwt sequence-associated storage key used to pass request ids for use when
~request is not provided. *)
let id_lwt_key : string Lwt.key =
Lwt.new_key ()
(* The actual request id "field" associated with each request by the logger. If
this field is missing, the logger assigns the request a fresh id. *)
let id_field =
Message.new_field
~name:request_id_label
~show_value:(fun id -> id)
()
(* Makes a best-effort attempt to retrieve the request id. *)
let get_request_id ?request () =
let request_id =
match request with
| None -> None
| Some request -> Message.field request id_field
in
match request_id with
| Some _ -> request_id
| None -> Lwt.get id_lwt_key
(* The current state of the request id sequence. *)
let last_id =
ref 0
TODO Nice logging for multiline strings ?
The " back end . " I inlined several examples from the Logs , Logs_lwt , and Fmt
docs into each other , and modified the result , to arrive at this function .
See those docs for the meanings of the various helpers and values .
The reporter needs to be suspended in a function because Dream sets up the
logger lazily ; it does n't query the output streams for whether they are TTYs
until needed . Setting up the reporter before TTY checking will cause it to
not output color .
docs into each other, and modified the result, to arrive at this function.
See those docs for the meanings of the various helpers and values.
The reporter needs to be suspended in a function because Dream sets up the
logger lazily; it doesn't query the output streams for whether they are TTYs
until needed. Setting up the reporter before TTY checking will cause it to
not output color. *)
let reporter ~now () =
(* Format into an internal buffer. *)
let buffer = Buffer.create 512 in
let formatter = Fmt.with_buffer ~like:Fmt.stderr buffer in
let flush () =
let message = Buffer.contents buffer in
Buffer.reset buffer;
message
in
(* Gets called by Logs for each log call that passes its level threshold.
~over is to be called when the I/O underlying the log operation is fully
complete. In practice, since most call sites are not using Lwt, they will
continue executing anyway. This means that the message must be formatted
and the buffer flushed before doing anything asynchronous, so that
subsequent logging operations don't get into the same generation of the
buffer.
The user's_callback argument is not exactly the user's callback - it's the
callback that got wrapped in function source (the "front end") below. That
wrapper is the actual user's callback, and it calls user's_callback. *)
let report src level ~over k user's_callback =
let level_style, level =
match level with
| Logs.App -> `White, " "
| Logs.Error -> `Red, "ERROR"
| Logs.Warning -> `Yellow, " WARN"
| Logs.Info -> `Green, " INFO"
| Logs.Debug -> `Blue, "DEBUG"
in
let write _ =
(* Get the formatted message out of the buffer right away, because we are
doing Lwt operations next, and the caller might not wait. *)
let message = flush () in
(* Write the message. *)
prerr_string message;
Stdlib.flush stderr;
over ();
k ()
in
(* Call the user's callback to get the actual message and trigger
formatting, and, eventually, writing. The wrappers don't use the ?header
argument, so we ignore it. *)
user's_callback @@ fun ?header ?tags format_and_arguments ->
ignore header;
Format the current local time . For the millisecond fraction , be careful
of rounding 999.5 + to 1000 on output .
of rounding 999.5+ to 1000 on output. *)
let time =
let unix_time = now () in
let time = Option.get (Ptime.of_float_s unix_time) in
let fraction =
fst (modf unix_time) *. 1000. in
let clamped_fraction =
if fraction > 999. then 999.
else fraction
in
let ((y, m, d), ((hh, mm, ss), _tz_offset_s)) =
Ptime.to_date_time time in
Printf.sprintf "%02i.%02i.%02i %02i:%02i:%02i.%03.0f"
d m (y mod 100)
hh mm ss clamped_fraction
in
(* Format the source name column. It is the right-aligned log source name,
clipped to the column width. If the source is the default application
source, leave the column empty. *)
let source =
let width = 15 in
if Logs.Src.name src = Logs.Src.name Logs.default then
String.make width ' '
else
let name = Logs.Src.name src in
if String.length name > width then
String.sub name (String.length name - width) width
else
(String.make (width - String.length name) ' ') ^ name
in
let source_prefix, source =
try
let dot_index = String.rindex source '.' + 1 in
String.sub source 0 dot_index,
String.sub source dot_index (String.length source - dot_index)
with Not_found ->
"", source
in
(* Check if a request id is available in the tags passed from the front
end. If not, try to get it from the promise-chain-local storage. If
we end up with a request id, format it. *)
let request_id_from_tags =
match tags with
| None -> None
| Some tags ->
Logs.Tag.find logs_lib_tag tags
in
let request_id =
match request_id_from_tags with
| Some _ -> request_id_from_tags
| None -> get_request_id ()
in
let request_id, request_style =
match request_id with
| Some "" | None -> "", `White
| Some request_id ->
(* The last byte of the request id is basically always going to be a
digit, growing incrementally, so we can use the parity of its
ASCII code to stripe the requests in the log. *)
let last_byte = request_id.[String.length request_id - 1] in
let color =
if (Char.code last_byte) land 1 = 0 then
`Cyan
else
`Magenta
in
" REQ " ^ request_id, color
in
(* The formatting proper. *)
Format.kfprintf write formatter
("%a %a%s %a%a @[" ^^ format_and_arguments ^^ "@]@.")
Fmt.(styled `Faint string) time
Fmt.(styled `White string) source_prefix source
Fmt.(styled level_style string) level
Fmt.(styled request_style (styled `Italic string)) request_id
in
{Logs.report}
Lazy initialization upon first use or call to initialize .
let enable =
ref true
let level =
ref Logs.Info
let custom_log_levels : (string * Logs.level) list ref =
ref []
let sources : (string * Logs.src) list ref =
ref []
let set_printexc =
ref true
let set_async_exception_hook =
ref true
let _initialized = ref None
let to_logs_level l =
match l with
| `Error -> Logs.Error
| `Warning -> Logs.Warning
| `Info -> Logs.Info
| `Debug -> Logs.Debug
exception Logs_are_not_initialized
let setup_logs =
"\nTo initialize logs with a default reporter, and set up Dream, \
do the following:\
\n If you are using MirageOS, use the Dream device in config.ml
\n If you are using Lwt/Unix, execute `Dream.log_initialize ()`
\n"
let () = Printexc.register_printer @@ function
| Logs_are_not_initialized ->
Some ("The default logger is not yet initialized. " ^ setup_logs)
| _ -> None
let initialized () : [ `Initialized ] =
match !_initialized with
| None -> raise Logs_are_not_initialized
| Some v -> Lazy.force v
(* The "front end." *)
type ('a, 'b) conditional_log =
((?request:Message.request ->
('a, Stdlib.Format.formatter, unit, 'b) Stdlib.format4 -> 'a) -> 'b) ->
unit
type sub_log = {
error : 'a. ('a, unit) conditional_log;
warning : 'a. ('a, unit) conditional_log;
info : 'a. ('a, unit) conditional_log;
debug : 'a. ('a, unit) conditional_log;
}
let sub_log ?level:level_ name =
(* This creates a wrapper, as described above. The wrapper forwards to a
logger of the Logs library, but instead of passing the formatter m to the
user's callback, it passes a formatter m', which is like m, but lacks a
?tags argument. It has a ?request argument instead. If ~request is given,
m' immediately tries to retrieve the request id, put it into a Logs tag,
and call Logs' m with the user's formatting arguments and the tag. *)
let forward ~(destination_log : _ Logs.log) user's_k =
let `Initialized = initialized () in
destination_log (fun log ->
user's_k (fun ?request format_and_arguments ->
let tags =
match request with
| None -> Logs.Tag.empty
| Some request ->
match get_request_id ~request () with
| None -> Logs.Tag.empty
| Some request_id ->
Logs.Tag.add logs_lib_tag request_id Logs.Tag.empty
in
log ~tags format_and_arguments))
in
let level =
List.find Option.is_some [
Option.map to_logs_level level_;
List.assoc_opt name !custom_log_levels;
Some !level
] in
(* Create the actual Logs source, and then wrap all the interesting
functions. *)
let src = Logs.Src.create name in
let (module Log) = Logs.src_log src in
Logs.Src.set_level src level;
custom_log_levels :=
(name, Option.get level)::(List.remove_assoc name !custom_log_levels);
sources := (name, src) :: (List.remove_assoc name !sources);
{
error = (fun k -> forward ~destination_log:Log.err k);
warning = (fun k -> forward ~destination_log:Log.warn k);
info = (fun k -> forward ~destination_log:Log.info k);
debug = (fun k -> forward ~destination_log:Log.debug k);
}
let convenience_log format_and_arguments =
Fmt.kstr
(fun message ->
let `Initialized = initialized () in
Logs.app (fun log -> log "%s" message))
format_and_arguments
(* Logs.app (fun log -> log format_and_arguments) *)
let report = Logs.((reporter ( ) ) .report ) in
report Logs.default Logs . App ~over : ignore ignore format_and_arguments
report Logs.default Logs.App ~over:ignore ignore format_and_arguments *)
(* A helper used in several places. *)
let iter_backtrace f backtrace =
backtrace
|> String.split_on_char '\n'
|> List.filter (fun line -> line <> "")
|> List.iter f
Use the above function to create a log source for Log 's own middleware , the
same way any other middleware would .
same way any other middleware would. *)
let log =
sub_log "dream.log"
let set_up_exception_hook () =
if !set_async_exception_hook then begin
set_async_exception_hook := false;
Lwt.async_exception_hook := fun exn ->
let backtrace = Printexc.get_backtrace () in
log.error (fun log -> log "Async exception: %s" (Printexc.to_string exn));
backtrace
|> iter_backtrace (fun line -> log.error (fun log -> log "%s" line))
end
let initialize_log
?(backtraces = true)
?(async_exception_hook = true)
?level:level_
?enable:(enable_ = true)
() =
if backtraces then
Printexc.record_backtrace true;
set_printexc := false;
if async_exception_hook then
set_up_exception_hook ();
set_async_exception_hook := false;
let level_ =
Option.map to_logs_level level_
|> Option.value ~default:Logs.Info in
enable := enable_;
level := level_;
let `Initialized = initialized () in
()
let set_log_level name level =
(* If logging hasn't been initialized, trigger this so that
configuration of log levels can proceed. *)
let `Initialized = initialized () in
let level = to_logs_level level in
custom_log_levels :=
(name, level)::(List.remove_assoc name !custom_log_levels);
let src = List.assoc_opt name !sources in
Option.iter (fun s -> Logs.Src.set_level s (Some level)) src
module Make (Pclock : Mirage_clock.PCLOCK) =
struct
let now () =
Ptime.to_float_s (Ptime.v (Pclock.now_d_ps ()))
let initializer_ ~setup_outputs = lazy begin
if !enable then begin
setup_outputs () ;
Logs.set_level ~all:true (Some !level);
Logs.set_reporter (reporter ~now ())
end ;
`Initialized
end
let set = ref false
let initialize ~setup_outputs =
if !set then Logs.debug (fun log -> log
"Dream__log.initialize has already been called, ignoring this call.")
else begin
(try
let `Initialized = initialized () in
Format.eprintf
"Dream__log.initialized has already been set, check that this call \
is intentional";
with
Logs_are_not_initialized -> ());
set := true;
_initialized := Some (initializer_ ~setup_outputs)
end
(* The request logging middleware. *)
let logger next_handler request =
let start = now () in
(* Turn on backtrace recording. *)
if !set_printexc then begin
Printexc.record_backtrace true;
set_printexc := false
end;
(* Get the requwst's id or assign a new one. *)
let id =
match Message.field request id_field with
| Some id -> id
| None ->
last_id := !last_id + 1;
let id = string_of_int !last_id in
Message.set_field request id_field id;
id
in
(* Identify the request in the log. *)
let user_agent =
Message.headers request "User-Agent"
|> String.concat " "
in
log.info (fun log ->
log ~request "%s %s %s %s"
(Method.method_to_string (Message.method_ request))
(Message.target request)
(Helpers.client request)
user_agent);
(* Call the rest of the app. *)
match Lwt.with_value id_lwt_key (Some id) (fun () -> next_handler request) with
| response ->
(* Log the elapsed time. If the response is a redirection, log the
target. *)
let location =
if Status.is_redirection (Message.status response) then
match Message.header response "Location" with
| Some location -> " " ^ location
| None -> ""
else ""
in
let status = Message.status response in
let report :
(?request:Message.request ->
('a, Format.formatter, unit, 'b) format4 -> 'a) -> 'b =
fun log ->
let elapsed = now () -. start in
log ~request "%i%s in %.0f μs"
(Status.status_to_int status)
location
(elapsed *. 1e6)
in
begin
if Status.is_server_error status then
log.error report
else
if Status.is_client_error status then
log.warning report
else
log.info report
end;
response
| exception exn ->
let backtrace = Printexc.get_backtrace () in
In case of exception , log the exception . We alsp log the backtrace
here , even though it is likely to be redundant , because some OCaml
libraries install exception printers that will clobber the backtrace
right during Printexc.to_string !
here, even though it is likely to be redundant, because some OCaml
libraries install exception printers that will clobber the backtrace
right during Printexc.to_string! *)
log.warning (fun log ->
log ~request "Aborted by: %s" (Printexc.to_string exn));
backtrace
|> iter_backtrace (fun line -> log.warning (fun log -> log "%s" line));
raise exn
end
TODO DOC Include logging itself in the timing . Or ? Is n't that pointless ?
End - to -end timing should include the HTTP parser as well . The logger
provides much more useful information if it helps the user optimize the app .
Sp , should probably some helpers for the user to do end - to - end timing
of the HTTP server and document how to use them .
End-to -end timing should include the HTTP parser as well. The logger
provides much more useful information if it helps the user optimize the app.
Sp, should probably craete some helpers for the user to do end-to-end timing
of the HTTP server and document how to use them. *)
TODO DOC Add docs on how to avoid dep .
(* TODO DOC why it's good to use the initializer early. *)
(* TODO LATER implement fire. *)
(* TODO LATER In case of streamed bodies, it is useful for the logger to be told
by the HTTP layer when streaming was actually completed. *)
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/src/server/log.ml | ocaml | Among other things, this module wraps the Logs library so as to prepend
request ids to log messages.
However, instead of prepending the id at the front end of Logs, in the
wrappers, we prepend the id at the back end instead - in the reporter. The
rationale for this is that we want to (try to) prepend the id even to strings
that don't come from Dream or the user's Dream app, and thus *definitely* do
not call this module's wrappers.
The wrappers try to get the request id from their argument ~request, and pass
it down to the reporter in a Logs tag.
The reporter reads the tag and uses that request id if it is available. If
the request id is not available, it is because the log message comes from a
point in the Dream app where an id has not been assigned to the request, or
because the log message comes from another dependency (or a sloppy call
site!). In that case, the reporter tries to retrieve the id from the
promise-chain-local storage of Lwt.
This is sufficient for attaching a request id to most log messages, in
practice.
The logging middleware assigns request ids to requests, and tries to show
them in the logs. The scheme works as follows:
- Request ids are strings stored in request-local variables.
- The automatically assigned request ids are taken from a simple global
sequence.
- The user can override the automatic request id by assigning a request id
in a middleware that runs before the logger. User-provided request ids can
be per-thread, can come from a proxy header, etc.
- The logger makes a best effort to forward the request id to all logging
statements that are being formatted. If the ~request argument is provided
during a logging call, that request's id is shown. To handle all other
cases, the logger puts the request's id into an Lwt sequence-associated
storage key, and the log message formatter tries to get it from there.
TODO Necessary helpers for the user setting the request id are not yet
exposed in the API, pending some other refactoring (request mutability).
Lwt sequence-associated storage key used to pass request ids for use when
~request is not provided.
The actual request id "field" associated with each request by the logger. If
this field is missing, the logger assigns the request a fresh id.
Makes a best-effort attempt to retrieve the request id.
The current state of the request id sequence.
Format into an internal buffer.
Gets called by Logs for each log call that passes its level threshold.
~over is to be called when the I/O underlying the log operation is fully
complete. In practice, since most call sites are not using Lwt, they will
continue executing anyway. This means that the message must be formatted
and the buffer flushed before doing anything asynchronous, so that
subsequent logging operations don't get into the same generation of the
buffer.
The user's_callback argument is not exactly the user's callback - it's the
callback that got wrapped in function source (the "front end") below. That
wrapper is the actual user's callback, and it calls user's_callback.
Get the formatted message out of the buffer right away, because we are
doing Lwt operations next, and the caller might not wait.
Write the message.
Call the user's callback to get the actual message and trigger
formatting, and, eventually, writing. The wrappers don't use the ?header
argument, so we ignore it.
Format the source name column. It is the right-aligned log source name,
clipped to the column width. If the source is the default application
source, leave the column empty.
Check if a request id is available in the tags passed from the front
end. If not, try to get it from the promise-chain-local storage. If
we end up with a request id, format it.
The last byte of the request id is basically always going to be a
digit, growing incrementally, so we can use the parity of its
ASCII code to stripe the requests in the log.
The formatting proper.
The "front end."
This creates a wrapper, as described above. The wrapper forwards to a
logger of the Logs library, but instead of passing the formatter m to the
user's callback, it passes a formatter m', which is like m, but lacks a
?tags argument. It has a ?request argument instead. If ~request is given,
m' immediately tries to retrieve the request id, put it into a Logs tag,
and call Logs' m with the user's formatting arguments and the tag.
Create the actual Logs source, and then wrap all the interesting
functions.
Logs.app (fun log -> log format_and_arguments)
A helper used in several places.
If logging hasn't been initialized, trigger this so that
configuration of log levels can proceed.
The request logging middleware.
Turn on backtrace recording.
Get the requwst's id or assign a new one.
Identify the request in the log.
Call the rest of the app.
Log the elapsed time. If the response is a redirection, log the
target.
TODO DOC why it's good to use the initializer early.
TODO LATER implement fire.
TODO LATER In case of streamed bodies, it is useful for the logger to be told
by the HTTP layer when streaming was actually completed. | This file is part of Dream , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2021
for details, or visit .
Copyright 2021 Anton Bachin *)
module Message = Dream_pure.Message
module Method = Dream_pure.Method
module Status = Dream_pure.Status
type log_level = [
| `Error
| `Warning
| `Info
| `Debug
]
let request_id_label = "dream.request_id"
Logs library tag uesd to pass an i d from a request provided through
~request .
~request. *)
let logs_lib_tag : string Logs.Tag.def =
Logs.Tag.def
request_id_label
Format.pp_print_string
let id_lwt_key : string Lwt.key =
Lwt.new_key ()
let id_field =
Message.new_field
~name:request_id_label
~show_value:(fun id -> id)
()
let get_request_id ?request () =
let request_id =
match request with
| None -> None
| Some request -> Message.field request id_field
in
match request_id with
| Some _ -> request_id
| None -> Lwt.get id_lwt_key
let last_id =
ref 0
TODO Nice logging for multiline strings ?
The " back end . " I inlined several examples from the Logs , Logs_lwt , and Fmt
docs into each other , and modified the result , to arrive at this function .
See those docs for the meanings of the various helpers and values .
The reporter needs to be suspended in a function because Dream sets up the
logger lazily ; it does n't query the output streams for whether they are TTYs
until needed . Setting up the reporter before TTY checking will cause it to
not output color .
docs into each other, and modified the result, to arrive at this function.
See those docs for the meanings of the various helpers and values.
The reporter needs to be suspended in a function because Dream sets up the
logger lazily; it doesn't query the output streams for whether they are TTYs
until needed. Setting up the reporter before TTY checking will cause it to
not output color. *)
let reporter ~now () =
let buffer = Buffer.create 512 in
let formatter = Fmt.with_buffer ~like:Fmt.stderr buffer in
let flush () =
let message = Buffer.contents buffer in
Buffer.reset buffer;
message
in
let report src level ~over k user's_callback =
let level_style, level =
match level with
| Logs.App -> `White, " "
| Logs.Error -> `Red, "ERROR"
| Logs.Warning -> `Yellow, " WARN"
| Logs.Info -> `Green, " INFO"
| Logs.Debug -> `Blue, "DEBUG"
in
let write _ =
let message = flush () in
prerr_string message;
Stdlib.flush stderr;
over ();
k ()
in
user's_callback @@ fun ?header ?tags format_and_arguments ->
ignore header;
Format the current local time . For the millisecond fraction , be careful
of rounding 999.5 + to 1000 on output .
of rounding 999.5+ to 1000 on output. *)
let time =
let unix_time = now () in
let time = Option.get (Ptime.of_float_s unix_time) in
let fraction =
fst (modf unix_time) *. 1000. in
let clamped_fraction =
if fraction > 999. then 999.
else fraction
in
let ((y, m, d), ((hh, mm, ss), _tz_offset_s)) =
Ptime.to_date_time time in
Printf.sprintf "%02i.%02i.%02i %02i:%02i:%02i.%03.0f"
d m (y mod 100)
hh mm ss clamped_fraction
in
let source =
let width = 15 in
if Logs.Src.name src = Logs.Src.name Logs.default then
String.make width ' '
else
let name = Logs.Src.name src in
if String.length name > width then
String.sub name (String.length name - width) width
else
(String.make (width - String.length name) ' ') ^ name
in
let source_prefix, source =
try
let dot_index = String.rindex source '.' + 1 in
String.sub source 0 dot_index,
String.sub source dot_index (String.length source - dot_index)
with Not_found ->
"", source
in
let request_id_from_tags =
match tags with
| None -> None
| Some tags ->
Logs.Tag.find logs_lib_tag tags
in
let request_id =
match request_id_from_tags with
| Some _ -> request_id_from_tags
| None -> get_request_id ()
in
let request_id, request_style =
match request_id with
| Some "" | None -> "", `White
| Some request_id ->
let last_byte = request_id.[String.length request_id - 1] in
let color =
if (Char.code last_byte) land 1 = 0 then
`Cyan
else
`Magenta
in
" REQ " ^ request_id, color
in
Format.kfprintf write formatter
("%a %a%s %a%a @[" ^^ format_and_arguments ^^ "@]@.")
Fmt.(styled `Faint string) time
Fmt.(styled `White string) source_prefix source
Fmt.(styled level_style string) level
Fmt.(styled request_style (styled `Italic string)) request_id
in
{Logs.report}
Lazy initialization upon first use or call to initialize .
let enable =
ref true
let level =
ref Logs.Info
let custom_log_levels : (string * Logs.level) list ref =
ref []
let sources : (string * Logs.src) list ref =
ref []
let set_printexc =
ref true
let set_async_exception_hook =
ref true
let _initialized = ref None
let to_logs_level l =
match l with
| `Error -> Logs.Error
| `Warning -> Logs.Warning
| `Info -> Logs.Info
| `Debug -> Logs.Debug
exception Logs_are_not_initialized
let setup_logs =
"\nTo initialize logs with a default reporter, and set up Dream, \
do the following:\
\n If you are using MirageOS, use the Dream device in config.ml
\n If you are using Lwt/Unix, execute `Dream.log_initialize ()`
\n"
let () = Printexc.register_printer @@ function
| Logs_are_not_initialized ->
Some ("The default logger is not yet initialized. " ^ setup_logs)
| _ -> None
let initialized () : [ `Initialized ] =
match !_initialized with
| None -> raise Logs_are_not_initialized
| Some v -> Lazy.force v
type ('a, 'b) conditional_log =
((?request:Message.request ->
('a, Stdlib.Format.formatter, unit, 'b) Stdlib.format4 -> 'a) -> 'b) ->
unit
type sub_log = {
error : 'a. ('a, unit) conditional_log;
warning : 'a. ('a, unit) conditional_log;
info : 'a. ('a, unit) conditional_log;
debug : 'a. ('a, unit) conditional_log;
}
let sub_log ?level:level_ name =
let forward ~(destination_log : _ Logs.log) user's_k =
let `Initialized = initialized () in
destination_log (fun log ->
user's_k (fun ?request format_and_arguments ->
let tags =
match request with
| None -> Logs.Tag.empty
| Some request ->
match get_request_id ~request () with
| None -> Logs.Tag.empty
| Some request_id ->
Logs.Tag.add logs_lib_tag request_id Logs.Tag.empty
in
log ~tags format_and_arguments))
in
let level =
List.find Option.is_some [
Option.map to_logs_level level_;
List.assoc_opt name !custom_log_levels;
Some !level
] in
let src = Logs.Src.create name in
let (module Log) = Logs.src_log src in
Logs.Src.set_level src level;
custom_log_levels :=
(name, Option.get level)::(List.remove_assoc name !custom_log_levels);
sources := (name, src) :: (List.remove_assoc name !sources);
{
error = (fun k -> forward ~destination_log:Log.err k);
warning = (fun k -> forward ~destination_log:Log.warn k);
info = (fun k -> forward ~destination_log:Log.info k);
debug = (fun k -> forward ~destination_log:Log.debug k);
}
let convenience_log format_and_arguments =
Fmt.kstr
(fun message ->
let `Initialized = initialized () in
Logs.app (fun log -> log "%s" message))
format_and_arguments
let report = Logs.((reporter ( ) ) .report ) in
report Logs.default Logs . App ~over : ignore ignore format_and_arguments
report Logs.default Logs.App ~over:ignore ignore format_and_arguments *)
let iter_backtrace f backtrace =
backtrace
|> String.split_on_char '\n'
|> List.filter (fun line -> line <> "")
|> List.iter f
Use the above function to create a log source for Log 's own middleware , the
same way any other middleware would .
same way any other middleware would. *)
let log =
sub_log "dream.log"
let set_up_exception_hook () =
if !set_async_exception_hook then begin
set_async_exception_hook := false;
Lwt.async_exception_hook := fun exn ->
let backtrace = Printexc.get_backtrace () in
log.error (fun log -> log "Async exception: %s" (Printexc.to_string exn));
backtrace
|> iter_backtrace (fun line -> log.error (fun log -> log "%s" line))
end
let initialize_log
?(backtraces = true)
?(async_exception_hook = true)
?level:level_
?enable:(enable_ = true)
() =
if backtraces then
Printexc.record_backtrace true;
set_printexc := false;
if async_exception_hook then
set_up_exception_hook ();
set_async_exception_hook := false;
let level_ =
Option.map to_logs_level level_
|> Option.value ~default:Logs.Info in
enable := enable_;
level := level_;
let `Initialized = initialized () in
()
let set_log_level name level =
let `Initialized = initialized () in
let level = to_logs_level level in
custom_log_levels :=
(name, level)::(List.remove_assoc name !custom_log_levels);
let src = List.assoc_opt name !sources in
Option.iter (fun s -> Logs.Src.set_level s (Some level)) src
module Make (Pclock : Mirage_clock.PCLOCK) =
struct
let now () =
Ptime.to_float_s (Ptime.v (Pclock.now_d_ps ()))
let initializer_ ~setup_outputs = lazy begin
if !enable then begin
setup_outputs () ;
Logs.set_level ~all:true (Some !level);
Logs.set_reporter (reporter ~now ())
end ;
`Initialized
end
let set = ref false
let initialize ~setup_outputs =
if !set then Logs.debug (fun log -> log
"Dream__log.initialize has already been called, ignoring this call.")
else begin
(try
let `Initialized = initialized () in
Format.eprintf
"Dream__log.initialized has already been set, check that this call \
is intentional";
with
Logs_are_not_initialized -> ());
set := true;
_initialized := Some (initializer_ ~setup_outputs)
end
let logger next_handler request =
let start = now () in
if !set_printexc then begin
Printexc.record_backtrace true;
set_printexc := false
end;
let id =
match Message.field request id_field with
| Some id -> id
| None ->
last_id := !last_id + 1;
let id = string_of_int !last_id in
Message.set_field request id_field id;
id
in
let user_agent =
Message.headers request "User-Agent"
|> String.concat " "
in
log.info (fun log ->
log ~request "%s %s %s %s"
(Method.method_to_string (Message.method_ request))
(Message.target request)
(Helpers.client request)
user_agent);
match Lwt.with_value id_lwt_key (Some id) (fun () -> next_handler request) with
| response ->
let location =
if Status.is_redirection (Message.status response) then
match Message.header response "Location" with
| Some location -> " " ^ location
| None -> ""
else ""
in
let status = Message.status response in
let report :
(?request:Message.request ->
('a, Format.formatter, unit, 'b) format4 -> 'a) -> 'b =
fun log ->
let elapsed = now () -. start in
log ~request "%i%s in %.0f μs"
(Status.status_to_int status)
location
(elapsed *. 1e6)
in
begin
if Status.is_server_error status then
log.error report
else
if Status.is_client_error status then
log.warning report
else
log.info report
end;
response
| exception exn ->
let backtrace = Printexc.get_backtrace () in
In case of exception , log the exception . We alsp log the backtrace
here , even though it is likely to be redundant , because some OCaml
libraries install exception printers that will clobber the backtrace
right during Printexc.to_string !
here, even though it is likely to be redundant, because some OCaml
libraries install exception printers that will clobber the backtrace
right during Printexc.to_string! *)
log.warning (fun log ->
log ~request "Aborted by: %s" (Printexc.to_string exn));
backtrace
|> iter_backtrace (fun line -> log.warning (fun log -> log "%s" line));
raise exn
end
TODO DOC Include logging itself in the timing . Or ? Is n't that pointless ?
End - to -end timing should include the HTTP parser as well . The logger
provides much more useful information if it helps the user optimize the app .
Sp , should probably some helpers for the user to do end - to - end timing
of the HTTP server and document how to use them .
End-to -end timing should include the HTTP parser as well. The logger
provides much more useful information if it helps the user optimize the app.
Sp, should probably craete some helpers for the user to do end-to-end timing
of the HTTP server and document how to use them. *)
TODO DOC Add docs on how to avoid dep .
|
6b05337be8e15011c10d423ca657c9da7648213e5c2e01e02ec13ac6d5bf8cf8 | tommaisey/aeon | sweep.help.scm | ;; Using sweep to modulate sine frequency
(let* ((t (impulse kr (mouse-x kr 0.5 20 1 0.1) 0))
(f (add (sweep t 700) 500)))
(audition (out 0 (mul (sin-osc ar f 0) 0.2))))
;; Using sweep to index into a buffer
(with-sc3
(lambda (fd)
(async fd (b-alloc-read 0 "/home/rohan/audio/metal.wav" 0 0))))
(let* ((t (impulse ar (mouse-x kr 0.5 20 1 0.1) 0))
(i (sweep t (buf-sample-rate ir 0))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
;; Backwards, variable offset
(let* ((t (impulse ar (mouse-x kr 0.5 10 1 0.1) 0))
(r (buf-sample-rate ir 0))
(i (add (sweep t (neg r)) (mul (buf-frames ir 0) (lf-noise0 kr 15)))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
;; Raising rate
(let* ((t (impulse ar (mouse-x kr 0.5 10 1 0.1) 0))
(r (add (sweep t 2) 0.5))
(i (sweep t (mul (buf-sample-rate ir 0) r))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
| null | https://raw.githubusercontent.com/tommaisey/aeon/80744a7235425c47a061ec8324d923c53ebedf15/libs/third-party/sc3/rsc3/help/ugen/triggers/sweep.help.scm | scheme | Using sweep to modulate sine frequency
Using sweep to index into a buffer
Backwards, variable offset
Raising rate |
(let* ((t (impulse kr (mouse-x kr 0.5 20 1 0.1) 0))
(f (add (sweep t 700) 500)))
(audition (out 0 (mul (sin-osc ar f 0) 0.2))))
(with-sc3
(lambda (fd)
(async fd (b-alloc-read 0 "/home/rohan/audio/metal.wav" 0 0))))
(let* ((t (impulse ar (mouse-x kr 0.5 20 1 0.1) 0))
(i (sweep t (buf-sample-rate ir 0))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
(let* ((t (impulse ar (mouse-x kr 0.5 10 1 0.1) 0))
(r (buf-sample-rate ir 0))
(i (add (sweep t (neg r)) (mul (buf-frames ir 0) (lf-noise0 kr 15)))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
(let* ((t (impulse ar (mouse-x kr 0.5 10 1 0.1) 0))
(r (add (sweep t 2) 0.5))
(i (sweep t (mul (buf-sample-rate ir 0) r))))
(audition (out 0 (buf-rd 1 ar 0 i 0 2))))
|
2e9478c99f8d45499b58625a02134c00931182879ede51dd04aa7690b7222ac8 | geophf/1HaskellADay | Solution.hs | module Y2018.M10.D08.Solution where
-
Happy Columbus Day and Indiginous People 's Day !
Today , we are given a set of ids for today and we will generate a subset of
those ids , given a set of indices . You can look at this as a random draw for
screening , perhaps . Or something else , if you 'd like .
-
Happy Columbus Day and Indiginous People's Day!
Today, we are given a set of ids for today and we will generate a subset of
those ids, given a set of indices. You can look at this as a random draw for
screening, perhaps. Or something else, if you'd like.
--}
import Data.Array
exDir, idsToday :: FilePath
exDir = "Y2018/M10/D08/"
idsToday = "ids-today.txt"
picks :: [Int]
picks = [4, 6, 7, 9, 10, 19, 23, 24, 29, 32, 33, 34, 35, 37, 39, 46, 54, 55,
58, 59, 63, 64, 67, 73, 78, 79, 89, 94, 98, 99]
type ID = String
picked :: FilePath -> [Int] -> IO [ID]
picked idFile picks = readFile idFile >>=
return . flip map picks . (!) . array (0,99) . zip [0..] . lines
-- We convert the list to an array to eliminate multiple linear traversals
-- while indexing into the ids to get the selected members.
-
> > > take 3 < $ > picked ( exDir + + idsToday ) picks
[ " thXKM68kkXSE74WJWGQxp8LV","n2NJbdKH9dTbcfJWvm2R49mZ","rVEQCZCJJM2ywMgLsRha3bvb " ]
-
>>> take 3 <$> picked (exDir ++ idsToday) picks
["thXKM68kkXSE74WJWGQxp8LV","n2NJbdKH9dTbcfJWvm2R49mZ","rVEQCZCJJM2ywMgLsRha3bvb"]
--}
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M10/D08/Solution.hs | haskell | }
We convert the list to an array to eliminate multiple linear traversals
while indexing into the ids to get the selected members.
} | module Y2018.M10.D08.Solution where
-
Happy Columbus Day and Indiginous People 's Day !
Today , we are given a set of ids for today and we will generate a subset of
those ids , given a set of indices . You can look at this as a random draw for
screening , perhaps . Or something else , if you 'd like .
-
Happy Columbus Day and Indiginous People's Day!
Today, we are given a set of ids for today and we will generate a subset of
those ids, given a set of indices. You can look at this as a random draw for
screening, perhaps. Or something else, if you'd like.
import Data.Array
exDir, idsToday :: FilePath
exDir = "Y2018/M10/D08/"
idsToday = "ids-today.txt"
picks :: [Int]
picks = [4, 6, 7, 9, 10, 19, 23, 24, 29, 32, 33, 34, 35, 37, 39, 46, 54, 55,
58, 59, 63, 64, 67, 73, 78, 79, 89, 94, 98, 99]
type ID = String
picked :: FilePath -> [Int] -> IO [ID]
picked idFile picks = readFile idFile >>=
return . flip map picks . (!) . array (0,99) . zip [0..] . lines
-
> > > take 3 < $ > picked ( exDir + + idsToday ) picks
[ " thXKM68kkXSE74WJWGQxp8LV","n2NJbdKH9dTbcfJWvm2R49mZ","rVEQCZCJJM2ywMgLsRha3bvb " ]
-
>>> take 3 <$> picked (exDir ++ idsToday) picks
["thXKM68kkXSE74WJWGQxp8LV","n2NJbdKH9dTbcfJWvm2R49mZ","rVEQCZCJJM2ywMgLsRha3bvb"]
|
2c96b6baff71efe131ed124bf8107e6620d205be9cdc9551858b4a820c7ce2a0 | yminsky/experiment-with-ocaml-5 | fib.mli | open! Base
module Seq : sig
val fib : int -> int
end
module Par : sig
val fib : num_domains:int -> int -> int
end
| null | https://raw.githubusercontent.com/yminsky/experiment-with-ocaml-5/47e609688c9381479326d73b7eede5003747f434/bench/fib.mli | ocaml | open! Base
module Seq : sig
val fib : int -> int
end
module Par : sig
val fib : num_domains:int -> int -> int
end
| |
df6395591338bacb50374f79e5c13a6e45678357410a75413d0d5639174021b5 | Ericson2314/lighthouse | BlockTable.hs | -- #hide
-----------------------------------------------------------------------------
-- |
Module : Text . .
Copyright : ( c ) , and the Oregon Graduate Institute of
Science and Technology , 1999 - 2001
-- License : BSD-style (see the file LICENSE)
Maintainer : < >
-- Stability : experimental
-- Portability : portable
--
-- An XHTML combinator library
--
-- These combinators can be used to build formated 2D tables.
-- The specific target usage is for HTML table generation.
-----------------------------------------------------------------------------
Examples of use :
> table1 : : > table1 = single " Hello " + -----+
|Hello|
This is a 1x1 cell + -----+
Note : single has type
single : : a - > BlockTable a
So the cells can contain anything .
> : :
> = single " World " + -----+
|World|
+ -----+
> table3 : :
> table3 = table1 % -% -----%-----+
|Hello%World|
% is used to indicate + -----%-----+
the join edge between
the two Tables .
> : :
> = table3 % /% -----+-----+
|Hello|World|
Notice the padding on the % % % % % % % % % % % % %
smaller ( bottom ) cell to |World |
force the table to be a + -----------+
rectangle .
> : :
> = table1 % -% + -----%-----+-----+
|Hello%Hello|World|
Notice the padding on the | % -----+-----+
leftmost cell , again to | % World |
force the table to be a + -----%-----------+
rectangle .
Now the table can be rendered with processTable , for example :
Main > processTable
[ [ ( " Hello",(1,2 ) ) ,
( " Hello",(1,1 ) ) ,
( " World",(1,1 ) ) ] ,
[ ( " ) ) ] ] : : [ [ ( [ Char],(Int , Int ) ) ] ]
Main >
Examples of use:
> table1 :: BlockTable String
> table1 = single "Hello" +-----+
|Hello|
This is a 1x1 cell +-----+
Note: single has type
single :: a -> BlockTable a
So the cells can contain anything.
> table2 :: BlockTable String
> table2 = single "World" +-----+
|World|
+-----+
> table3 :: BlockTable String
> table3 = table1 %-% table2 +-----%-----+
|Hello%World|
% is used to indicate +-----%-----+
the join edge between
the two Tables.
> table4 :: BlockTable String
> table4 = table3 %/% table2 +-----+-----+
|Hello|World|
Notice the padding on the %%%%%%%%%%%%%
smaller (bottom) cell to |World |
force the table to be a +-----------+
rectangle.
> table5 :: BlockTable String
> table5 = table1 %-% table4 +-----%-----+-----+
|Hello%Hello|World|
Notice the padding on the | %-----+-----+
leftmost cell, again to | %World |
force the table to be a +-----%-----------+
rectangle.
Now the table can be rendered with processTable, for example:
Main> processTable table5
[[("Hello",(1,2)),
("Hello",(1,1)),
("World",(1,1))],
[("World",(2,1))]] :: [[([Char],(Int,Int))]]
Main>
-}
module Text.XHtml.BlockTable (
*
BlockTable,
-- * Contruction Functions
single,
above,
beside,
-- * Investigation Functions
getMatrix,
showsTable,
showTable,
) where
infixr 4 `beside`
infixr 3 `above`
--
-- * Construction Functions
--
-- Perhaps one day I'll write the Show instance
-- to show boxes aka the above ascii renditions.
instance (Show a) => Show (BlockTable a) where
showsPrec _ = showsTable
type TableI a = [[(a,(Int,Int))]] -> [[(a,(Int,Int))]]
data BlockTable a = Table (Int -> Int -> TableI a) Int Int
-- | Creates a (1x1) table entry
single :: a -> BlockTable a
single a = Table (\ x y z -> [(a,(x+1,y+1))] : z) 1 1
-- | Composes tables vertically.
above :: BlockTable a -> BlockTable a -> BlockTable a
-- | Composes tables horizontally.
beside :: BlockTable a -> BlockTable a -> BlockTable a
t1 `above` t2 = trans (combine (trans t1) (trans t2) (.))
t1 `beside` t2 = combine t1 t2 (\ lst1 lst2 r ->
let
-- Note this depends on the fact that
-- that the result has the same number
of lines as the y dimention ; one list
-- per line. This is not true in general
-- but is always true for these combinators.
-- I should assert this!
-- I should even prove this.
beside (x:xs) (y:ys) = (x ++ y) : beside xs ys
beside (x:xs) [] = x : xs ++ r
beside [] (y:ys) = y : ys ++ r
beside [] [] = r
in
beside (lst1 []) (lst2 []))
-- | trans flips (transposes) over the x and y axis of
-- the table. It is only used internally, and typically
-- in pairs, ie. (flip ... munge ... (un)flip).
trans :: BlockTable a -> BlockTable a
trans (Table f1 x1 y1) = Table (flip f1) y1 x1
combine :: BlockTable a
-> BlockTable b
-> (TableI a -> TableI b -> TableI c)
-> BlockTable c
combine (Table f1 x1 y1) (Table f2 x2 y2) comb = Table new_fn (x1+x2) max_y
where
max_y = max y1 y2
new_fn x y =
case compare y1 y2 of
EQ -> comb (f1 0 y) (f2 x y)
GT -> comb (f1 0 y) (f2 x (y + y1 - y2))
LT -> comb (f1 0 (y + y2 - y1)) (f2 x y)
--
-- * Investigation Functions
--
-- | This is the other thing you can do with a Table;
-- turn it into a 2D list, tagged with the (x,y)
-- sizes of each cell in the table.
getMatrix :: BlockTable a -> [[(a,(Int,Int))]]
getMatrix (Table r _ _) = r 0 0 []
-- You can also look at a table
showsTable :: (Show a) => BlockTable a -> ShowS
showsTable table = shows (getMatrix table)
showTable :: (Show a) => BlockTable a -> String
showTable table = showsTable table ""
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/xhtml/Text/XHtml/BlockTable.hs | haskell | #hide
---------------------------------------------------------------------------
|
License : BSD-style (see the file LICENSE)
Stability : experimental
Portability : portable
An XHTML combinator library
These combinators can be used to build formated 2D tables.
The specific target usage is for HTML table generation.
---------------------------------------------------------------------------
---+
---+
---+
---+
---%-----+
---%-----+
---+-----+
---------+
---%-----+-----+
---+-----+
---%-----------+
---+
---+
---+
---+
---%-----+
---%-----+
---+-----+
---------+
---%-----+-----+
---+-----+
---%-----------+
* Contruction Functions
* Investigation Functions
* Construction Functions
Perhaps one day I'll write the Show instance
to show boxes aka the above ascii renditions.
| Creates a (1x1) table entry
| Composes tables vertically.
| Composes tables horizontally.
Note this depends on the fact that
that the result has the same number
per line. This is not true in general
but is always true for these combinators.
I should assert this!
I should even prove this.
| trans flips (transposes) over the x and y axis of
the table. It is only used internally, and typically
in pairs, ie. (flip ... munge ... (un)flip).
* Investigation Functions
| This is the other thing you can do with a Table;
turn it into a 2D list, tagged with the (x,y)
sizes of each cell in the table.
You can also look at a table |
Module : Text . .
Copyright : ( c ) , and the Oregon Graduate Institute of
Science and Technology , 1999 - 2001
Maintainer : < >
Examples of use :
|Hello|
Note : single has type
single : : a - > BlockTable a
So the cells can contain anything .
> : :
|World|
> table3 : :
|Hello%World|
the join edge between
the two Tables .
> : :
|Hello|World|
Notice the padding on the % % % % % % % % % % % % %
smaller ( bottom ) cell to |World |
rectangle .
> : :
|Hello%Hello|World|
leftmost cell , again to | % World |
rectangle .
Now the table can be rendered with processTable , for example :
Main > processTable
[ [ ( " Hello",(1,2 ) ) ,
( " Hello",(1,1 ) ) ,
( " World",(1,1 ) ) ] ,
[ ( " ) ) ] ] : : [ [ ( [ Char],(Int , Int ) ) ] ]
Main >
Examples of use:
> table1 :: BlockTable String
|Hello|
Note: single has type
single :: a -> BlockTable a
So the cells can contain anything.
> table2 :: BlockTable String
|World|
> table3 :: BlockTable String
|Hello%World|
the join edge between
the two Tables.
> table4 :: BlockTable String
|Hello|World|
Notice the padding on the %%%%%%%%%%%%%
smaller (bottom) cell to |World |
rectangle.
> table5 :: BlockTable String
|Hello%Hello|World|
leftmost cell, again to | %World |
rectangle.
Now the table can be rendered with processTable, for example:
Main> processTable table5
[[("Hello",(1,2)),
("Hello",(1,1)),
("World",(1,1))],
[("World",(2,1))]] :: [[([Char],(Int,Int))]]
Main>
-}
module Text.XHtml.BlockTable (
*
BlockTable,
single,
above,
beside,
getMatrix,
showsTable,
showTable,
) where
infixr 4 `beside`
infixr 3 `above`
instance (Show a) => Show (BlockTable a) where
showsPrec _ = showsTable
type TableI a = [[(a,(Int,Int))]] -> [[(a,(Int,Int))]]
data BlockTable a = Table (Int -> Int -> TableI a) Int Int
single :: a -> BlockTable a
single a = Table (\ x y z -> [(a,(x+1,y+1))] : z) 1 1
above :: BlockTable a -> BlockTable a -> BlockTable a
beside :: BlockTable a -> BlockTable a -> BlockTable a
t1 `above` t2 = trans (combine (trans t1) (trans t2) (.))
t1 `beside` t2 = combine t1 t2 (\ lst1 lst2 r ->
let
of lines as the y dimention ; one list
beside (x:xs) (y:ys) = (x ++ y) : beside xs ys
beside (x:xs) [] = x : xs ++ r
beside [] (y:ys) = y : ys ++ r
beside [] [] = r
in
beside (lst1 []) (lst2 []))
trans :: BlockTable a -> BlockTable a
trans (Table f1 x1 y1) = Table (flip f1) y1 x1
combine :: BlockTable a
-> BlockTable b
-> (TableI a -> TableI b -> TableI c)
-> BlockTable c
combine (Table f1 x1 y1) (Table f2 x2 y2) comb = Table new_fn (x1+x2) max_y
where
max_y = max y1 y2
new_fn x y =
case compare y1 y2 of
EQ -> comb (f1 0 y) (f2 x y)
GT -> comb (f1 0 y) (f2 x (y + y1 - y2))
LT -> comb (f1 0 (y + y2 - y1)) (f2 x y)
getMatrix :: BlockTable a -> [[(a,(Int,Int))]]
getMatrix (Table r _ _) = r 0 0 []
showsTable :: (Show a) => BlockTable a -> ShowS
showsTable table = shows (getMatrix table)
showTable :: (Show a) => BlockTable a -> String
showTable table = showsTable table ""
|
a03eb6d93abefec0cd0a364b11772a7a0db3390d6186d563b20d339e5224144a | wulczer/tsung_ws | ts_config_websocket.erl | -module(ts_config_websocket).
-export([parse_config/2]).
-include("ts_profile.hrl").
-include("ts_websocket.hrl").
-include("ts_config.hrl").
-include("xmerl.hrl").
% parse dynamic variables
parse_config(Element = #xmlElement{name=dyn_variable}, Conf = #config{}) ->
ts_config:parse(Element,Conf);
% parse websocket tags
parse_config(Element = #xmlElement{name=websocket},
Config=#config{curid= Id, session_tab = Tab,
match = MatchRegExp, dynvar = DynVar,
subst = SubstFlag, sessions = [CurS | _]}) ->
Type = ts_config:getAttr(atom, Element#xmlElement.attributes, type),
% send messages can be no_ack, the rest is always ack = parse
Ack = case Type of
send ->
ts_config:getAttr(atom, Element#xmlElement.attributes, ack, parse);
_ ->
parse
end,
Url = ts_config:getAttr(string, Element#xmlElement.attributes, url, "/"),
% connect message can have a origin attribute
Origin = ts_config:getAttr(string, Element#xmlElement.attributes,
origin, undefined),
Data = list_to_binary(ts_config:getText(Element#xmlElement.content)),
Request = #websocket_request{type = Type, url = Url,
origin = Origin, data = Data},
Msg = #ts_request{ack = Ack,
endpage = true,
dynvar_specs = DynVar,
subst = SubstFlag,
match = MatchRegExp,
param = Request},
ts_config:mark_prev_req(Id-1, Tab, CurS),
ets:insert(Tab,{{CurS#session.id, Id}, Msg }),
lists:foldl(fun(A,B) -> ts_config:parse(A,B) end,
Config#config{dynvar = []},
Element#xmlElement.content);
% parse other tags
parse_config(Element=#xmlElement{}, Conf=#config{}) ->
ts_config:parse(Element,Conf);
parse non - XML elements
parse_config(_, Conf=#config{}) ->
Conf.
| null | https://raw.githubusercontent.com/wulczer/tsung_ws/4395d4e84a4f763da427d41ed9552a552f3f0fa7/src/tsung_controller/ts_config_websocket.erl | erlang | parse dynamic variables
parse websocket tags
send messages can be no_ack, the rest is always ack = parse
connect message can have a origin attribute
parse other tags | -module(ts_config_websocket).
-export([parse_config/2]).
-include("ts_profile.hrl").
-include("ts_websocket.hrl").
-include("ts_config.hrl").
-include("xmerl.hrl").
parse_config(Element = #xmlElement{name=dyn_variable}, Conf = #config{}) ->
ts_config:parse(Element,Conf);
parse_config(Element = #xmlElement{name=websocket},
Config=#config{curid= Id, session_tab = Tab,
match = MatchRegExp, dynvar = DynVar,
subst = SubstFlag, sessions = [CurS | _]}) ->
Type = ts_config:getAttr(atom, Element#xmlElement.attributes, type),
Ack = case Type of
send ->
ts_config:getAttr(atom, Element#xmlElement.attributes, ack, parse);
_ ->
parse
end,
Url = ts_config:getAttr(string, Element#xmlElement.attributes, url, "/"),
Origin = ts_config:getAttr(string, Element#xmlElement.attributes,
origin, undefined),
Data = list_to_binary(ts_config:getText(Element#xmlElement.content)),
Request = #websocket_request{type = Type, url = Url,
origin = Origin, data = Data},
Msg = #ts_request{ack = Ack,
endpage = true,
dynvar_specs = DynVar,
subst = SubstFlag,
match = MatchRegExp,
param = Request},
ts_config:mark_prev_req(Id-1, Tab, CurS),
ets:insert(Tab,{{CurS#session.id, Id}, Msg }),
lists:foldl(fun(A,B) -> ts_config:parse(A,B) end,
Config#config{dynvar = []},
Element#xmlElement.content);
parse_config(Element=#xmlElement{}, Conf=#config{}) ->
ts_config:parse(Element,Conf);
parse non - XML elements
parse_config(_, Conf=#config{}) ->
Conf.
|
0ff396ae38ea6c26d1901f5a8995082c48dad834606f4473e443bbf02af1da5e | facebook/duckling | Corpus.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.EN.Corpus
( corpus
, defaultCorpus
, negativeCorpus
, latentCorpus
, diffCorpus
) where
import Data.String
import Prelude
import Duckling.Core
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month, refTime)
import Duckling.TimeGrain.Types hiding (add)
corpus :: Corpus
corpus = (testContext, testOptions, allExamples)
defaultCorpus :: Corpus
defaultCorpus = (testContext, testOptions, allExamples ++ custom)
where
custom = concat
[ examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "2/15"
, "on 2/15"
, "2 / 15"
, "2-15"
, "2 - 15"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "10/31/1974"
, "10/31/74"
, "10-31-74"
, "10.31.1974"
, "31/Oct/1974"
, "31-Oct-74"
, "31st Oct 1974"
]
, examples (datetime (2013, 4, 25, 16, 0, 0) Minute)
[ "4/25 at 4:00pm"
, "4/25 at 16h00"
, "4/25 at 16h"
]
, examples (datetimeHoliday (2013, 11, 28, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving day"
, "thanksgiving"
, "thanksgiving 2013"
, "this thanksgiving"
, "next thanksgiving day"
, "thanksgiving in 9 months"
, "thanksgiving 9 months from now"
]
, examples (datetimeHoliday (2014, 11, 27, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving of next year"
, "thanksgiving in a year"
, "thanksgiving 2014"
]
, examples (datetimeHoliday (2012, 11, 22, 0, 0, 0) Day "Thanksgiving Day")
[ "last thanksgiving"
, "thanksgiving day 2012"
, "thanksgiving 3 months ago"
, "thanksgiving 1 year ago"
]
, examples (datetimeHoliday (2016, 11, 24, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2016"
, "thanksgiving in 3 years"
]
, examples (datetimeHoliday (2017, 11, 23, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2017"
]
]
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext, testOptions, examples)
where
examples =
[ "laughing out loud"
, "1 adult"
, "we are separated"
, "25"
, "this is the one"
, "this one"
, "this past one"
, "at single"
, "at a couple of"
, "at pairs"
, "at a few"
, "at dozens"
, "single o'clock"
, "dozens o'clock"
, "Rat 6"
, "rat 6"
, "3 30"
, "three twenty"
, "at 650.650.6500"
, "at 650-650-6500"
, "two sixty a m"
, "Pay ABC 2000"
, "4a"
, "4a."
, "A4 A5"
, "palm"
, "Martin Luther King' day"
, "two three"
]
latentCorpus :: Corpus
latentCorpus = (testContext, testOptions {withLatent = True}, xs)
where
xs = concat
[ examples (datetime (2013, 2, 24, 0, 0, 0) Day)
[ "the 24"
, "On 24th"
]
, examples (datetime (2013, 2, 12, 7, 0, 0) Hour)
[ "7"
, "7a"
]
, examples (datetime (2013, 2, 12, 19, 0, 0) Hour)
[ "7p"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "ten thirty"
, "ten-thirty"
]
, examples (datetime (1974, 1, 1, 0, 0, 0) Year)
[ "1974"
]
, examples (datetime (2013, 5, 1, 0, 0, 0) Month)
[ "May"
]
, examples (datetimeInterval
((2013, 2, 12, 0, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "morning"
]
, examples (datetimeInterval
((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "afternoon"
]
, examples (datetimeInterval
((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "evening"
]
, examples (datetimeInterval
((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "night"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "the week"
]
, examples (datetime (2013, 2, 12, 12, 3, 0) Minute)
[ "twelve zero three"
, "twelve o three"
, "twelve ou three"
, "twelve oh three"
, "twelve-zero-three"
, "twelve-oh-three"
]
, examples (datetimeInterval ((1960, 1, 1, 0, 0, 0), (1962, 1, 1, 0, 0, 0)) Year)
[ "1960 - 1961"
]
, examples (datetime (2013, 2, 12, 20, 15, 0) Minute)
[ "tonight 815"
]
]
diffContext :: Context
diffContext = Context
{ locale = makeLocale EN Nothing
, referenceTime = refTime (2013, 2, 15, 4, 30, 0) (-2)
}
diffCorpus :: Corpus
diffCorpus = (diffContext, testOptions, diffExamples)
where
diffExamples =
examples (datetime (2013, 3, 8, 0, 0, 0) Day)
[ "3 fridays from now"
, "three fridays from now"
]
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 12, 4, 30, 0) Second)
[ "now"
, "right now"
, "just now"
, "at the moment"
, "ATM"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "today"
, "at this time"
]
, examples (datetime (2013, 2, 1, 0, 0, 0) Month)
[ "2/2013"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "in 2014"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "yesterday"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "tomorrow"
, "tomorrows"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "monday"
, "mon."
, "this monday"
, "Monday, Feb 18"
, "Mon, February 18"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "tuesday"
, "Tuesday the 19th"
, "Tuesday 19th"
]
, examples (datetime (2013, 8, 15, 0, 0, 0) Day)
[ "Thu 15th"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "thursday"
, "thu"
, "thu."
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "friday"
, "fri"
, "fri."
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "saturday"
, "sat"
, "sat."
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "sunday"
, "sun"
, "sun."
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "the 1st of march"
, "first of march"
, "the first of march"
, "march first"
]
, examples (datetime (2013, 3, 2, 0, 0, 0) Day)
[ "the 2nd of march"
, "second of march"
, "the second of march"
]
, examples (datetime (2013, 3, 3, 0, 0, 0) Day)
[ "march 3"
, "the third of march"
]
, examples (datetime (2013, 3, 15, 0, 0, 0) Day)
[ "the ides of march"
]
, examples (datetime (2015, 3, 3, 0, 0, 0) Day)
[ "march 3 2015"
, "march 3rd 2015"
, "march third 2015"
, "3/3/2015"
, "3/3/15"
, "2015-3-3"
, "2015-03-03"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "on the 15th"
, "the 15th of february"
, "15 of february"
, "february the 15th"
, "february 15"
, "15th february"
, "February 15"
]
, examples (datetime (2013, 8, 8, 0, 0, 0) Day)
[ "Aug 8"
]
, examples (datetime (2014, 3, 1, 0, 0, 0) Month)
[ "March in 1 year"
, "March in a year"
]
, examples (datetime (2014, 7, 18, 0, 0, 0) Day)
[ "Fri, Jul 18"
, "Jul 18, Fri"
]
, examples (datetime (2014, 10, 1, 0, 0, 0) Month)
[ "October 2014"
, "2014-10"
, "2014/10"
]
, examples (datetime (2015, 4, 14, 0, 0, 0) Day)
[ "14april 2015"
, "April 14, 2015"
, "14th April 15"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "next tuesday"
, "around next tuesday"
]
, examples (datetime (2013, 2, 22, 0, 0, 0) Day)
[ "friday after next"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "next March"
]
, examples (datetime (2014, 3, 1, 0, 0, 0) Month)
[ "March after next"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "Sunday, Feb 10"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "Wed, Feb13"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Week)
[ "this week"
, "current week"
]
, examples (datetime (2013, 2, 4, 0, 0, 0) Week)
[ "last week"
, "past week"
, "previous week"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Week)
[ "next week"
, "the following week"
, "around next week"
, "upcoming week"
, "coming week"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Month)
[ "last month"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "next month"
]
, examples (datetime (2013, 3, 20, 0, 0, 0) Day)
[ "20 of next month"
, "20th of the next month"
, "20th day of next month"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "20th of the current month"
, "20 of this month"
]
, examples (datetime (2013, 1, 20, 0, 0, 0) Day)
[ "20th of the previous month"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Quarter)
[ "this quarter"
, "this qtr"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Quarter)
[ "next quarter"
, "next qtr"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "third quarter"
, "3rd quarter"
, "third qtr"
, "3rd qtr"
, "the 3rd qtr"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "4th quarter 2018"
, "4th qtr 2018"
, "the 4th qtr of 2018"
, "18q4"
, "2018Q4"
]
, examples (datetime (2012, 1, 1, 0, 0, 0) Year)
[ "last year"
, "last yr"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Year)
[ "this year"
, "current year"
, "this yr"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "next year"
, "next yr"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "in 2014 A.D.",
"in 2014 AD"
]
, examples (datetime (-2014, 1, 1, 0, 0, 0) Year)
[ "in 2014 B.C.",
"in 2014 BC"
]
, examples (datetime (14, 1, 1, 0, 0, 0) Year)
[ "in 14 a.d."
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "last sunday"
, "sunday from last week"
, "last week's sunday"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "last tuesday"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "next wednesday"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "wednesday of next week"
, "wednesday next week"
, "wednesday after next"
]
, examples (datetime (2013, 2, 22, 0, 0, 0) Day)
[ "friday after next"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "monday of this week"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "tuesday of this week"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "wednesday of this week"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "the day after tomorrow"
]
, examples (datetime (2013, 2, 14, 17, 0, 0) Hour)
[ "day after tomorrow 5pm"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "the day before yesterday"
]
, examples (datetime (2013, 2, 10, 8, 0, 0) Hour)
[ "day before yesterday 8am"
]
, examples (datetime (2013, 3, 25, 0, 0, 0) Day)
[ "last Monday of March"
]
, examples (datetime (2014, 3, 30, 0, 0, 0) Day)
[ "last Sunday of March 2014"
]
, examples (datetime (2013, 10, 3, 0, 0, 0) Day)
[ "third day of october"
]
, examples (datetime (2014, 10, 6, 0, 0, 0) Week)
[ "first week of october 2014"
]
, examples (datetime (2018, 12, 10, 0, 0, 0) Week)
[ "third last week of 2018"
, "the third last week of 2018"
, "the 3rd last week of 2018"
]
, examples (datetime (2018, 10, 15, 0, 0, 0) Week)
[ "2nd last week of October 2018"
, "the second last week of October 2018"
]
, examples (datetime (2013, 5, 27, 0, 0, 0) Day)
[ "fifth last day of May"
, "the 5th last day of May"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Week)
[ "the week of october 6th"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Week)
[ "the week of october 7th"
]
, examples (datetime (2015, 10, 31, 0, 0, 0) Day)
[ "last day of october 2015"
, "last day in october 2015"
]
, examples (datetime (2014, 9, 22, 0, 0, 0) Week)
[ "last week of september 2014"
]
, examples (datetime (2013, 10, 1, 0, 0, 0) Day)
[ "first tuesday of october"
, "first tuesday in october"
]
, examples (datetime (2014, 9, 16, 0, 0, 0) Day)
[ "third tuesday of september 2014"
]
, examples (datetime (2014, 10, 1, 0, 0, 0) Day)
[ "first wednesday of october 2014"
]
, examples (datetime (2014, 10, 8, 0, 0, 0) Day)
[ "second wednesday of october 2014"
]
, examples (datetime (2015, 1, 13, 0, 0, 0) Day)
[ "third tuesday after christmas 2014"
]
, examples (datetime (2013, 2, 13, 3, 0, 0) Hour)
[ "at 3am"
, "3 in the AM"
, "at 3 AM"
, "3 oclock am"
, "at three am"
, "this morning at 3"
, "3 in the morning"
, "at 3 in the morning"
, "early morning @ 3"
]
, examples (datetime (2013, 2, 12, 10, 0, 0) Hour)
[ "this morning @ 10"
, "this morning at 10am"
]
, examples (datetime (2013, 2, 13, 3, 18, 0) Minute)
[ "3:18am"
, "3:18a"
, "3h18"
]
, examples (datetime (2016, 2, 1, 7, 0, 0) Hour)
[ "at 7 in 3 years"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Hour)
[ "at 3pm"
, "@ 3pm"
, "3PM"
, "3pm"
, "3 oclock pm"
, "3 o'clock in the afternoon"
, "3ish pm"
, "3pm approximately"
, "at about 3pm"
, "at 3p"
, "at 3p."
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Minute)
[ "15h00"
, "at 15h00"
, "15h"
, "at 15h"
]
, examples (datetime (2013, 2, 12, 15, 15, 0) Minute)
[ "at 15 past 3pm"
, "a quarter past 3pm"
, "for a quarter past 3pm"
, "3:15 in the afternoon"
, "15:15"
, "15h15"
, "3:15pm"
, "3:15PM"
, "3:15p"
, "at 3 15"
, "15 minutes past 3pm"
, "15 minutes past 15h"
]
, examples (datetime (2013, 2, 12, 15, 20, 0) Minute)
[ "at 20 past 3pm"
, "3:20 in the afternoon"
, "3:20 in afternoon"
, "twenty after 3pm"
, "3:20p"
, "15h20"
, "at three twenty"
, "20 minutes past 3pm"
, "this afternoon at 3:20"
, "tonight @ 3:20"
]
, examples (datetime (2013, 2, 12, 15, 30, 0) Minute)
[ "at half past three pm"
, "half past 3 pm"
, "15:30"
, "15h30"
, "3:30pm"
, "3:30PM"
, "330 p.m."
, "3:30 p m"
, "3:30"
, "half three"
, "30 minutes past 3 pm"
]
, examples (datetime (2013, 2, 12, 12, 15, 0) Minute)
[ "at 15 past noon"
, "a quarter past noon"
, "for a quarter past noon"
, "12:15 in the afternoon"
, "12:15"
, "12h15"
, "12:15pm"
, "12:15PM"
, "12:15p"
, "at 12 15"
, "15 minutes past noon"
]
, examples (datetime (2013, 2, 12, 9, 59, 0) Minute)
[ "nine fifty nine a m"
]
, examples (datetime (2013, 2, 12, 15, 23, 24) Second)
[ "15:23:24"
]
, examples (datetime (2013, 2, 12, 9, 1, 10) Second)
[ "9:01:10 AM"
]
, examples (datetime (2013, 2, 12, 11, 45, 0) Minute)
[ "a quarter to noon"
, "11:45am"
, "11h45"
, "15 to noon"
]
, examples (datetime (2013, 2, 12, 13, 15, 0) Minute)
[ "a quarter past 1pm"
, "for a quarter past 1pm"
, "1:15pm"
, "13h15"
, "15 minutes from 1pm"
]
, examples (datetime (2013, 2, 12, 14, 15, 0) Minute)
[ "a quarter past 2pm"
, "for a quarter past 2pm"
]
, examples (datetime (2013, 2, 12, 20, 15, 0) Minute)
[ "a quarter past 8pm"
, "for a quarter past 8pm"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "8 tonight"
, "tonight at 8 o'clock"
, "eight tonight"
, "8 this evening"
, "at 8 in the evening"
, "in the evening at eight"
]
, examples (datetime (2013, 9, 20, 19, 30, 0) Minute)
[ "at 7:30 PM on Fri, Sep 20"
, "at 19h30 on Fri, Sep 20"
]
, examples (datetime (2013, 2, 16, 9, 0, 0) Hour)
[ "at 9am on Saturday"
, "Saturday morning at 9"
]
, examples (datetime (2013, 2, 16, 9, 0, 0) Hour)
[ "on Saturday for 9am"
]
, examples (datetime (2014, 7, 18, 19, 0, 0) Minute)
[ "Fri, Jul 18, 2014 07:00 PM"
, "Fri, Jul 18, 2014 19h00"
, "Fri, Jul 18, 2014 19h"
]
, examples (datetime (2013, 2, 12, 4, 30, 1) Second)
[ "in a sec"
, "one second from now"
, "in 1\""
]
, examples (datetime (2013, 2, 12, 4, 31, 0) Second)
[ "in a minute"
, "in one minute"
, "in 1'"
]
, examples (datetime (2013, 2, 12, 4, 32, 0) Second)
[ "in 2 minutes"
, "in 2 more minutes"
, "2 minutes from now"
, "in a couple of minutes"
, "in a pair of minutes"
]
, examples (datetime (2013, 2, 12, 4, 33, 0) Second)
[ "in three minutes"
, "in a few minutes"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Second)
[ "in 60 minutes"
]
, examples (datetime (2013, 2, 12, 4, 45, 0) Second)
[ "in a quarter of an hour"
, "in 1/4h"
, "in 1/4 h"
, "in 1/4 hour"
]
, examples (datetime (2013, 2, 12, 5, 0, 0) Second)
[ "in half an hour"
, "in 1/2h"
, "in 1/2 h"
, "in 1/2 hour"
]
, examples (datetime (2013, 2, 12, 5, 15, 0) Second)
[ "in three-quarters of an hour"
, "in 3/4h"
, "in 3/4 h"
, "in 3/4 hour"
]
, examples (datetime (2013, 2, 12, 7, 0, 0) Second)
[ "in 2.5 hours"
, "in 2 and an half hours"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "in one hour"
, "in 1h"
]
, examples (datetime (2013, 2, 12, 6, 30, 0) Minute)
[ "in a couple hours"
, "in a couple of hours"
]
, examples (datetime (2013, 2, 12, 7, 30, 0) Minute)
[ "in a few hours"
, "in few hours"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Minute)
[ "in 24 hours"
]
, examples (datetime (2013, 2, 13, 4, 0, 0) Hour)
[ "in a day"
, "a day from now"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Second)
[ "a day from right now"
]
, examples (datetime (2016, 2, 12, 0, 0, 0) Day)
[ "3 years from today"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "3 fridays from now"
, "three fridays from now"
]
, examples (datetime (2013, 2, 24, 0, 0, 0) Day)
[ "2 sundays from now"
, "two sundays from now"
]
, examples (datetime (2013, 3, 12, 0, 0, 0) Day)
[ "4 tuesdays from now"
, "four tuesdays from now"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "in 7 days"
]
, examples (datetime (2013, 2, 19, 17, 0, 0) Hour)
[ "in 7 days at 5pm"
]
, examples (datetime (2017, 2, 1, 17, 0, 0) Hour)
[ "in 4 years at 5pm"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "in 1 week"
, "in a week"
]
, examples (datetime (2013, 2, 12, 5, 0, 0) Second)
[ "in about half an hour"
]
, examples (datetime (2013, 2, 5, 4, 0, 0) Hour)
[ "7 days ago"
]
, examples (datetime (2013, 1, 29, 4, 0, 0) Hour)
[ "14 days Ago"
, "a fortnight ago"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "a week ago"
, "one week ago"
, "1 week ago"
]
, examples (datetime (2013, 1, 31, 0, 0, 0) Day)
[ "2 thursdays back"
, "2 thursdays ago"
]
, examples (datetime (2013, 1, 22, 0, 0, 0) Day)
[ "three weeks ago"
]
, examples (datetime (2012, 11, 12, 0, 0, 0) Day)
[ "three months ago"
]
, examples (datetime (2013, 02, 04, 0, 0, 0) Day)
[ "the first Monday of this month"
, "the first Monday of the month"
, "the first Monday in this month"
, "first Monday in the month"
]
, examples (datetime (2011, 2, 1, 0, 0, 0) Month)
[ "two years ago"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "7 days hence"
]
, examples (datetime (2013, 2, 26, 4, 0, 0) Hour)
[ "14 days hence"
, "a fortnight hence"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "a week hence"
, "one week hence"
, "1 week hence"
]
, examples (datetime (2013, 3, 5, 0, 0, 0) Day)
[ "three weeks hence"
]
, examples (datetime (2013, 5, 12, 0, 0, 0) Day)
[ "three months hence"
]
, examples (datetime (2015, 2, 1, 0, 0, 0) Month)
[ "two years hence"
]
, examples (datetime (2013, 12, 25, 0, 0, 0) Day)
[ "one year After christmas"
, "a year from Christmas"
]
, examples (datetimeInterval ((2013, 12, 18, 0, 0, 0), (2013, 12, 29, 0, 0, 0)) Day)
[ "for 10 days from 18th Dec"
, "from 18th Dec for 10 days"
, "18th Dec for 10 days"
]
, examples (datetimeInterval ((2013, 2, 12, 16, 0, 0), (2013, 2, 12, 16, 31, 0)) Minute)
[ "for 30' starting from 4pm"
, "from 4pm for thirty minutes"
, "4pm for 30 mins"
, "16h for 30 mins"
]
, examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day)
[ "this Summer"
, "current summer"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "this winter"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 19, 0, 0, 0)) Day)
[ "this season"
, "current seasons"
]
, examples (datetimeInterval ((2012, 9, 23, 0, 0, 0), (2012, 12, 20, 0, 0, 0)) Day)
[ "last season"
, "past seasons"
, "previous seasons"
]
, examples (datetimeInterval ((2013, 3, 20, 0, 0, 0), (2013, 6, 20, 0, 0, 0)) Day)
[ "next season"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "last night"
, "yesterday evening"
]
, examples (datetimeInterval ((2013, 2, 11, 21, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "late last night"
]
, examples (datetimeHoliday (2013, 12, 25, 0, 0, 0) Day "Christmas")
[ "xmas"
, "christmas"
, "christmas day"
]
, examples (datetimeHoliday (2013, 12, 25, 18, 0, 0) Hour "Christmas")
[ "xmas at 6 pm"
]
, examples (datetimeIntervalHoliday ((2013, 12, 25, 0, 0, 0), (2013, 12, 25, 12, 0, 0)) Hour "Christmas")
[ "morning of xmas"
, "morning of christmas 2013"
, "morning of this christmas day"
]
, examples (datetimeHoliday (2013, 12, 31, 0, 0, 0) Day "New Year's Eve")
[ "new year's eve"
, "new years eve"
]
, examples (datetimeHoliday (2014, 1, 1, 0, 0, 0) Day "New Year's Day")
[ "new year's day"
, "new years day"
]
, examples (datetimeHoliday (2013, 2, 14, 0, 0, 0) Day "Valentine's Day")
[ "valentine's day"
, "valentine day"
]
, examples (datetime (2013, 7, 4, 0, 0, 0) Day)
[ "4th of July"
, "4 of july"
]
, examples (datetimeHoliday (2013, 10, 31, 0, 0, 0) Day "Halloween")
[ "halloween"
, "next halloween"
, "Halloween 2013"
]
, examples (datetimeHoliday (2013, 11, 29, 0, 0, 0) Day "Black Friday")
[ "black friday"
, "black friday of this year"
, "black friday 2013"
]
, examples (datetimeHoliday (2017, 11, 24, 0, 0, 0) Day "Black Friday")
[ "black friday 2017"
]
, examples (datetimeHoliday (2013, 10, 16, 0, 0, 0) Day "Boss's Day")
[ "boss's day"
, "boss's"
, "boss day"
, "next boss's day"
]
, examples (datetimeHoliday (2016, 10, 17, 0, 0, 0) Day "Boss's Day")
[ "boss's day 2016"
]
, examples (datetimeHoliday (2021, 10, 15, 0, 0, 0) Day "Boss's Day")
[ "boss's day 2021"
]
, examples (datetimeHoliday (2014, 1, 20, 0, 0, 0) Day "Martin Luther King's Day")
[ "MLK day"
, "next Martin Luther King day"
, "next Martin Luther King's day"
, "next Martin Luther Kings day"
, "this MLK day"
]
, examples (datetimeHoliday (2013, 1, 21, 0, 0, 0) Day "Martin Luther King's Day")
[ "last MLK Jr. day"
, "MLK day 2013"
]
, examples (datetimeHoliday (2012, 1, 16, 0, 0, 0) Day "Martin Luther King's Day")
[ "MLK day of last year"
, "MLK day 2012"
, "Civil Rights Day of last year"
]
, examples (datetimeHoliday (2013, 11, 1, 0, 0, 0) Day "World Vegan Day")
[ "world vegan day"
]
, examples (datetimeHoliday (2013, 3, 31, 0, 0, 0) Day "Easter Sunday")
[ "easter"
, "easter 2013"
]
, examples (datetimeHoliday (2012, 4, 08, 0, 0, 0) Day "Easter Sunday")
[ "last easter"
]
, examples (datetimeHoliday (2013, 4, 1, 0, 0, 0) Day "Easter Monday")
[ "easter mon"
]
, examples (datetimeHoliday (2010, 4, 4, 0, 0, 0) Day "Easter Sunday")
[ "easter 2010"
, "Easter Sunday two thousand ten"
]
, examples (datetime (2013, 4, 3, 0, 0, 0) Day)
[ "three days after Easter"
]
, examples (datetimeHoliday (2013, 3, 28, 0, 0, 0) Day "Maundy Thursday")
[ "Maundy Thursday"
, "Covenant thu"
, "Thu of Mysteries"
]
, examples (datetimeHoliday (2013, 5, 19, 0, 0, 0) Day "Pentecost")
[ "Pentecost"
, "white sunday 2013"
]
, examples (datetimeHoliday (2013, 5, 20, 0, 0, 0) Day "Whit Monday")
[ "whit monday"
, "Monday of the Holy Spirit"
]
, examples (datetimeHoliday (2013, 3, 24, 0, 0, 0) Day "Palm Sunday")
[ "palm sunday"
, "branch sunday 2013"
]
, examples (datetimeHoliday (2013, 5, 26, 0, 0, 0) Day "Trinity Sunday")
[ "trinity sunday"
]
, examples (datetimeHoliday (2013, 2, 12, 0, 0, 0) Day "Shrove Tuesday")
[ "pancake day 2013"
, "mardi gras"
]
, examples (datetimeHoliday (2013, 3, 17, 0, 0, 0) Day "St Patrick's Day")
[ "st patrick's day 2013"
, "st paddy's day"
, "saint paddy's day"
, "saint patricks day"
]
, examples (datetimeIntervalHoliday ((2018, 2, 14, 0, 0, 0), (2018, 4, 1, 0, 0, 0)) Day "Lent")
[ "lent 2018"
]
, examples (datetimeHoliday (2018, 4, 8, 0, 0, 0) Day "Orthodox Easter Sunday")
[ "orthodox easter 2018"
]
, examples (datetimeHoliday (2020, 4, 17, 0, 0, 0) Day "Orthodox Good Friday")
[ "orthodox good friday 2020"
, "orthodox great friday 2020"
]
, examples (datetimeHoliday (2018, 2, 19, 0, 0, 0) Day "Clean Monday")
[ "clean monday 2018"
, "orthodox shrove monday two thousand eighteen"
]
, examples (datetimeHoliday (2018, 3, 31, 0, 0, 0) Day "Lazarus Saturday")
[ "lazarus saturday 2018"
]
, examples (datetimeIntervalHoliday ((2018, 2, 19, 0, 0, 0), (2018, 3, 31, 0, 0, 0)) Day "Great Lent")
[ "great fast 2018"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "this evening"
, "today evening"
, "tonight"
]
, examples (datetimeInterval ((2013, 2, 8, 18, 0, 0), (2013, 2, 11, 0, 0, 0)) Hour)
[ "this past weekend"
]
, examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour)
[ "tomorrow evening"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 14, 0, 0)) Hour)
[ "tomorrow lunch"
, "tomorrow at lunch"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "yesterday evening"
]
, examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour)
[ "this week-end"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour)
[ "monday mOrnIng"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 18, 9, 0, 0)) Hour)
[ "monday early in the morning"
, "monday early morning"
, "monday in the early hours of the morning"
]
, examples (datetimeInterval ((2013, 2, 12, 21, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "late tonight"
, "late tonite"
]
, examples (datetimeInterval ((2013, 2, 15, 0, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour)
[ "february the 15th in the morning"
, "15 of february in the morning"
, "morning of the 15th of february"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second)
[ "last 2 seconds"
, "last two seconds"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second)
[ "next 3 seconds"
, "next three seconds"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute)
[ "last 2 minutes"
, "last two minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute)
[ "next 3 minutes"
, "next three minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 3, 0, 0), (2013, 2, 12, 4, 0, 0)) Hour)
[ "last 1 hour"
, "last one hour"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "next 3 hours"
, "next three hours"
]
, examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day)
[ "last 2 days"
, "last two days"
, "past 2 days"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "next 3 days"
, "next three days"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "next few days"
]
, examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week)
[ "last 2 weeks"
, "last two weeks"
, "past 2 weeks"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week)
[ "next 3 weeks"
, "next three weeks"
]
, examples (datetimeInterval ((2012, 12, 1, 0, 0, 0), (2013, 2, 1, 0, 0, 0)) Month)
[ "last 2 months"
, "last two months"
]
, examples (datetimeInterval ((2013, 3, 1, 0, 0, 0), (2013, 6, 1, 0, 0, 0)) Month)
[ "next 3 months"
, "next three months"
]
, examples (datetimeInterval ((2011, 1, 1, 0, 0, 0), (2013, 1, 1, 0, 0, 0)) Year)
[ "last 2 years"
, "last two years"
]
, examples (datetimeInterval ((2014, 1, 1, 0, 0, 0), (2017, 1, 1, 0, 0, 0)) Year)
[ "next 3 years"
, "next three years"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "July 13-15"
, "July 13 to 15"
, "July 13 thru 15"
, "July 13 through 15"
, "July 13 - July 15"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "from July 13-15"
, "from 13 to 15 July"
, "from 13th to 15th July"
, "from the 13 to 15 July"
, "from the 13th to 15th July"
, "from the 13th to the 15th July"
, "from the 13 to the 15 July"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "from 13 to 15 of July"
, "from 13th to 15 of July"
, "from 13 to 15th of July"
, "from 13th to 15th of July"
, "from 13 to the 15 of July"
, "from 13th to the 15 of July"
, "from 13 to the 15th of July"
, "from 13th to the 15th of July"
, "from the 13 to the 15 of July"
, "from the 13th to the 15 of July"
, "from the 13 to the 15th of July"
, "from the 13th to the 15th of July"
]
, examples (datetimeInterval ((2013, 8, 8, 0, 0, 0), (2013, 8, 13, 0, 0, 0)) Day)
[ "Aug 8 - Aug 12"
]
, examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute)
[ "9:30 - 11:00"
, "9h30 - 11h00"
, "9h30 - 11h"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 30, 0), (2013, 2, 12, 15, 1, 0)) Minute)
[ "9:30 - 11:00 CST"
, "9h30 - 11h00 CST"
, "9h30 - 11h CST"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 0, 0), (2013, 2, 12, 16, 1, 0)) Minute)
[ "15:00 GMT - 18:00 GMT"
, "15h00 GMT - 18h00 GMT"
, "15h GMT - 18h GMT"
]
, examples (datetimeInterval
((2015, 3, 28, 17, 00, 0), (2015, 3, 29, 21, 0, 1)) Second)
[ "2015-03-28 17:00:00/2015-03-29 21:00:00"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 11, 1, 0)) Minute)
[ "from 9:30 - 11:00 on Thursday"
, "between 9:30 and 11:00 on thursday"
, "between 9h30 and 11h00 on thursday"
, "9:30 - 11:00 on Thursday"
, "9h30 - 11h00 on Thursday"
, "later than 9:30 but before 11:00 on Thursday"
, "Thursday from 9:30 to 11:00"
, "from 9:30 untill 11:00 on thursday"
, "Thursday from 9:30 untill 11:00"
, "9:30 till 11:00 on Thursday"
]
, examples (datetimeInterval ((2013, 2, 13, 1, 0, 0), (2013, 2, 13, 2, 31, 0)) Minute)
[ "tomorrow in between 1-2:30 ish"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 17, 0, 0)) Hour)
[ "3-4pm"
, "from 3 to 4 in the PM"
, "around 3-4pm"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 30, 0), (2013, 2, 12, 18, 1, 0)) Minute)
[ "3:30 to 6 PM"
, "3:30-6 p.m."
, "3:30-6:00pm"
, "15h30-18h"
, "from 3:30 to six p.m."
, "from 3:30 to 6:00pm"
, "later than 3:30pm but before 6pm"
, "between 3:30pm and 6 pm"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 18, 0, 1)) Second)
[ "3pm - 6:00:00pm"
]
, examples (datetimeInterval ((2013, 2, 12, 8, 0, 0), (2013, 2, 12, 14, 0, 0)) Hour)
[ "8am - 1pm"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 0, 0), (2013, 2, 14, 12, 0, 0)) Hour)
[ "Thursday from 9a to 11a"
, "this Thu 9-11am"
]
, examples (datetimeInterval ((2013, 2, 12, 11, 30, 0), (2013, 2, 12, 13, 31, 0)) Minute)
[ "11:30-1:30"
]
, examples (datetime (2013, 9, 21, 13, 30, 0) Minute)
[ "1:30 PM on Sat, Sep 21"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 26, 0, 0, 0)) Second)
[ "Within 2 weeks"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 14, 0, 0)) Second)
[ "by 2:00pm"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 13, 0, 0, 0)) Second)
[ "by EOD"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 3, 1, 0, 0, 0)) Second)
[ "by EOM"
, "by the EOM"
, "by end of the month"
, "by the end of month"
]
, examples (datetimeInterval ((2013, 2, 21, 0, 0, 0), (2013, 3, 1, 0, 0, 0)) Day)
[ "EOM"
, "the EOM"
, "at the EOM"
, "the end of the month"
, "end of the month"
, "at the end of month"
]
, examples (datetimeInterval ((2013, 2, 1, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Day)
[ "BOM"
, "the BOM"
, "at the BOM"
, "beginning of the month"
, "the beginning of the month"
, "at the beginning of month"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 4, 1, 0, 0, 0)) Second)
[ "by the end of next month"
]
, examples (datetime (2013, 2, 12, 13, 0, 0) Minute)
[ "4pm CET"
]
, examples (datetime (2013, 2, 14, 6, 0, 0) Minute)
[ "Thursday 8:00 GMT"
, "Thursday 8:00 gmt"
, "Thursday 8h00 GMT"
, "Thursday 8h00 gmt"
, "Thursday 8h GMT"
, "Thursday 8h gmt"
, "Thu at 8 GMT"
, "Thu at 8 gmt"
, "Thursday 9 am BST"
, "Thursday 9 am (BST)"
]
, examples (datetime (2013, 2, 14, 14, 0, 0) Minute)
[ "Thursday 8:00 PST"
, "Thursday 8:00 pst"
, "Thursday 8h00 PST"
, "Thursday 8h00 pst"
, "Thursday 8h PST"
, "Thursday 8h pst"
, "Thu at 8 am PST"
, "Thu at 8 am pst"
, "Thursday at 9:30pm ist"
]
, examples (datetime (2013, 2, 12, 14, 0, 0) Hour)
[ "today at 2pm"
, "at 2pm"
, "this afternoon at 2"
, "this evening at 2"
, "tonight at 2"
]
, examples (datetime (2013, 2, 13, 15, 0, 0) Hour)
[ "3pm tomorrow"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "today in one hour"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 4, 30, 0) Second)
[ "ASAP"
, "as soon as possible"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 14, 0, 0) Minute)
[ "until 2:00pm"
, "through 2:00pm"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 14, 0, 0) Hour)
[ "after 2 pm"
, "from 2 pm"
, "since 2pm"
]
, examples (datetimeOpenInterval After (2014, 1, 1, 0, 0, 0) Year)
[ "anytime after 2014"
, "since 2014"
]
, examples (datetimeOpenInterval Before (2014, 1, 1, 0, 0, 0) Year)
[ "sometimes before 2014"
, "through 2014"
]
, examples (datetimeOpenInterval After (2013, 2, 17, 4, 0, 0) Hour)
[ "after 5 days"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 11, 0, 0) Hour)
[ "before 11 am"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "in the afternoon"
]
, examples (datetimeInterval ((2013, 2, 12, 8, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "8am until 6"
]
, examples (datetime (2013, 2, 12, 13, 30, 0) Minute)
[ "at 1:30pm"
, "1:30pm"
, "at 13h30"
, "13h30"
]
, examples (datetime (2013, 2, 12, 4, 45, 0) Second)
[ "in 15 minutes"
, "in 15'"
, "in 15"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 0, 0), (2013, 2, 12, 17, 0, 0)) Hour)
[ "after lunch"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 21, 0, 0)) Hour)
[ "after school"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "10:30"
, "approximately 1030"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "this morning"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "next monday"
]
, examples (datetime (2013, 2, 12, 12, 0, 0) Hour)
[ "at 12pm"
, "at noon"
, "midday"
, "the midday"
, "mid day"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Hour)
[ "at 12am"
, "at midnight"
, "this morning at 12"
, "this evening at 12"
, "this afternoon at 12"
]
, examples (datetime (2013, 2, 13, 9, 0, 0) Hour)
[ "9 tomorrow morning"
, "9 tomorrow"
]
, examples (datetime (2013, 2, 13, 21, 0, 0) Hour)
[ "9 tomorrow evening"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "March"
, "in March"
, "during March"
]
, examples (datetime (2013, 2, 13, 17, 0, 0) Hour)
[ "tomorrow afternoon at 5"
, "at 5 tomorrow afternoon"
, "at 5pm tomorrow"
, "tomorrow at 5pm"
, "tomorrow evening at 5"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 19, 0, 0)) Hour)
[ "tomorrow afternoon"
, "tomorrow afternoonish"
]
, examples (datetimeInterval ((2013, 2, 13, 13, 0, 0), (2013, 2, 13, 15, 0, 0)) Hour)
[ "1pm-2pm tomorrow"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "on the first"
, "the 1st"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "at 1030"
, "around 1030"
, "ten thirty am"
]
, examples (datetime (2013, 2, 12, 19, 30, 0) Minute)
[ "at 730 in the evening"
, "seven thirty p.m."
]
, examples (datetime (2013, 2, 13, 1, 50, 0) Minute)
[ "tomorrow at 150ish"
]
, examples (datetime (2013, 2, 12, 23, 0, 0) Hour)
[ "tonight at 11"
, "this evening at 11"
, "this afternoon at 11"
, "tonight at 11pm"
]
, examples (datetime (2013, 2, 12, 4, 23, 0) Minute)
-- yes, the result is in the past, we may need to revisit
[ "at 4:23"
, "4:23am"
, "four twenty-three a m"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Day)
[ "the closest Monday to Oct 5th"
]
, examples (datetime (2013, 9, 30, 0, 0, 0) Day)
[ "the second closest Mon to October fifth"
]
, examples (datetimeInterval ((2013, 3, 1, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Day)
[ "early March"
]
, examples (datetimeInterval ((2013, 3, 11, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "mid March"
]
, examples (datetimeInterval ((2013, 3, 21, 0, 0, 0), (2013, 4, 1, 0, 0, 0)) Day)
[ "late March"
]
, examples (datetimeInterval ((2013, 10, 25, 18, 0, 0), (2013, 10, 28, 0, 0, 0)) Hour)
[ "last weekend of October"
, "last week-end in October"
, "last week end of October"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "all week"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "rest of the week"
]
, examples (datetimeInterval ((2013, 7, 26, 18, 0, 0), (2013, 7, 29, 0, 0, 0)) Hour)
[ "last wkend of July"
]
, examples (datetimeInterval ((2017, 10, 27, 18, 0, 0), (2017, 10, 30, 0, 0, 0)) Hour)
[ "last weekend of October 2017"
]
, examples (datetimeInterval ((2013, 8, 27, 0, 0, 0), (2013, 8, 30, 0, 0, 0)) Day)
[ "August 27th - 29th"
, "from August 27th - 29th"
]
, examples (datetimeInterval ((2013, 10, 23, 0, 0, 0), (2013, 10, 27, 0, 0, 0)) Day)
[ "23rd to 26th Oct"
]
, examples (datetimeInterval ((2013, 9, 1, 0, 0, 0), (2013, 9, 9, 0, 0, 0)) Day)
[ "1-8 september"
]
, examples (datetimeInterval ((2013, 9, 12, 0, 0, 0), (2013, 9, 17, 0, 0, 0)) Day)
[ "12 to 16 september"
]
, examples (datetimeInterval ((2013, 8, 19, 0, 0, 0), (2013, 8, 22, 0, 0, 0)) Day)
[ "19th To 21st aug"
]
, examples (datetimeInterval ((2013, 4, 21, 0, 0, 0), (2013, 5, 1, 0, 0, 0)) Day)
[ "end of April"
, "at the end of April"
]
, examples (datetimeInterval ((2014, 1, 1, 0, 0, 0), (2014, 1, 11, 0, 0, 0)) Day)
[ "beginning of January"
, "at the beginning of January"
]
, examples (datetimeInterval ((2012, 9, 1, 0, 0, 0), (2013, 1, 1, 0, 0, 0)) Month)
[ "end of 2012"
, "at the end of 2012"
]
, examples (datetimeInterval ((2017, 1, 1, 0, 0, 0), (2017, 4, 1, 0, 0, 0)) Month)
[ "beginning of 2017"
, "at the beginning of 2017"
]
, examples (datetimeInterval ((2013, 1, 1, 0, 0, 0), (2013, 4, 1, 0, 0, 0)) Month)
[ "beginning of year"
, "the beginning of the year"
, "the BOY"
, "BOY"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2014, 1, 1, 0, 0, 0)) Second)
[ "by EOY"
, "by the EOY"
, "by end of the year"
, "by the end of year"
]
, examples (datetimeInterval ((2013, 9, 1, 0, 0, 0), (2014, 1, 1, 0, 0, 0)) Month)
[ "EOY"
, "the EOY"
, "at the EOY"
, "the end of the year"
, "end of the year"
, "at the end of year"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 14, 0, 0, 0)) Day)
[ "beginning of this week"
, "beginning of current week"
, "at the beginning of this week"
, "at the beginning of current week"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 21, 0, 0, 0)) Day)
[ "beginning of coming week"
, "at the beginning of coming week"
]
, examples (datetimeInterval ((2013, 2, 4, 0, 0, 0), (2013, 2, 7, 0, 0, 0)) Day)
[ "beginning of last week"
, "beginning of past week"
, "beginning of previous week"
, "at the beginning of last week"
, "at the beginning of past week"
, "at the beginning of previous week"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 21, 0, 0, 0)) Day)
[ "beginning of next week"
, "beginning of the following week"
, "beginning of around next week"
, "at the beginning of next week"
, "at the beginning of the following week"
, "at the beginning of around next week"
]
, examples (datetimeInterval ((2013, 2, 15, 0, 0, 0), (2013, 2, 18, 0, 0, 0)) Day)
[ "end of this week"
, "end of current week"
, "at the end of this week"
, "at the end of current week"
]
, examples (datetimeInterval ((2013, 2, 22, 0, 0, 0), (2013, 2, 25, 0, 0, 0)) Day)
[ "end of coming week"
, "at the end of coming week"
]
, examples (datetimeInterval ((2013, 2, 8, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Day)
[ "end of last week"
, "end of past week"
, "end of previous week"
, "at the end of last week"
, "at the end of past week"
, "at the end of previous week"
]
, examples (datetimeInterval ((2013, 2, 22, 0, 0, 0), (2013, 2, 25, 0, 0, 0)) Day)
[ "end of next week"
, "end of the following week"
, "end of around next week"
, "at the end of next week"
, "at the end of the following week"
, "at the end of around next week"
]
, examples (datetimeHoliday (2014, 1, 31, 0, 0, 0) Day "Chinese New Year")
[ "chinese new year"
, "chinese lunar new year's day"
]
, examples (datetimeHoliday (2013, 2, 10, 0, 0, 0) Day "Chinese New Year")
[ "last chinese new year"
, "last chinese lunar new year's day"
, "last chinese new years"
]
, examples (datetimeHoliday (2018, 2, 16, 0, 0, 0) Day "Chinese New Year")
[ "chinese new year's day 2018"
]
, examples (datetimeHoliday (2018, 9, 18, 0, 0, 0) Day "Yom Kippur")
[ "yom kippur 2018"
]
, examples (datetimeHoliday (2018, 9, 30, 0, 0, 0) Day "Shemini Atzeret")
[ "shemini atzeret 2018"
]
, examples (datetimeHoliday (2018, 10, 1, 0, 0, 0) Day "Simchat Torah")
[ "simchat torah 2018"
]
, examples (datetimeHoliday (2018, 7, 21, 0, 0, 0) Day "Tisha B'Av")
[ "tisha b'av 2018"
]
, examples (datetimeHoliday (2018, 4, 18, 0, 0, 0) Day "Yom Ha'atzmaut")
[ "yom haatzmaut 2018"
]
, examples (datetimeHoliday (2017, 5, 13, 0, 0, 0) Day "Lag BaOmer")
[ "lag b'omer 2017"
]
, examples (datetimeHoliday (2018, 4, 11, 0, 0, 0) Day "Yom HaShoah")
[ "Yom Hashoah 2018"
, "Holocaust Day 2018"
]
, examples (datetimeIntervalHoliday ((2018, 9, 9, 0, 0, 0), (2018, 9, 12, 0, 0, 0)) Day "Rosh Hashanah")
[ "rosh hashanah 2018"
, "rosh hashana 2018"
, "rosh hashanna 2018"
]
, examples (datetimeIntervalHoliday ((2018, 12, 2, 0, 0, 0), (2018, 12, 10, 0, 0, 0)) Day "Hanukkah")
[ "Chanukah 2018"
, "hanukah 2018"
, "hannukkah 2018"
]
, examples (datetimeIntervalHoliday ((2018, 3, 30, 0, 0, 0), (2018, 4, 8, 0, 0, 0)) Day "Passover")
[ "passover 2018"
]
, examples (datetimeIntervalHoliday ((2018, 9, 23, 0, 0, 0), (2018, 10, 2, 0, 0, 0)) Day "Sukkot")
[ "feast of the ingathering 2018"
, "succos 2018"
]
, examples (datetimeIntervalHoliday ((2018, 5, 19, 0, 0, 0), (2018, 5, 22, 0, 0, 0)) Day "Shavuot")
[ "shavuot 2018"
]
, examples (datetimeHoliday (2017, 11, 30, 0, 0, 0) Day "Mawlid")
[ "mawlid al-nabawi 2017"
]
, examples (datetimeHoliday (1950, 7, 16, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1950"
]
, examples (datetimeHoliday (1975, 10, 6, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1975"
]
, examples (datetimeHoliday (1988, 5, 16, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1988"
]
, examples (datetimeHoliday (2018, 6, 15, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2018"
]
, examples (datetimeHoliday (2034, 12, 12, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2034"
]
, examples (datetimeHoliday (2046, 8, 4, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2046"
]
, examples (datetimeHoliday (2050, 6, 21, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2050"
]
, examples (datetimeHoliday (2018, 8, 21, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 2018"
, "id ul-adha 2018"
, "sacrifice feast 2018"
, "Bakr Id 2018"
]
, examples (datetimeHoliday (1980, 10, 19, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1980"
, "id ul-adha 1980"
, "sacrifice feast 1980"
, "Bakr Id 1980"
]
, examples (datetimeHoliday (1966, 4, 1, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1966"
, "id ul-adha 1966"
, "sacrifice feast 1966"
, "Bakr Id 1966"
]
, examples (datetimeHoliday (1974, 1, 3, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1974"
, "id ul-adha 1974"
, "sacrifice feast 1974"
, "Bakr Id 1974"
]
, examples (datetimeHoliday (2017, 6, 22, 0, 0, 0) Day "Laylat al-Qadr")
[ "laylat al kadr 2017"
, "night of measures 2017"
]
, examples (datetimeHoliday (2018, 6, 11, 0, 0, 0) Day "Laylat al-Qadr")
[ "laylat al-qadr 2018"
, "night of power 2018"
]
, examples (datetimeHoliday (2018, 9, 11, 0, 0, 0) Day "Islamic New Year")
[ "Islamic New Year 2018"
, "Amun Jadid 2018"
]
, examples (datetimeHoliday (2017, 9, 30, 0, 0, 0) Day "Ashura")
[ "day of Ashura 2017"
]
, examples (datetimeHoliday (2018, 1, 30, 0, 0, 0) Day "Tu BiShvat")
[ "tu bishvat 2018"
]
, examples (datetimeHoliday (2017, 6, 23, 0, 0, 0) Day "Jumu'atul-Wida")
[ "Jamat Ul-Vida 2017"
, "Jumu'atul-Wida 2017"
]
, examples (datetimeHoliday (2018, 6, 8, 0, 0, 0) Day "Jumu'atul-Wida")
[ "Jamat Ul-Vida 2018"
, "Jumu'atul-Wida 2018"
]
, examples (datetimeHoliday (2018, 4, 13, 0, 0, 0) Day "Isra and Mi'raj")
[ "isra and mi'raj 2018"
, "the prophet's ascension 2018"
]
, examples (datetimeHoliday (2019, 4, 3, 0, 0, 0) Day "Isra and Mi'raj")
[ "the night journey 2019"
, "ascension to heaven 2019"
]
, examples (datetimeIntervalHoliday ((1950, 6, 17, 0, 0, 0), (1950, 7, 16, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 1950"
]
, examples (datetimeIntervalHoliday ((1977, 8, 15, 0, 0, 0), (1977, 9, 14, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 1977"
]
, examples (datetimeIntervalHoliday ((2018, 5, 16, 0, 0, 0), (2018, 6, 15, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2018"
]
, examples (datetimeIntervalHoliday ((2034, 11, 12, 0, 0, 0), (2034, 12, 12, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2034"
]
, examples (datetimeIntervalHoliday ((2046, 7, 5, 0, 0, 0), (2046, 8, 4, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2046"
]
, examples (datetimeIntervalHoliday ((2050, 5, 22, 0, 0, 0), (2050, 6, 21, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2050"
]
, examples (datetimeHoliday (2017, 10, 17, 0, 0, 0) Day "Dhanteras")
[ "dhanatrayodashi in 2017"
]
, examples (datetimeHoliday (2019, 10, 25, 0, 0, 0) Day "Dhanteras")
[ "dhanteras 2019"
]
, examples (datetimeHoliday (2019, 10, 26, 0, 0, 0) Day "Naraka Chaturdashi")
[ "kali chaudas 2019"
, "choti diwali two thousand nineteen"
]
, examples (datetimeHoliday (2019, 10, 27, 0, 0, 0) Day "Diwali")
[ "diwali 2019"
, "Deepavali in 2019"
, "Lakshmi Puja six years hence"
]
, examples (datetimeHoliday (2019, 10, 29, 0, 0, 0) Day "Bhai Dooj")
[ "bhai dooj 2019"
]
, examples (datetimeHoliday (2019, 11, 2, 0, 0, 0) Day "Chhath")
[ "chhath 2019"
, "dala puja 2019"
, "Surya Shashthi in 2019"
]
, examples (datetimeHoliday (2021, 10, 12, 0, 0, 0) Day "Maha Saptami")
[ "Maha Saptami 2021"
]
, examples (datetimeHoliday (2018, 10, 18, 0, 0, 0) Day "Vijayadashami")
[ "Dussehra 2018"
, "vijayadashami in five years"
]
, examples (datetimeIntervalHoliday ((2018, 10, 9, 0, 0, 0), (2018, 10, 19, 0, 0, 0)) Day "Navaratri")
[ "navaratri 2018"
, "durga puja in 2018"
]
, examples (datetimeHoliday (2018, 10, 27, 0, 0, 0) Day "Karva Chauth")
[ "karva chauth 2018"
, "karva chauth in 2018"
]
, examples (datetimeHoliday (2018, 7, 14, 0, 0, 0) Day "Ratha-Yatra")
[ "ratha-yatra 2018"
]
, examples (datetimeHoliday (2018, 8, 26, 0, 0, 0) Day "Raksha Bandhan")
[ "rakhi 2018"
]
, examples (datetimeHoliday (2020, 4, 6, 0, 0, 0) Day "Mahavir Jayanti")
[ "mahavir jayanti 2020"
, "mahaveer janma kalyanak 2020"
]
, examples (datetimeHoliday (2020, 2, 21, 0, 0, 0) Day "Maha Shivaratri")
[ "maha shivaratri 2020"
]
, examples (datetimeHoliday (2018, 2, 10, 0, 0, 0) Day "Dayananda Saraswati Jayanti")
[ "saraswati jayanti 2018"
]
, examples (datetimeHoliday (2018, 1, 14, 0, 0, 0) Day "Thai Pongal")
[ "pongal 2018"
, "makara sankranthi 2018"
]
, examples (datetimeHoliday (2018, 1, 13, 0, 0, 0) Day "Boghi")
[ "bogi pandigai 2018"
]
, examples (datetimeHoliday (2018, 1, 15, 0, 0, 0) Day "Mattu Pongal")
[ "maattu pongal 2018"
]
, examples (datetimeHoliday (2018, 1, 16, 0, 0, 0) Day "Kaanum Pongal")
[ "kaanum pongal 2018"
, "kanni pongal 2018"
]
, examples (datetimeHoliday (2019, 1, 15, 0, 0, 0) Day "Thai Pongal")
[ "makar sankranti 2019"
, "maghi in 2019"
]
, examples (datetimeHoliday (2018, 4, 14, 0, 0, 0) Day "Vaisakhi")
[ "Vaisakhi 2018"
, "baisakhi in 2018"
, "Vasakhi 2018"
, "vaishakhi 2018"
]
, examples (datetimeHoliday (2018, 8, 24, 0, 0, 0) Day "Thiru Onam")
[ "onam 2018"
, "Thiru Onam 2018"
, "Thiruvonam 2018"
]
, examples (datetimeHoliday (2019, 2, 10, 0, 0, 0) Day "Vasant Panchami")
[ "vasant panchami in 2019"
, "basant panchami 2019"
]
, examples (datetimeHoliday (2019, 3, 20, 0, 0, 0) Day "Holika Dahan")
[ "chhoti holi 2019"
, "holika dahan 2019"
, "kamudu pyre 2019"
]
, examples (datetimeHoliday (2019, 8, 23, 0, 0, 0) Day "Krishna Janmashtami")
[ "krishna janmashtami 2019"
, "gokulashtami 2019"
]
, examples (datetimeHoliday (2019, 3, 21, 0, 0, 0) Day "Holi")
[ "holi 2019"
, "dhulandi 2019"
, "phagwah 2019"
]
, examples (datetimeHoliday (2018, 8, 17, 0, 0, 0) Day "Parsi New Year")
[ "Parsi New Year 2018"
, "Jamshedi Navroz 2018"
]
, examples (datetimeHoliday (2022, 8, 16, 0, 0, 0) Day "Parsi New Year")
[ "jamshedi Navroz 2022"
, "parsi new year 2022"
]
, examples (datetimeIntervalHoliday ((2013, 4, 26, 0, 0, 0), (2013, 4, 29, 0, 0, 0)) Day "Global Youth Service Day")
[ "GYSD 2013"
, "global youth service day"
]
, examples (datetimeHoliday (2013, 5, 24, 0, 0, 0) Day "Vesak")
[ "vesak"
, "vaisakha"
, "Buddha day"
, "Buddha Purnima"
]
, examples (datetimeIntervalHoliday ((2013, 3, 23, 20, 30, 0), (2013, 3, 23, 21, 31, 0)) Minute "Earth Hour")
[ "earth hour"
]
, examples (datetimeIntervalHoliday ((2016, 3, 19, 20, 30, 0), (2016, 3, 19, 21, 31, 0)) Minute "Earth Hour")
[ "earth hour 2016"
]
, examples (datetimeHoliday (2013, 2, 23, 0, 0, 0) Day "Purim")
[ "purim"
]
, examples (datetimeHoliday (2013, 2, 24, 0, 0, 0) Day "Shushan Purim")
[ "Shushan Purim"
]
, examples (datetimeHoliday (2014, 1, 7, 0, 0, 0) Day "Guru Gobind Singh Jayanti")
[ "guru gobind singh birthday"
, "guru gobind singh jayanti 2014"
, "guru gobind singh jayanti"
, "Guru Govind Singh Jayanti"
]
, examples (datetimeHoliday (2018, 4, 27, 0, 0, 0) Day "King's Day")
[ "Koningsdag 2018"
, "koningsdag 2018"
, "king's day 2018"
, "King's Day 2018"
]
, examples (datetimeHoliday (2014, 4, 26, 0, 0, 0) Day "King's Day")
[ "Koningsdag 2014"
, "koningsdag 2014"
, "King's Day 2014"
, "king's day 2014"
]
, examples (datetimeHoliday (2018, 5, 9, 0, 0, 0) Day "Rabindra Jayanti")
[ "rabindra jayanti 2018"
, "Rabindranath Jayanti 2018"
, "Rabindra Jayanti 2018"
]
, examples (datetimeHoliday (2019, 5, 9, 0, 0, 0) Day "Rabindra Jayanti")
[ "rabindra jayanti 2019"
, "Rabindranath Jayanti 2019"
, "Rabindra Jayanti 2019"
]
, examples (datetimeHoliday (2018, 1, 31, 0, 0, 0) Day "Guru Ravidass Jayanti")
[ "guru Ravidas jayanti 2018"
, "Guru Ravidass birthday 2018"
, "guru ravidass Jayanti 2018"
]
, examples (datetimeHoliday (2019, 2, 19, 0, 0, 0) Day "Guru Ravidass Jayanti")
[ "Guru Ravidass Jayanti 2019"
, "Guru Ravidas Birthday 2019"
, "guru ravidas jayanti 2019"
]
, examples (datetimeHoliday (2019, 10, 13, 0, 0, 0) Day "Pargat Diwas")
[ "valmiki jayanti 2019"
, "Valmiki Jayanti 2019"
, "pargat diwas 2019"
]
, examples (datetimeHoliday (2018, 10, 24, 0, 0, 0) Day "Pargat Diwas")
[ "maharishi valmiki jayanti 2018"
, "pargat diwas 2018"
, "Pargat Diwas 2018"
]
, examples (datetimeHoliday (2019, 9, 2, 0, 0, 0) Day "Ganesh Chaturthi")
[ "ganesh chaturthi 2019"
]
, examples (datetimeHoliday (2020, 4, 2, 0, 0, 0) Day "Rama Navami")
[ "rama navami 2020"
]
, examples (datetimeHoliday (2018, 3, 18, 0, 0, 0) Day "Ugadi")
[ "Ugadi 2018"
, "ugadi 2018"
, "yugadi 2018"
, "Yugadi 2018"
, "samvatsaradi 2018"
, "chaitra sukladi 2018"
, "chaitra sukhladi 2018"
]
, examples (datetimeHoliday (2012, 12, 25, 0, 0, 0) Day "Christmas")
[ "the closest xmas to today"
]
, examples (datetimeHoliday (2013, 12, 25, 0, 0, 0) Day "Christmas")
[ "the second closest xmas to today"
]
, examples (datetimeHoliday (2011, 12, 25, 0, 0, 0) Day "Christmas")
[ "the 3rd closest xmas to today"
]
, examples (datetime (2013, 10, 25, 0, 0, 0) Day)
[ "last friday of october"
, "last friday in october"
]
, examples (datetime (2013, 2, 25, 0, 0, 0) Week)
[ "upcoming two weeks"
, "upcoming two week"
, "upcoming 2 weeks"
, "upcoming 2 week"
, "two upcoming weeks"
, "two upcoming week"
, "2 upcoming weeks"
, "2 upcoming week"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "upcoming two days"
, "upcoming two day"
, "upcoming 2 days"
, "upcoming 2 day"
, "two upcoming days"
, "two upcoming day"
, "2 upcoming days"
, "2 upcoming day"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Month)
[ "upcoming two months"
, "upcoming two month"
, "upcoming 2 months"
, "upcoming 2 month"
, "two upcoming months"
, "two upcoming month"
, "2 upcoming months"
, "2 upcoming month"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "upcoming two quarters"
, "upcoming two quarter"
, "upcoming 2 quarters"
, "upcoming 2 quarter"
, "two upcoming quarters"
, "two upcoming quarter"
, "2 upcoming quarters"
, "2 upcoming quarter"
]
, examples (datetime (2015, 1, 1, 0, 0, 0) Year)
[ "upcoming two years"
, "upcoming two year"
, "upcoming 2 years"
, "upcoming 2 year"
, "two upcoming years"
, "two upcoming year"
, "2 upcoming years"
, "2 upcoming year"
]
, examples (datetime (2013, 2, 13, 13, 40, 0) Minute)
[ "20 minutes to 2pm tomorrow"
]
, examples (datetime (2013, 1, 7, 0, 0, 0) Day)
[
"first monday of last month"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Day)
[
"first tuesday of last month"
]
, examples (datetime (2013, 1, 14, 0, 0, 0) Day)
[
"second monday of last month"
]
, examples (datetime (2013, 2, 23, 0, 0, 0) Day)
[ "next saturday" ]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "next monday" ]
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/Duckling/Time/EN/Corpus.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings #
yes, the result is in the past, we may need to revisit | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.Time.EN.Corpus
( corpus
, defaultCorpus
, negativeCorpus
, latentCorpus
, diffCorpus
) where
import Data.String
import Prelude
import Duckling.Core
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.Corpus
import Duckling.Time.Types hiding (Month, refTime)
import Duckling.TimeGrain.Types hiding (add)
corpus :: Corpus
corpus = (testContext, testOptions, allExamples)
defaultCorpus :: Corpus
defaultCorpus = (testContext, testOptions, allExamples ++ custom)
where
custom = concat
[ examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "2/15"
, "on 2/15"
, "2 / 15"
, "2-15"
, "2 - 15"
]
, examples (datetime (1974, 10, 31, 0, 0, 0) Day)
[ "10/31/1974"
, "10/31/74"
, "10-31-74"
, "10.31.1974"
, "31/Oct/1974"
, "31-Oct-74"
, "31st Oct 1974"
]
, examples (datetime (2013, 4, 25, 16, 0, 0) Minute)
[ "4/25 at 4:00pm"
, "4/25 at 16h00"
, "4/25 at 16h"
]
, examples (datetimeHoliday (2013, 11, 28, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving day"
, "thanksgiving"
, "thanksgiving 2013"
, "this thanksgiving"
, "next thanksgiving day"
, "thanksgiving in 9 months"
, "thanksgiving 9 months from now"
]
, examples (datetimeHoliday (2014, 11, 27, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving of next year"
, "thanksgiving in a year"
, "thanksgiving 2014"
]
, examples (datetimeHoliday (2012, 11, 22, 0, 0, 0) Day "Thanksgiving Day")
[ "last thanksgiving"
, "thanksgiving day 2012"
, "thanksgiving 3 months ago"
, "thanksgiving 1 year ago"
]
, examples (datetimeHoliday (2016, 11, 24, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2016"
, "thanksgiving in 3 years"
]
, examples (datetimeHoliday (2017, 11, 23, 0, 0, 0) Day "Thanksgiving Day")
[ "thanksgiving 2017"
]
]
negativeCorpus :: NegativeCorpus
negativeCorpus = (testContext, testOptions, examples)
where
examples =
[ "laughing out loud"
, "1 adult"
, "we are separated"
, "25"
, "this is the one"
, "this one"
, "this past one"
, "at single"
, "at a couple of"
, "at pairs"
, "at a few"
, "at dozens"
, "single o'clock"
, "dozens o'clock"
, "Rat 6"
, "rat 6"
, "3 30"
, "three twenty"
, "at 650.650.6500"
, "at 650-650-6500"
, "two sixty a m"
, "Pay ABC 2000"
, "4a"
, "4a."
, "A4 A5"
, "palm"
, "Martin Luther King' day"
, "two three"
]
latentCorpus :: Corpus
latentCorpus = (testContext, testOptions {withLatent = True}, xs)
where
xs = concat
[ examples (datetime (2013, 2, 24, 0, 0, 0) Day)
[ "the 24"
, "On 24th"
]
, examples (datetime (2013, 2, 12, 7, 0, 0) Hour)
[ "7"
, "7a"
]
, examples (datetime (2013, 2, 12, 19, 0, 0) Hour)
[ "7p"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "ten thirty"
, "ten-thirty"
]
, examples (datetime (1974, 1, 1, 0, 0, 0) Year)
[ "1974"
]
, examples (datetime (2013, 5, 1, 0, 0, 0) Month)
[ "May"
]
, examples (datetimeInterval
((2013, 2, 12, 0, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "morning"
]
, examples (datetimeInterval
((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "afternoon"
]
, examples (datetimeInterval
((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "evening"
]
, examples (datetimeInterval
((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "night"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "the week"
]
, examples (datetime (2013, 2, 12, 12, 3, 0) Minute)
[ "twelve zero three"
, "twelve o three"
, "twelve ou three"
, "twelve oh three"
, "twelve-zero-three"
, "twelve-oh-three"
]
, examples (datetimeInterval ((1960, 1, 1, 0, 0, 0), (1962, 1, 1, 0, 0, 0)) Year)
[ "1960 - 1961"
]
, examples (datetime (2013, 2, 12, 20, 15, 0) Minute)
[ "tonight 815"
]
]
diffContext :: Context
diffContext = Context
{ locale = makeLocale EN Nothing
, referenceTime = refTime (2013, 2, 15, 4, 30, 0) (-2)
}
diffCorpus :: Corpus
diffCorpus = (diffContext, testOptions, diffExamples)
where
diffExamples =
examples (datetime (2013, 3, 8, 0, 0, 0) Day)
[ "3 fridays from now"
, "three fridays from now"
]
allExamples :: [Example]
allExamples = concat
[ examples (datetime (2013, 2, 12, 4, 30, 0) Second)
[ "now"
, "right now"
, "just now"
, "at the moment"
, "ATM"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "today"
, "at this time"
]
, examples (datetime (2013, 2, 1, 0, 0, 0) Month)
[ "2/2013"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "in 2014"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "yesterday"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "tomorrow"
, "tomorrows"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "monday"
, "mon."
, "this monday"
, "Monday, Feb 18"
, "Mon, February 18"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "tuesday"
, "Tuesday the 19th"
, "Tuesday 19th"
]
, examples (datetime (2013, 8, 15, 0, 0, 0) Day)
[ "Thu 15th"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "thursday"
, "thu"
, "thu."
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "friday"
, "fri"
, "fri."
]
, examples (datetime (2013, 2, 16, 0, 0, 0) Day)
[ "saturday"
, "sat"
, "sat."
]
, examples (datetime (2013, 2, 17, 0, 0, 0) Day)
[ "sunday"
, "sun"
, "sun."
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "the 1st of march"
, "first of march"
, "the first of march"
, "march first"
]
, examples (datetime (2013, 3, 2, 0, 0, 0) Day)
[ "the 2nd of march"
, "second of march"
, "the second of march"
]
, examples (datetime (2013, 3, 3, 0, 0, 0) Day)
[ "march 3"
, "the third of march"
]
, examples (datetime (2013, 3, 15, 0, 0, 0) Day)
[ "the ides of march"
]
, examples (datetime (2015, 3, 3, 0, 0, 0) Day)
[ "march 3 2015"
, "march 3rd 2015"
, "march third 2015"
, "3/3/2015"
, "3/3/15"
, "2015-3-3"
, "2015-03-03"
]
, examples (datetime (2013, 2, 15, 0, 0, 0) Day)
[ "on the 15th"
, "the 15th of february"
, "15 of february"
, "february the 15th"
, "february 15"
, "15th february"
, "February 15"
]
, examples (datetime (2013, 8, 8, 0, 0, 0) Day)
[ "Aug 8"
]
, examples (datetime (2014, 3, 1, 0, 0, 0) Month)
[ "March in 1 year"
, "March in a year"
]
, examples (datetime (2014, 7, 18, 0, 0, 0) Day)
[ "Fri, Jul 18"
, "Jul 18, Fri"
]
, examples (datetime (2014, 10, 1, 0, 0, 0) Month)
[ "October 2014"
, "2014-10"
, "2014/10"
]
, examples (datetime (2015, 4, 14, 0, 0, 0) Day)
[ "14april 2015"
, "April 14, 2015"
, "14th April 15"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "next tuesday"
, "around next tuesday"
]
, examples (datetime (2013, 2, 22, 0, 0, 0) Day)
[ "friday after next"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "next March"
]
, examples (datetime (2014, 3, 1, 0, 0, 0) Month)
[ "March after next"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "Sunday, Feb 10"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "Wed, Feb13"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Week)
[ "this week"
, "current week"
]
, examples (datetime (2013, 2, 4, 0, 0, 0) Week)
[ "last week"
, "past week"
, "previous week"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Week)
[ "next week"
, "the following week"
, "around next week"
, "upcoming week"
, "coming week"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Month)
[ "last month"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "next month"
]
, examples (datetime (2013, 3, 20, 0, 0, 0) Day)
[ "20 of next month"
, "20th of the next month"
, "20th day of next month"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "20th of the current month"
, "20 of this month"
]
, examples (datetime (2013, 1, 20, 0, 0, 0) Day)
[ "20th of the previous month"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Quarter)
[ "this quarter"
, "this qtr"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Quarter)
[ "next quarter"
, "next qtr"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "third quarter"
, "3rd quarter"
, "third qtr"
, "3rd qtr"
, "the 3rd qtr"
]
, examples (datetime (2018, 10, 1, 0, 0, 0) Quarter)
[ "4th quarter 2018"
, "4th qtr 2018"
, "the 4th qtr of 2018"
, "18q4"
, "2018Q4"
]
, examples (datetime (2012, 1, 1, 0, 0, 0) Year)
[ "last year"
, "last yr"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Year)
[ "this year"
, "current year"
, "this yr"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "next year"
, "next yr"
]
, examples (datetime (2014, 1, 1, 0, 0, 0) Year)
[ "in 2014 A.D.",
"in 2014 AD"
]
, examples (datetime (-2014, 1, 1, 0, 0, 0) Year)
[ "in 2014 B.C.",
"in 2014 BC"
]
, examples (datetime (14, 1, 1, 0, 0, 0) Year)
[ "in 14 a.d."
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "last sunday"
, "sunday from last week"
, "last week's sunday"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "last tuesday"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "next wednesday"
]
, examples (datetime (2013, 2, 20, 0, 0, 0) Day)
[ "wednesday of next week"
, "wednesday next week"
, "wednesday after next"
]
, examples (datetime (2013, 2, 22, 0, 0, 0) Day)
[ "friday after next"
]
, examples (datetime (2013, 2, 11, 0, 0, 0) Day)
[ "monday of this week"
]
, examples (datetime (2013, 2, 12, 0, 0, 0) Day)
[ "tuesday of this week"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Day)
[ "wednesday of this week"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "the day after tomorrow"
]
, examples (datetime (2013, 2, 14, 17, 0, 0) Hour)
[ "day after tomorrow 5pm"
]
, examples (datetime (2013, 2, 10, 0, 0, 0) Day)
[ "the day before yesterday"
]
, examples (datetime (2013, 2, 10, 8, 0, 0) Hour)
[ "day before yesterday 8am"
]
, examples (datetime (2013, 3, 25, 0, 0, 0) Day)
[ "last Monday of March"
]
, examples (datetime (2014, 3, 30, 0, 0, 0) Day)
[ "last Sunday of March 2014"
]
, examples (datetime (2013, 10, 3, 0, 0, 0) Day)
[ "third day of october"
]
, examples (datetime (2014, 10, 6, 0, 0, 0) Week)
[ "first week of october 2014"
]
, examples (datetime (2018, 12, 10, 0, 0, 0) Week)
[ "third last week of 2018"
, "the third last week of 2018"
, "the 3rd last week of 2018"
]
, examples (datetime (2018, 10, 15, 0, 0, 0) Week)
[ "2nd last week of October 2018"
, "the second last week of October 2018"
]
, examples (datetime (2013, 5, 27, 0, 0, 0) Day)
[ "fifth last day of May"
, "the 5th last day of May"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Week)
[ "the week of october 6th"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Week)
[ "the week of october 7th"
]
, examples (datetime (2015, 10, 31, 0, 0, 0) Day)
[ "last day of october 2015"
, "last day in october 2015"
]
, examples (datetime (2014, 9, 22, 0, 0, 0) Week)
[ "last week of september 2014"
]
, examples (datetime (2013, 10, 1, 0, 0, 0) Day)
[ "first tuesday of october"
, "first tuesday in october"
]
, examples (datetime (2014, 9, 16, 0, 0, 0) Day)
[ "third tuesday of september 2014"
]
, examples (datetime (2014, 10, 1, 0, 0, 0) Day)
[ "first wednesday of october 2014"
]
, examples (datetime (2014, 10, 8, 0, 0, 0) Day)
[ "second wednesday of october 2014"
]
, examples (datetime (2015, 1, 13, 0, 0, 0) Day)
[ "third tuesday after christmas 2014"
]
, examples (datetime (2013, 2, 13, 3, 0, 0) Hour)
[ "at 3am"
, "3 in the AM"
, "at 3 AM"
, "3 oclock am"
, "at three am"
, "this morning at 3"
, "3 in the morning"
, "at 3 in the morning"
, "early morning @ 3"
]
, examples (datetime (2013, 2, 12, 10, 0, 0) Hour)
[ "this morning @ 10"
, "this morning at 10am"
]
, examples (datetime (2013, 2, 13, 3, 18, 0) Minute)
[ "3:18am"
, "3:18a"
, "3h18"
]
, examples (datetime (2016, 2, 1, 7, 0, 0) Hour)
[ "at 7 in 3 years"
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Hour)
[ "at 3pm"
, "@ 3pm"
, "3PM"
, "3pm"
, "3 oclock pm"
, "3 o'clock in the afternoon"
, "3ish pm"
, "3pm approximately"
, "at about 3pm"
, "at 3p"
, "at 3p."
]
, examples (datetime (2013, 2, 12, 15, 0, 0) Minute)
[ "15h00"
, "at 15h00"
, "15h"
, "at 15h"
]
, examples (datetime (2013, 2, 12, 15, 15, 0) Minute)
[ "at 15 past 3pm"
, "a quarter past 3pm"
, "for a quarter past 3pm"
, "3:15 in the afternoon"
, "15:15"
, "15h15"
, "3:15pm"
, "3:15PM"
, "3:15p"
, "at 3 15"
, "15 minutes past 3pm"
, "15 minutes past 15h"
]
, examples (datetime (2013, 2, 12, 15, 20, 0) Minute)
[ "at 20 past 3pm"
, "3:20 in the afternoon"
, "3:20 in afternoon"
, "twenty after 3pm"
, "3:20p"
, "15h20"
, "at three twenty"
, "20 minutes past 3pm"
, "this afternoon at 3:20"
, "tonight @ 3:20"
]
, examples (datetime (2013, 2, 12, 15, 30, 0) Minute)
[ "at half past three pm"
, "half past 3 pm"
, "15:30"
, "15h30"
, "3:30pm"
, "3:30PM"
, "330 p.m."
, "3:30 p m"
, "3:30"
, "half three"
, "30 minutes past 3 pm"
]
, examples (datetime (2013, 2, 12, 12, 15, 0) Minute)
[ "at 15 past noon"
, "a quarter past noon"
, "for a quarter past noon"
, "12:15 in the afternoon"
, "12:15"
, "12h15"
, "12:15pm"
, "12:15PM"
, "12:15p"
, "at 12 15"
, "15 minutes past noon"
]
, examples (datetime (2013, 2, 12, 9, 59, 0) Minute)
[ "nine fifty nine a m"
]
, examples (datetime (2013, 2, 12, 15, 23, 24) Second)
[ "15:23:24"
]
, examples (datetime (2013, 2, 12, 9, 1, 10) Second)
[ "9:01:10 AM"
]
, examples (datetime (2013, 2, 12, 11, 45, 0) Minute)
[ "a quarter to noon"
, "11:45am"
, "11h45"
, "15 to noon"
]
, examples (datetime (2013, 2, 12, 13, 15, 0) Minute)
[ "a quarter past 1pm"
, "for a quarter past 1pm"
, "1:15pm"
, "13h15"
, "15 minutes from 1pm"
]
, examples (datetime (2013, 2, 12, 14, 15, 0) Minute)
[ "a quarter past 2pm"
, "for a quarter past 2pm"
]
, examples (datetime (2013, 2, 12, 20, 15, 0) Minute)
[ "a quarter past 8pm"
, "for a quarter past 8pm"
]
, examples (datetime (2013, 2, 12, 20, 0, 0) Hour)
[ "8 tonight"
, "tonight at 8 o'clock"
, "eight tonight"
, "8 this evening"
, "at 8 in the evening"
, "in the evening at eight"
]
, examples (datetime (2013, 9, 20, 19, 30, 0) Minute)
[ "at 7:30 PM on Fri, Sep 20"
, "at 19h30 on Fri, Sep 20"
]
, examples (datetime (2013, 2, 16, 9, 0, 0) Hour)
[ "at 9am on Saturday"
, "Saturday morning at 9"
]
, examples (datetime (2013, 2, 16, 9, 0, 0) Hour)
[ "on Saturday for 9am"
]
, examples (datetime (2014, 7, 18, 19, 0, 0) Minute)
[ "Fri, Jul 18, 2014 07:00 PM"
, "Fri, Jul 18, 2014 19h00"
, "Fri, Jul 18, 2014 19h"
]
, examples (datetime (2013, 2, 12, 4, 30, 1) Second)
[ "in a sec"
, "one second from now"
, "in 1\""
]
, examples (datetime (2013, 2, 12, 4, 31, 0) Second)
[ "in a minute"
, "in one minute"
, "in 1'"
]
, examples (datetime (2013, 2, 12, 4, 32, 0) Second)
[ "in 2 minutes"
, "in 2 more minutes"
, "2 minutes from now"
, "in a couple of minutes"
, "in a pair of minutes"
]
, examples (datetime (2013, 2, 12, 4, 33, 0) Second)
[ "in three minutes"
, "in a few minutes"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Second)
[ "in 60 minutes"
]
, examples (datetime (2013, 2, 12, 4, 45, 0) Second)
[ "in a quarter of an hour"
, "in 1/4h"
, "in 1/4 h"
, "in 1/4 hour"
]
, examples (datetime (2013, 2, 12, 5, 0, 0) Second)
[ "in half an hour"
, "in 1/2h"
, "in 1/2 h"
, "in 1/2 hour"
]
, examples (datetime (2013, 2, 12, 5, 15, 0) Second)
[ "in three-quarters of an hour"
, "in 3/4h"
, "in 3/4 h"
, "in 3/4 hour"
]
, examples (datetime (2013, 2, 12, 7, 0, 0) Second)
[ "in 2.5 hours"
, "in 2 and an half hours"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "in one hour"
, "in 1h"
]
, examples (datetime (2013, 2, 12, 6, 30, 0) Minute)
[ "in a couple hours"
, "in a couple of hours"
]
, examples (datetime (2013, 2, 12, 7, 30, 0) Minute)
[ "in a few hours"
, "in few hours"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Minute)
[ "in 24 hours"
]
, examples (datetime (2013, 2, 13, 4, 0, 0) Hour)
[ "in a day"
, "a day from now"
]
, examples (datetime (2013, 2, 13, 4, 30, 0) Second)
[ "a day from right now"
]
, examples (datetime (2016, 2, 12, 0, 0, 0) Day)
[ "3 years from today"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "3 fridays from now"
, "three fridays from now"
]
, examples (datetime (2013, 2, 24, 0, 0, 0) Day)
[ "2 sundays from now"
, "two sundays from now"
]
, examples (datetime (2013, 3, 12, 0, 0, 0) Day)
[ "4 tuesdays from now"
, "four tuesdays from now"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "in 7 days"
]
, examples (datetime (2013, 2, 19, 17, 0, 0) Hour)
[ "in 7 days at 5pm"
]
, examples (datetime (2017, 2, 1, 17, 0, 0) Hour)
[ "in 4 years at 5pm"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "in 1 week"
, "in a week"
]
, examples (datetime (2013, 2, 12, 5, 0, 0) Second)
[ "in about half an hour"
]
, examples (datetime (2013, 2, 5, 4, 0, 0) Hour)
[ "7 days ago"
]
, examples (datetime (2013, 1, 29, 4, 0, 0) Hour)
[ "14 days Ago"
, "a fortnight ago"
]
, examples (datetime (2013, 2, 5, 0, 0, 0) Day)
[ "a week ago"
, "one week ago"
, "1 week ago"
]
, examples (datetime (2013, 1, 31, 0, 0, 0) Day)
[ "2 thursdays back"
, "2 thursdays ago"
]
, examples (datetime (2013, 1, 22, 0, 0, 0) Day)
[ "three weeks ago"
]
, examples (datetime (2012, 11, 12, 0, 0, 0) Day)
[ "three months ago"
]
, examples (datetime (2013, 02, 04, 0, 0, 0) Day)
[ "the first Monday of this month"
, "the first Monday of the month"
, "the first Monday in this month"
, "first Monday in the month"
]
, examples (datetime (2011, 2, 1, 0, 0, 0) Month)
[ "two years ago"
]
, examples (datetime (2013, 2, 19, 4, 0, 0) Hour)
[ "7 days hence"
]
, examples (datetime (2013, 2, 26, 4, 0, 0) Hour)
[ "14 days hence"
, "a fortnight hence"
]
, examples (datetime (2013, 2, 19, 0, 0, 0) Day)
[ "a week hence"
, "one week hence"
, "1 week hence"
]
, examples (datetime (2013, 3, 5, 0, 0, 0) Day)
[ "three weeks hence"
]
, examples (datetime (2013, 5, 12, 0, 0, 0) Day)
[ "three months hence"
]
, examples (datetime (2015, 2, 1, 0, 0, 0) Month)
[ "two years hence"
]
, examples (datetime (2013, 12, 25, 0, 0, 0) Day)
[ "one year After christmas"
, "a year from Christmas"
]
, examples (datetimeInterval ((2013, 12, 18, 0, 0, 0), (2013, 12, 29, 0, 0, 0)) Day)
[ "for 10 days from 18th Dec"
, "from 18th Dec for 10 days"
, "18th Dec for 10 days"
]
, examples (datetimeInterval ((2013, 2, 12, 16, 0, 0), (2013, 2, 12, 16, 31, 0)) Minute)
[ "for 30' starting from 4pm"
, "from 4pm for thirty minutes"
, "4pm for 30 mins"
, "16h for 30 mins"
]
, examples (datetimeInterval ((2013, 6, 21, 0, 0, 0), (2013, 9, 24, 0, 0, 0)) Day)
[ "this Summer"
, "current summer"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "this winter"
]
, examples (datetimeInterval ((2012, 12, 21, 0, 0, 0), (2013, 3, 19, 0, 0, 0)) Day)
[ "this season"
, "current seasons"
]
, examples (datetimeInterval ((2012, 9, 23, 0, 0, 0), (2012, 12, 20, 0, 0, 0)) Day)
[ "last season"
, "past seasons"
, "previous seasons"
]
, examples (datetimeInterval ((2013, 3, 20, 0, 0, 0), (2013, 6, 20, 0, 0, 0)) Day)
[ "next season"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "last night"
, "yesterday evening"
]
, examples (datetimeInterval ((2013, 2, 11, 21, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "late last night"
]
, examples (datetimeHoliday (2013, 12, 25, 0, 0, 0) Day "Christmas")
[ "xmas"
, "christmas"
, "christmas day"
]
, examples (datetimeHoliday (2013, 12, 25, 18, 0, 0) Hour "Christmas")
[ "xmas at 6 pm"
]
, examples (datetimeIntervalHoliday ((2013, 12, 25, 0, 0, 0), (2013, 12, 25, 12, 0, 0)) Hour "Christmas")
[ "morning of xmas"
, "morning of christmas 2013"
, "morning of this christmas day"
]
, examples (datetimeHoliday (2013, 12, 31, 0, 0, 0) Day "New Year's Eve")
[ "new year's eve"
, "new years eve"
]
, examples (datetimeHoliday (2014, 1, 1, 0, 0, 0) Day "New Year's Day")
[ "new year's day"
, "new years day"
]
, examples (datetimeHoliday (2013, 2, 14, 0, 0, 0) Day "Valentine's Day")
[ "valentine's day"
, "valentine day"
]
, examples (datetime (2013, 7, 4, 0, 0, 0) Day)
[ "4th of July"
, "4 of july"
]
, examples (datetimeHoliday (2013, 10, 31, 0, 0, 0) Day "Halloween")
[ "halloween"
, "next halloween"
, "Halloween 2013"
]
, examples (datetimeHoliday (2013, 11, 29, 0, 0, 0) Day "Black Friday")
[ "black friday"
, "black friday of this year"
, "black friday 2013"
]
, examples (datetimeHoliday (2017, 11, 24, 0, 0, 0) Day "Black Friday")
[ "black friday 2017"
]
, examples (datetimeHoliday (2013, 10, 16, 0, 0, 0) Day "Boss's Day")
[ "boss's day"
, "boss's"
, "boss day"
, "next boss's day"
]
, examples (datetimeHoliday (2016, 10, 17, 0, 0, 0) Day "Boss's Day")
[ "boss's day 2016"
]
, examples (datetimeHoliday (2021, 10, 15, 0, 0, 0) Day "Boss's Day")
[ "boss's day 2021"
]
, examples (datetimeHoliday (2014, 1, 20, 0, 0, 0) Day "Martin Luther King's Day")
[ "MLK day"
, "next Martin Luther King day"
, "next Martin Luther King's day"
, "next Martin Luther Kings day"
, "this MLK day"
]
, examples (datetimeHoliday (2013, 1, 21, 0, 0, 0) Day "Martin Luther King's Day")
[ "last MLK Jr. day"
, "MLK day 2013"
]
, examples (datetimeHoliday (2012, 1, 16, 0, 0, 0) Day "Martin Luther King's Day")
[ "MLK day of last year"
, "MLK day 2012"
, "Civil Rights Day of last year"
]
, examples (datetimeHoliday (2013, 11, 1, 0, 0, 0) Day "World Vegan Day")
[ "world vegan day"
]
, examples (datetimeHoliday (2013, 3, 31, 0, 0, 0) Day "Easter Sunday")
[ "easter"
, "easter 2013"
]
, examples (datetimeHoliday (2012, 4, 08, 0, 0, 0) Day "Easter Sunday")
[ "last easter"
]
, examples (datetimeHoliday (2013, 4, 1, 0, 0, 0) Day "Easter Monday")
[ "easter mon"
]
, examples (datetimeHoliday (2010, 4, 4, 0, 0, 0) Day "Easter Sunday")
[ "easter 2010"
, "Easter Sunday two thousand ten"
]
, examples (datetime (2013, 4, 3, 0, 0, 0) Day)
[ "three days after Easter"
]
, examples (datetimeHoliday (2013, 3, 28, 0, 0, 0) Day "Maundy Thursday")
[ "Maundy Thursday"
, "Covenant thu"
, "Thu of Mysteries"
]
, examples (datetimeHoliday (2013, 5, 19, 0, 0, 0) Day "Pentecost")
[ "Pentecost"
, "white sunday 2013"
]
, examples (datetimeHoliday (2013, 5, 20, 0, 0, 0) Day "Whit Monday")
[ "whit monday"
, "Monday of the Holy Spirit"
]
, examples (datetimeHoliday (2013, 3, 24, 0, 0, 0) Day "Palm Sunday")
[ "palm sunday"
, "branch sunday 2013"
]
, examples (datetimeHoliday (2013, 5, 26, 0, 0, 0) Day "Trinity Sunday")
[ "trinity sunday"
]
, examples (datetimeHoliday (2013, 2, 12, 0, 0, 0) Day "Shrove Tuesday")
[ "pancake day 2013"
, "mardi gras"
]
, examples (datetimeHoliday (2013, 3, 17, 0, 0, 0) Day "St Patrick's Day")
[ "st patrick's day 2013"
, "st paddy's day"
, "saint paddy's day"
, "saint patricks day"
]
, examples (datetimeIntervalHoliday ((2018, 2, 14, 0, 0, 0), (2018, 4, 1, 0, 0, 0)) Day "Lent")
[ "lent 2018"
]
, examples (datetimeHoliday (2018, 4, 8, 0, 0, 0) Day "Orthodox Easter Sunday")
[ "orthodox easter 2018"
]
, examples (datetimeHoliday (2020, 4, 17, 0, 0, 0) Day "Orthodox Good Friday")
[ "orthodox good friday 2020"
, "orthodox great friday 2020"
]
, examples (datetimeHoliday (2018, 2, 19, 0, 0, 0) Day "Clean Monday")
[ "clean monday 2018"
, "orthodox shrove monday two thousand eighteen"
]
, examples (datetimeHoliday (2018, 3, 31, 0, 0, 0) Day "Lazarus Saturday")
[ "lazarus saturday 2018"
]
, examples (datetimeIntervalHoliday ((2018, 2, 19, 0, 0, 0), (2018, 3, 31, 0, 0, 0)) Day "Great Lent")
[ "great fast 2018"
]
, examples (datetimeInterval ((2013, 2, 12, 18, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "this evening"
, "today evening"
, "tonight"
]
, examples (datetimeInterval ((2013, 2, 8, 18, 0, 0), (2013, 2, 11, 0, 0, 0)) Hour)
[ "this past weekend"
]
, examples (datetimeInterval ((2013, 2, 13, 18, 0, 0), (2013, 2, 14, 0, 0, 0)) Hour)
[ "tomorrow evening"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 14, 0, 0)) Hour)
[ "tomorrow lunch"
, "tomorrow at lunch"
]
, examples (datetimeInterval ((2013, 2, 11, 18, 0, 0), (2013, 2, 12, 0, 0, 0)) Hour)
[ "yesterday evening"
]
, examples (datetimeInterval ((2013, 2, 15, 18, 0, 0), (2013, 2, 18, 0, 0, 0)) Hour)
[ "this week-end"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 18, 12, 0, 0)) Hour)
[ "monday mOrnIng"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 18, 9, 0, 0)) Hour)
[ "monday early in the morning"
, "monday early morning"
, "monday in the early hours of the morning"
]
, examples (datetimeInterval ((2013, 2, 12, 21, 0, 0), (2013, 2, 13, 0, 0, 0)) Hour)
[ "late tonight"
, "late tonite"
]
, examples (datetimeInterval ((2013, 2, 15, 0, 0, 0), (2013, 2, 15, 12, 0, 0)) Hour)
[ "february the 15th in the morning"
, "15 of february in the morning"
, "morning of the 15th of february"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 29, 58), (2013, 2, 12, 4, 30, 0)) Second)
[ "last 2 seconds"
, "last two seconds"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 1), (2013, 2, 12, 4, 30, 4)) Second)
[ "next 3 seconds"
, "next three seconds"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 28, 0), (2013, 2, 12, 4, 30, 0)) Minute)
[ "last 2 minutes"
, "last two minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 31, 0), (2013, 2, 12, 4, 34, 0)) Minute)
[ "next 3 minutes"
, "next three minutes"
]
, examples (datetimeInterval ((2013, 2, 12, 3, 0, 0), (2013, 2, 12, 4, 0, 0)) Hour)
[ "last 1 hour"
, "last one hour"
]
, examples (datetimeInterval ((2013, 2, 12, 5, 0, 0), (2013, 2, 12, 8, 0, 0)) Hour)
[ "next 3 hours"
, "next three hours"
]
, examples (datetimeInterval ((2013, 2, 10, 0, 0, 0), (2013, 2, 12, 0, 0, 0)) Day)
[ "last 2 days"
, "last two days"
, "past 2 days"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "next 3 days"
, "next three days"
]
, examples (datetimeInterval ((2013, 2, 13, 0, 0, 0), (2013, 2, 16, 0, 0, 0)) Day)
[ "next few days"
]
, examples (datetimeInterval ((2013, 1, 28, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Week)
[ "last 2 weeks"
, "last two weeks"
, "past 2 weeks"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Week)
[ "next 3 weeks"
, "next three weeks"
]
, examples (datetimeInterval ((2012, 12, 1, 0, 0, 0), (2013, 2, 1, 0, 0, 0)) Month)
[ "last 2 months"
, "last two months"
]
, examples (datetimeInterval ((2013, 3, 1, 0, 0, 0), (2013, 6, 1, 0, 0, 0)) Month)
[ "next 3 months"
, "next three months"
]
, examples (datetimeInterval ((2011, 1, 1, 0, 0, 0), (2013, 1, 1, 0, 0, 0)) Year)
[ "last 2 years"
, "last two years"
]
, examples (datetimeInterval ((2014, 1, 1, 0, 0, 0), (2017, 1, 1, 0, 0, 0)) Year)
[ "next 3 years"
, "next three years"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "July 13-15"
, "July 13 to 15"
, "July 13 thru 15"
, "July 13 through 15"
, "July 13 - July 15"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "from July 13-15"
, "from 13 to 15 July"
, "from 13th to 15th July"
, "from the 13 to 15 July"
, "from the 13th to 15th July"
, "from the 13th to the 15th July"
, "from the 13 to the 15 July"
]
, examples (datetimeInterval ((2013, 7, 13, 0, 0, 0), (2013, 7, 16, 0, 0, 0)) Day)
[ "from 13 to 15 of July"
, "from 13th to 15 of July"
, "from 13 to 15th of July"
, "from 13th to 15th of July"
, "from 13 to the 15 of July"
, "from 13th to the 15 of July"
, "from 13 to the 15th of July"
, "from 13th to the 15th of July"
, "from the 13 to the 15 of July"
, "from the 13th to the 15 of July"
, "from the 13 to the 15th of July"
, "from the 13th to the 15th of July"
]
, examples (datetimeInterval ((2013, 8, 8, 0, 0, 0), (2013, 8, 13, 0, 0, 0)) Day)
[ "Aug 8 - Aug 12"
]
, examples (datetimeInterval ((2013, 2, 12, 9, 30, 0), (2013, 2, 12, 11, 1, 0)) Minute)
[ "9:30 - 11:00"
, "9h30 - 11h00"
, "9h30 - 11h"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 30, 0), (2013, 2, 12, 15, 1, 0)) Minute)
[ "9:30 - 11:00 CST"
, "9h30 - 11h00 CST"
, "9h30 - 11h CST"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 0, 0), (2013, 2, 12, 16, 1, 0)) Minute)
[ "15:00 GMT - 18:00 GMT"
, "15h00 GMT - 18h00 GMT"
, "15h GMT - 18h GMT"
]
, examples (datetimeInterval
((2015, 3, 28, 17, 00, 0), (2015, 3, 29, 21, 0, 1)) Second)
[ "2015-03-28 17:00:00/2015-03-29 21:00:00"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 30, 0), (2013, 2, 14, 11, 1, 0)) Minute)
[ "from 9:30 - 11:00 on Thursday"
, "between 9:30 and 11:00 on thursday"
, "between 9h30 and 11h00 on thursday"
, "9:30 - 11:00 on Thursday"
, "9h30 - 11h00 on Thursday"
, "later than 9:30 but before 11:00 on Thursday"
, "Thursday from 9:30 to 11:00"
, "from 9:30 untill 11:00 on thursday"
, "Thursday from 9:30 untill 11:00"
, "9:30 till 11:00 on Thursday"
]
, examples (datetimeInterval ((2013, 2, 13, 1, 0, 0), (2013, 2, 13, 2, 31, 0)) Minute)
[ "tomorrow in between 1-2:30 ish"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 17, 0, 0)) Hour)
[ "3-4pm"
, "from 3 to 4 in the PM"
, "around 3-4pm"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 30, 0), (2013, 2, 12, 18, 1, 0)) Minute)
[ "3:30 to 6 PM"
, "3:30-6 p.m."
, "3:30-6:00pm"
, "15h30-18h"
, "from 3:30 to six p.m."
, "from 3:30 to 6:00pm"
, "later than 3:30pm but before 6pm"
, "between 3:30pm and 6 pm"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 18, 0, 1)) Second)
[ "3pm - 6:00:00pm"
]
, examples (datetimeInterval ((2013, 2, 12, 8, 0, 0), (2013, 2, 12, 14, 0, 0)) Hour)
[ "8am - 1pm"
]
, examples (datetimeInterval ((2013, 2, 14, 9, 0, 0), (2013, 2, 14, 12, 0, 0)) Hour)
[ "Thursday from 9a to 11a"
, "this Thu 9-11am"
]
, examples (datetimeInterval ((2013, 2, 12, 11, 30, 0), (2013, 2, 12, 13, 31, 0)) Minute)
[ "11:30-1:30"
]
, examples (datetime (2013, 9, 21, 13, 30, 0) Minute)
[ "1:30 PM on Sat, Sep 21"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 26, 0, 0, 0)) Second)
[ "Within 2 weeks"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 12, 14, 0, 0)) Second)
[ "by 2:00pm"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 2, 13, 0, 0, 0)) Second)
[ "by EOD"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 3, 1, 0, 0, 0)) Second)
[ "by EOM"
, "by the EOM"
, "by end of the month"
, "by the end of month"
]
, examples (datetimeInterval ((2013, 2, 21, 0, 0, 0), (2013, 3, 1, 0, 0, 0)) Day)
[ "EOM"
, "the EOM"
, "at the EOM"
, "the end of the month"
, "end of the month"
, "at the end of month"
]
, examples (datetimeInterval ((2013, 2, 1, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Day)
[ "BOM"
, "the BOM"
, "at the BOM"
, "beginning of the month"
, "the beginning of the month"
, "at the beginning of month"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2013, 4, 1, 0, 0, 0)) Second)
[ "by the end of next month"
]
, examples (datetime (2013, 2, 12, 13, 0, 0) Minute)
[ "4pm CET"
]
, examples (datetime (2013, 2, 14, 6, 0, 0) Minute)
[ "Thursday 8:00 GMT"
, "Thursday 8:00 gmt"
, "Thursday 8h00 GMT"
, "Thursday 8h00 gmt"
, "Thursday 8h GMT"
, "Thursday 8h gmt"
, "Thu at 8 GMT"
, "Thu at 8 gmt"
, "Thursday 9 am BST"
, "Thursday 9 am (BST)"
]
, examples (datetime (2013, 2, 14, 14, 0, 0) Minute)
[ "Thursday 8:00 PST"
, "Thursday 8:00 pst"
, "Thursday 8h00 PST"
, "Thursday 8h00 pst"
, "Thursday 8h PST"
, "Thursday 8h pst"
, "Thu at 8 am PST"
, "Thu at 8 am pst"
, "Thursday at 9:30pm ist"
]
, examples (datetime (2013, 2, 12, 14, 0, 0) Hour)
[ "today at 2pm"
, "at 2pm"
, "this afternoon at 2"
, "this evening at 2"
, "tonight at 2"
]
, examples (datetime (2013, 2, 13, 15, 0, 0) Hour)
[ "3pm tomorrow"
]
, examples (datetime (2013, 2, 12, 5, 30, 0) Minute)
[ "today in one hour"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 4, 30, 0) Second)
[ "ASAP"
, "as soon as possible"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 14, 0, 0) Minute)
[ "until 2:00pm"
, "through 2:00pm"
]
, examples (datetimeOpenInterval After (2013, 2, 12, 14, 0, 0) Hour)
[ "after 2 pm"
, "from 2 pm"
, "since 2pm"
]
, examples (datetimeOpenInterval After (2014, 1, 1, 0, 0, 0) Year)
[ "anytime after 2014"
, "since 2014"
]
, examples (datetimeOpenInterval Before (2014, 1, 1, 0, 0, 0) Year)
[ "sometimes before 2014"
, "through 2014"
]
, examples (datetimeOpenInterval After (2013, 2, 17, 4, 0, 0) Hour)
[ "after 5 days"
]
, examples (datetimeOpenInterval Before (2013, 2, 12, 11, 0, 0) Hour)
[ "before 11 am"
]
, examples (datetimeInterval ((2013, 2, 12, 12, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "in the afternoon"
]
, examples (datetimeInterval ((2013, 2, 12, 8, 0, 0), (2013, 2, 12, 19, 0, 0)) Hour)
[ "8am until 6"
]
, examples (datetime (2013, 2, 12, 13, 30, 0) Minute)
[ "at 1:30pm"
, "1:30pm"
, "at 13h30"
, "13h30"
]
, examples (datetime (2013, 2, 12, 4, 45, 0) Second)
[ "in 15 minutes"
, "in 15'"
, "in 15"
]
, examples (datetimeInterval ((2013, 2, 12, 13, 0, 0), (2013, 2, 12, 17, 0, 0)) Hour)
[ "after lunch"
]
, examples (datetimeInterval ((2013, 2, 12, 15, 0, 0), (2013, 2, 12, 21, 0, 0)) Hour)
[ "after school"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "10:30"
, "approximately 1030"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 12, 12, 0, 0)) Hour)
[ "this morning"
]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "next monday"
]
, examples (datetime (2013, 2, 12, 12, 0, 0) Hour)
[ "at 12pm"
, "at noon"
, "midday"
, "the midday"
, "mid day"
]
, examples (datetime (2013, 2, 13, 0, 0, 0) Hour)
[ "at 12am"
, "at midnight"
, "this morning at 12"
, "this evening at 12"
, "this afternoon at 12"
]
, examples (datetime (2013, 2, 13, 9, 0, 0) Hour)
[ "9 tomorrow morning"
, "9 tomorrow"
]
, examples (datetime (2013, 2, 13, 21, 0, 0) Hour)
[ "9 tomorrow evening"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Month)
[ "March"
, "in March"
, "during March"
]
, examples (datetime (2013, 2, 13, 17, 0, 0) Hour)
[ "tomorrow afternoon at 5"
, "at 5 tomorrow afternoon"
, "at 5pm tomorrow"
, "tomorrow at 5pm"
, "tomorrow evening at 5"
]
, examples (datetimeInterval ((2013, 2, 13, 12, 0, 0), (2013, 2, 13, 19, 0, 0)) Hour)
[ "tomorrow afternoon"
, "tomorrow afternoonish"
]
, examples (datetimeInterval ((2013, 2, 13, 13, 0, 0), (2013, 2, 13, 15, 0, 0)) Hour)
[ "1pm-2pm tomorrow"
]
, examples (datetime (2013, 3, 1, 0, 0, 0) Day)
[ "on the first"
, "the 1st"
]
, examples (datetime (2013, 2, 12, 10, 30, 0) Minute)
[ "at 1030"
, "around 1030"
, "ten thirty am"
]
, examples (datetime (2013, 2, 12, 19, 30, 0) Minute)
[ "at 730 in the evening"
, "seven thirty p.m."
]
, examples (datetime (2013, 2, 13, 1, 50, 0) Minute)
[ "tomorrow at 150ish"
]
, examples (datetime (2013, 2, 12, 23, 0, 0) Hour)
[ "tonight at 11"
, "this evening at 11"
, "this afternoon at 11"
, "tonight at 11pm"
]
, examples (datetime (2013, 2, 12, 4, 23, 0) Minute)
[ "at 4:23"
, "4:23am"
, "four twenty-three a m"
]
, examples (datetime (2013, 10, 7, 0, 0, 0) Day)
[ "the closest Monday to Oct 5th"
]
, examples (datetime (2013, 9, 30, 0, 0, 0) Day)
[ "the second closest Mon to October fifth"
]
, examples (datetimeInterval ((2013, 3, 1, 0, 0, 0), (2013, 3, 11, 0, 0, 0)) Day)
[ "early March"
]
, examples (datetimeInterval ((2013, 3, 11, 0, 0, 0), (2013, 3, 21, 0, 0, 0)) Day)
[ "mid March"
]
, examples (datetimeInterval ((2013, 3, 21, 0, 0, 0), (2013, 4, 1, 0, 0, 0)) Day)
[ "late March"
]
, examples (datetimeInterval ((2013, 10, 25, 18, 0, 0), (2013, 10, 28, 0, 0, 0)) Hour)
[ "last weekend of October"
, "last week-end in October"
, "last week end of October"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "all week"
]
, examples (datetimeInterval ((2013, 2, 12, 0, 0, 0), (2013, 2, 17, 0, 0, 0)) Day)
[ "rest of the week"
]
, examples (datetimeInterval ((2013, 7, 26, 18, 0, 0), (2013, 7, 29, 0, 0, 0)) Hour)
[ "last wkend of July"
]
, examples (datetimeInterval ((2017, 10, 27, 18, 0, 0), (2017, 10, 30, 0, 0, 0)) Hour)
[ "last weekend of October 2017"
]
, examples (datetimeInterval ((2013, 8, 27, 0, 0, 0), (2013, 8, 30, 0, 0, 0)) Day)
[ "August 27th - 29th"
, "from August 27th - 29th"
]
, examples (datetimeInterval ((2013, 10, 23, 0, 0, 0), (2013, 10, 27, 0, 0, 0)) Day)
[ "23rd to 26th Oct"
]
, examples (datetimeInterval ((2013, 9, 1, 0, 0, 0), (2013, 9, 9, 0, 0, 0)) Day)
[ "1-8 september"
]
, examples (datetimeInterval ((2013, 9, 12, 0, 0, 0), (2013, 9, 17, 0, 0, 0)) Day)
[ "12 to 16 september"
]
, examples (datetimeInterval ((2013, 8, 19, 0, 0, 0), (2013, 8, 22, 0, 0, 0)) Day)
[ "19th To 21st aug"
]
, examples (datetimeInterval ((2013, 4, 21, 0, 0, 0), (2013, 5, 1, 0, 0, 0)) Day)
[ "end of April"
, "at the end of April"
]
, examples (datetimeInterval ((2014, 1, 1, 0, 0, 0), (2014, 1, 11, 0, 0, 0)) Day)
[ "beginning of January"
, "at the beginning of January"
]
, examples (datetimeInterval ((2012, 9, 1, 0, 0, 0), (2013, 1, 1, 0, 0, 0)) Month)
[ "end of 2012"
, "at the end of 2012"
]
, examples (datetimeInterval ((2017, 1, 1, 0, 0, 0), (2017, 4, 1, 0, 0, 0)) Month)
[ "beginning of 2017"
, "at the beginning of 2017"
]
, examples (datetimeInterval ((2013, 1, 1, 0, 0, 0), (2013, 4, 1, 0, 0, 0)) Month)
[ "beginning of year"
, "the beginning of the year"
, "the BOY"
, "BOY"
]
, examples (datetimeInterval ((2013, 2, 12, 4, 30, 0), (2014, 1, 1, 0, 0, 0)) Second)
[ "by EOY"
, "by the EOY"
, "by end of the year"
, "by the end of year"
]
, examples (datetimeInterval ((2013, 9, 1, 0, 0, 0), (2014, 1, 1, 0, 0, 0)) Month)
[ "EOY"
, "the EOY"
, "at the EOY"
, "the end of the year"
, "end of the year"
, "at the end of year"
]
, examples (datetimeInterval ((2013, 2, 11, 0, 0, 0), (2013, 2, 14, 0, 0, 0)) Day)
[ "beginning of this week"
, "beginning of current week"
, "at the beginning of this week"
, "at the beginning of current week"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 21, 0, 0, 0)) Day)
[ "beginning of coming week"
, "at the beginning of coming week"
]
, examples (datetimeInterval ((2013, 2, 4, 0, 0, 0), (2013, 2, 7, 0, 0, 0)) Day)
[ "beginning of last week"
, "beginning of past week"
, "beginning of previous week"
, "at the beginning of last week"
, "at the beginning of past week"
, "at the beginning of previous week"
]
, examples (datetimeInterval ((2013, 2, 18, 0, 0, 0), (2013, 2, 21, 0, 0, 0)) Day)
[ "beginning of next week"
, "beginning of the following week"
, "beginning of around next week"
, "at the beginning of next week"
, "at the beginning of the following week"
, "at the beginning of around next week"
]
, examples (datetimeInterval ((2013, 2, 15, 0, 0, 0), (2013, 2, 18, 0, 0, 0)) Day)
[ "end of this week"
, "end of current week"
, "at the end of this week"
, "at the end of current week"
]
, examples (datetimeInterval ((2013, 2, 22, 0, 0, 0), (2013, 2, 25, 0, 0, 0)) Day)
[ "end of coming week"
, "at the end of coming week"
]
, examples (datetimeInterval ((2013, 2, 8, 0, 0, 0), (2013, 2, 11, 0, 0, 0)) Day)
[ "end of last week"
, "end of past week"
, "end of previous week"
, "at the end of last week"
, "at the end of past week"
, "at the end of previous week"
]
, examples (datetimeInterval ((2013, 2, 22, 0, 0, 0), (2013, 2, 25, 0, 0, 0)) Day)
[ "end of next week"
, "end of the following week"
, "end of around next week"
, "at the end of next week"
, "at the end of the following week"
, "at the end of around next week"
]
, examples (datetimeHoliday (2014, 1, 31, 0, 0, 0) Day "Chinese New Year")
[ "chinese new year"
, "chinese lunar new year's day"
]
, examples (datetimeHoliday (2013, 2, 10, 0, 0, 0) Day "Chinese New Year")
[ "last chinese new year"
, "last chinese lunar new year's day"
, "last chinese new years"
]
, examples (datetimeHoliday (2018, 2, 16, 0, 0, 0) Day "Chinese New Year")
[ "chinese new year's day 2018"
]
, examples (datetimeHoliday (2018, 9, 18, 0, 0, 0) Day "Yom Kippur")
[ "yom kippur 2018"
]
, examples (datetimeHoliday (2018, 9, 30, 0, 0, 0) Day "Shemini Atzeret")
[ "shemini atzeret 2018"
]
, examples (datetimeHoliday (2018, 10, 1, 0, 0, 0) Day "Simchat Torah")
[ "simchat torah 2018"
]
, examples (datetimeHoliday (2018, 7, 21, 0, 0, 0) Day "Tisha B'Av")
[ "tisha b'av 2018"
]
, examples (datetimeHoliday (2018, 4, 18, 0, 0, 0) Day "Yom Ha'atzmaut")
[ "yom haatzmaut 2018"
]
, examples (datetimeHoliday (2017, 5, 13, 0, 0, 0) Day "Lag BaOmer")
[ "lag b'omer 2017"
]
, examples (datetimeHoliday (2018, 4, 11, 0, 0, 0) Day "Yom HaShoah")
[ "Yom Hashoah 2018"
, "Holocaust Day 2018"
]
, examples (datetimeIntervalHoliday ((2018, 9, 9, 0, 0, 0), (2018, 9, 12, 0, 0, 0)) Day "Rosh Hashanah")
[ "rosh hashanah 2018"
, "rosh hashana 2018"
, "rosh hashanna 2018"
]
, examples (datetimeIntervalHoliday ((2018, 12, 2, 0, 0, 0), (2018, 12, 10, 0, 0, 0)) Day "Hanukkah")
[ "Chanukah 2018"
, "hanukah 2018"
, "hannukkah 2018"
]
, examples (datetimeIntervalHoliday ((2018, 3, 30, 0, 0, 0), (2018, 4, 8, 0, 0, 0)) Day "Passover")
[ "passover 2018"
]
, examples (datetimeIntervalHoliday ((2018, 9, 23, 0, 0, 0), (2018, 10, 2, 0, 0, 0)) Day "Sukkot")
[ "feast of the ingathering 2018"
, "succos 2018"
]
, examples (datetimeIntervalHoliday ((2018, 5, 19, 0, 0, 0), (2018, 5, 22, 0, 0, 0)) Day "Shavuot")
[ "shavuot 2018"
]
, examples (datetimeHoliday (2017, 11, 30, 0, 0, 0) Day "Mawlid")
[ "mawlid al-nabawi 2017"
]
, examples (datetimeHoliday (1950, 7, 16, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1950"
]
, examples (datetimeHoliday (1975, 10, 6, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1975"
]
, examples (datetimeHoliday (1988, 5, 16, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 1988"
]
, examples (datetimeHoliday (2018, 6, 15, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2018"
]
, examples (datetimeHoliday (2034, 12, 12, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2034"
]
, examples (datetimeHoliday (2046, 8, 4, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2046"
]
, examples (datetimeHoliday (2050, 6, 21, 0, 0, 0) Day "Eid al-Fitr")
[ "Eid al-Fitr 2050"
]
, examples (datetimeHoliday (2018, 8, 21, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 2018"
, "id ul-adha 2018"
, "sacrifice feast 2018"
, "Bakr Id 2018"
]
, examples (datetimeHoliday (1980, 10, 19, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1980"
, "id ul-adha 1980"
, "sacrifice feast 1980"
, "Bakr Id 1980"
]
, examples (datetimeHoliday (1966, 4, 1, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1966"
, "id ul-adha 1966"
, "sacrifice feast 1966"
, "Bakr Id 1966"
]
, examples (datetimeHoliday (1974, 1, 3, 0, 0, 0) Day "Eid al-Adha")
[ "Eid al-Adha 1974"
, "id ul-adha 1974"
, "sacrifice feast 1974"
, "Bakr Id 1974"
]
, examples (datetimeHoliday (2017, 6, 22, 0, 0, 0) Day "Laylat al-Qadr")
[ "laylat al kadr 2017"
, "night of measures 2017"
]
, examples (datetimeHoliday (2018, 6, 11, 0, 0, 0) Day "Laylat al-Qadr")
[ "laylat al-qadr 2018"
, "night of power 2018"
]
, examples (datetimeHoliday (2018, 9, 11, 0, 0, 0) Day "Islamic New Year")
[ "Islamic New Year 2018"
, "Amun Jadid 2018"
]
, examples (datetimeHoliday (2017, 9, 30, 0, 0, 0) Day "Ashura")
[ "day of Ashura 2017"
]
, examples (datetimeHoliday (2018, 1, 30, 0, 0, 0) Day "Tu BiShvat")
[ "tu bishvat 2018"
]
, examples (datetimeHoliday (2017, 6, 23, 0, 0, 0) Day "Jumu'atul-Wida")
[ "Jamat Ul-Vida 2017"
, "Jumu'atul-Wida 2017"
]
, examples (datetimeHoliday (2018, 6, 8, 0, 0, 0) Day "Jumu'atul-Wida")
[ "Jamat Ul-Vida 2018"
, "Jumu'atul-Wida 2018"
]
, examples (datetimeHoliday (2018, 4, 13, 0, 0, 0) Day "Isra and Mi'raj")
[ "isra and mi'raj 2018"
, "the prophet's ascension 2018"
]
, examples (datetimeHoliday (2019, 4, 3, 0, 0, 0) Day "Isra and Mi'raj")
[ "the night journey 2019"
, "ascension to heaven 2019"
]
, examples (datetimeIntervalHoliday ((1950, 6, 17, 0, 0, 0), (1950, 7, 16, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 1950"
]
, examples (datetimeIntervalHoliday ((1977, 8, 15, 0, 0, 0), (1977, 9, 14, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 1977"
]
, examples (datetimeIntervalHoliday ((2018, 5, 16, 0, 0, 0), (2018, 6, 15, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2018"
]
, examples (datetimeIntervalHoliday ((2034, 11, 12, 0, 0, 0), (2034, 12, 12, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2034"
]
, examples (datetimeIntervalHoliday ((2046, 7, 5, 0, 0, 0), (2046, 8, 4, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2046"
]
, examples (datetimeIntervalHoliday ((2050, 5, 22, 0, 0, 0), (2050, 6, 21, 0, 0, 0)) Day "Ramadan")
[ "Ramadan 2050"
]
, examples (datetimeHoliday (2017, 10, 17, 0, 0, 0) Day "Dhanteras")
[ "dhanatrayodashi in 2017"
]
, examples (datetimeHoliday (2019, 10, 25, 0, 0, 0) Day "Dhanteras")
[ "dhanteras 2019"
]
, examples (datetimeHoliday (2019, 10, 26, 0, 0, 0) Day "Naraka Chaturdashi")
[ "kali chaudas 2019"
, "choti diwali two thousand nineteen"
]
, examples (datetimeHoliday (2019, 10, 27, 0, 0, 0) Day "Diwali")
[ "diwali 2019"
, "Deepavali in 2019"
, "Lakshmi Puja six years hence"
]
, examples (datetimeHoliday (2019, 10, 29, 0, 0, 0) Day "Bhai Dooj")
[ "bhai dooj 2019"
]
, examples (datetimeHoliday (2019, 11, 2, 0, 0, 0) Day "Chhath")
[ "chhath 2019"
, "dala puja 2019"
, "Surya Shashthi in 2019"
]
, examples (datetimeHoliday (2021, 10, 12, 0, 0, 0) Day "Maha Saptami")
[ "Maha Saptami 2021"
]
, examples (datetimeHoliday (2018, 10, 18, 0, 0, 0) Day "Vijayadashami")
[ "Dussehra 2018"
, "vijayadashami in five years"
]
, examples (datetimeIntervalHoliday ((2018, 10, 9, 0, 0, 0), (2018, 10, 19, 0, 0, 0)) Day "Navaratri")
[ "navaratri 2018"
, "durga puja in 2018"
]
, examples (datetimeHoliday (2018, 10, 27, 0, 0, 0) Day "Karva Chauth")
[ "karva chauth 2018"
, "karva chauth in 2018"
]
, examples (datetimeHoliday (2018, 7, 14, 0, 0, 0) Day "Ratha-Yatra")
[ "ratha-yatra 2018"
]
, examples (datetimeHoliday (2018, 8, 26, 0, 0, 0) Day "Raksha Bandhan")
[ "rakhi 2018"
]
, examples (datetimeHoliday (2020, 4, 6, 0, 0, 0) Day "Mahavir Jayanti")
[ "mahavir jayanti 2020"
, "mahaveer janma kalyanak 2020"
]
, examples (datetimeHoliday (2020, 2, 21, 0, 0, 0) Day "Maha Shivaratri")
[ "maha shivaratri 2020"
]
, examples (datetimeHoliday (2018, 2, 10, 0, 0, 0) Day "Dayananda Saraswati Jayanti")
[ "saraswati jayanti 2018"
]
, examples (datetimeHoliday (2018, 1, 14, 0, 0, 0) Day "Thai Pongal")
[ "pongal 2018"
, "makara sankranthi 2018"
]
, examples (datetimeHoliday (2018, 1, 13, 0, 0, 0) Day "Boghi")
[ "bogi pandigai 2018"
]
, examples (datetimeHoliday (2018, 1, 15, 0, 0, 0) Day "Mattu Pongal")
[ "maattu pongal 2018"
]
, examples (datetimeHoliday (2018, 1, 16, 0, 0, 0) Day "Kaanum Pongal")
[ "kaanum pongal 2018"
, "kanni pongal 2018"
]
, examples (datetimeHoliday (2019, 1, 15, 0, 0, 0) Day "Thai Pongal")
[ "makar sankranti 2019"
, "maghi in 2019"
]
, examples (datetimeHoliday (2018, 4, 14, 0, 0, 0) Day "Vaisakhi")
[ "Vaisakhi 2018"
, "baisakhi in 2018"
, "Vasakhi 2018"
, "vaishakhi 2018"
]
, examples (datetimeHoliday (2018, 8, 24, 0, 0, 0) Day "Thiru Onam")
[ "onam 2018"
, "Thiru Onam 2018"
, "Thiruvonam 2018"
]
, examples (datetimeHoliday (2019, 2, 10, 0, 0, 0) Day "Vasant Panchami")
[ "vasant panchami in 2019"
, "basant panchami 2019"
]
, examples (datetimeHoliday (2019, 3, 20, 0, 0, 0) Day "Holika Dahan")
[ "chhoti holi 2019"
, "holika dahan 2019"
, "kamudu pyre 2019"
]
, examples (datetimeHoliday (2019, 8, 23, 0, 0, 0) Day "Krishna Janmashtami")
[ "krishna janmashtami 2019"
, "gokulashtami 2019"
]
, examples (datetimeHoliday (2019, 3, 21, 0, 0, 0) Day "Holi")
[ "holi 2019"
, "dhulandi 2019"
, "phagwah 2019"
]
, examples (datetimeHoliday (2018, 8, 17, 0, 0, 0) Day "Parsi New Year")
[ "Parsi New Year 2018"
, "Jamshedi Navroz 2018"
]
, examples (datetimeHoliday (2022, 8, 16, 0, 0, 0) Day "Parsi New Year")
[ "jamshedi Navroz 2022"
, "parsi new year 2022"
]
, examples (datetimeIntervalHoliday ((2013, 4, 26, 0, 0, 0), (2013, 4, 29, 0, 0, 0)) Day "Global Youth Service Day")
[ "GYSD 2013"
, "global youth service day"
]
, examples (datetimeHoliday (2013, 5, 24, 0, 0, 0) Day "Vesak")
[ "vesak"
, "vaisakha"
, "Buddha day"
, "Buddha Purnima"
]
, examples (datetimeIntervalHoliday ((2013, 3, 23, 20, 30, 0), (2013, 3, 23, 21, 31, 0)) Minute "Earth Hour")
[ "earth hour"
]
, examples (datetimeIntervalHoliday ((2016, 3, 19, 20, 30, 0), (2016, 3, 19, 21, 31, 0)) Minute "Earth Hour")
[ "earth hour 2016"
]
, examples (datetimeHoliday (2013, 2, 23, 0, 0, 0) Day "Purim")
[ "purim"
]
, examples (datetimeHoliday (2013, 2, 24, 0, 0, 0) Day "Shushan Purim")
[ "Shushan Purim"
]
, examples (datetimeHoliday (2014, 1, 7, 0, 0, 0) Day "Guru Gobind Singh Jayanti")
[ "guru gobind singh birthday"
, "guru gobind singh jayanti 2014"
, "guru gobind singh jayanti"
, "Guru Govind Singh Jayanti"
]
, examples (datetimeHoliday (2018, 4, 27, 0, 0, 0) Day "King's Day")
[ "Koningsdag 2018"
, "koningsdag 2018"
, "king's day 2018"
, "King's Day 2018"
]
, examples (datetimeHoliday (2014, 4, 26, 0, 0, 0) Day "King's Day")
[ "Koningsdag 2014"
, "koningsdag 2014"
, "King's Day 2014"
, "king's day 2014"
]
, examples (datetimeHoliday (2018, 5, 9, 0, 0, 0) Day "Rabindra Jayanti")
[ "rabindra jayanti 2018"
, "Rabindranath Jayanti 2018"
, "Rabindra Jayanti 2018"
]
, examples (datetimeHoliday (2019, 5, 9, 0, 0, 0) Day "Rabindra Jayanti")
[ "rabindra jayanti 2019"
, "Rabindranath Jayanti 2019"
, "Rabindra Jayanti 2019"
]
, examples (datetimeHoliday (2018, 1, 31, 0, 0, 0) Day "Guru Ravidass Jayanti")
[ "guru Ravidas jayanti 2018"
, "Guru Ravidass birthday 2018"
, "guru ravidass Jayanti 2018"
]
, examples (datetimeHoliday (2019, 2, 19, 0, 0, 0) Day "Guru Ravidass Jayanti")
[ "Guru Ravidass Jayanti 2019"
, "Guru Ravidas Birthday 2019"
, "guru ravidas jayanti 2019"
]
, examples (datetimeHoliday (2019, 10, 13, 0, 0, 0) Day "Pargat Diwas")
[ "valmiki jayanti 2019"
, "Valmiki Jayanti 2019"
, "pargat diwas 2019"
]
, examples (datetimeHoliday (2018, 10, 24, 0, 0, 0) Day "Pargat Diwas")
[ "maharishi valmiki jayanti 2018"
, "pargat diwas 2018"
, "Pargat Diwas 2018"
]
, examples (datetimeHoliday (2019, 9, 2, 0, 0, 0) Day "Ganesh Chaturthi")
[ "ganesh chaturthi 2019"
]
, examples (datetimeHoliday (2020, 4, 2, 0, 0, 0) Day "Rama Navami")
[ "rama navami 2020"
]
, examples (datetimeHoliday (2018, 3, 18, 0, 0, 0) Day "Ugadi")
[ "Ugadi 2018"
, "ugadi 2018"
, "yugadi 2018"
, "Yugadi 2018"
, "samvatsaradi 2018"
, "chaitra sukladi 2018"
, "chaitra sukhladi 2018"
]
, examples (datetimeHoliday (2012, 12, 25, 0, 0, 0) Day "Christmas")
[ "the closest xmas to today"
]
, examples (datetimeHoliday (2013, 12, 25, 0, 0, 0) Day "Christmas")
[ "the second closest xmas to today"
]
, examples (datetimeHoliday (2011, 12, 25, 0, 0, 0) Day "Christmas")
[ "the 3rd closest xmas to today"
]
, examples (datetime (2013, 10, 25, 0, 0, 0) Day)
[ "last friday of october"
, "last friday in october"
]
, examples (datetime (2013, 2, 25, 0, 0, 0) Week)
[ "upcoming two weeks"
, "upcoming two week"
, "upcoming 2 weeks"
, "upcoming 2 week"
, "two upcoming weeks"
, "two upcoming week"
, "2 upcoming weeks"
, "2 upcoming week"
]
, examples (datetime (2013, 2, 14, 0, 0, 0) Day)
[ "upcoming two days"
, "upcoming two day"
, "upcoming 2 days"
, "upcoming 2 day"
, "two upcoming days"
, "two upcoming day"
, "2 upcoming days"
, "2 upcoming day"
]
, examples (datetime (2013, 4, 1, 0, 0, 0) Month)
[ "upcoming two months"
, "upcoming two month"
, "upcoming 2 months"
, "upcoming 2 month"
, "two upcoming months"
, "two upcoming month"
, "2 upcoming months"
, "2 upcoming month"
]
, examples (datetime (2013, 7, 1, 0, 0, 0) Quarter)
[ "upcoming two quarters"
, "upcoming two quarter"
, "upcoming 2 quarters"
, "upcoming 2 quarter"
, "two upcoming quarters"
, "two upcoming quarter"
, "2 upcoming quarters"
, "2 upcoming quarter"
]
, examples (datetime (2015, 1, 1, 0, 0, 0) Year)
[ "upcoming two years"
, "upcoming two year"
, "upcoming 2 years"
, "upcoming 2 year"
, "two upcoming years"
, "two upcoming year"
, "2 upcoming years"
, "2 upcoming year"
]
, examples (datetime (2013, 2, 13, 13, 40, 0) Minute)
[ "20 minutes to 2pm tomorrow"
]
, examples (datetime (2013, 1, 7, 0, 0, 0) Day)
[
"first monday of last month"
]
, examples (datetime (2013, 1, 1, 0, 0, 0) Day)
[
"first tuesday of last month"
]
, examples (datetime (2013, 1, 14, 0, 0, 0) Day)
[
"second monday of last month"
]
, examples (datetime (2013, 2, 23, 0, 0, 0) Day)
[ "next saturday" ]
, examples (datetime (2013, 2, 18, 0, 0, 0) Day)
[ "next monday" ]
]
|
f1161b7ea5646a5e36d3b981cb0331d9d24c98ef17b9f47726ab9ed919e57756 | tmattio/js-bindings | vscode_languageclient_linked_editing_range.mli | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es5
(* import * as code from 'vscode'; *)
(* import * as proto from 'vscode-languageserver-protocol'; *)
(* import { TextDocumentFeature, BaseLanguageClient } from './client'; *)
module ProvideLinkedEditingRangeSignature : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val apply
: t
-> this:unit
-> document:Code.TextDocument.t
-> position:Code.Position.t
-> token:Code.CancellationToken.t
-> Code.LinkedEditingRanges.t Code.ProviderResult.t
[@@js.apply]
end
[@@js.scope "ProvideLinkedEditingRangeSignature"]
module LinkedEditingRangeMiddleware : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val provide_linked_editing_range
: t
-> this:unit
-> document:Code.TextDocument.t
-> position:Code.Position.t
-> token:Code.CancellationToken.t
-> next:ProvideLinkedEditingRangeSignature.t
-> Code.LinkedEditingRanges.t Code.ProviderResult.t
[@@js.call "provideLinkedEditingRange"]
end
[@@js.scope "LinkedEditingRangeMiddleware"]
module LinkedEditingFeature : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val create : client:BaseLanguageClient.t -> t [@@js.create]
val fill_client_capabilities
: t
-> capabilities:Proto.ClientCapabilities.t
-> unit
[@@js.call "fillClientCapabilities"]
val initialize
: t
-> capabilities:Proto.ServerCapabilities.t
-> document_selector:Proto.DocumentSelector.t
-> unit
[@@js.call "initialize"]
val register_language_provider
: t
-> options:Proto.LinkedEditingRangeRegistrationOptions.t
-> Code.Disposable.t * Code.LinkedEditingRangeProvider.t
[@@js.call "registerLanguageProvider"]
val cast
: t
-> ( Proto.LinkedEditingRangeOptions.t or_boolean
, Proto.LinkedEditingRangeRegistrationOptions.t
, Code.LinkedEditingRangeProvider.t )
TextDocumentFeature.t
[@@js.cast]
end
[@@js.scope "LinkedEditingFeature"]
| null | https://raw.githubusercontent.com/tmattio/js-bindings/ca3bd6a12db519c8de7f41b303f14cf70cfd4c5f/lib/vscode-languageclient/vscode_languageclient_linked_editing_range.mli | ocaml | import * as code from 'vscode';
import * as proto from 'vscode-languageserver-protocol';
import { TextDocumentFeature, BaseLanguageClient } from './client'; | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es5
module ProvideLinkedEditingRangeSignature : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val apply
: t
-> this:unit
-> document:Code.TextDocument.t
-> position:Code.Position.t
-> token:Code.CancellationToken.t
-> Code.LinkedEditingRanges.t Code.ProviderResult.t
[@@js.apply]
end
[@@js.scope "ProvideLinkedEditingRangeSignature"]
module LinkedEditingRangeMiddleware : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val provide_linked_editing_range
: t
-> this:unit
-> document:Code.TextDocument.t
-> position:Code.Position.t
-> token:Code.CancellationToken.t
-> next:ProvideLinkedEditingRangeSignature.t
-> Code.LinkedEditingRanges.t Code.ProviderResult.t
[@@js.call "provideLinkedEditingRange"]
end
[@@js.scope "LinkedEditingRangeMiddleware"]
module LinkedEditingFeature : sig
type t
val t_to_js : t -> Ojs.t
val t_of_js : Ojs.t -> t
val create : client:BaseLanguageClient.t -> t [@@js.create]
val fill_client_capabilities
: t
-> capabilities:Proto.ClientCapabilities.t
-> unit
[@@js.call "fillClientCapabilities"]
val initialize
: t
-> capabilities:Proto.ServerCapabilities.t
-> document_selector:Proto.DocumentSelector.t
-> unit
[@@js.call "initialize"]
val register_language_provider
: t
-> options:Proto.LinkedEditingRangeRegistrationOptions.t
-> Code.Disposable.t * Code.LinkedEditingRangeProvider.t
[@@js.call "registerLanguageProvider"]
val cast
: t
-> ( Proto.LinkedEditingRangeOptions.t or_boolean
, Proto.LinkedEditingRangeRegistrationOptions.t
, Code.LinkedEditingRangeProvider.t )
TextDocumentFeature.t
[@@js.cast]
end
[@@js.scope "LinkedEditingFeature"]
|
d4615fe80afb474eecaf32e5e16d7b05a757f8907eb3d33a2f626a9144653376 | bhaskara/programmable-reinforcement-learning | maxq0.lisp | (defpackage maxq0
(:documentation
"Package for the MAXQ0 algorithm and associated feature templates for concurrent ALisp programs.
")
(:use common-lisp
utils
policy
calisp-obs)
(:export
<maxq0>))
(in-package maxq0)
(defclass <maxq0> (<calisp-learning-algorithm> <q-learning-algorithm>)
((prev-omega :accessor prev-omega)
(prev-u :accessor prev-u)
(prev-s :accessor prev-s)
(initq :accessor initq)
(time_elapsed :accessor time_elapsed :initform 0)
(q-function :reader q-fn :type <maxq0-q-function> :initarg :q-fn :writer set-q-fn
:initform (make-instance 'maxq0-q-function:<maxq0-q-function>
:fn-approx (make-instance 'fn-approx:<linear-fn-approx>)))
(eta-fn :reader eta-fn :initarg eta-fn :initform eta-linear-tabular)
(reward-decomposer :reader reward-decomposer :initarg :reward-decomposer)
(:documentation "Class <maxq0>. Subclass of <calisp-learning-algorithm> that uses MAXQ0-learning.
Initargs
:t-lrate learning rate
:q-fn q-function
"))
(defmethod initialize-instance :after ((alg <maxq>) &rest args &key q-function)
(declare (ignore args))
(setf (initq alg) (clone q-function)))
(defmethod inform-start-episode ((alg <maxq0>) s)
(setf (prev-s alg) s)
(slot-makunbound alg 'prev-omega)
(slot-makunbound alg 'prev-u))
(defmethod inform-calisp-step ((alg <maxq0>) omega u)
(setf (prev-omega alg) omega
(prev-u alg) u))
(defmethod inform-env-step ((alg <maxq0) act rew next term)
(when (slot-boundp alg 'prev-omega)
(let ((rewards (funcall (reward-decomposer alg) (prev-omega alg) (prev-s alg) act rew next)))
(assert (= rew (reduce #'+ rewards :key #'cdr)) ()
"Rewards ~a don't add up to ~a in reward decomposition for doing ~a in ~a and getting to ~a" rewards rew act (prev-s alg) next)
(dolist (trew rewards)
(let ((tid (car trew))
(drew (cdr trew)))
(update-tid (q-fn alg) (prev-omega alg) nil drew
(funcall (eta-fn alg) (get-subtask (prev-omega alg) tid) time_elapsed) tid)))))
(setf (prev-s alg) next))
(defmethod inform-end-choice-block ((alg <maxq0>) tid omega)
(update-tid (q-fn alg) (prev-omega alg) (get-subtask omega tid)
(evaluate-max-node omega (get-subtask (prev-omega alg) tid) tid)
(funcall (eta-fn alg) (get-subtask (prev-omega alg) tid) time_elapsed) tid))
(defun eta-linear-tabular (subtask time)
(if (equalp subtask "goto") 0.001
0.01))
NOTE : Ask whether there is an easy way to store the previous omega with respect to
;; inform-end-choice-block | null | https://raw.githubusercontent.com/bhaskara/programmable-reinforcement-learning/8afc98116a8f78163b3f86076498d84b3f596217/lisp/envs/stratagus/resource/maxq0.lisp | lisp | inform-end-choice-block | (defpackage maxq0
(:documentation
"Package for the MAXQ0 algorithm and associated feature templates for concurrent ALisp programs.
")
(:use common-lisp
utils
policy
calisp-obs)
(:export
<maxq0>))
(in-package maxq0)
(defclass <maxq0> (<calisp-learning-algorithm> <q-learning-algorithm>)
((prev-omega :accessor prev-omega)
(prev-u :accessor prev-u)
(prev-s :accessor prev-s)
(initq :accessor initq)
(time_elapsed :accessor time_elapsed :initform 0)
(q-function :reader q-fn :type <maxq0-q-function> :initarg :q-fn :writer set-q-fn
:initform (make-instance 'maxq0-q-function:<maxq0-q-function>
:fn-approx (make-instance 'fn-approx:<linear-fn-approx>)))
(eta-fn :reader eta-fn :initarg eta-fn :initform eta-linear-tabular)
(reward-decomposer :reader reward-decomposer :initarg :reward-decomposer)
(:documentation "Class <maxq0>. Subclass of <calisp-learning-algorithm> that uses MAXQ0-learning.
Initargs
:t-lrate learning rate
:q-fn q-function
"))
(defmethod initialize-instance :after ((alg <maxq>) &rest args &key q-function)
(declare (ignore args))
(setf (initq alg) (clone q-function)))
(defmethod inform-start-episode ((alg <maxq0>) s)
(setf (prev-s alg) s)
(slot-makunbound alg 'prev-omega)
(slot-makunbound alg 'prev-u))
(defmethod inform-calisp-step ((alg <maxq0>) omega u)
(setf (prev-omega alg) omega
(prev-u alg) u))
(defmethod inform-env-step ((alg <maxq0) act rew next term)
(when (slot-boundp alg 'prev-omega)
(let ((rewards (funcall (reward-decomposer alg) (prev-omega alg) (prev-s alg) act rew next)))
(assert (= rew (reduce #'+ rewards :key #'cdr)) ()
"Rewards ~a don't add up to ~a in reward decomposition for doing ~a in ~a and getting to ~a" rewards rew act (prev-s alg) next)
(dolist (trew rewards)
(let ((tid (car trew))
(drew (cdr trew)))
(update-tid (q-fn alg) (prev-omega alg) nil drew
(funcall (eta-fn alg) (get-subtask (prev-omega alg) tid) time_elapsed) tid)))))
(setf (prev-s alg) next))
(defmethod inform-end-choice-block ((alg <maxq0>) tid omega)
(update-tid (q-fn alg) (prev-omega alg) (get-subtask omega tid)
(evaluate-max-node omega (get-subtask (prev-omega alg) tid) tid)
(funcall (eta-fn alg) (get-subtask (prev-omega alg) tid) time_elapsed) tid))
(defun eta-linear-tabular (subtask time)
(if (equalp subtask "goto") 0.001
0.01))
NOTE : Ask whether there is an easy way to store the previous omega with respect to |
6ac0fd228e614f9b703d8e856c2d065e843e11239811e83d771f3248e113845e | Funky-Punky/FPV_SS22_Repetitorium | assignment.mli | module type Queue = sig
type 'a t
exception NoElementLeft
val create_queue : unit -> 'a t
val enqueue : 'a t -> 'a -> unit
val dequeue_opt : 'a t -> 'a option
val dequeue : 'a t -> 'a
val empty : 'a t -> unit
val reverse : 'a t -> unit
val discard_queue : 'a t -> unit
end
module MyQueue : Queue
| null | https://raw.githubusercontent.com/Funky-Punky/FPV_SS22_Repetitorium/99e0d0f63513d3b809d7b26bb1a511f28d1d71c3/solutions/queue/src/assignment.mli | ocaml | module type Queue = sig
type 'a t
exception NoElementLeft
val create_queue : unit -> 'a t
val enqueue : 'a t -> 'a -> unit
val dequeue_opt : 'a t -> 'a option
val dequeue : 'a t -> 'a
val empty : 'a t -> unit
val reverse : 'a t -> unit
val discard_queue : 'a t -> unit
end
module MyQueue : Queue
| |
efaec2ef18befa58e685ddeea4166ff6f6af760f00c906c799b4f4c0cb0a680e | ryanpbrewster/haskell | number_pairs.hs | -- number_pairs.hs
- You are given a sorted array of positive integers and a number ' X ' . Print
- out all pairs of numbers whose sum is equal to X. Print out only unique
- pairs and the pairs should be in ascending order
- Input sample :
-
- Your program should accept as its first argument a filename . This file will
- contain a comma separated list of sorted numbers and then the sum ' X ' ,
- separated by semicolon . Ignore all empty lines . If no pair exists , print the
- string NULL eg .
-
- 1,2,3,4,6;5
- 2,4,5,6,9,11,15;20
- 1,2,3,4;50
-
- Output sample :
-
- Print out the pairs of numbers that equal to the sum X. The pairs should
- themselves be printed in sorted order i.e the first number of each pair
- should be in ascending order .e.g .
-
- 1,4;2,3
- 5,15;9,11
- NULL
- You are given a sorted array of positive integers and a number 'X'. Print
- out all pairs of numbers whose sum is equal to X. Print out only unique
- pairs and the pairs should be in ascending order
- Input sample:
-
- Your program should accept as its first argument a filename. This file will
- contain a comma separated list of sorted numbers and then the sum 'X',
- separated by semicolon. Ignore all empty lines. If no pair exists, print the
- string NULL eg.
-
- 1,2,3,4,6;5
- 2,4,5,6,9,11,15;20
- 1,2,3,4;50
-
- Output sample:
-
- Print out the pairs of numbers that equal to the sum X. The pairs should
- themselves be printed in sorted order i.e the first number of each pair
- should be in ascending order .e.g.
-
- 1,4;2,3
- 5,15;9,11
- NULL
-}
import Data.List (intercalate, sort)
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
pairsThatSumTo targ [] = []
pairsThatSumTo targ (x:xs) = let useit = [ (x,y) | y <- xs, x+y == targ ]
loseit = pairsThatSumTo targ xs
in useit ++ loseit
showPairs [] = "NULL"
showPairs prs = let prs' = [ (show p) ++ "," ++ (show q) | (p,q) <- prs ]
in intercalate ";" prs'
solveProblem txt = let inputs = [ map read $ wordsBy ",;" ln | ln <- lines txt ]
anss = [ pairsThatSumTo (last inp) (init inp) | inp <- inputs ]
outputs = map (showPairs.sort) anss
in unlines outputs
wordsBy delims s = wordsBy' delims s
where wordsBy' _ [] = []
wordsBy' delims s = let (f,r) = break (`elem` delims) s
in f:wordsBy' delims (dropWhile (`elem` delims) r)
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/number_pairs.hs | haskell | number_pairs.hs |
- You are given a sorted array of positive integers and a number ' X ' . Print
- out all pairs of numbers whose sum is equal to X. Print out only unique
- pairs and the pairs should be in ascending order
- Input sample :
-
- Your program should accept as its first argument a filename . This file will
- contain a comma separated list of sorted numbers and then the sum ' X ' ,
- separated by semicolon . Ignore all empty lines . If no pair exists , print the
- string NULL eg .
-
- 1,2,3,4,6;5
- 2,4,5,6,9,11,15;20
- 1,2,3,4;50
-
- Output sample :
-
- Print out the pairs of numbers that equal to the sum X. The pairs should
- themselves be printed in sorted order i.e the first number of each pair
- should be in ascending order .e.g .
-
- 1,4;2,3
- 5,15;9,11
- NULL
- You are given a sorted array of positive integers and a number 'X'. Print
- out all pairs of numbers whose sum is equal to X. Print out only unique
- pairs and the pairs should be in ascending order
- Input sample:
-
- Your program should accept as its first argument a filename. This file will
- contain a comma separated list of sorted numbers and then the sum 'X',
- separated by semicolon. Ignore all empty lines. If no pair exists, print the
- string NULL eg.
-
- 1,2,3,4,6;5
- 2,4,5,6,9,11,15;20
- 1,2,3,4;50
-
- Output sample:
-
- Print out the pairs of numbers that equal to the sum X. The pairs should
- themselves be printed in sorted order i.e the first number of each pair
- should be in ascending order .e.g.
-
- 1,4;2,3
- 5,15;9,11
- NULL
-}
import Data.List (intercalate, sort)
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
pairsThatSumTo targ [] = []
pairsThatSumTo targ (x:xs) = let useit = [ (x,y) | y <- xs, x+y == targ ]
loseit = pairsThatSumTo targ xs
in useit ++ loseit
showPairs [] = "NULL"
showPairs prs = let prs' = [ (show p) ++ "," ++ (show q) | (p,q) <- prs ]
in intercalate ";" prs'
solveProblem txt = let inputs = [ map read $ wordsBy ",;" ln | ln <- lines txt ]
anss = [ pairsThatSumTo (last inp) (init inp) | inp <- inputs ]
outputs = map (showPairs.sort) anss
in unlines outputs
wordsBy delims s = wordsBy' delims s
where wordsBy' _ [] = []
wordsBy' delims s = let (f,r) = break (`elem` delims) s
in f:wordsBy' delims (dropWhile (`elem` delims) r)
|
abf3f13cd44cd742e49448717088ed7c15e21a12d824c67fe5383b254a965aac | picty/parsifal | libntp.ml | open Parsifal
open BasePTypes
open PTypes
alias association_id = uint16
alias keyid = uint32
alias reference_clock_code [novalueof] = string(4)
let value_of_reference_clock_code refcode =
let value =
match refcode with
| "GOES" -> "GEOS Geosynchroneous Orbit Environment Satellite"
| "GPS\x00" -> "GPS Global Position System"
| "GAL\x00" -> "GAL Galileo Positioning System"
| "PPS\x00" -> "PPS Generic pulse-per-second"
| "IRIG" -> "IRIG Inter-Range Instrumentation Group"
| "WWVB" -> "WWVB LF Radio WWVB FR. Collins, CO 60 kHz"
| "DCF\x00" -> "DCF LF Radio DCF77 Mainflingen, DE 77.5 kHz"
| "HBG\x00" -> "HBG LF Radio HBG Prangins, HB 75 kHz"
| "MSF\x00" -> "MSF LF Radio MSF Anthorn, UK 60 kHz"
| "JJY\x00" -> "JJY LF Radio JJY Fukushima, JP 40 kHz, Saga, JP 60 kHz"
| "LORC" -> "LORC MF Radio LORAN C station, 100 kHz"
| "TDF\x00" -> "TDF MF Radio Allouis, FR 162 kHz"
| "CHU\x00" -> "CHU HF Radio CHU Ottawa, Ontario"
| "WWV\x00" -> "WWV HF Radio Ft. Collins, CO"
| "WWVH" -> "WWVH HF Radio WWVH Kauai, HI"
| "NIST" -> "NIST NIST telephone modem"
| "ACTS" -> "ACTS NIST telephone modem"
| "USNO" -> "USNO USNO telephone modem"
| "PTB\x00" -> "PTB European telephone modem"
| _ -> refcode
in
VString(value, true)
enum mode_enum (3, UnknownVal ReservedMode) =
| 1 -> SymmetricActiveMode, "1 Symmetric Active"
| 2 -> SymmetricPassiveMode, "2 Symmetric Passive"
| 3 -> ClientMode, "3 Client"
| 4 -> ServerMode, "4 Server"
| 5 -> BroadcastMode, "5 Broadcast"
| 6 -> NTPControlMsgMode, "6 NTP control message"
| 7 -> PrivateUseMode, "7 Reserved for private use"
enum host_mode_enum (8, UnknownVal UnspecifiedMode) =
| 1 -> SymmetricActiveMode, "1 Symmetric Active"
| 2 -> SymmetricPassiveMode, "2 Symmetric Passive"
| 3 -> ClientMode, "3 Client"
| 4 -> ServerMode, "4 Server"
| 5 -> BroadcastMode, "5 Broadcast"
| 6 -> NTPControlMsgMode, "6 NTP control message"
| 7 -> PrivateUseMode, "7 Reserved for private use"
| 8 -> BClientMode, "8 BClient"
(* RFC1305 %B.1 *)
enum opcode(5, UnknownVal ReservedOpcode) =
| 1 -> ReadStatOpCode, "Read status command/response"
| 2 -> ReadVarOpCode, "Read variables command/response"
| 3 -> WriteVarOpCode, "Write variables command/response"
| 4 -> ReadClockVarOpCode, "Read clock variables command/response"
| 5 -> WriteClockVarOpCode, "Write clock variables command/response"
| 6 -> SetTrapOpCode, "Set trap address/port command/response"
| 7 -> TrapOpCode, "Trap response"
(* RFC1305 %B.2.3 *)
enum clock_source (6, UnknownVal ReservedSource) =
| 0 -> UnspecifiedSource
| 1 -> CalibratedAtomicClock, "Calibrated atomic clock (e.g. HP 5061)"
| 2 -> VLFRadio, "VLF (band 4) or LF (band 5) radio (e.g. OMEGA, WWVB)"
| 3 -> HFRadio, "HF (band 7) radio (e.g. CHU, MSF, WWVH)"
| 4 -> UHFSat, "UHF (band 9) satellite (e.g. GOES, GPS)"
| 5 -> LocalNet, "local net (e.g. DCN, TSP, DTS)"
| 6 -> UDPNTP, "UDP/NTP"
| 7 -> UDPTIME, "UDP/TIME"
| 8 -> Manual, "Eyeball and wrist watch"
| 9 -> TelephoneModem, "Telephone modem (e.g. NIST)"
(* RFC1305 %B.2.1 *)
enum evt_code (4, UnknownVal ReservedEvtCode) =
| 0 -> UnspecifiedEvtCode, "Unspecified event"
| 1 -> SysRestart, "System restart"
| 2 -> SysFault, "System or Hardware Fault"
| 3 -> SysNewStatus, "System new status word (leap bits or synchronization change)"
| 4 -> SysNewSyncSource, "System new synchronization source or stratum (sys.peer or sys.stratum change)"
| 5 -> SysClockReset, "System clock reset (offset correction exceeds CLOCK.MAX)"
| 6 -> SysInvalidTime, "System invalid time or date"
| 7 -> SysClockExn, "System clock exception"
enum leap_indicator (2, UnknownVal UnknownLeapIndicator) =
| 0 -> NoWarning, "No warning"
| 1 -> Plus1Sec, "Last minute of the day has 61 seconds"
| 2 -> Minus1Sec, "Last minute of the day has 59 seconds"
| 3 -> UnknownState, "Unknown (clock unsychronized)"
(* RFC1305 %B.2.1 *)
struct system_status_word = {
leap_indicator: leap_indicator;
clock_source: clock_source;
evt_counter: bit_int[4];
evt_code: evt_code;
}
(* RFC1305 %B.2.2 *)
struct peer_status = {
peer_config: bit_bool;
peer_authenable: bit_bool;
peer_authentic: bit_bool;
peer_reach: bit_bool;
reserved: bit_bool;
}
(* RFC1305 %B.2.2 *)
enum peer_selection (3, UnknownVal ReservedPeerSelection) =
| 0 -> RejectedSelection, "Rejected"
| 1 -> PassedSanityChecks, "Passed sanity checks"
| 2 -> PassedCandidateChecks, "Passed candidate checks"
| 3 -> PassedOutlyerChecks, "Passed outlyer checks"
| 4 -> CurrentSyncSourceDistExceeded, "Current synchronization source; max distance exceeded"
| 6 -> CurrentSyncSourceDistOkay, "Current synchronization source; max distance okay"
(* RFC1305 %B.2.2 *)
enum peer_evt_code (4, UnknownVal ReservedEvtCode) =
| 0 -> UnspecifiedEvtCode, "Unspecified"
| 1 -> PeerIPErr, "Peer IP error"
| 2 -> PeerAuthFail, "Peer authentication failure"
| 3 -> PeerUnreach, "Peer unreachable"
| 4 -> PeerReach, "Peer now reachable"
| 5 -> PeerClockExn, "Peer clock exception"
(* RFC1305 %B.2.2 *)
struct peer_status_word = {
peer_status: peer_status;
peer_selection: peer_selection;
peer_evt_counter: bit_int[4];
peer_evt_code: peer_evt_code;
}
(* RFC1305 %B.2.3 *)
enum clock_status (8, UnknownVal ReservedClockStatus) =
| 0 -> ClockNominalStatus, "Clock operating within nominals"
| 1 -> ReplyTimeoutStatus, "Reply timeout"
| 2 -> BadReplyFormatStatus, "Bad reply format"
| 3 -> HardwareOrSoftwareFault, "Hardware of software fault"
| 4 -> PropagationFailure, "Propagation failure"
| 5 -> BadDateFormatOrVal, "Bad date format or value"
| 6 -> BadTimeFormatOrVal, "Bad time format or value"
(* RFC1305 %B.2.3 *)
struct clock_status_word = {
clock_status: clock_status;
FM : XXX I do n't understand the content of this field . Unparsed at the moment
}
(* RFC1305 %B.2.4 *)
enum error_code (8, UnknownVal ReservedError) =
| 0 -> UnspecifiedError, "Unspecified"
| 1 -> AuthFail, "Authentication failure"
| 2 -> InvalidMsgLenOrFormat, "Invalid message length or format"
| 3 -> InvalidOpCode, "Invalid opcoode"
| 4 -> UnknownAssocID, "Unknown association ID"
| 5 -> UnknownVarName, "Unknown variable name"
| 6 -> InvalidVarVal, "Invalid variable value"
| 7 -> AdminProhibited, "Administratively prohibited"
(* RFC1305 %B.2.4 *)
struct error_status_word = {
error_code: error_code;
placeholder: uint8;
}
(* RFC1305 %B.2 *)
type status_words = | SystemStatusWord of system_status_word
| PeerStatusWord of peer_status_word
| ClockStatusWord of clock_status_word
| ErrorStatusWord of error_status_word
| UnparsedStatusWord of binstring
let parse_status_words response error opcode association_id unparsed_status input =
let new_input = get_in_container input "status_word_container" unparsed_status in
match response, error, opcode, association_id with
| true, false, ReadStatOpCode, 0
| true, false, ReadVarOpCode, 0 -> SystemStatusWord (parse_system_status_word new_input)
| true, false, ReadStatOpCode, _
| true, false, ReadVarOpCode, _
| true, false, WriteVarOpCode, _ -> PeerStatusWord (parse_peer_status_word new_input)
| _, false, ReadClockVarOpCode, _
| _, false, WriteClockVarOpCode, _ -> ClockStatusWord (parse_clock_status_word new_input)
| true, true, _, _ -> ErrorStatusWord (parse_error_status_word new_input)
| _ -> (UnparsedStatusWord unparsed_status)
let value_of_status_words v =
match v with
| SystemStatusWord x -> value_of_system_status_word x
| PeerStatusWord x -> value_of_peer_status_word x
| ClockStatusWord x -> value_of_clock_status_word x
| ErrorStatusWord x -> value_of_error_status_word x
| UnparsedStatusWord x -> VString(x, true)
let compute_len_of_data_in_control_packet len input =
let remlen = input.cur_length - input.cur_offset in
if len > remlen then
(* XXX FM: Do we really want to accept that the len is nonesense and still parse it? *)
remlen
else
min 468 len
let compute_padding_len_in_control_packet len =
let rem = len mod 4 in
if rem <> 0 then
4 - rem
else
0
(* RFC1305 %B.3 Read status *)
struct assoc_status = {
association_id: association_id;
status_word: peer_status_word;
}
alias associations_statuses = list of assoc_status
union control_data [enrich] (UnparsedData of binstring) =
| ReadStatOpCode, 0 -> BinStatusData of associations_statuses
| ReadStatOpCode, _ -> StatusData of string
| ReadVarOpCode, _ -> VariablesRead of string
| WriteVarOpCode, _ -> VariablesWritten of string
| ReadClockVarOpCode, _ -> ClockRead of string
| WriteClockVarOpCode, _ -> ClockWritten of string
| SetTrapOpCode, _ -> SetTrap of string
| TrapOpCode, _ -> GotTrap of string
RFC 1305 % B.1
struct control_packet = {
null_magic: bit_int[2];
version: bit_int[3];
mode: mode_enum;
response: bit_bool;
error: bit_bool;
more: bit_bool;
opcode: opcode;
sequence: uint16;
unparsed_status: binstring(2);
association_id: association_id;
parse_field status: status_words(response; error; opcode; association_id; unparsed_status);
offset: uint16;
len: uint16;
data: container(compute_len_of_data_in_control_packet len input) of control_data(opcode, association_id);
optional padding: binstring(compute_padding_len_in_control_packet len);
optional authenticator: binstring(12);
}
struct authentication_material = {
keyid: keyid;
digest: binstring(16);
}
enum implementation_id (8, UnknownVal UnknownImplementation) =
| 0 -> UNIV, "UNIV"
| 2 -> OldXNTPD, "Old NTPd pre IPv6"
| 3 -> XNTPD, "NTPd post IPv6"
| 255 -> ReservedImplId, "Reserved ID"
enum mod7reqcode (8, UnknownVal UnknownReqCode) =
| 0 -> ReqPeerList, "Request Peer List"
| 1 -> ReqPeerListSum, "Request summary of all peers"
| 2 -> ReqPeerInfo, "Request standard peer info"
| 3 -> ReqPeerStats, "Request peer statistics"
| 4 -> ReqSysInfo, "Request peer information"
| 5 -> ReqSysStats, "Request system statistics"
| 6 -> ReqIOStats, "Request I/0 stats"
| 7 -> ReqMemStats, "Request memory statistics"
| 8 -> ReqLoopInfo, "Request information from the loop filter"
| 9 -> ReqTimerStats, "Request time statistics"
| 10 -> ReqConfig, "Request to configure a new peer"
| 11 -> ReqUnconfig, "Request to unconfigure an existing peer"
| 12 -> ReqSetSysFlag, "Request to set system flags"
| 13 -> ReqClearSysFlag, "Request to clear system flags"
| 14 -> ReqMonitor, "Monitor (unused)"
| 15 -> ReqNoMonitor, "No Monitor (unused)"
| 16 -> ReqGetRestrict, "Request restrict list"
| 17 -> ReqResAddFlags, "Request flags addition to restrict list"
| 18 -> ReqResSubFlags, "Request flags removal to restrict list"
| 19 -> ReqUnrestrict, "Request entry removal from retrict list"
| 20 -> ReqMonGetlist, "Return data collected by monitor"
| 21 -> ReqResetStats, "Request reset of statistics counters"
| 22 -> ReqResetPeer, "Request reset of peer statistics counters"
| 23 -> ReqRereadKeys, "Request reread of the encryption key files"
| 24 -> ReqDoDirtyHack, "Do some dirty hack (unused)"
| 25 -> ReqDontDirtyHack, "Dont do some dirty hack (unused)"
| 26 -> ReqTrustKey, "Request a trusted key addition"
| 27 -> ReqUntrustKey, "Request a trusted key removal"
| 28 -> ReqAuthInfo, "Request authentication information"
| 29 -> ReqTraps, "Request currently set traps list"
| 30 -> ReqAddTrap, "Request trap addition"
| 31 -> ReqClearTrap, "Request trap clearance"
| 32 -> ReqRequestKey, "Define a new request keyid"
| 33 -> ReqControlKey, "Define a new control keyid"
| 34 -> ReqGetControlStats, "Get statistics from the control module"
| 35 -> ReqGetLeapInfo, "Get leap info (unused)"
| 36 -> ReqGetClockInfo, "Get clock information"
| 37 -> ReqGetClockFudge, "Get clock fudge factors"
| 38 -> ReqGetKernel, "Get kernel ppl/pps infos"
| 39 -> ReqGetClockBugInfo, "Get clock debugging info"
| 41 -> ReqSetPrecision, "Set precision (unused)"
| 42 -> ReqMonGetList1, "Return collected v1 monitor data"
| 43 -> ReqHostnameAssocID, "Return hostname association id"
| 44 -> ReqIfStats, "Get interface statistics"
| 45 -> ReqIfReload, "Request interface list reloading"
enum mod7errcode (4, UnknownVal UnspecifiedError) =
| 0 -> NoError, "No error"
| 1 -> IncompatibleImplNum, "Incompatible implementation number"
| 2 -> UnimplReqCode, "Unimplemented request code"
| 3 -> FmtErr, "Format error (wrong data items, data size, packet size etc.)"
| 4 -> NoData, "No data available (e.g. request for details on unknown peer)"
| 5 | 6 -> DontKnow, "I don't know"
| 7 -> AuthFail, "Authentication failure"
alias ip4_mask = ipv4
alias ip6_mask = ipv6
mod7_peer_info_flags should be 8 bits , but it seeps developers
try to have a 9 - th flag , iburst ( in ntp_request.h , INFO_IBURST_FLAG
is 0x100 ... which is out of range of a . This is why we may need
a 16 - bit version of these flags .
try to have a 9-th flag, iburst (in ntp_request.h, INFO_IBURST_FLAG
is 0x100... which is out of range of a u_char. This is why we may need
a 16-bit version of these flags. *)
struct mod7_peer_info_flags [param long_version]= {
placeholder: conditional_container(long_version) of list(7) of bit_bool;
iburst: conditional_container(long_version) of bit_bool;
short_list: bit_bool;
sel_candidate: bit_bool;
authenable: bit_bool;
prefer: bit_bool;
refclock: bit_bool;
burst: bit_bool;
syspeer: bit_bool;
config: bit_bool;
}
alias mod7_peer_info_flags_16bits = mod7_peer_info_flags(true)
alias mod7_peer_info_flags_8bits = mod7_peer_info_flags(false)
type uint32_boolean = bool
let parse_uint32_boolean input =
(parse_uint32 input) <> 0
let dump_uint32_boolean buf b =
dump_uint32 buf (if b then 1 else 0)
let value_of_uint32_boolean b = VBool b
struct mod7_req_peer_list = {
addr: ipv4;
port: uint16;
hmode: host_mode_enum;
flags: mod7_peer_info_flags_8bits;
v6_flag: uint32_boolean;
placeholder: uint32;
v6addr: ipv6;
}
(* include/ntp_fp.h *)
struct ul_fp = {
integral_part: uint32;
fractional_part: uint32;
}
struct sl_fp = {
integral_part: sint32;
fractional_part: sint32;
}
alias s_fp = sint32
alias l_fp = ul_fp
alias u_fp = uint32
struct mod7_req_peer_list_sum = {
dst_addr: ipv4;
src_addr: ipv4;
src_port: uint16;
stratum: uint8;
host_polling_interval: sint8;
peer_polling_interval: sint8;
reachability: uint8;
flags: mod7_peer_info_flags_8bits;
hmode: host_mode_enum;
delay: s_fp;
offset: l_fp;
dispersion: u_fp;
v6_flag: uint32_boolean;
placeholder: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_req_peer_info = {
dstaddr: ipv4;
srcaddr: ipv4;
src_port: uint16;
flags: mod7_peer_info_flags_8bits;
XXX FM : this is a leap_indicator with 6 useless bits
hmode: host_mode_enum;
pmode: host_mode_enum;
stratum: uint8;
peer_polling_interval: uint8;
host_polling_interval: uint8;
precision: sint8;
sometimes , it is only a 3 bit long value ...
placeholder: uint8;
reachability: uint8; (* XXX FM Is this a boolean? *)
unreachability: uint8; (* XXX FM Is this a boolean? *)
flash: uint8;
ttl: uint8;
flash2: uint16;
association_id: association_id;
keyid: keyid;
placeholder_pkeyid: uint32;
reference_id: reference_clock_code;
timer: uint32;
rootdelay: s_fp;
rootdispersion: u_fp;
ref_timestamp: l_fp;
origin_timestamp_org: l_fp;
receive_timestamp_rec: l_fp;
transmit_timestamp_xmt: l_fp;
8 is the NTP_SHIFT value defined in include / ntp.h from version 4.2.6.p5
filtoffset: list(8) of l_fp;
order: list(8) of uint8;
delay: s_fp;
dispersion: u_fp;
offset: l_fp;
selectdisp: u_fp;
placeholder2: list(7) of sint32;
estbdelay: s_fp;
v6_flag: uint32_boolean;
placeholder3: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_req_peer_stats = {
dstaddr: ipv4;
srcaddr: ipv4;
src_port: uint16;
flags: mod7_peer_info_flags_16bits;
time_reset: uint32;
time_received: uint32;
time_tosend: uint32;
time_reachable: uint32;
sent: uint32;
placeholder: uint32;
processed: uint32;
placeholder2: uint32;
badauth: uint32;
bogus_origin: uint32;
old_packet: uint32; (* duplicates *)
placeholder3: list(2) of uint32;
bad_dispersion: uint32;
bad_ref_time: uint32;
placeholder4: uint32;
candidate: uint8;
placeholder5: list(3) of uint8;
v6_flag: uint32_boolean;
placeholder6: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_loop_info = {
last_offset: l_fp;
drift_comp: l_fp;
compliance: uint32;
watchdog_timer: uint32;
}
struct mod7_sys_info_flags = {
pps_sync: bit_bool;
cal: bit_bool;
filegen: bit_bool;
monitor: bit_bool;
kernel: bit_bool;
ntp: bit_bool; (* what else? *)
authenticate: bit_bool;
bclient: bit_bool; (* XXX FM: broadcast client ? *)
}
struct mod7_sys_info = {
peer: ipv4;
peer_mode: host_mode_enum;
XXX FM : is that the same as the leap indicators but on 8 bits ?
stratum: uint8;
precision: sint8;
rootdelay: s_fp;
rootdispersion: u_fp;
reference_id: reference_clock_code;
reference_time: l_fp;
sys_polling_interval: uint32;
flags: mod7_sys_info_flags;
placeholder: list(3) of uint8;
broadcast_offset: s_fp;
frequency: s_fp;
authdelay: ul_fp;
stability: u_fp;
v6_flag: uint32_boolean;
placeholder2: uint32;
peer_v6_addr: ipv6;
}
struct mod7_sys_stats = {
time_since_restart: uint32;
time_since_reset: uint32;
access_denied_cnt: uint32;
old_version_pckt_cnt: uint32;
new_version_pckt_cnt: uint32;
unknown_version_pckt_cnt: uint32;
bad_len_or_format_cnt: uint32;
processed_pckt_cnt: uint32;
bad_auth_cnt: uint32;
received_pckt_cnt: uint32;
rate_exceeded_cnt: uint32;
}
struct mod7_mem_stats = {
time_since_reset: uint32;
total_peer_mem: uint16;
free_peer_mem: uint16;
find_peer_calls: uint32;
allocations: uint32;
demobilizations: uint32;
128 is from NTP_HASH_SIZE defined in include / ntp.h
}
struct mod7_io_stats = {
time_since_reset: uint32;
total_recv_bufs: uint16;
free_recv_bufs: uint16;
full_recv_bufs: uint16;
low_water: uint16; (* number of times we've added buffers ; comment extracted from source code *)
dropped_pckt_cnt: uint32;
ignored_pckt_cnt: uint32;
received_pckt_cnt: uint32;
sent_pckt_cnt: uint32;
not_sent_pckt_cnt: uint32;
interrupts_cnt: uint32;
int_received: uint32;
}
struct mod7_timer_stats = {
time_since_reset: uint32;
alarms_cnt: uint32;
overflows_cnt: uint32;
xmt_calls: uint32;
}
struct mod7_conf_flags = {
two highest flags are undefined in ntp 4.2.6.p5
skey: bit_bool;
noselect: bit_bool;
iburst: bit_bool;
burst: bit_bool;
prefer: bit_bool;
authenable: bit_bool;
}
struct mod7_conf_peer = {
peer_addr: ipv4;
hmode: host_mode_enum;
sometimes it is only 3 bit long ...
min_host_polling_interval: uint8;
max_host_polling_interval: uint8;
flags: mod7_conf_flags;
ttl: uint8;
placeholder: uint16;
keyid: keyid;
pubkey_filename: string(256);
v6_flag: uint32_boolean;
placeholder2: uint32;
peer_v6_addr: ipv6;
}
struct mod7_conf_unpeer = {
peer_addr: ipv4;
v6_flag: uint32_boolean;
peer_v6_addr: ipv6;
}
struct mod7_sys_flags = {
placeholder: list(24) of bit_bool; (* undefined flags *)
cal: bit_bool;
auth: bit_bool;
filegen: bit_bool;
monitor: bit_bool;
kernel: bit_bool;
ntp: bit_bool; (* what else ? *)
pps: bit_bool;
bclient: bit_bool;
}
As for mod7_peer_info_flags , some developers of NTPd think that the
bit field should be 32 bits , others 16 bits ... it varies following
the structure ... there is only 13 bits defined anyway ...
bit field should be 32 bits, others 16 bits... it varies following
the structure... there is only 13 bits defined anyway... *)
struct mod7_restrict_flags [param four_bytes_version] = {
placeholder: conditional_container(four_bytes_version) of list(16) of bit_bool;
placeholder2: list(3) of bit_bool;
timeout: bit_bool; (* timeout this entry *)
ms_sntp: bit_bool; (* enable ms-sntp authentication *)
kod: bit_bool; (* send kiss of death packet *)
lp_trap: bit_bool; (* low priority trap *)
no_trap: bit_bool; (* set trap denied *)
no_modify: bit_bool; (* modify denied *)
mod 6/7 denied
limited: bit_bool; (* rate limited *)
no_peer: bit_bool; (* new association denied *)
version: bit_bool; (* version mismatch *)
called in code source DONTTRUST
dont_serve: bit_bool; (* access denied *)
ignore: bit_bool; (* ignore packet *)
}
alias mod7_restrict_flags_16bits = mod7_restrict_flags(false)
alias mod7_restrict_flags_32bits = mod7_restrict_flags(true)
struct mod7_match_flags = {
placeholder: list(2) of bit_bool;
ntp_only: bit_bool;
interface: bit_bool;
placeholder2: list(12) of bit_bool;
}
struct mod7_info_restrict = {
addr: ipv4;
mask: ip4_mask;
count: uint32;
flags: mod7_restrict_flags_16bits;
mflags: mod7_match_flags;
v6_flag: uint32_boolean;
placeholder: uint32;
addr6: ipv6;
mask6: ip6_mask;
}
struct mod7_set_restrict = {
addr: ipv4;
mask: ip4_mask;
flags: mod7_restrict_flags_16bits;
mflags: mod7_match_flags;
v6_flag: uint32_boolean;
addr6: ipv6;
mask6: ip6_mask;
}
struct mod7_padded_mode_enum = {
placeholder: list(5) of bit_bool;
mode: mode_enum;
}
struct mod7_monlist_gen [param monlist1_version] = {
last_pckt_timestamp: uint32;
first_pckt_timestamp: uint32;
restrict_flags: mod7_restrict_flags_32bits;
pckt_recv_cnt: uint32;
host_addr: ipv4;
dest_addr: conditional_container(monlist1_version) of ipv4;
XXX FM : it could be mod7_peer_info_flags BUT mod7_peer_info_flags
are only 8 bits long ( or 9 ... it depends ... ; so do n't know ; do n't enrich
are only 8 bits long (or 9... it depends... ; so don't know ; don't enrich *)
flags: conditional_container(monlist1_version) of uint32;
last_pckt_src_port: uint16;
last_pckt_mode: mod7_padded_mode_enum;
sometimes it is only 3 bit long ...
v6_flag: uint32_boolean;
placeholder: uint32;
host_v6_addr: ipv6;
dest_v6_addr: conditional_container(monlist1_version) of ipv6;
}
alias mod7_monlist = mod7_monlist_gen(false)
alias mod7_monlist_1 = mod7_monlist_gen(true)
struct mod7_reset_flags = {
placeholder: list(25) of bit_bool;
ctl: bit_bool;
auth: bit_bool;
timer: bit_bool;
mem: bit_bool;
sys: bit_bool;
io: bit_bool;
all_peers: bit_bool;
}
struct mod7_info_auth = {
time_reset: uint32;
keys_cnt: uint32;
free_keys_cnt: uint32;
key_lookups_cnt: uint32;
key_not_found_cnt: uint32;
encryptions_cnt: uint32;
decryptions_cnt: uint32;
expired_keys_cnt: uint32;
uncached_keys_usage_cnt: uint32;
}
struct mod7_trap_flags = {
placeholder: list(29) of bit_bool;
configured: bit_bool;
non_priority: bit_bool;
in_use: bit_bool;
}
struct mod7_get_traps = {
src_addr: ipv4;
dst_addr: ipv4;
dst_port: uint16;
sequence_num: uint16;
last_set_timestamp: uint32;
orig_set_timestamp: uint32;
resets_cnt: uint32;
flags: mod7_trap_flags;
v6_flag: uint32_boolean;
src_addr6: ipv6;
dst_addr6: ipv6;
}
struct mod7_set_trap = {
src_addr: ipv4;
dst_addr: ipv4;
dst_port: uint16;
placeholder: uint16;
v6_flag: uint32_boolean;
src_addr6: ipv6;
dst_addr6: ipv6;
}
struct mod7_control_stats = {
time_reset: uint32;
req_cnt: uint32;
bad_pckt_cnt: uint32;
sent_responses_cnt: uint32;
sent_fragments_cnt: uint32;
sent_errors_cnt: uint32;
too_short_input_cnt: uint32;
recv_responses_cnt: uint32;
recv_fragments_cnt: uint32;
recv_errors_cnt: uint32;
recv_bad_offset_cnt: uint32;
recv_bad_version_cnt: uint32;
recv_too_short_data_cnt: uint32;
bad_opcode_cnt: uint32;
sent_async_msg: uint32;
}
struct mod7_clock_info = { (* XXX FM: No information about the fields... TODO *)
clockadr: uint32;
clock_type: uint8;
flags: uint8;
last_evt: uint8;
cur_status: uint8;
polls: uint32;
noresponse: uint32;
badformat: uint32;
baddata: uint32;
time_started: uint32;
fudgetime: list(2) of l_fp;
fudgeval1: sint32;
fudgeval2: uint32;
}
struct mod7_clock_fudge = { (* XXX FM: no comment... no information to enrich but the source code... *)
clockadr: uint32;
which: uint32;
fudgetime: l_fp;
flags: uint32;
}
struct mod7_get_kernel = { (* XXX FM: no comment... no information to enrich but the source code... *)
offset: sint32;
freq: sint32;
maxerror: sint32;
esterror: sint32;
kernel_status: uint16;
shift: uint16;
constant: sint32;
precision: sint32;
tolerance: sint32;
ppsfreq: sint32;
jitter: sint32;
stabil: sint32;
jitcnt: sint32;
calcnt: sint32;
errcnt: sint32;
stbcnt: sint32;
}
struct mod7_clock_bug_info = {
clockadr: uint32;
nvalues: uint8;
ntimes: uint8;
svalues: uint16;
stimes: uint32;
values: list(16) of uint32;
times: list(32) of l_fp;
}
struct mod7_dns_assoc = {
peer_addr: ipv4;
association_id: association_id;
hostname: string(26); (* sounds soooooo much like a bad idea! *)
}
union mod7_payload [enrich] (UnparsedPayload) =
| ReqPeerList, false -> ReqPeerListPayload of binstring
| ReqPeerList, true -> AnsPeerListPayload of mod7_req_peer_list
| ReqPeerListSum, false -> ReqPeerListSumPayload of binstring
| ReqPeerListSum, true -> AnsPeerListSumPayload of mod7_req_peer_list_sum
(* This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer *)
| ReqPeerInfo, false -> ReqPeerInfoPayload of mod7_req_peer_list
| ReqPeerInfo, true -> AnsPeerInfoPayload of mod7_req_peer_info
(* This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer *)
| ReqPeerStats, false -> ReqPeerStatsPayload of mod7_req_peer_list
| ReqPeerStats, true -> AnsPeerStatsPayload of mod7_req_peer_stats
| ReqSysInfo, false -> ReqSysInfoPayload of binstring
| ReqSysInfo, true -> AnsSysInfoPayload of mod7_sys_info
| ReqSysStats, false -> ReqSysStatsPayload of binstring
| ReqSysStats, true -> AnsSysStatsPayload of mod7_sys_stats
| ReqIOStats, false -> ReqIOStatsPayload of binstring
| ReqIOStats, true -> AnsIOStatsPayload of mod7_io_stats
| ReqMemStats, false -> ReqMemStatsPayload of binstring
| ReqMemStats, true -> AnsMemStatsPayload of mod7_mem_stats
| ReqLoopInfo, false -> ReqLoopInfoPayload of binstring
| ReqLoopInfo, true -> AnsLoopInfoPayload of mod7_loop_info
| ReqTimerStats, false -> ReqTimerStatsPayload of binstring
| ReqTimerStats, true -> AnsTimerStatsPayload of mod7_timer_stats
| ReqConfig, _ -> ReqConfigPayload of mod7_conf_peer
| ReqUnconfig, _ -> ReqUnconfigPayload of mod7_conf_unpeer
| ReqSetSysFlag, _ -> ReqSetSysFlagsPayload of mod7_sys_flags
| ReqClearSysFlag, _ -> ReqClearSysFlagsPayload of mod7_sys_flags
(*
| ReqMonitor ->
| ReqNoMonitor ->
*)
| ReqGetRestrict, _ -> ReqGetRestrictPayload of mod7_info_restrict (* XXX Verify the parameter if this is a query *)
| ReqResAddFlags, _ -> ReqResAddFlagsPayload of mod7_set_restrict (* XXX Verify the parameter if this is a query *)
| ReqResSubFlags, _ -> ReqResSubFlagsPayload of mod7_set_restrict (* XXX Verify the parameter if this is a query *)
(*| ReqUnrestrict -> *) (* has no payload *)
| ReqMonGetlist, _ -> ReqMonGetListPayload of mod7_monlist
| ReqResetStats, _ -> ReqResetStatsPayload of mod7_reset_flags(* XXX Verify the parameter if this is a query *)
| ReqResetPeer - >
| ReqRereadKeys - >
| ReqDoDirtyHack - >
| ReqDontDirtyHack - >
| ReqTrustKey - >
| ReqUntrustKey - >
| ReqResetPeer ->
| ReqRereadKeys ->
| ReqDoDirtyHack ->
| ReqDontDirtyHack ->
| ReqTrustKey ->
| ReqUntrustKey ->
*)
| ReqAuthInfo, _ -> ReqAuthInfoPayload of mod7_info_auth (* XXX Verify the parameter if this is a query *)
| ReqTraps, _ -> ReqTrapsPayload of mod7_get_traps (* XXX Verify the parameter if this is a query *)
| ReqAddTrap, _ -> ReqAddTrapPayload of mod7_set_trap (* XXX Verify the parameter if this is a query *)
| ReqClearTrap, _ -> ReqClearTrapPayload of mod7_set_trap (* XXX Verify the parameter if this is a query *)
(*
| ReqRequestKey ->
| ReqControlKey ->
*)
| ReqGetControlStats, _ -> ReqGetControlStatsPayload of mod7_control_stats (* XXX Verify the parameter if this is a query *)
(*
| ReqGetLeapInfo ->
*)
(* This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer *)
| ReqGetClockInfo, false -> ReqGetClockInfoPayload of mod7_req_peer_list
| ReqGetClockInfo, true -> AnsGetClockInfoPayload of mod7_clock_info
| ReqGetClockFudge, false -> ReqGetClockFudgePayload of binstring
| ReqGetClockFudge, true -> AnsGetClockFudgePayload of mod7_clock_fudge
| ReqGetKernel, false -> ReqGetKernelPayload of binstring
| ReqGetKernel, true -> AnsGetKernelPayload of mod7_get_kernel
(* This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer *)
| ReqGetClockBugInfo, false -> ReqGetClockBugInfoPayload of mod7_req_peer_list
| ReqGetClockBugInfo, true -> AnsGetClockBugInfoPayload of mod7_clock_bug_info
(*
| ReqSetPrecision ->
*)
| ReqMonGetList1, _ -> ReqMonGetList1Payload of mod7_monlist_1
( * commented because I can not find actual code to handle this in source
(* commented because I cannot find actual code to handle this in ntpd source *)
| ReqHostnameAssocID -> ReqHostnameAssocIDPayload of mod7_dns_assoc
| ReqIfStats -> ReqIfStatsPayload of mod7_if_stats (* cannot be parsed... because of the use of union*)
| ReqIfReload ->
*)
(* Specific NTPd; Source du format : Qualys*)
struct ntpd_private_packet = {
response: bit_bool;
more: bit_bool;
version: bit_int[3];
mode: mode_enum;
authenticated: bit_bool;
sequence: bit_int[7];
implementation: implementation_id;
reqcode: mod7reqcode;
errcode: mod7errcode;
parse_checkpoint XXX Check that errcode=0 if response values false
data_item_count: bit_int[12];
mbz: bit_magic(mk_list 4 false);
data_item_len: bit_int[12];
data: list(data_item_count) of container(data_item_len) of mod7_payload(reqcode,response);
authentication_material: conditional_container(response && authenticated) of authentication_material;
}
(* RFC5905 *)
struct extension_fields = {
field_type: uint16;
field_len: uint16;
value: binstring(field_len);
}
alias kiss_of_death_code [novalueof] = string(4)
let value_of_kiss_of_death_code kod =
let value =
match kod with
| "ACST" -> "ACST Association belongs to a unicast server"
| "AUTH" -> "AUTH Server authentication failed"
| "AUTO" -> "AUTO Autokey sequence failed"
| "BCST" -> "BCST Association belongs to a broadcast server"
| "CRYP" -> "CRYP Cryptographic authentication or identification failed"
| "DENY" -> "DENY Access denied by remote server"
| "DROP" -> "DROP Lost peer in symmetric mode"
| "RSTR" -> "RSTR Access denied due to local policy"
| "INIT" -> "INIT Association not yet synchronized"
| "MCST" -> "MCST Association belongs to a dynamically discovered server"
| "NKEY" -> "NKEY No key found"
| "RATE" -> "RATE Rate exceeded"
| "RMOT" -> "RMOT Alteration of association from a remote host running ntpdc"
| "STEP" -> "STEP Step changed in sys time has occured but the association has not yet resynchronized"
| _ -> kod
in
VString(value, true)
union reference [enrich] (UnparsedReference) =
| 0 -> KoDPacket of kiss_of_death_code
| 1 -> ReferenceClock of reference_clock_code
(* This struct expects to be enclosed in a container or to be the last thing to parse in the document *)
struct time_packet = {
leap_indicator: leap_indicator;
version: bit_int[3];
mode: mode_enum;
stratum: uint8;
poll: uint8;
precision: uint8;
root_delay: uint32;
root_dispersion: uint32;
reference_id: reference(stratum);
reference_timestamp: uint64;
origin_timestamp: uint64;
receive_timestamp: uint64;
transmit_timestamp: uint64;
optional extension_fields: container(input.cur_length - input.cur_offset - 20) of list of extension_fields;
20 corresponds to the len of key_id + digest that are mandatory if extensions are in use )
authentication_material: conditional_container(extension_fields <> None) of authentication_material;
}
type ntp_packet = TimePacket of time_packet
| ControlPacket of control_packet
| NTPDPrivatePacket of ntpd_private_packet
let parse_ntp_packet input =
let fst_byte = peek_uint8 input in
let mode = fst_byte land 0x7 in
match mode with
| 0 | 1 | 2 | 3 | 4 | 5 -> TimePacket (parse_time_packet input)
| 6 -> ControlPacket (parse_control_packet input)
| 7 -> NTPDPrivatePacket (parse_ntpd_private_packet input)
| _ -> failwith "Should not happen as value is coded on 3 bit"
let dump_ntp_packet buf = function
| TimePacket p -> dump_time_packet buf p
| ControlPacket p -> dump_control_packet buf p
| NTPDPrivatePacket p -> dump_ntpd_private_packet buf p
let value_of_ntp_packet = function
| TimePacket p -> value_of_time_packet p
| ControlPacket p -> value_of_control_packet p
| NTPDPrivatePacket p -> value_of_ntpd_private_packet p
| null | https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/net/libntp.ml | ocaml | RFC1305 %B.1
RFC1305 %B.2.3
RFC1305 %B.2.1
RFC1305 %B.2.1
RFC1305 %B.2.2
RFC1305 %B.2.2
RFC1305 %B.2.2
RFC1305 %B.2.2
RFC1305 %B.2.3
RFC1305 %B.2.3
RFC1305 %B.2.4
RFC1305 %B.2.4
RFC1305 %B.2
XXX FM: Do we really want to accept that the len is nonesense and still parse it?
RFC1305 %B.3 Read status
include/ntp_fp.h
XXX FM Is this a boolean?
XXX FM Is this a boolean?
duplicates
what else?
XXX FM: broadcast client ?
number of times we've added buffers ; comment extracted from source code
undefined flags
what else ?
timeout this entry
enable ms-sntp authentication
send kiss of death packet
low priority trap
set trap denied
modify denied
rate limited
new association denied
version mismatch
access denied
ignore packet
XXX FM: No information about the fields... TODO
XXX FM: no comment... no information to enrich but the source code...
XXX FM: no comment... no information to enrich but the source code...
sounds soooooo much like a bad idea!
This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer
This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer
| ReqMonitor ->
| ReqNoMonitor ->
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
| ReqUnrestrict ->
has no payload
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
XXX Verify the parameter if this is a query
| ReqRequestKey ->
| ReqControlKey ->
XXX Verify the parameter if this is a query
| ReqGetLeapInfo ->
This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer
This type of queries requires a list of peers in input. Therefore
the payload type is different in a query and in an answer
| ReqSetPrecision ->
commented because I cannot find actual code to handle this in ntpd source
cannot be parsed... because of the use of union
Specific NTPd; Source du format : Qualys
RFC5905
This struct expects to be enclosed in a container or to be the last thing to parse in the document | open Parsifal
open BasePTypes
open PTypes
alias association_id = uint16
alias keyid = uint32
alias reference_clock_code [novalueof] = string(4)
let value_of_reference_clock_code refcode =
let value =
match refcode with
| "GOES" -> "GEOS Geosynchroneous Orbit Environment Satellite"
| "GPS\x00" -> "GPS Global Position System"
| "GAL\x00" -> "GAL Galileo Positioning System"
| "PPS\x00" -> "PPS Generic pulse-per-second"
| "IRIG" -> "IRIG Inter-Range Instrumentation Group"
| "WWVB" -> "WWVB LF Radio WWVB FR. Collins, CO 60 kHz"
| "DCF\x00" -> "DCF LF Radio DCF77 Mainflingen, DE 77.5 kHz"
| "HBG\x00" -> "HBG LF Radio HBG Prangins, HB 75 kHz"
| "MSF\x00" -> "MSF LF Radio MSF Anthorn, UK 60 kHz"
| "JJY\x00" -> "JJY LF Radio JJY Fukushima, JP 40 kHz, Saga, JP 60 kHz"
| "LORC" -> "LORC MF Radio LORAN C station, 100 kHz"
| "TDF\x00" -> "TDF MF Radio Allouis, FR 162 kHz"
| "CHU\x00" -> "CHU HF Radio CHU Ottawa, Ontario"
| "WWV\x00" -> "WWV HF Radio Ft. Collins, CO"
| "WWVH" -> "WWVH HF Radio WWVH Kauai, HI"
| "NIST" -> "NIST NIST telephone modem"
| "ACTS" -> "ACTS NIST telephone modem"
| "USNO" -> "USNO USNO telephone modem"
| "PTB\x00" -> "PTB European telephone modem"
| _ -> refcode
in
VString(value, true)
enum mode_enum (3, UnknownVal ReservedMode) =
| 1 -> SymmetricActiveMode, "1 Symmetric Active"
| 2 -> SymmetricPassiveMode, "2 Symmetric Passive"
| 3 -> ClientMode, "3 Client"
| 4 -> ServerMode, "4 Server"
| 5 -> BroadcastMode, "5 Broadcast"
| 6 -> NTPControlMsgMode, "6 NTP control message"
| 7 -> PrivateUseMode, "7 Reserved for private use"
enum host_mode_enum (8, UnknownVal UnspecifiedMode) =
| 1 -> SymmetricActiveMode, "1 Symmetric Active"
| 2 -> SymmetricPassiveMode, "2 Symmetric Passive"
| 3 -> ClientMode, "3 Client"
| 4 -> ServerMode, "4 Server"
| 5 -> BroadcastMode, "5 Broadcast"
| 6 -> NTPControlMsgMode, "6 NTP control message"
| 7 -> PrivateUseMode, "7 Reserved for private use"
| 8 -> BClientMode, "8 BClient"
enum opcode(5, UnknownVal ReservedOpcode) =
| 1 -> ReadStatOpCode, "Read status command/response"
| 2 -> ReadVarOpCode, "Read variables command/response"
| 3 -> WriteVarOpCode, "Write variables command/response"
| 4 -> ReadClockVarOpCode, "Read clock variables command/response"
| 5 -> WriteClockVarOpCode, "Write clock variables command/response"
| 6 -> SetTrapOpCode, "Set trap address/port command/response"
| 7 -> TrapOpCode, "Trap response"
enum clock_source (6, UnknownVal ReservedSource) =
| 0 -> UnspecifiedSource
| 1 -> CalibratedAtomicClock, "Calibrated atomic clock (e.g. HP 5061)"
| 2 -> VLFRadio, "VLF (band 4) or LF (band 5) radio (e.g. OMEGA, WWVB)"
| 3 -> HFRadio, "HF (band 7) radio (e.g. CHU, MSF, WWVH)"
| 4 -> UHFSat, "UHF (band 9) satellite (e.g. GOES, GPS)"
| 5 -> LocalNet, "local net (e.g. DCN, TSP, DTS)"
| 6 -> UDPNTP, "UDP/NTP"
| 7 -> UDPTIME, "UDP/TIME"
| 8 -> Manual, "Eyeball and wrist watch"
| 9 -> TelephoneModem, "Telephone modem (e.g. NIST)"
enum evt_code (4, UnknownVal ReservedEvtCode) =
| 0 -> UnspecifiedEvtCode, "Unspecified event"
| 1 -> SysRestart, "System restart"
| 2 -> SysFault, "System or Hardware Fault"
| 3 -> SysNewStatus, "System new status word (leap bits or synchronization change)"
| 4 -> SysNewSyncSource, "System new synchronization source or stratum (sys.peer or sys.stratum change)"
| 5 -> SysClockReset, "System clock reset (offset correction exceeds CLOCK.MAX)"
| 6 -> SysInvalidTime, "System invalid time or date"
| 7 -> SysClockExn, "System clock exception"
enum leap_indicator (2, UnknownVal UnknownLeapIndicator) =
| 0 -> NoWarning, "No warning"
| 1 -> Plus1Sec, "Last minute of the day has 61 seconds"
| 2 -> Minus1Sec, "Last minute of the day has 59 seconds"
| 3 -> UnknownState, "Unknown (clock unsychronized)"
struct system_status_word = {
leap_indicator: leap_indicator;
clock_source: clock_source;
evt_counter: bit_int[4];
evt_code: evt_code;
}
struct peer_status = {
peer_config: bit_bool;
peer_authenable: bit_bool;
peer_authentic: bit_bool;
peer_reach: bit_bool;
reserved: bit_bool;
}
enum peer_selection (3, UnknownVal ReservedPeerSelection) =
| 0 -> RejectedSelection, "Rejected"
| 1 -> PassedSanityChecks, "Passed sanity checks"
| 2 -> PassedCandidateChecks, "Passed candidate checks"
| 3 -> PassedOutlyerChecks, "Passed outlyer checks"
| 4 -> CurrentSyncSourceDistExceeded, "Current synchronization source; max distance exceeded"
| 6 -> CurrentSyncSourceDistOkay, "Current synchronization source; max distance okay"
enum peer_evt_code (4, UnknownVal ReservedEvtCode) =
| 0 -> UnspecifiedEvtCode, "Unspecified"
| 1 -> PeerIPErr, "Peer IP error"
| 2 -> PeerAuthFail, "Peer authentication failure"
| 3 -> PeerUnreach, "Peer unreachable"
| 4 -> PeerReach, "Peer now reachable"
| 5 -> PeerClockExn, "Peer clock exception"
struct peer_status_word = {
peer_status: peer_status;
peer_selection: peer_selection;
peer_evt_counter: bit_int[4];
peer_evt_code: peer_evt_code;
}
enum clock_status (8, UnknownVal ReservedClockStatus) =
| 0 -> ClockNominalStatus, "Clock operating within nominals"
| 1 -> ReplyTimeoutStatus, "Reply timeout"
| 2 -> BadReplyFormatStatus, "Bad reply format"
| 3 -> HardwareOrSoftwareFault, "Hardware of software fault"
| 4 -> PropagationFailure, "Propagation failure"
| 5 -> BadDateFormatOrVal, "Bad date format or value"
| 6 -> BadTimeFormatOrVal, "Bad time format or value"
struct clock_status_word = {
clock_status: clock_status;
FM : XXX I do n't understand the content of this field . Unparsed at the moment
}
enum error_code (8, UnknownVal ReservedError) =
| 0 -> UnspecifiedError, "Unspecified"
| 1 -> AuthFail, "Authentication failure"
| 2 -> InvalidMsgLenOrFormat, "Invalid message length or format"
| 3 -> InvalidOpCode, "Invalid opcoode"
| 4 -> UnknownAssocID, "Unknown association ID"
| 5 -> UnknownVarName, "Unknown variable name"
| 6 -> InvalidVarVal, "Invalid variable value"
| 7 -> AdminProhibited, "Administratively prohibited"
struct error_status_word = {
error_code: error_code;
placeholder: uint8;
}
type status_words = | SystemStatusWord of system_status_word
| PeerStatusWord of peer_status_word
| ClockStatusWord of clock_status_word
| ErrorStatusWord of error_status_word
| UnparsedStatusWord of binstring
let parse_status_words response error opcode association_id unparsed_status input =
let new_input = get_in_container input "status_word_container" unparsed_status in
match response, error, opcode, association_id with
| true, false, ReadStatOpCode, 0
| true, false, ReadVarOpCode, 0 -> SystemStatusWord (parse_system_status_word new_input)
| true, false, ReadStatOpCode, _
| true, false, ReadVarOpCode, _
| true, false, WriteVarOpCode, _ -> PeerStatusWord (parse_peer_status_word new_input)
| _, false, ReadClockVarOpCode, _
| _, false, WriteClockVarOpCode, _ -> ClockStatusWord (parse_clock_status_word new_input)
| true, true, _, _ -> ErrorStatusWord (parse_error_status_word new_input)
| _ -> (UnparsedStatusWord unparsed_status)
let value_of_status_words v =
match v with
| SystemStatusWord x -> value_of_system_status_word x
| PeerStatusWord x -> value_of_peer_status_word x
| ClockStatusWord x -> value_of_clock_status_word x
| ErrorStatusWord x -> value_of_error_status_word x
| UnparsedStatusWord x -> VString(x, true)
let compute_len_of_data_in_control_packet len input =
let remlen = input.cur_length - input.cur_offset in
if len > remlen then
remlen
else
min 468 len
let compute_padding_len_in_control_packet len =
let rem = len mod 4 in
if rem <> 0 then
4 - rem
else
0
struct assoc_status = {
association_id: association_id;
status_word: peer_status_word;
}
alias associations_statuses = list of assoc_status
union control_data [enrich] (UnparsedData of binstring) =
| ReadStatOpCode, 0 -> BinStatusData of associations_statuses
| ReadStatOpCode, _ -> StatusData of string
| ReadVarOpCode, _ -> VariablesRead of string
| WriteVarOpCode, _ -> VariablesWritten of string
| ReadClockVarOpCode, _ -> ClockRead of string
| WriteClockVarOpCode, _ -> ClockWritten of string
| SetTrapOpCode, _ -> SetTrap of string
| TrapOpCode, _ -> GotTrap of string
RFC 1305 % B.1
struct control_packet = {
null_magic: bit_int[2];
version: bit_int[3];
mode: mode_enum;
response: bit_bool;
error: bit_bool;
more: bit_bool;
opcode: opcode;
sequence: uint16;
unparsed_status: binstring(2);
association_id: association_id;
parse_field status: status_words(response; error; opcode; association_id; unparsed_status);
offset: uint16;
len: uint16;
data: container(compute_len_of_data_in_control_packet len input) of control_data(opcode, association_id);
optional padding: binstring(compute_padding_len_in_control_packet len);
optional authenticator: binstring(12);
}
struct authentication_material = {
keyid: keyid;
digest: binstring(16);
}
enum implementation_id (8, UnknownVal UnknownImplementation) =
| 0 -> UNIV, "UNIV"
| 2 -> OldXNTPD, "Old NTPd pre IPv6"
| 3 -> XNTPD, "NTPd post IPv6"
| 255 -> ReservedImplId, "Reserved ID"
enum mod7reqcode (8, UnknownVal UnknownReqCode) =
| 0 -> ReqPeerList, "Request Peer List"
| 1 -> ReqPeerListSum, "Request summary of all peers"
| 2 -> ReqPeerInfo, "Request standard peer info"
| 3 -> ReqPeerStats, "Request peer statistics"
| 4 -> ReqSysInfo, "Request peer information"
| 5 -> ReqSysStats, "Request system statistics"
| 6 -> ReqIOStats, "Request I/0 stats"
| 7 -> ReqMemStats, "Request memory statistics"
| 8 -> ReqLoopInfo, "Request information from the loop filter"
| 9 -> ReqTimerStats, "Request time statistics"
| 10 -> ReqConfig, "Request to configure a new peer"
| 11 -> ReqUnconfig, "Request to unconfigure an existing peer"
| 12 -> ReqSetSysFlag, "Request to set system flags"
| 13 -> ReqClearSysFlag, "Request to clear system flags"
| 14 -> ReqMonitor, "Monitor (unused)"
| 15 -> ReqNoMonitor, "No Monitor (unused)"
| 16 -> ReqGetRestrict, "Request restrict list"
| 17 -> ReqResAddFlags, "Request flags addition to restrict list"
| 18 -> ReqResSubFlags, "Request flags removal to restrict list"
| 19 -> ReqUnrestrict, "Request entry removal from retrict list"
| 20 -> ReqMonGetlist, "Return data collected by monitor"
| 21 -> ReqResetStats, "Request reset of statistics counters"
| 22 -> ReqResetPeer, "Request reset of peer statistics counters"
| 23 -> ReqRereadKeys, "Request reread of the encryption key files"
| 24 -> ReqDoDirtyHack, "Do some dirty hack (unused)"
| 25 -> ReqDontDirtyHack, "Dont do some dirty hack (unused)"
| 26 -> ReqTrustKey, "Request a trusted key addition"
| 27 -> ReqUntrustKey, "Request a trusted key removal"
| 28 -> ReqAuthInfo, "Request authentication information"
| 29 -> ReqTraps, "Request currently set traps list"
| 30 -> ReqAddTrap, "Request trap addition"
| 31 -> ReqClearTrap, "Request trap clearance"
| 32 -> ReqRequestKey, "Define a new request keyid"
| 33 -> ReqControlKey, "Define a new control keyid"
| 34 -> ReqGetControlStats, "Get statistics from the control module"
| 35 -> ReqGetLeapInfo, "Get leap info (unused)"
| 36 -> ReqGetClockInfo, "Get clock information"
| 37 -> ReqGetClockFudge, "Get clock fudge factors"
| 38 -> ReqGetKernel, "Get kernel ppl/pps infos"
| 39 -> ReqGetClockBugInfo, "Get clock debugging info"
| 41 -> ReqSetPrecision, "Set precision (unused)"
| 42 -> ReqMonGetList1, "Return collected v1 monitor data"
| 43 -> ReqHostnameAssocID, "Return hostname association id"
| 44 -> ReqIfStats, "Get interface statistics"
| 45 -> ReqIfReload, "Request interface list reloading"
enum mod7errcode (4, UnknownVal UnspecifiedError) =
| 0 -> NoError, "No error"
| 1 -> IncompatibleImplNum, "Incompatible implementation number"
| 2 -> UnimplReqCode, "Unimplemented request code"
| 3 -> FmtErr, "Format error (wrong data items, data size, packet size etc.)"
| 4 -> NoData, "No data available (e.g. request for details on unknown peer)"
| 5 | 6 -> DontKnow, "I don't know"
| 7 -> AuthFail, "Authentication failure"
alias ip4_mask = ipv4
alias ip6_mask = ipv6
mod7_peer_info_flags should be 8 bits , but it seeps developers
try to have a 9 - th flag , iburst ( in ntp_request.h , INFO_IBURST_FLAG
is 0x100 ... which is out of range of a . This is why we may need
a 16 - bit version of these flags .
try to have a 9-th flag, iburst (in ntp_request.h, INFO_IBURST_FLAG
is 0x100... which is out of range of a u_char. This is why we may need
a 16-bit version of these flags. *)
struct mod7_peer_info_flags [param long_version]= {
placeholder: conditional_container(long_version) of list(7) of bit_bool;
iburst: conditional_container(long_version) of bit_bool;
short_list: bit_bool;
sel_candidate: bit_bool;
authenable: bit_bool;
prefer: bit_bool;
refclock: bit_bool;
burst: bit_bool;
syspeer: bit_bool;
config: bit_bool;
}
alias mod7_peer_info_flags_16bits = mod7_peer_info_flags(true)
alias mod7_peer_info_flags_8bits = mod7_peer_info_flags(false)
type uint32_boolean = bool
let parse_uint32_boolean input =
(parse_uint32 input) <> 0
let dump_uint32_boolean buf b =
dump_uint32 buf (if b then 1 else 0)
let value_of_uint32_boolean b = VBool b
struct mod7_req_peer_list = {
addr: ipv4;
port: uint16;
hmode: host_mode_enum;
flags: mod7_peer_info_flags_8bits;
v6_flag: uint32_boolean;
placeholder: uint32;
v6addr: ipv6;
}
struct ul_fp = {
integral_part: uint32;
fractional_part: uint32;
}
struct sl_fp = {
integral_part: sint32;
fractional_part: sint32;
}
alias s_fp = sint32
alias l_fp = ul_fp
alias u_fp = uint32
struct mod7_req_peer_list_sum = {
dst_addr: ipv4;
src_addr: ipv4;
src_port: uint16;
stratum: uint8;
host_polling_interval: sint8;
peer_polling_interval: sint8;
reachability: uint8;
flags: mod7_peer_info_flags_8bits;
hmode: host_mode_enum;
delay: s_fp;
offset: l_fp;
dispersion: u_fp;
v6_flag: uint32_boolean;
placeholder: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_req_peer_info = {
dstaddr: ipv4;
srcaddr: ipv4;
src_port: uint16;
flags: mod7_peer_info_flags_8bits;
XXX FM : this is a leap_indicator with 6 useless bits
hmode: host_mode_enum;
pmode: host_mode_enum;
stratum: uint8;
peer_polling_interval: uint8;
host_polling_interval: uint8;
precision: sint8;
sometimes , it is only a 3 bit long value ...
placeholder: uint8;
flash: uint8;
ttl: uint8;
flash2: uint16;
association_id: association_id;
keyid: keyid;
placeholder_pkeyid: uint32;
reference_id: reference_clock_code;
timer: uint32;
rootdelay: s_fp;
rootdispersion: u_fp;
ref_timestamp: l_fp;
origin_timestamp_org: l_fp;
receive_timestamp_rec: l_fp;
transmit_timestamp_xmt: l_fp;
8 is the NTP_SHIFT value defined in include / ntp.h from version 4.2.6.p5
filtoffset: list(8) of l_fp;
order: list(8) of uint8;
delay: s_fp;
dispersion: u_fp;
offset: l_fp;
selectdisp: u_fp;
placeholder2: list(7) of sint32;
estbdelay: s_fp;
v6_flag: uint32_boolean;
placeholder3: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_req_peer_stats = {
dstaddr: ipv4;
srcaddr: ipv4;
src_port: uint16;
flags: mod7_peer_info_flags_16bits;
time_reset: uint32;
time_received: uint32;
time_tosend: uint32;
time_reachable: uint32;
sent: uint32;
placeholder: uint32;
processed: uint32;
placeholder2: uint32;
badauth: uint32;
bogus_origin: uint32;
placeholder3: list(2) of uint32;
bad_dispersion: uint32;
bad_ref_time: uint32;
placeholder4: uint32;
candidate: uint8;
placeholder5: list(3) of uint8;
v6_flag: uint32_boolean;
placeholder6: uint32;
dstv6addr: ipv6;
srcv6addr: ipv6;
}
struct mod7_loop_info = {
last_offset: l_fp;
drift_comp: l_fp;
compliance: uint32;
watchdog_timer: uint32;
}
struct mod7_sys_info_flags = {
pps_sync: bit_bool;
cal: bit_bool;
filegen: bit_bool;
monitor: bit_bool;
kernel: bit_bool;
authenticate: bit_bool;
}
struct mod7_sys_info = {
peer: ipv4;
peer_mode: host_mode_enum;
XXX FM : is that the same as the leap indicators but on 8 bits ?
stratum: uint8;
precision: sint8;
rootdelay: s_fp;
rootdispersion: u_fp;
reference_id: reference_clock_code;
reference_time: l_fp;
sys_polling_interval: uint32;
flags: mod7_sys_info_flags;
placeholder: list(3) of uint8;
broadcast_offset: s_fp;
frequency: s_fp;
authdelay: ul_fp;
stability: u_fp;
v6_flag: uint32_boolean;
placeholder2: uint32;
peer_v6_addr: ipv6;
}
struct mod7_sys_stats = {
time_since_restart: uint32;
time_since_reset: uint32;
access_denied_cnt: uint32;
old_version_pckt_cnt: uint32;
new_version_pckt_cnt: uint32;
unknown_version_pckt_cnt: uint32;
bad_len_or_format_cnt: uint32;
processed_pckt_cnt: uint32;
bad_auth_cnt: uint32;
received_pckt_cnt: uint32;
rate_exceeded_cnt: uint32;
}
struct mod7_mem_stats = {
time_since_reset: uint32;
total_peer_mem: uint16;
free_peer_mem: uint16;
find_peer_calls: uint32;
allocations: uint32;
demobilizations: uint32;
128 is from NTP_HASH_SIZE defined in include / ntp.h
}
struct mod7_io_stats = {
time_since_reset: uint32;
total_recv_bufs: uint16;
free_recv_bufs: uint16;
full_recv_bufs: uint16;
dropped_pckt_cnt: uint32;
ignored_pckt_cnt: uint32;
received_pckt_cnt: uint32;
sent_pckt_cnt: uint32;
not_sent_pckt_cnt: uint32;
interrupts_cnt: uint32;
int_received: uint32;
}
struct mod7_timer_stats = {
time_since_reset: uint32;
alarms_cnt: uint32;
overflows_cnt: uint32;
xmt_calls: uint32;
}
struct mod7_conf_flags = {
two highest flags are undefined in ntp 4.2.6.p5
skey: bit_bool;
noselect: bit_bool;
iburst: bit_bool;
burst: bit_bool;
prefer: bit_bool;
authenable: bit_bool;
}
struct mod7_conf_peer = {
peer_addr: ipv4;
hmode: host_mode_enum;
sometimes it is only 3 bit long ...
min_host_polling_interval: uint8;
max_host_polling_interval: uint8;
flags: mod7_conf_flags;
ttl: uint8;
placeholder: uint16;
keyid: keyid;
pubkey_filename: string(256);
v6_flag: uint32_boolean;
placeholder2: uint32;
peer_v6_addr: ipv6;
}
struct mod7_conf_unpeer = {
peer_addr: ipv4;
v6_flag: uint32_boolean;
peer_v6_addr: ipv6;
}
struct mod7_sys_flags = {
cal: bit_bool;
auth: bit_bool;
filegen: bit_bool;
monitor: bit_bool;
kernel: bit_bool;
pps: bit_bool;
bclient: bit_bool;
}
As for mod7_peer_info_flags , some developers of NTPd think that the
bit field should be 32 bits , others 16 bits ... it varies following
the structure ... there is only 13 bits defined anyway ...
bit field should be 32 bits, others 16 bits... it varies following
the structure... there is only 13 bits defined anyway... *)
struct mod7_restrict_flags [param four_bytes_version] = {
placeholder: conditional_container(four_bytes_version) of list(16) of bit_bool;
placeholder2: list(3) of bit_bool;
mod 6/7 denied
called in code source DONTTRUST
}
alias mod7_restrict_flags_16bits = mod7_restrict_flags(false)
alias mod7_restrict_flags_32bits = mod7_restrict_flags(true)
struct mod7_match_flags = {
placeholder: list(2) of bit_bool;
ntp_only: bit_bool;
interface: bit_bool;
placeholder2: list(12) of bit_bool;
}
struct mod7_info_restrict = {
addr: ipv4;
mask: ip4_mask;
count: uint32;
flags: mod7_restrict_flags_16bits;
mflags: mod7_match_flags;
v6_flag: uint32_boolean;
placeholder: uint32;
addr6: ipv6;
mask6: ip6_mask;
}
struct mod7_set_restrict = {
addr: ipv4;
mask: ip4_mask;
flags: mod7_restrict_flags_16bits;
mflags: mod7_match_flags;
v6_flag: uint32_boolean;
addr6: ipv6;
mask6: ip6_mask;
}
struct mod7_padded_mode_enum = {
placeholder: list(5) of bit_bool;
mode: mode_enum;
}
struct mod7_monlist_gen [param monlist1_version] = {
last_pckt_timestamp: uint32;
first_pckt_timestamp: uint32;
restrict_flags: mod7_restrict_flags_32bits;
pckt_recv_cnt: uint32;
host_addr: ipv4;
dest_addr: conditional_container(monlist1_version) of ipv4;
XXX FM : it could be mod7_peer_info_flags BUT mod7_peer_info_flags
are only 8 bits long ( or 9 ... it depends ... ; so do n't know ; do n't enrich
are only 8 bits long (or 9... it depends... ; so don't know ; don't enrich *)
flags: conditional_container(monlist1_version) of uint32;
last_pckt_src_port: uint16;
last_pckt_mode: mod7_padded_mode_enum;
sometimes it is only 3 bit long ...
v6_flag: uint32_boolean;
placeholder: uint32;
host_v6_addr: ipv6;
dest_v6_addr: conditional_container(monlist1_version) of ipv6;
}
alias mod7_monlist = mod7_monlist_gen(false)
alias mod7_monlist_1 = mod7_monlist_gen(true)
struct mod7_reset_flags = {
placeholder: list(25) of bit_bool;
ctl: bit_bool;
auth: bit_bool;
timer: bit_bool;
mem: bit_bool;
sys: bit_bool;
io: bit_bool;
all_peers: bit_bool;
}
struct mod7_info_auth = {
time_reset: uint32;
keys_cnt: uint32;
free_keys_cnt: uint32;
key_lookups_cnt: uint32;
key_not_found_cnt: uint32;
encryptions_cnt: uint32;
decryptions_cnt: uint32;
expired_keys_cnt: uint32;
uncached_keys_usage_cnt: uint32;
}
struct mod7_trap_flags = {
placeholder: list(29) of bit_bool;
configured: bit_bool;
non_priority: bit_bool;
in_use: bit_bool;
}
struct mod7_get_traps = {
src_addr: ipv4;
dst_addr: ipv4;
dst_port: uint16;
sequence_num: uint16;
last_set_timestamp: uint32;
orig_set_timestamp: uint32;
resets_cnt: uint32;
flags: mod7_trap_flags;
v6_flag: uint32_boolean;
src_addr6: ipv6;
dst_addr6: ipv6;
}
struct mod7_set_trap = {
src_addr: ipv4;
dst_addr: ipv4;
dst_port: uint16;
placeholder: uint16;
v6_flag: uint32_boolean;
src_addr6: ipv6;
dst_addr6: ipv6;
}
struct mod7_control_stats = {
time_reset: uint32;
req_cnt: uint32;
bad_pckt_cnt: uint32;
sent_responses_cnt: uint32;
sent_fragments_cnt: uint32;
sent_errors_cnt: uint32;
too_short_input_cnt: uint32;
recv_responses_cnt: uint32;
recv_fragments_cnt: uint32;
recv_errors_cnt: uint32;
recv_bad_offset_cnt: uint32;
recv_bad_version_cnt: uint32;
recv_too_short_data_cnt: uint32;
bad_opcode_cnt: uint32;
sent_async_msg: uint32;
}
clockadr: uint32;
clock_type: uint8;
flags: uint8;
last_evt: uint8;
cur_status: uint8;
polls: uint32;
noresponse: uint32;
badformat: uint32;
baddata: uint32;
time_started: uint32;
fudgetime: list(2) of l_fp;
fudgeval1: sint32;
fudgeval2: uint32;
}
clockadr: uint32;
which: uint32;
fudgetime: l_fp;
flags: uint32;
}
offset: sint32;
freq: sint32;
maxerror: sint32;
esterror: sint32;
kernel_status: uint16;
shift: uint16;
constant: sint32;
precision: sint32;
tolerance: sint32;
ppsfreq: sint32;
jitter: sint32;
stabil: sint32;
jitcnt: sint32;
calcnt: sint32;
errcnt: sint32;
stbcnt: sint32;
}
struct mod7_clock_bug_info = {
clockadr: uint32;
nvalues: uint8;
ntimes: uint8;
svalues: uint16;
stimes: uint32;
values: list(16) of uint32;
times: list(32) of l_fp;
}
struct mod7_dns_assoc = {
peer_addr: ipv4;
association_id: association_id;
}
union mod7_payload [enrich] (UnparsedPayload) =
| ReqPeerList, false -> ReqPeerListPayload of binstring
| ReqPeerList, true -> AnsPeerListPayload of mod7_req_peer_list
| ReqPeerListSum, false -> ReqPeerListSumPayload of binstring
| ReqPeerListSum, true -> AnsPeerListSumPayload of mod7_req_peer_list_sum
| ReqPeerInfo, false -> ReqPeerInfoPayload of mod7_req_peer_list
| ReqPeerInfo, true -> AnsPeerInfoPayload of mod7_req_peer_info
| ReqPeerStats, false -> ReqPeerStatsPayload of mod7_req_peer_list
| ReqPeerStats, true -> AnsPeerStatsPayload of mod7_req_peer_stats
| ReqSysInfo, false -> ReqSysInfoPayload of binstring
| ReqSysInfo, true -> AnsSysInfoPayload of mod7_sys_info
| ReqSysStats, false -> ReqSysStatsPayload of binstring
| ReqSysStats, true -> AnsSysStatsPayload of mod7_sys_stats
| ReqIOStats, false -> ReqIOStatsPayload of binstring
| ReqIOStats, true -> AnsIOStatsPayload of mod7_io_stats
| ReqMemStats, false -> ReqMemStatsPayload of binstring
| ReqMemStats, true -> AnsMemStatsPayload of mod7_mem_stats
| ReqLoopInfo, false -> ReqLoopInfoPayload of binstring
| ReqLoopInfo, true -> AnsLoopInfoPayload of mod7_loop_info
| ReqTimerStats, false -> ReqTimerStatsPayload of binstring
| ReqTimerStats, true -> AnsTimerStatsPayload of mod7_timer_stats
| ReqConfig, _ -> ReqConfigPayload of mod7_conf_peer
| ReqUnconfig, _ -> ReqUnconfigPayload of mod7_conf_unpeer
| ReqSetSysFlag, _ -> ReqSetSysFlagsPayload of mod7_sys_flags
| ReqClearSysFlag, _ -> ReqClearSysFlagsPayload of mod7_sys_flags
| ReqMonGetlist, _ -> ReqMonGetListPayload of mod7_monlist
| ReqResetPeer - >
| ReqRereadKeys - >
| ReqDoDirtyHack - >
| ReqDontDirtyHack - >
| ReqTrustKey - >
| ReqUntrustKey - >
| ReqResetPeer ->
| ReqRereadKeys ->
| ReqDoDirtyHack ->
| ReqDontDirtyHack ->
| ReqTrustKey ->
| ReqUntrustKey ->
*)
| ReqGetClockInfo, false -> ReqGetClockInfoPayload of mod7_req_peer_list
| ReqGetClockInfo, true -> AnsGetClockInfoPayload of mod7_clock_info
| ReqGetClockFudge, false -> ReqGetClockFudgePayload of binstring
| ReqGetClockFudge, true -> AnsGetClockFudgePayload of mod7_clock_fudge
| ReqGetKernel, false -> ReqGetKernelPayload of binstring
| ReqGetKernel, true -> AnsGetKernelPayload of mod7_get_kernel
| ReqGetClockBugInfo, false -> ReqGetClockBugInfoPayload of mod7_req_peer_list
| ReqGetClockBugInfo, true -> AnsGetClockBugInfoPayload of mod7_clock_bug_info
| ReqMonGetList1, _ -> ReqMonGetList1Payload of mod7_monlist_1
( * commented because I can not find actual code to handle this in source
| ReqHostnameAssocID -> ReqHostnameAssocIDPayload of mod7_dns_assoc
| ReqIfReload ->
*)
struct ntpd_private_packet = {
response: bit_bool;
more: bit_bool;
version: bit_int[3];
mode: mode_enum;
authenticated: bit_bool;
sequence: bit_int[7];
implementation: implementation_id;
reqcode: mod7reqcode;
errcode: mod7errcode;
parse_checkpoint XXX Check that errcode=0 if response values false
data_item_count: bit_int[12];
mbz: bit_magic(mk_list 4 false);
data_item_len: bit_int[12];
data: list(data_item_count) of container(data_item_len) of mod7_payload(reqcode,response);
authentication_material: conditional_container(response && authenticated) of authentication_material;
}
struct extension_fields = {
field_type: uint16;
field_len: uint16;
value: binstring(field_len);
}
alias kiss_of_death_code [novalueof] = string(4)
let value_of_kiss_of_death_code kod =
let value =
match kod with
| "ACST" -> "ACST Association belongs to a unicast server"
| "AUTH" -> "AUTH Server authentication failed"
| "AUTO" -> "AUTO Autokey sequence failed"
| "BCST" -> "BCST Association belongs to a broadcast server"
| "CRYP" -> "CRYP Cryptographic authentication or identification failed"
| "DENY" -> "DENY Access denied by remote server"
| "DROP" -> "DROP Lost peer in symmetric mode"
| "RSTR" -> "RSTR Access denied due to local policy"
| "INIT" -> "INIT Association not yet synchronized"
| "MCST" -> "MCST Association belongs to a dynamically discovered server"
| "NKEY" -> "NKEY No key found"
| "RATE" -> "RATE Rate exceeded"
| "RMOT" -> "RMOT Alteration of association from a remote host running ntpdc"
| "STEP" -> "STEP Step changed in sys time has occured but the association has not yet resynchronized"
| _ -> kod
in
VString(value, true)
union reference [enrich] (UnparsedReference) =
| 0 -> KoDPacket of kiss_of_death_code
| 1 -> ReferenceClock of reference_clock_code
struct time_packet = {
leap_indicator: leap_indicator;
version: bit_int[3];
mode: mode_enum;
stratum: uint8;
poll: uint8;
precision: uint8;
root_delay: uint32;
root_dispersion: uint32;
reference_id: reference(stratum);
reference_timestamp: uint64;
origin_timestamp: uint64;
receive_timestamp: uint64;
transmit_timestamp: uint64;
optional extension_fields: container(input.cur_length - input.cur_offset - 20) of list of extension_fields;
20 corresponds to the len of key_id + digest that are mandatory if extensions are in use )
authentication_material: conditional_container(extension_fields <> None) of authentication_material;
}
type ntp_packet = TimePacket of time_packet
| ControlPacket of control_packet
| NTPDPrivatePacket of ntpd_private_packet
let parse_ntp_packet input =
let fst_byte = peek_uint8 input in
let mode = fst_byte land 0x7 in
match mode with
| 0 | 1 | 2 | 3 | 4 | 5 -> TimePacket (parse_time_packet input)
| 6 -> ControlPacket (parse_control_packet input)
| 7 -> NTPDPrivatePacket (parse_ntpd_private_packet input)
| _ -> failwith "Should not happen as value is coded on 3 bit"
let dump_ntp_packet buf = function
| TimePacket p -> dump_time_packet buf p
| ControlPacket p -> dump_control_packet buf p
| NTPDPrivatePacket p -> dump_ntpd_private_packet buf p
let value_of_ntp_packet = function
| TimePacket p -> value_of_time_packet p
| ControlPacket p -> value_of_control_packet p
| NTPDPrivatePacket p -> value_of_ntpd_private_packet p
|
f113241d7cf56b19a5289e24a0c072f82874df2a8d8d98614a1d33d63f883a34 | namin/staged-miniKanren | staged-regexp.scm | inspired by -parsing-with-derivatives
(define regexp-NULL #f) ; -- the empty set
(define regexp-BLANK #t) ; -- the empty string
(define (valid-seqo exp)
(fresh (pat1 pat2)
(== `(seq ,pat1 ,pat2) exp)
(=/= regexp-NULL pat1)
(=/= regexp-BLANK pat1)
(=/= regexp-NULL pat2)
(=/= regexp-BLANK pat2)))
(define (seqo pat1 pat2 out)
(conde
[(== regexp-NULL pat1) (== regexp-NULL out)]
[(== regexp-NULL pat2) (== regexp-NULL out) (=/= regexp-NULL pat1)]
[(== regexp-BLANK pat1) (== pat2 out) (=/= regexp-NULL pat2)]
[(== regexp-BLANK pat2) (== pat1 out) (=/= regexp-NULL pat1) (=/= regexp-BLANK pat1)]
[(=/= regexp-NULL pat1) (=/= regexp-BLANK pat1) (=/= regexp-NULL pat2) (=/= regexp-BLANK pat2) (== `(seq ,pat1 ,pat2) out)]))
(define (valid-alto exp)
(fresh (pat1 pat2)
(== `(alt ,pat1 ,pat2) exp)
(=/= regexp-NULL pat1)
(=/= regexp-NULL pat2)
(=/= pat1 pat2)))
(define (alto pat1 pat2 out)
(conde
[(== pat1 pat2) (== pat1 out)]
[(=/= pat1 pat2)
(conde
[(== regexp-NULL pat1) (== pat2 out)]
[(== regexp-NULL pat2) (== pat1 out) (=/= regexp-NULL pat1)]
[(=/= regexp-NULL pat1) (=/= regexp-NULL pat2) (== `(alt ,pat1 ,pat2) out)])]))
(define (valid-repo exp)
(fresh (pat)
(== `(rep ,pat) exp)
(=/= regexp-BLANK pat)
(=/= regexp-NULL pat)
(fresh (re1 re2)
(conde
((symbolo pat))
((== `(seq ,re1 ,re2) pat))
((== `(alt ,re1 ,re2) pat))))))
(define (repo pat out)
(conde
[(== regexp-BLANK out)
(conde
[(== regexp-NULL pat)]
[(== regexp-BLANK pat)])]
[(conde
((symbolo pat) (== `(rep ,pat) out))
((fresh (re1 re2)
(conde
((== `(rep ,re1) pat)
; remove nested reps
(== pat out))
((== `(seq ,re1 ,re2) pat)
(== `(rep ,pat) out))
((== `(alt ,re1 ,re2) pat)
(== `(rep ,pat) out))))))]))
(define (regexp-matcho pattern data out)
(conde
((== '() data) (deltao pattern out))
((fresh (a d res)
(== (cons a d) data)
(derivo pattern a res)
(regexp-matcho res d out)))))
(define (deltao re out)
(conde
[(== regexp-BLANK re) (== #t out)]
[(== regexp-NULL re) (== #f out)]
[(symbolo re) (== #f out)]
[(fresh (re1)
(== `(rep ,re1) re)
(== #t out)
(valid-repo re))]
[(fresh (re1 re2 res1 res2)
(== `(seq ,re1 ,re2) re)
(valid-seqo re)
(conde
((== #f res1) (== #f out))
((== #t res1) (== #f res2) (== #f out))
((== #t res1) (== #t res2) (== #t out)))
(deltao re1 res1)
(deltao re2 res2))]
[(fresh (re1 re2 res1 res2)
(== `(alt ,re1 ,re2) re)
(valid-alto re)
(conde
((== #t res1) (== #t out))
((== #f res1) (== #t res2) (== #t out))
((== #f res1) (== #f res2) (== #f out)))
(deltao re1 res1)
(deltao re2 res2))]))
(define (derivo re c out)
(fresh ()
(symbolo c)
(conde
[(== regexp-BLANK re) (== regexp-NULL out)]
[(== regexp-NULL re) (== regexp-NULL out)]
[(symbolo re)
(conde
[(l== c re) (== regexp-BLANK out)]
[(=/= c re) (== regexp-NULL out)])]
[(fresh (re1 res1)
(== `(rep ,re1) re)
(valid-repo re)
(seqo res1 re out)
(derivo re1 c res1))]
[(fresh (re1 re2 res1 res2)
(== `(alt ,re1 ,re2) re)
(valid-alto re)
(derivo re1 c res1)
(derivo re2 c res2)
(alto res1 res2 out))]
[(fresh (re1 re2 res1 res2 res3 res4 res5)
(== `(seq ,re1 ,re2) re)
(valid-seqo re)
(derivo re1 c res1)
(deltao re1 res3)
(derivo re2 c res4)
(seqo res1 re2 res2)
(seqo res3 res4 res5)
(alto res2 res5 out))])))
| null | https://raw.githubusercontent.com/namin/staged-miniKanren/f5b665170000720f5d499ab03f31b5c55871ec4f/staged-regexp.scm | scheme | -- the empty set
-- the empty string
remove nested reps | inspired by -parsing-with-derivatives
(define (valid-seqo exp)
(fresh (pat1 pat2)
(== `(seq ,pat1 ,pat2) exp)
(=/= regexp-NULL pat1)
(=/= regexp-BLANK pat1)
(=/= regexp-NULL pat2)
(=/= regexp-BLANK pat2)))
(define (seqo pat1 pat2 out)
(conde
[(== regexp-NULL pat1) (== regexp-NULL out)]
[(== regexp-NULL pat2) (== regexp-NULL out) (=/= regexp-NULL pat1)]
[(== regexp-BLANK pat1) (== pat2 out) (=/= regexp-NULL pat2)]
[(== regexp-BLANK pat2) (== pat1 out) (=/= regexp-NULL pat1) (=/= regexp-BLANK pat1)]
[(=/= regexp-NULL pat1) (=/= regexp-BLANK pat1) (=/= regexp-NULL pat2) (=/= regexp-BLANK pat2) (== `(seq ,pat1 ,pat2) out)]))
(define (valid-alto exp)
(fresh (pat1 pat2)
(== `(alt ,pat1 ,pat2) exp)
(=/= regexp-NULL pat1)
(=/= regexp-NULL pat2)
(=/= pat1 pat2)))
(define (alto pat1 pat2 out)
(conde
[(== pat1 pat2) (== pat1 out)]
[(=/= pat1 pat2)
(conde
[(== regexp-NULL pat1) (== pat2 out)]
[(== regexp-NULL pat2) (== pat1 out) (=/= regexp-NULL pat1)]
[(=/= regexp-NULL pat1) (=/= regexp-NULL pat2) (== `(alt ,pat1 ,pat2) out)])]))
(define (valid-repo exp)
(fresh (pat)
(== `(rep ,pat) exp)
(=/= regexp-BLANK pat)
(=/= regexp-NULL pat)
(fresh (re1 re2)
(conde
((symbolo pat))
((== `(seq ,re1 ,re2) pat))
((== `(alt ,re1 ,re2) pat))))))
(define (repo pat out)
(conde
[(== regexp-BLANK out)
(conde
[(== regexp-NULL pat)]
[(== regexp-BLANK pat)])]
[(conde
((symbolo pat) (== `(rep ,pat) out))
((fresh (re1 re2)
(conde
((== `(rep ,re1) pat)
(== pat out))
((== `(seq ,re1 ,re2) pat)
(== `(rep ,pat) out))
((== `(alt ,re1 ,re2) pat)
(== `(rep ,pat) out))))))]))
(define (regexp-matcho pattern data out)
(conde
((== '() data) (deltao pattern out))
((fresh (a d res)
(== (cons a d) data)
(derivo pattern a res)
(regexp-matcho res d out)))))
(define (deltao re out)
(conde
[(== regexp-BLANK re) (== #t out)]
[(== regexp-NULL re) (== #f out)]
[(symbolo re) (== #f out)]
[(fresh (re1)
(== `(rep ,re1) re)
(== #t out)
(valid-repo re))]
[(fresh (re1 re2 res1 res2)
(== `(seq ,re1 ,re2) re)
(valid-seqo re)
(conde
((== #f res1) (== #f out))
((== #t res1) (== #f res2) (== #f out))
((== #t res1) (== #t res2) (== #t out)))
(deltao re1 res1)
(deltao re2 res2))]
[(fresh (re1 re2 res1 res2)
(== `(alt ,re1 ,re2) re)
(valid-alto re)
(conde
((== #t res1) (== #t out))
((== #f res1) (== #t res2) (== #t out))
((== #f res1) (== #f res2) (== #f out)))
(deltao re1 res1)
(deltao re2 res2))]))
(define (derivo re c out)
(fresh ()
(symbolo c)
(conde
[(== regexp-BLANK re) (== regexp-NULL out)]
[(== regexp-NULL re) (== regexp-NULL out)]
[(symbolo re)
(conde
[(l== c re) (== regexp-BLANK out)]
[(=/= c re) (== regexp-NULL out)])]
[(fresh (re1 res1)
(== `(rep ,re1) re)
(valid-repo re)
(seqo res1 re out)
(derivo re1 c res1))]
[(fresh (re1 re2 res1 res2)
(== `(alt ,re1 ,re2) re)
(valid-alto re)
(derivo re1 c res1)
(derivo re2 c res2)
(alto res1 res2 out))]
[(fresh (re1 re2 res1 res2 res3 res4 res5)
(== `(seq ,re1 ,re2) re)
(valid-seqo re)
(derivo re1 c res1)
(deltao re1 res3)
(derivo re2 c res4)
(seqo res1 re2 res2)
(seqo res3 res4 res5)
(alto res2 res5 out))])))
|
601cbeada668406e3ced009d80f243be2b15440082db07f288d7308ffe05e189 | l29ah/hatexmpp3 | GTK.hs | module GTK.GTK where
import Control.Concurrent
import Graphics.UI.Gtk
initGTK :: IO ()
initGTK = do
forkIO $ do
unsafeInitGUIForThreadedRTS
mainGUI
return ()
| null | https://raw.githubusercontent.com/l29ah/hatexmpp3/9d3e25c6acf4c0978a2c1d88b3572ad20b1c228d/GTK/GTK.hs | haskell | module GTK.GTK where
import Control.Concurrent
import Graphics.UI.Gtk
initGTK :: IO ()
initGTK = do
forkIO $ do
unsafeInitGUIForThreadedRTS
mainGUI
return ()
| |
96593ccb225642ea9b18227882d27afb00441006214cf99f0963572ff1b6815b | calyau/maxima | numericalio.lisp | Copyright 2005 by
;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License .
;; This program has NO WARRANTY, not even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
(in-package :maxima)
;; Read functions:
;;
M : read_matrix ( source , sep_ch_flag )
read_matrix ( source , M , sep_ch_flag )
A : read_array ( source , sep_ch_flag )
read_array ( source , A , sep_ch_flag )
read_hashed_array ( source , A , sep_ch_flag )
L : read_nested_list ( source , sep_ch_flag )
L : read_list ( source , sep_ch_flag )
read_list ( source , L , sep_ch_flag )
;;
;; read_binary_matrix (source, M)
;; A : read_binary_array (source)
;; read_binary_array (source, A)
;; L: read_binary_list (source)
;; read_binary_list (source, L)
;;
;; `source' is a file name or input stream.
;;
;; Write functions:
;;
;; `sink' is a file name or output stream.
;;
write_data ( X , sink , sep_ch_flag )
;; write_binary_data (X, sink)
;;
;; Helpers:
;;
byte_order_flag recognized values : msb , lsb
;;
;; assume_external_byte_order (byte_order_flag)
;;
(defun $assume_external_byte_order (x)
(cond
((eq x '$lsb)
(define-external-byte-order :lsb))
((eq x '$msb)
(define-external-byte-order :msb))
(t
(merror "assume_external_byte_order: unrecognized byte order flag: ~a" x))))
(defun lisp-or-declared-maxima-array-p (x)
(or (arrayp x) (mget x 'array)))
;; THESE FILE-OPENING FUNCTIONS WANT TO BE MOVED TO STRINGPROC (HOME OF OTHER SUCH FUNCTIONS) !!
(defun $openw_binary (file)
(open
file
:direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8)
:if-does-not-exist :create))
(defun $opena_binary (file)
(open
file
:direction :output
:if-exists :append
:element-type '(unsigned-byte 8)
:if-does-not-exist :create))
(defun $openr_binary (file) (open file :element-type '(unsigned-byte 8)))
;; -------------------- read functions --------------------
;; ---- functions to read a matrix
(defun $read_matrix (stream-or-filename &rest args)
(if ($matrixp (car args))
(let*
((M (car args))
(sep-ch-flag (cadr args))
(nrow (length (cdr M)))
(ncol (if (> nrow 0) (length (cdadr M)) 0))
(L ($read_list stream-or-filename sep-ch-flag (* nrow ncol))))
;; COPYING DATA HERE !!
(fill-matrix-from-list L M nrow ncol))
(let ((sep-ch-flag (car args)))
`(($matrix) ,@(cdr ($read_nested_list stream-or-filename sep-ch-flag))))))
(defun $read_binary_matrix (stream-or-filename M)
(if ($matrixp M)
(let*
((nrow (length (cdr M)))
(ncol (if (> nrow 0) (length (cdadr M)) 0))
(L ($read_binary_list stream-or-filename (* nrow ncol))))
;; COPYING DATA HERE !!
(fill-matrix-from-list L M nrow ncol))
(merror "read_binary_matrix: expected a matrix, found ~a instead" (type-of M))))
(defun fill-matrix-from-list (L M nrow ncol)
(let ((k 0))
(dotimes (i nrow)
(let ((row (nth (1+ i) M)))
(dotimes (j ncol)
(setf (nth (1+ j) row) (nth (1+ k) L))
(setq k (1+ k))))))
M)
---- functions to read a Lisp array or Maxima declared array
(defun $read_array (stream-or-filename &rest args)
(if (and args (lisp-or-declared-maxima-array-p (car args)))
(let
((A (car args))
(sep-ch-flag (and (cdr args) (cadr args)))
(mode (or (and (cddr args) (caddr args)) 'text)))
(read-into-existing-array stream-or-filename A sep-ch-flag mode))
(let
((sep-ch-flag (and args (car args)))
(mode (or (and (cdr args) (cadr args)) 'text)))
(read-and-return-new-array stream-or-filename sep-ch-flag mode))))
(defun $read_binary_array (file-name &rest args)
(if (car args)
(read-into-existing-array file-name (car args) nil 'binary)
(read-and-return-new-array file-name nil 'binary)))
(defun read-into-existing-array (file-name A sep-ch-flag mode)
(if (not (arrayp A))
(setq A (get (mget A 'array) 'array)))
(let*
((dimensions (array-dimensions A))
(n (apply #'* dimensions)))
(read-into-existing-array-size-known file-name A sep-ch-flag mode n)
'$done))
(defun read-into-existing-array-size-known (stream-or-filename A sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-into-existing-array-size-known-from-stream stream-or-filename A sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-into-existing-array-size-known-from-stream in A sep-ch-flag mode n)
(merror "read_array: no such file `~a'" file-name))))))
(defun read-into-existing-array-size-known-from-stream (in A sep-ch-flag mode n)
(let (x (sep-ch (get-input-sep-ch sep-ch-flag in)))
(dotimes (i n)
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return A))
(setf (row-major-aref A i) x))))
(defun read-into-existing-array-size-unknown-from-stream (in A sep-ch mode)
(let (x)
(loop
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return A))
(vector-push-extend x A))))
(defun read-and-return-new-array (stream-or-filename sep-ch-flag mode)
(if (streamp stream-or-filename)
(read-and-return-new-array-from-stream stream-or-filename sep-ch-flag mode)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-and-return-new-array-from-stream in sep-ch-flag mode)
(merror "read_array: no such file `~a'" file-name))))))
(defun read-and-return-new-array-from-stream (in sep-ch-flag mode)
(let ((A (make-array 0 :adjustable t :fill-pointer t))
(sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(read-into-existing-array-size-unknown-from-stream in A sep-ch mode)))
---- functions to read a Maxima undeclared array
(defun $read_hashed_array (stream-or-filename A &optional sep-ch-flag)
(if (streamp stream-or-filename)
(read-hashed-array-from-stream stream-or-filename A sep-ch-flag)
(let ((file-name (require-string stream-or-filename)))
(with-open-file (in file-name :if-does-not-exist nil)
(if (not (null in))
(read-hashed-array-from-stream in A sep-ch-flag)
(merror "read_hashed_array no such file `~a'" file-name))))))
(defun read-hashed-array-from-stream (in A sep-ch-flag)
(let (key L (sep-ch (get-input-sep-ch sep-ch-flag in)))
(loop
(setq L (read-line in nil 'eof))
(if (eq L 'eof) (return))
(setq L (make-mlist-from-string L sep-ch))
(cond
((> ($length L) 0)
(setq key ($first L))
(if (= ($length L) 1)
(arrstore (list (list A 'array) key) nil)
(arrstore (list (list A 'array) key) ($rest L)))))))
A)
;; ---- functions to read a list or nested list
(defun $read_nested_list (stream-or-filename &optional sep-ch-flag)
(if (streamp stream-or-filename)
(read-nested-list-from-stream stream-or-filename sep-ch-flag)
(let ((file-name (require-string stream-or-filename)))
(with-open-file (in file-name :if-does-not-exist nil)
(if (not (null in))
(read-nested-list-from-stream in sep-ch-flag)
(merror "read_nested_list: no such file `~a'" file-name))))))
(defun read-nested-list-from-stream (in sep-ch-flag)
(let (A L (sep-ch (get-input-sep-ch sep-ch-flag in)))
(loop
(setq L (read-line in nil 'eof))
(if (eq L 'eof)
(return (cons '(mlist simp) (nreverse A))))
(setq A (cons (make-mlist-from-string L sep-ch) A)))))
(defun $read_list (stream-or-filename &rest args)
(if ($listp (car args))
(let*
((L (car args))
(sep-ch-flag (cadr args))
(n (or (caddr args) ($length L))))
(read-into-existing-list stream-or-filename L sep-ch-flag 'text n))
(if (integerp (car args))
(let ((n (car args)))
(read-list stream-or-filename nil 'text n))
(let ((sep-ch-flag (car args)) (n (cadr args)))
(read-list stream-or-filename sep-ch-flag 'text n)))))
(defun read-into-existing-list (stream-or-filename L sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-into-existing-list-from-stream stream-or-filename L sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-into-existing-list-from-stream in L sep-ch-flag mode n)
(merror "read_list: no such file `~a'" file-name))))))
(defun read-into-existing-list-from-stream (in L sep-ch-flag mode n)
(let (x (sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(dotimes (i n)
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return))
(setf (nth (1+ i) L) x))
L))
(defun read-list (stream-or-filename sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-list-from-stream stream-or-filename sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-list-from-stream in sep-ch-flag mode n)
(merror "read_list: no such file `~a'" file-name))))))
(defun read-list-from-stream (in sep-ch-flag mode n)
(let (A x (sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(loop
(if
(or
(and n (eql n 0))
(eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in)))
'eof))
(return (cons '(mlist simp) (nreverse A))))
(setq A (nconc (list x) A))
(if n (decf n)))))
(defun $read_binary_list (stream-or-filename &rest args)
(if ($listp (car args))
(let*
((L (car args))
(n (or (cadr args) ($length L))))
(read-into-existing-list stream-or-filename L nil 'binary n))
(let ((n (car args)))
(read-list stream-or-filename nil 'binary n))))
(defun make-mlist-from-string (s sep-ch)
scan - one - token - g is n't happy with symbol at end of string .
(setq s (concatenate 'string s " "))
(with-input-from-string (*parse-stream* s)
(let ((token) (L) (LL) (sign))
(loop
(setq token (scan-one-token-g t 'eof))
(cond
((eq token 'eof)
(cond
((not (null sign))
(format t "numericalio: trailing sign (~S) at end of line; strange, but just eat it.~%" sign)))
(cond
((eql sep-ch #\space)
(return (cons '(mlist) LL)))
(t
(return (cons '(mlist) (appropriate-append L LL)))))))
(cond
((or (eq token '$-) (eq token '$+))
(setq sign (cond ((eq token '$-) -1) (t 1))))
(t
(cond
((not (null sign))
(setq token (m* sign token))
(setq sign nil)))
(cond
((eql sep-ch #\space)
(setq LL (append LL (list token))))
(t
(cond
((eql token sep-ch)
(setq L (appropriate-append L LL))
(setq LL nil))
(t
(setq LL (append LL (list token)))))))))))))
(defun appropriate-append (L LL)
(cond
((null LL) (append L '(nil)))
((= (length LL) 1) (append L LL))
(t (append L (list (append '((mlist)) LL))))))
;; ----- begin backwards compatibility stuff ... sigh -----
(defun $read_lisp_array (file-name A &optional sep-ch-flag)
($read_array file-name A sep-ch-flag))
(defun $read_maxima_array (file-name A &optional sep-ch-flag)
($read_array file-name A sep-ch-flag))
;; ----- end backwards compatibility stuff ... sigh -----
---- read one element
(let (pushback-sep-ch)
(defun parse-next-element (in sep-ch)
(let
((*parse-stream* in)
(sign 1)
(initial-pos (file-position in))
token
found-sep-ch)
(loop
(if pushback-sep-ch
(setq token pushback-sep-ch pushback-sep-ch nil)
(setq token (scan-one-token-g t 'eof)))
(cond
((eq token 'eof)
(if found-sep-ch
(return nil)
(return 'eof)))
((and (eql token sep-ch) (not (eql sep-ch #\space)))
(if (or found-sep-ch (eql initial-pos 0))
(progn
(setq pushback-sep-ch token)
(return nil))
(setq found-sep-ch token)))
((member token '($- $+))
(setq sign (* sign (if (eq token '$-) -1 1))))
(t
(return (m* sign token))))))))
;; -------------------- write functions -------------------
(defun open-file-appropriately (file-name mode)
(open file-name
:direction :output
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8))
:if-exists (if (or (eq $file_output_append '$true) (eq $file_output_append t)) :append :supersede)
:if-does-not-exist :create))
(defun $write_data (X stream-or-filename &optional sep-ch-flag)
(write-data X stream-or-filename sep-ch-flag 'text))
(defun $write_binary_data (X stream-or-filename)
(write-data X stream-or-filename nil 'binary))
(defun write-data (X stream-or-filename sep-ch-flag mode)
(let
((out
(if (streamp stream-or-filename)
stream-or-filename
(open-file-appropriately (require-string stream-or-filename) mode))))
(cond
(($matrixp X)
(write-matrix X out sep-ch-flag mode))
((arrayp X)
(write-lisp-array X out sep-ch-flag mode))
((mget X 'array)
(write-maxima-array X out sep-ch-flag mode))
((mget X 'hashar)
(write-hashed-array X out sep-ch-flag mode))
(($listp X)
(write-list X out sep-ch-flag mode))
(t (merror "write_data: don't know what to do with a ~M" (type-of X))))
(if (streamp stream-or-filename)
(finish-output out)
(close out))
'$done))
(defun write-matrix (M out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)))
(mapcar #'(lambda (x) (write-list-lowlevel (cdr x) out sep-ch mode)) (cdr M))))
(defun write-lisp-array (A out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)) (d (array-dimensions A)))
(write-lisp-array-helper A d '() out sep-ch mode)))
(defun write-lisp-array-helper (A d indices out sep-ch mode)
(cond ((equalp (length d) 1)
(let ((L '()))
(loop for i from 0 to (- (car d) 1) do
(let ((x (apply 'aref (append (list A) (reverse (cons i indices))))))
(setq L (cons x L))))
(write-list-lowlevel (reverse L) out sep-ch mode)))
(t
(loop for i from 0 to (- (car d) 1) do
(write-lisp-array-helper A (cdr d) (cons i indices) out sep-ch mode)
(if (and (eq mode 'text) (> (length d) 2))
(terpri out))))))
(defun write-maxima-array (A out sep-ch-flag mode)
(write-lisp-array (symbol-array (mget A 'array)) out sep-ch-flag mode))
(defun write-hashed-array (A out sep-ch-flag mode)
(let
((keys (cdddr (meval (list '($arrayinfo) A))))
(sep-ch (get-output-sep-ch sep-ch-flag out))
L)
(loop
(if (not keys) (return))
(setq L ($arrayapply A (car keys)))
(cond ((listp L) (pop L))
(t (setq L (list L))))
(write-list-lowlevel (append (cdr (pop keys)) L) out sep-ch mode))))
(defun write-list (L out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)))
(write-list-lowlevel (cdr L) out sep-ch mode)))
(defun write-list-lowlevel (L out sep-ch mode)
(setq sep-ch (cond ((symbolp sep-ch) (cadr (exploden sep-ch))) (t sep-ch)))
(cond ((not (null L))
(loop
(if (not L) (return))
(let ((e (pop L)))
(cond (($listp e)
(write-list-lowlevel (cdr e) out sep-ch mode))
(t
(cond
((eq mode 'text)
(let
(($lispdisp t))
(declare (special $lispdisp))
(mgrind e out))
(cond
((null L) (terpri out))
(t (write-char sep-ch out))))
((eq mode 'binary)
(if ($numberp e)
(write-float ($float e) out)
(merror "write_data: encountered non-numeric data in binary output")))
(t
(merror "write_data: unrecognized mode"))))))))))
(defun get-input-sep-ch (sep-ch-flag my-stream)
(cond
((eq sep-ch-flag '$tab)
(format t "numericalio: separator flag ``tab'' not recognized for input; assume ``space'' instead.~%")
#\space)
(t (get-output-sep-ch sep-ch-flag my-stream))))
(defun get-output-sep-ch (sep-ch-flag my-stream)
(cond
((eq sep-ch-flag '$space) #\space)
((eq sep-ch-flag '$tab) #\tab)
((or (eq sep-ch-flag '$comma) (eq sep-ch-flag '$csv)) '$\,) ; '$csv is backwards compatibility ... sigh
((eq sep-ch-flag '$pipe) '$\|)
((eq sep-ch-flag '$semicolon) '$\;)
((null sep-ch-flag)
(cond
((ignore-errors (equal (pathname-type (truename my-stream)) "csv"))
'$\,)
(t #\space)))
(t
(format t "numericalio: separator flag ~S not recognized; assume ``space''.~%" (stripdollar sep-ch-flag))
#\space)))
(defun require-string (s)
(cond
((stringp s)
s)
(t
(merror "numericalio: expected a string, instead found a ~:M" (type-of s)))))
| null | https://raw.githubusercontent.com/calyau/maxima/9352a3f5c22b9b5d0b367fddeb0185c53d7f4d02/share/numericalio/numericalio.lisp | lisp | This program is free software; you can redistribute it and/or
This program has NO WARRANTY, not even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Read functions:
read_binary_matrix (source, M)
A : read_binary_array (source)
read_binary_array (source, A)
L: read_binary_list (source)
read_binary_list (source, L)
`source' is a file name or input stream.
Write functions:
`sink' is a file name or output stream.
write_binary_data (X, sink)
Helpers:
assume_external_byte_order (byte_order_flag)
THESE FILE-OPENING FUNCTIONS WANT TO BE MOVED TO STRINGPROC (HOME OF OTHER SUCH FUNCTIONS) !!
-------------------- read functions --------------------
---- functions to read a matrix
COPYING DATA HERE !!
COPYING DATA HERE !!
---- functions to read a list or nested list
----- begin backwards compatibility stuff ... sigh -----
----- end backwards compatibility stuff ... sigh -----
-------------------- write functions -------------------
'$csv is backwards compatibility ... sigh
) | Copyright 2005 by
modify it under the terms of the GNU General Public License .
(in-package :maxima)
M : read_matrix ( source , sep_ch_flag )
read_matrix ( source , M , sep_ch_flag )
A : read_array ( source , sep_ch_flag )
read_array ( source , A , sep_ch_flag )
read_hashed_array ( source , A , sep_ch_flag )
L : read_nested_list ( source , sep_ch_flag )
L : read_list ( source , sep_ch_flag )
read_list ( source , L , sep_ch_flag )
write_data ( X , sink , sep_ch_flag )
byte_order_flag recognized values : msb , lsb
(defun $assume_external_byte_order (x)
(cond
((eq x '$lsb)
(define-external-byte-order :lsb))
((eq x '$msb)
(define-external-byte-order :msb))
(t
(merror "assume_external_byte_order: unrecognized byte order flag: ~a" x))))
(defun lisp-or-declared-maxima-array-p (x)
(or (arrayp x) (mget x 'array)))
(defun $openw_binary (file)
(open
file
:direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8)
:if-does-not-exist :create))
(defun $opena_binary (file)
(open
file
:direction :output
:if-exists :append
:element-type '(unsigned-byte 8)
:if-does-not-exist :create))
(defun $openr_binary (file) (open file :element-type '(unsigned-byte 8)))
(defun $read_matrix (stream-or-filename &rest args)
(if ($matrixp (car args))
(let*
((M (car args))
(sep-ch-flag (cadr args))
(nrow (length (cdr M)))
(ncol (if (> nrow 0) (length (cdadr M)) 0))
(L ($read_list stream-or-filename sep-ch-flag (* nrow ncol))))
(fill-matrix-from-list L M nrow ncol))
(let ((sep-ch-flag (car args)))
`(($matrix) ,@(cdr ($read_nested_list stream-or-filename sep-ch-flag))))))
(defun $read_binary_matrix (stream-or-filename M)
(if ($matrixp M)
(let*
((nrow (length (cdr M)))
(ncol (if (> nrow 0) (length (cdadr M)) 0))
(L ($read_binary_list stream-or-filename (* nrow ncol))))
(fill-matrix-from-list L M nrow ncol))
(merror "read_binary_matrix: expected a matrix, found ~a instead" (type-of M))))
(defun fill-matrix-from-list (L M nrow ncol)
(let ((k 0))
(dotimes (i nrow)
(let ((row (nth (1+ i) M)))
(dotimes (j ncol)
(setf (nth (1+ j) row) (nth (1+ k) L))
(setq k (1+ k))))))
M)
---- functions to read a Lisp array or Maxima declared array
(defun $read_array (stream-or-filename &rest args)
(if (and args (lisp-or-declared-maxima-array-p (car args)))
(let
((A (car args))
(sep-ch-flag (and (cdr args) (cadr args)))
(mode (or (and (cddr args) (caddr args)) 'text)))
(read-into-existing-array stream-or-filename A sep-ch-flag mode))
(let
((sep-ch-flag (and args (car args)))
(mode (or (and (cdr args) (cadr args)) 'text)))
(read-and-return-new-array stream-or-filename sep-ch-flag mode))))
(defun $read_binary_array (file-name &rest args)
(if (car args)
(read-into-existing-array file-name (car args) nil 'binary)
(read-and-return-new-array file-name nil 'binary)))
(defun read-into-existing-array (file-name A sep-ch-flag mode)
(if (not (arrayp A))
(setq A (get (mget A 'array) 'array)))
(let*
((dimensions (array-dimensions A))
(n (apply #'* dimensions)))
(read-into-existing-array-size-known file-name A sep-ch-flag mode n)
'$done))
(defun read-into-existing-array-size-known (stream-or-filename A sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-into-existing-array-size-known-from-stream stream-or-filename A sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-into-existing-array-size-known-from-stream in A sep-ch-flag mode n)
(merror "read_array: no such file `~a'" file-name))))))
(defun read-into-existing-array-size-known-from-stream (in A sep-ch-flag mode n)
(let (x (sep-ch (get-input-sep-ch sep-ch-flag in)))
(dotimes (i n)
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return A))
(setf (row-major-aref A i) x))))
(defun read-into-existing-array-size-unknown-from-stream (in A sep-ch mode)
(let (x)
(loop
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return A))
(vector-push-extend x A))))
(defun read-and-return-new-array (stream-or-filename sep-ch-flag mode)
(if (streamp stream-or-filename)
(read-and-return-new-array-from-stream stream-or-filename sep-ch-flag mode)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-and-return-new-array-from-stream in sep-ch-flag mode)
(merror "read_array: no such file `~a'" file-name))))))
(defun read-and-return-new-array-from-stream (in sep-ch-flag mode)
(let ((A (make-array 0 :adjustable t :fill-pointer t))
(sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(read-into-existing-array-size-unknown-from-stream in A sep-ch mode)))
---- functions to read a Maxima undeclared array
(defun $read_hashed_array (stream-or-filename A &optional sep-ch-flag)
(if (streamp stream-or-filename)
(read-hashed-array-from-stream stream-or-filename A sep-ch-flag)
(let ((file-name (require-string stream-or-filename)))
(with-open-file (in file-name :if-does-not-exist nil)
(if (not (null in))
(read-hashed-array-from-stream in A sep-ch-flag)
(merror "read_hashed_array no such file `~a'" file-name))))))
(defun read-hashed-array-from-stream (in A sep-ch-flag)
(let (key L (sep-ch (get-input-sep-ch sep-ch-flag in)))
(loop
(setq L (read-line in nil 'eof))
(if (eq L 'eof) (return))
(setq L (make-mlist-from-string L sep-ch))
(cond
((> ($length L) 0)
(setq key ($first L))
(if (= ($length L) 1)
(arrstore (list (list A 'array) key) nil)
(arrstore (list (list A 'array) key) ($rest L)))))))
A)
(defun $read_nested_list (stream-or-filename &optional sep-ch-flag)
(if (streamp stream-or-filename)
(read-nested-list-from-stream stream-or-filename sep-ch-flag)
(let ((file-name (require-string stream-or-filename)))
(with-open-file (in file-name :if-does-not-exist nil)
(if (not (null in))
(read-nested-list-from-stream in sep-ch-flag)
(merror "read_nested_list: no such file `~a'" file-name))))))
(defun read-nested-list-from-stream (in sep-ch-flag)
(let (A L (sep-ch (get-input-sep-ch sep-ch-flag in)))
(loop
(setq L (read-line in nil 'eof))
(if (eq L 'eof)
(return (cons '(mlist simp) (nreverse A))))
(setq A (cons (make-mlist-from-string L sep-ch) A)))))
(defun $read_list (stream-or-filename &rest args)
(if ($listp (car args))
(let*
((L (car args))
(sep-ch-flag (cadr args))
(n (or (caddr args) ($length L))))
(read-into-existing-list stream-or-filename L sep-ch-flag 'text n))
(if (integerp (car args))
(let ((n (car args)))
(read-list stream-or-filename nil 'text n))
(let ((sep-ch-flag (car args)) (n (cadr args)))
(read-list stream-or-filename sep-ch-flag 'text n)))))
(defun read-into-existing-list (stream-or-filename L sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-into-existing-list-from-stream stream-or-filename L sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-into-existing-list-from-stream in L sep-ch-flag mode n)
(merror "read_list: no such file `~a'" file-name))))))
(defun read-into-existing-list-from-stream (in L sep-ch-flag mode n)
(let (x (sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(dotimes (i n)
(if (eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in))) 'eof)
(return))
(setf (nth (1+ i) L) x))
L))
(defun read-list (stream-or-filename sep-ch-flag mode n)
(if (streamp stream-or-filename)
(read-list-from-stream stream-or-filename sep-ch-flag mode n)
(let ((file-name (require-string stream-or-filename)))
(with-open-file
(in file-name
:if-does-not-exist nil
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8)))
(if (not (null in))
(read-list-from-stream in sep-ch-flag mode n)
(merror "read_list: no such file `~a'" file-name))))))
(defun read-list-from-stream (in sep-ch-flag mode n)
(let (A x (sep-ch (if (eq mode 'text) (get-input-sep-ch sep-ch-flag in))))
(loop
(if
(or
(and n (eql n 0))
(eq (setq x (if (eq mode 'text) (parse-next-element in sep-ch) (read-float-64 in)))
'eof))
(return (cons '(mlist simp) (nreverse A))))
(setq A (nconc (list x) A))
(if n (decf n)))))
(defun $read_binary_list (stream-or-filename &rest args)
(if ($listp (car args))
(let*
((L (car args))
(n (or (cadr args) ($length L))))
(read-into-existing-list stream-or-filename L nil 'binary n))
(let ((n (car args)))
(read-list stream-or-filename nil 'binary n))))
(defun make-mlist-from-string (s sep-ch)
scan - one - token - g is n't happy with symbol at end of string .
(setq s (concatenate 'string s " "))
(with-input-from-string (*parse-stream* s)
(let ((token) (L) (LL) (sign))
(loop
(setq token (scan-one-token-g t 'eof))
(cond
((eq token 'eof)
(cond
((not (null sign))
(format t "numericalio: trailing sign (~S) at end of line; strange, but just eat it.~%" sign)))
(cond
((eql sep-ch #\space)
(return (cons '(mlist) LL)))
(t
(return (cons '(mlist) (appropriate-append L LL)))))))
(cond
((or (eq token '$-) (eq token '$+))
(setq sign (cond ((eq token '$-) -1) (t 1))))
(t
(cond
((not (null sign))
(setq token (m* sign token))
(setq sign nil)))
(cond
((eql sep-ch #\space)
(setq LL (append LL (list token))))
(t
(cond
((eql token sep-ch)
(setq L (appropriate-append L LL))
(setq LL nil))
(t
(setq LL (append LL (list token)))))))))))))
(defun appropriate-append (L LL)
(cond
((null LL) (append L '(nil)))
((= (length LL) 1) (append L LL))
(t (append L (list (append '((mlist)) LL))))))
(defun $read_lisp_array (file-name A &optional sep-ch-flag)
($read_array file-name A sep-ch-flag))
(defun $read_maxima_array (file-name A &optional sep-ch-flag)
($read_array file-name A sep-ch-flag))
---- read one element
(let (pushback-sep-ch)
(defun parse-next-element (in sep-ch)
(let
((*parse-stream* in)
(sign 1)
(initial-pos (file-position in))
token
found-sep-ch)
(loop
(if pushback-sep-ch
(setq token pushback-sep-ch pushback-sep-ch nil)
(setq token (scan-one-token-g t 'eof)))
(cond
((eq token 'eof)
(if found-sep-ch
(return nil)
(return 'eof)))
((and (eql token sep-ch) (not (eql sep-ch #\space)))
(if (or found-sep-ch (eql initial-pos 0))
(progn
(setq pushback-sep-ch token)
(return nil))
(setq found-sep-ch token)))
((member token '($- $+))
(setq sign (* sign (if (eq token '$-) -1 1))))
(t
(return (m* sign token))))))))
(defun open-file-appropriately (file-name mode)
(open file-name
:direction :output
:element-type (if (eq mode 'text) 'character '(unsigned-byte 8))
:if-exists (if (or (eq $file_output_append '$true) (eq $file_output_append t)) :append :supersede)
:if-does-not-exist :create))
(defun $write_data (X stream-or-filename &optional sep-ch-flag)
(write-data X stream-or-filename sep-ch-flag 'text))
(defun $write_binary_data (X stream-or-filename)
(write-data X stream-or-filename nil 'binary))
(defun write-data (X stream-or-filename sep-ch-flag mode)
(let
((out
(if (streamp stream-or-filename)
stream-or-filename
(open-file-appropriately (require-string stream-or-filename) mode))))
(cond
(($matrixp X)
(write-matrix X out sep-ch-flag mode))
((arrayp X)
(write-lisp-array X out sep-ch-flag mode))
((mget X 'array)
(write-maxima-array X out sep-ch-flag mode))
((mget X 'hashar)
(write-hashed-array X out sep-ch-flag mode))
(($listp X)
(write-list X out sep-ch-flag mode))
(t (merror "write_data: don't know what to do with a ~M" (type-of X))))
(if (streamp stream-or-filename)
(finish-output out)
(close out))
'$done))
(defun write-matrix (M out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)))
(mapcar #'(lambda (x) (write-list-lowlevel (cdr x) out sep-ch mode)) (cdr M))))
(defun write-lisp-array (A out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)) (d (array-dimensions A)))
(write-lisp-array-helper A d '() out sep-ch mode)))
(defun write-lisp-array-helper (A d indices out sep-ch mode)
(cond ((equalp (length d) 1)
(let ((L '()))
(loop for i from 0 to (- (car d) 1) do
(let ((x (apply 'aref (append (list A) (reverse (cons i indices))))))
(setq L (cons x L))))
(write-list-lowlevel (reverse L) out sep-ch mode)))
(t
(loop for i from 0 to (- (car d) 1) do
(write-lisp-array-helper A (cdr d) (cons i indices) out sep-ch mode)
(if (and (eq mode 'text) (> (length d) 2))
(terpri out))))))
(defun write-maxima-array (A out sep-ch-flag mode)
(write-lisp-array (symbol-array (mget A 'array)) out sep-ch-flag mode))
(defun write-hashed-array (A out sep-ch-flag mode)
(let
((keys (cdddr (meval (list '($arrayinfo) A))))
(sep-ch (get-output-sep-ch sep-ch-flag out))
L)
(loop
(if (not keys) (return))
(setq L ($arrayapply A (car keys)))
(cond ((listp L) (pop L))
(t (setq L (list L))))
(write-list-lowlevel (append (cdr (pop keys)) L) out sep-ch mode))))
(defun write-list (L out sep-ch-flag mode)
(let ((sep-ch (get-output-sep-ch sep-ch-flag out)))
(write-list-lowlevel (cdr L) out sep-ch mode)))
(defun write-list-lowlevel (L out sep-ch mode)
(setq sep-ch (cond ((symbolp sep-ch) (cadr (exploden sep-ch))) (t sep-ch)))
(cond ((not (null L))
(loop
(if (not L) (return))
(let ((e (pop L)))
(cond (($listp e)
(write-list-lowlevel (cdr e) out sep-ch mode))
(t
(cond
((eq mode 'text)
(let
(($lispdisp t))
(declare (special $lispdisp))
(mgrind e out))
(cond
((null L) (terpri out))
(t (write-char sep-ch out))))
((eq mode 'binary)
(if ($numberp e)
(write-float ($float e) out)
(merror "write_data: encountered non-numeric data in binary output")))
(t
(merror "write_data: unrecognized mode"))))))))))
(defun get-input-sep-ch (sep-ch-flag my-stream)
(cond
((eq sep-ch-flag '$tab)
(format t "numericalio: separator flag ``tab'' not recognized for input; assume ``space'' instead.~%")
#\space)
(t (get-output-sep-ch sep-ch-flag my-stream))))
(defun get-output-sep-ch (sep-ch-flag my-stream)
(cond
((eq sep-ch-flag '$space) #\space)
((eq sep-ch-flag '$tab) #\tab)
((eq sep-ch-flag '$pipe) '$\|)
((null sep-ch-flag)
(cond
((ignore-errors (equal (pathname-type (truename my-stream)) "csv"))
'$\,)
(t #\space)))
(t
(format t "numericalio: separator flag ~S not recognized; assume ``space''.~%" (stripdollar sep-ch-flag))
#\space)))
(defun require-string (s)
(cond
((stringp s)
s)
(t
(merror "numericalio: expected a string, instead found a ~:M" (type-of s)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.